diff --git a/pool/shard007/Python/0069676_tagging.py b/pool/shard007/Python/0069676_tagging.py new file mode 100644 index 0000000000000000000000000000000000000000..f3a999be999ede32f8ab1e25bfdff3c1f604d0ad --- /dev/null +++ b/pool/shard007/Python/0069676_tagging.py @@ -0,0 +1,228 @@ +import os +import re +import shutil +import string +import os.path +import textwrap +import beets.autotag +from beets.mediafile import MediaFile +from beets.util import sanitize_path +from .utils import locate, ext_matcher + + +ALBUM_TEMPLATE = string.Template('$artist - $album ($year) [$format_info]') +AUDIO_FILE_TEMPLATE = string.Template('$number $title$extension') +RELEASE_DESCRIPTION_TEMPLATE = string.Template(''' +Track list: +$track_list +'''.strip()) +AUDIO_EXTENSIONS = ('.flac', '.mp3') +ALLOWED_EXTENSIONS = AUDIO_EXTENSIONS + ('.cue', '.log', '.gif', '.jpeg', '.jpg', '.md5', '.nfo', '.pdf', '.png', + '.sfv', '.txt') +BLOCKED_CHARS_REGEX = re.compile(r'[:?<>\*|"/]') +MAX_FILENAME_LENGTH = 180 + + +class InvalidFormatException(Exception): + pass + + +def directory_name(release): + ''' + Returns the proper directory name for a Release. + ''' + artist = textwrap.shorten(release.album_artist, width=50, placeholder='_') + album = textwrap.shorten(release.title, width=40, placeholder='_') + year = release.year + if release.bitrate == 'V0 (VBR)': + format_info = 'V0' + elif release.bitrate == '320': + format_info = '320' + else: + format_info = release.format + if release.medium != 'CD': + format_info = release.medium + ' ' + format_info + path = ALBUM_TEMPLATE.substitute(**locals()) + if release.catalog_number: + path += ' {' + release.catalog_number + '}' + path = path.replace('/', '_').replace('\\', '_') + path = sanitize_path(path) + return path + + +def audio_filename(path, is_compilation=False): + '''' + Returns the proper filename for the audio file located at `path`. + + Assumes that the audio file has already been properly tagged. + + If `is_compilation` is True, it means the audio file is part of + a compilation, and thus the track artist will be included in the + filename. + ''' + mediafile = MediaFile(path) + + if mediafile.disctotal and mediafile.disc and mediafile.disctotal > 1: + number = '{}.{:02}'.format(mediafile.disc, mediafile.track) + else: + number = '{:02}'.format(mediafile.track) + + if is_compilation: + title = '{} - {}'.format(mediafile.artist, mediafile.title) + else: + title = mediafile.title + + _, extension = os.path.splitext(path) + filename = AUDIO_FILE_TEMPLATE.substitute(**locals()) + filename = BLOCKED_CHARS_REGEX.sub('_', filename) + return filename + + +def apply_metadata(release): + ''' + Assuming that `release` has a valid AlbumMatch, this function will + apply the new metadata to the release's audio files. + ''' + beets.autotag.apply_metadata(release.info, release.match.mapping) + for item, _ in release.match.mapping.items(): + item.try_write() + + +def fix_release_filenames(release, directory=None, copy=False): + ''' + Renames a release and all of its files so that it has the proper + directory name and includes only allowed files with filenames less + than {} characters total. + + If `directory` is specified, the release will be moved + there. Otherwise, it will be renamed in its current directory. + '''.format(MAX_FILENAME_LENGTH) + if directory is None: + directory = os.path.dirname(release.path) + + output_dir = os.path.join(directory, directory_name(release)) + os.makedirs(output_dir, exist_ok=not copy) + + rename_audio_files(release, directory=output_dir, copy=copy) + rename_other_files(release, directory=output_dir, copy=copy) + + release.path = output_dir + return release + + +def rename_audio_files(release, directory, copy=False): + ''' + Moves (or copies) `release.audio_files` to their proper location within `directory`. + + Assumes that the audio files have already been properly tagged. + ''' + for audio_file in release.audio_files: + filename = audio_filename(audio_file, is_compilation=release.type == 7) + path = os.path.join(directory, filename) + path = truncate_path(path) + if copy: + shutil.copy2(audio_file, path) + else: + shutil.move(audio_file, path) + + +def rename_other_files(release, directory, copy=False): + ''' + Moves (or copies) `release.other_files` to their proper location within `directory`. + ''' + for other_file in release.other_files: + relpath = os.path.relpath(other_file, start=release.path) + path = os.path.join(directory, relpath) + path = truncate_path(path) + os.makedirs(os.path.dirname(path), exist_ok=True) + if copy: + shutil.copy2(other_file, path) + else: + shutil.move(other_file, path) + +def truncate_path(path): + ''' + Truncates `path` to contain no more than {max_length} characters. + + If `path` has fewer than {max_length} characters, it will be returned unchanged. + '''.format(max_length=MAX_FILENAME_LENGTH) + if len(path) <= MAX_FILENAME_LENGTH: + return path + + base, ext = os.path.splitext(os.path.basename(path)) + offset = MAX_FILENAME_LENGTH - len(path) + assert len(base) + offset > 0 + return os.path.join(os.path.dirname(path), base[:offset] + ext) + + +def audio_files(path): + ''' + Returns a list of all audio files within `path`. + ''' + return sorted(locate(path, ext_matcher(*AUDIO_EXTENSIONS))) + + +def allowed_files(path): + ''' + Returns a list of all allowed files within `path`. + ''' + return sorted(locate(path, ext_matcher(*ALLOWED_EXTENSIONS))) + + +def log_files(path): + ''' + Returns a list of all log files within `path`. + ''' + return sorted(locate(path, ext_matcher('.log'))) + + +def audio_format(path): + ''' + Returns the format (FLAC / MP3) of the release located at `path`. + ''' + mediafile = MediaFile(audio_files(path)[0]) + if mediafile.format == 'FLAC': + return 'FLAC' + elif mediafile.format == 'MP3': + return 'MP3' + raise InvalidFormatException('{} is not a valid audio release.'.format(path)) + + +def audio_bitrate(path): + ''' + Returns the bitrate (Lossless / 24bit Lossless / 320 / V0 (VBR)) + of the release located at `path`. + ''' + mediafile = MediaFile(audio_files(path)[0]) + if mediafile.format == 'FLAC' and mediafile.bitdepth == 24: + return '24bit Lossless' + elif mediafile.format == 'FLAC' and mediafile.bitdepth == 16: + return 'Lossless' + elif mediafile.format == 'MP3' and mediafile.bitrate == 320000: + return '320' + elif mediafile.format == 'MP3': + bitrates = [MediaFile(audio_file).bitrate for audio_file in audio_files(path)] + average_bitrate = sum(bitrates) / len(bitrates) + if average_bitrate >= 200000: + return 'V0 (VBR)' + raise InvalidFormatException('{} is not a valid audio release.'.format(path)) + + +def release_year(path): + ''' + Returns the year in which the release located at `path` was released. + ''' + match = re.search(r'\d{4}', path) + if match: + return int(match.group(0)) + mediafile = MediaFile(audio_files(path)[0]) + return mediafile.year + + +def release_description(release): + ''' + Returns a bbcode formatted description for `release`. + ''' + track_list = ['[#]{}'.format(track.title) for track in release.info.tracks] + track_list = '\n'.join(track_list) + return RELEASE_DESCRIPTION_TEMPLATE.substitute(**locals()) diff --git a/pool/shard007/Python/0069680_3003-playback_trajectory.py b/pool/shard007/Python/0069680_3003-playback_trajectory.py new file mode 100644 index 0000000000000000000000000000000000000000..829f448afff554a794ab8b2f5b303d1a5068c45c --- /dev/null +++ b/pool/shard007/Python/0069680_3003-playback_trajectory.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +# Software License Agreement (BSD License) +# +# Copyright (c) 2019, UFACTORY, Inc. +# All rights reserved. +# +# Author: Vinman + +""" +Description: playback trajectory + 1. requires firmware 1.2.0 and above support + 2. need to record the trajectory in advance +""" + +import os +import sys +import time + +sys.path.append(os.path.join(os.path.dirname(__file__), '../../..')) + +from xarm.wrapper import XArmAPI + + +####################################################### +""" +Just for test example +""" +if len(sys.argv) >= 2: + ip = sys.argv[1] +else: + try: + from configparser import ConfigParser + parser = ConfigParser() + parser.read('../robot.conf') + ip = parser.get('xArm', 'ip') + except: + ip = input('Please input the xArm ip address:') + if not ip: + print('input error, exit') + sys.exit(1) +######################################################## + + +arm = XArmAPI(ip, is_radian=True) +arm.motion_enable(enable=True) +arm.set_mode(0) +arm.set_state(state=0) + + +arm.load_trajectory('test.traj') +arm.playback_trajectory() + + diff --git a/pool/shard007/Python/0069687_coroutine.py b/pool/shard007/Python/0069687_coroutine.py new file mode 100644 index 0000000000000000000000000000000000000000..b75daef25069a405b41f4862aaa7a5bb7c690fff --- /dev/null +++ b/pool/shard007/Python/0069687_coroutine.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python +#coding:utf-8 +# Author : tuxpy +# Email : q8886888@qq.com.com +# Last modified : 2015-08-25 19:59:30 +# Filename : coroutine.py +# Description : +import gevent +from gevent import Greenlet, monkey +from functools import wraps + +class Coroutine(Greenlet): + def __init__(self, func, args = None, kwargs = None, callback = None): + Greenlet.__init__(self) + self._args = args or () + self._kwargs = kwargs or {} + self._callback = callback + self._func = func + + def _run(self): + error = None + result = None + try: + result = self._func(*self._args, **self._kwargs) + except Exception as e: + error = e + + if self._callback: + self._callback(result, error) + + +def coroutine(func): + @wraps(func) + def wrap(*args, **kwargs): + monkey.patch_all() + callback = kwargs.pop('callback', None) + _coroutine = Coroutine(func, args, kwargs, + callback = callback) + _coroutine.start() + + return wrap diff --git a/pool/shard007/Python/0069691_capture_device_capabilities.py b/pool/shard007/Python/0069691_capture_device_capabilities.py new file mode 100644 index 0000000000000000000000000000000000000000..b3b3d3d716eb0922b6c3923446062169533a01c9 --- /dev/null +++ b/pool/shard007/Python/0069691_capture_device_capabilities.py @@ -0,0 +1,136 @@ +#!/usr/bin/python +# Copyright 2014 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Code generator DeviceCapabilities literal.""" + +import argparse +import ctypes +import evdev +import os +import sys + + +TEST_DATA_GROUP_SIZE = 64 # Aligns with sysfs on 64-bit devices. + + +def bits_to_groups(bits): + return (bits + TEST_DATA_GROUP_SIZE - 1) / TEST_DATA_GROUP_SIZE + + +# As in /sys/class/input/input*/capabilities/* +def serialize_bitfield(bitfield, max_bit): + result = "" + group_count = bits_to_groups(max_bit) + for group in xrange(group_count - 1, -1, -1): + group_val = 0 + for group_bit in xrange(TEST_DATA_GROUP_SIZE): + code = group * TEST_DATA_GROUP_SIZE + group_bit + if code in bitfield: + group_val |= (1 << group_bit) + if group_val or result: + result += '%x' % group_val + if group: + result += ' ' + if not result: + return '0' + return result + + +def dump_absinfo(out, capabilities, identifier): + out.write('const DeviceAbsoluteAxis %s[] = {\n' % identifier) + + for code, absinfo in capabilities[evdev.ecodes.EV_ABS]: + # Set value := 0 to make it deterministic. + code_name = evdev.ecodes.bytype[evdev.ecodes.EV_ABS][code] + absinfo_struct = (0, absinfo.min, absinfo.max, absinfo.fuzz, absinfo.flat, + absinfo.resolution) + data = (code_name,) + absinfo_struct + out.write(' {%s, {%d, %d, %d, %d, %d, %d}},\n' % data) + + out.write('};\n') + + +def dump_capabilities(out, dev, identifier): + capabilities = dev.capabilities() + has_abs = evdev.ecodes.EV_ABS in capabilities + + sysfs_path = '/sys/class/input/' + os.path.basename(dev.fn) + + # python-evdev is missing some features + uniq = open(sysfs_path + '/device/uniq', 'r').read().strip() + prop = open(sysfs_path + '/device/properties', 'r').read().strip() + ff = open(sysfs_path + '/device/capabilities/ff', 'r').read().strip() + + # python-evdev parses the id wrong. + bustype = open(sysfs_path + '/device/id/bustype', 'r').read().strip() + vendor = open(sysfs_path + '/device/id/vendor', 'r').read().strip() + product = open(sysfs_path + '/device/id/product', 'r').read().strip() + version = open(sysfs_path + '/device/id/version', 'r').read().strip() + + # python-evdev drops EV_REP from the event set. + ev = open(sysfs_path + '/device/capabilities/ev', 'r').read().strip() + + if ctypes.sizeof(ctypes.c_long()) != 8: + # /sys/class/input/*/properties format is word size dependent. + # Could be fixed by regrouping but for now, just raise an error. + raise ValueError("Must be run on 64-bit machine") + + key_bits = capabilities.get(evdev.ecodes.EV_KEY, []) + rel_bits = capabilities.get(evdev.ecodes.EV_REL, []) + abs_bits = [abs[0] for abs in capabilities.get(evdev.ecodes.EV_ABS, [])] + msc_bits = capabilities.get(evdev.ecodes.EV_MSC, []) + sw_bits = capabilities.get(evdev.ecodes.EV_SW, []) + led_bits = capabilities.get(evdev.ecodes.EV_LED, []) + + fields = [ + ('path', os.path.realpath(sysfs_path)), + ('name', dev.name), + ('phys', dev.phys), + ('uniq', uniq), + ('bustype', bustype), + ('vendor', vendor), + ('product', product), + ('version', version), + ('prop', prop), + ('ev', ev), + ('key', serialize_bitfield(key_bits, evdev.ecodes.KEY_CNT)), + ('rel', serialize_bitfield(rel_bits, evdev.ecodes.REL_CNT)), + ('abs', serialize_bitfield(abs_bits, evdev.ecodes.ABS_CNT)), + ('msc', serialize_bitfield(msc_bits, evdev.ecodes.MSC_CNT)), + ('sw', serialize_bitfield(sw_bits, evdev.ecodes.SW_CNT)), + ('led', serialize_bitfield(led_bits, evdev.ecodes.LED_CNT)), + ('ff', ff), + ] + + if has_abs: + absinfo_identifier = identifier + 'AbsAxes' + dump_absinfo(out, capabilities, absinfo_identifier) + + out.write('const DeviceCapabilities %s = {\n' % identifier) + for name, val in fields: + out.write(' /* %s */ "%s",\n' % (name, val)) + + if has_abs: + out.write(' %s,\n' % absinfo_identifier) + out.write(' arraysize(%s),\n' % absinfo_identifier) + + out.write('};\n') + + +def main(argv): + parser = argparse.ArgumentParser() + parser.add_argument('device') + parser.add_argument('identifier') + args = parser.parse_args(argv) + + dev = evdev.InputDevice(args.device) + out = sys.stdout + + dump_capabilities(out, dev, args.identifier) + return 0 + + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/pool/shard007/Python/0069693_cmd_filter.py b/pool/shard007/Python/0069693_cmd_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..1d798d7eb5fe5b79c5cd359b479e21fbe5f0b587 --- /dev/null +++ b/pool/shard007/Python/0069693_cmd_filter.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- +# +import re +from rest_framework import serializers + +from django.utils.translation import ugettext_lazy as _ +from ..models import CommandFilter, CommandFilterRule +from orgs.mixins.serializers import BulkOrgResourceModelSerializer +from orgs.utils import tmp_to_root_org +from common.utils import get_object_or_none, lazyproperty +from terminal.models import Session + + +class CommandFilterSerializer(BulkOrgResourceModelSerializer): + + class Meta: + model = CommandFilter + fields_mini = ['id', 'name'] + fields_small = fields_mini + [ + 'org_id', 'org_name', + 'is_active', + 'date_created', 'date_updated', + 'comment', 'created_by', + ] + fields_fk = ['rules'] + fields_m2m = ['users', 'user_groups', 'system_users', 'assets', 'applications'] + fields = fields_small + fields_fk + fields_m2m + extra_kwargs = { + 'rules': {'read_only': True} + } + + +class CommandFilterRuleSerializer(BulkOrgResourceModelSerializer): + type_display = serializers.ReadOnlyField(source='get_type_display') + action_display = serializers.ReadOnlyField(source='get_action_display') + + class Meta: + model = CommandFilterRule + fields_mini = ['id'] + fields_small = fields_mini + [ + 'type', 'type_display', 'content', 'ignore_case', 'pattern', 'priority', + 'action', 'action_display', 'reviewers', + 'date_created', 'date_updated', + 'comment', 'created_by', + ] + fields_fk = ['filter'] + fields = fields_small + fields_fk + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.set_action_choices() + + def set_action_choices(self): + from django.conf import settings + action = self.fields.get('action') + if not action: + return + choices = action._choices + if not settings.XPACK_ENABLED: + choices.pop(CommandFilterRule.ActionChoices.confirm, None) + action._choices = choices + + def validate_content(self, content): + tp = self.initial_data.get("type") + if tp == CommandFilterRule.TYPE_COMMAND: + regex = CommandFilterRule.construct_command_regex(content) + else: + regex = content + ignore_case = self.initial_data.get('ignore_case') + succeed, error, pattern = CommandFilterRule.compile_regex(regex, ignore_case) + if not succeed: + raise serializers.ValidationError(error) + return content + + +class CommandConfirmSerializer(serializers.Serializer): + session_id = serializers.UUIDField(required=True, allow_null=False) + cmd_filter_rule_id = serializers.UUIDField(required=True, allow_null=False) + run_command = serializers.CharField(required=True, allow_null=False) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.session = None + self.cmd_filter_rule = None + + def validate_session_id(self, session_id): + self.session = self.validate_object_exist(Session, session_id) + return session_id + + def validate_cmd_filter_rule_id(self, cmd_filter_rule_id): + self.cmd_filter_rule = self.validate_object_exist(CommandFilterRule, cmd_filter_rule_id) + return cmd_filter_rule_id + + @staticmethod + def validate_object_exist(model, field_id): + with tmp_to_root_org(): + obj = get_object_or_none(model, id=field_id) + if not obj: + error = '{} Model object does not exist'.format(model.__name__) + raise serializers.ValidationError(error) + return obj + + @lazyproperty + def org(self): + return self.session.org diff --git a/pool/shard007/Python/0069694_gmin_rotamer.py b/pool/shard007/Python/0069694_gmin_rotamer.py new file mode 100644 index 0000000000000000000000000000000000000000..66cdc50cf3a72823122adcb7e0fe800d6fc85228 --- /dev/null +++ b/pool/shard007/Python/0069694_gmin_rotamer.py @@ -0,0 +1,158 @@ +import joblib +import re +import os.path +import rotamer.topology.read_amber_prmtop as prmtop + +kcal_mol_in_joules = 4184 +gas_constant = 8.3145 + +class RotamerMove(): + def __init__(self, pickle_filename=None, prmtop_filename=None, settings_filename=None): + """ + Initialise from either a file or a pickled RotamerMove instance. + """ + if pickle_filename: + self = joblib.load(pickle_filename) + elif prmtop_filename: + self.parse_prmtop(prmtop_filename) + self.moving_residues = [] + self.deps = set() + self.save_file = None + if settings_filename: + self.read_settings(settings_filename) + else: + raise ValueError("Either pickle_filename or prmtop_filename must be specified.") + + def parse_prmtop(self, prmtop_filename): + self.molecule = prmtop.parse_topology_file(prmtop_filename) + + def read_settings(self, settings_filename): + """ + Read settings for the rotamer move, which determines the residues that move and which distribution the move is + selected from. + + :param settings_filename: filename of file containing settings + """ + with open(settings_filename, "r") as settings_file: + for line in settings_file: + # List comp splits the string and gets rid of empty strings + tokenized = [tok for tok in re.split("[ ,]", line) if tok] + # Go through the possible options + # Residue list + if re.match("res", tokenized[0]): + self.moving_residues = self.parse_res_list(" ".join(tokenized[1:])) + # Dependencies + elif any([re.match("depend", tok) for tok in tokenized]): + if any(["bb" in tok or "backbone" in tok for tok in tokenized]): + self.deps.add("backbone") + if any(["neighbour" in tok or "neighbor" in tok for tok in tokenized]): + self.deps.add("neighbour_idents") + if any(["sidechain" in tok or "sc" in tok for tok in tokenized]): + self.deps.add("neighbour_identities") + self.deps.add("neighbour_sidechains") + # Rotamer distribution temperature + elif re.match("temp", tokenized[0]): + kelvin = any(["K" in tok for tok in tokenized[1:]]) + if kelvin: + tokenized[1:] = [tok.strip("K ") for tok in tokenized[1:] if tok.strip("K ")] + self.temp = float(tokenized[1]) * gas_constant / kcal_mol_in_joules + else: + self.temp = float(tokenized[1]) + + def print_settings(self): + """ + Prints the current settings for the rotamer moves. + """ + for k, v in self.__dict__.items(): + print k, v + + def save_move(self): + """ + Pickles the object, to save the move parameters between subsequent GMIN steps. + + :return: + """ + if not self.save_file: + import tempfile + savedir = tempfile.mkdtemp() + self.save_file = os.path.join(savedir, "rotamer.pkl") + joblib.dump(self, self.save_file) + return self.save_file + + def parse_res_list(self, res_list): + """ + Parses the given residue list and returns a list of matching residue indices. + + :param res_list: list of residues according to the defined format + :return: list of indices of matching residues + """ + res_idxs = set() + # Get rid of whitespace around hyphens, just in case + res_list = re.sub(" - ", "-", res_list) + # Split into tokens + res_list = res_list.split() + subtract = False + for i, res in enumerate(res_list): + if res == "not": + subtract = True + continue + elif "-" in res: + res_sublist = range(int(res.split("-")[0]), int(res.split("-")[1]) + 1) + else: + res_sublist = [int(res)] + if subtract: + for r in res_sublist: + res_idxs.remove(r) + subtract = False + else: + for r in res_sublist: + res_idxs.add(r) + return list(res_idxs) + + def __call__(self, coords): + """ + Performs the rotamer move on a given set of coordinates. + + There are a few possible dependency levels: + + 1) Identity of the amino acid being moved. + + In this case, we build a partition function by averaging over all of the neighbours and all neighbouring + configurations. + + 2) Identity of the amino acid and configuration of its backbone (phi/psi angles). + + In this case, we use variable kernel density estimates to construct conditional distributions of phi/psi + angles as a function of rotamer states, and invert these using Bayes' rule to obtain P(r|phi, psi) (from + Shapovalov MV and Dunbrack RL, Structure, 19, pp844-858, 2011) + + 3) Identity of the amino acid and identity of the neighbouring amino acids. + + This is the same as case 1, but constructing separate partition functions for each pair of amino acid + neighbours (i.e. 22 * 22 = 484 in total). + + 4) Identity of the amino acid, its neighbours and rotameric states of the neighbours. + + This is the same as case 3, but constructing a conditional probability for the central rotamers in terms of + the neighbouring rotameric states. *** TODO: Should this be an inversion of P(r_i-1, r_i+1 | r_i)? *** + + 5) Combinations of 3 and 4 with backbone configurations. + + Each of these requires a slightly different method for calculating the probability distributions and different + amounts of structural information prior to making a move. + + :param coords: Initial coordinates + :return: New coordinates (after the move) + """ + + + +if __name__ == "__main__": + move = RotamerMove(prmtop_filename="../tests/data/ARG_LYS_ASN.prmtop") + move.read_settings("../tests/data/example_settings") + # move.print_settings() + location = move.save_move() + joblib.dump(move, location) + move_copy = RotamerMove(pickle_filename=location) + move_copy = joblib.load(location) + move_copy.print_settings() diff --git a/pool/shard007/Python/0069696_server.py b/pool/shard007/Python/0069696_server.py new file mode 100644 index 0000000000000000000000000000000000000000..eafd2cbba49923f115b45063a78d8e83e7961565 --- /dev/null +++ b/pool/shard007/Python/0069696_server.py @@ -0,0 +1,72 @@ +import sys +import tensorflow as tf +import os +from flask import Flask, request, redirect, url_for +from werkzeug import secure_filename + +# change this as you see fit +#filename = sys.argv[1] +#print("filename : " + filename) +#image_path = sys.argv[1] + + + +# Loads label file, strips off carriage return +label_lines = [line.rstrip() for line + in tf.gfile.GFile("labels.txt")] + +# Unpersists graph from file +with tf.gfile.FastGFile("model.pb", 'rb') as f: + graph_def = tf.GraphDef() + graph_def.ParseFromString(f.read()) + _ = tf.import_graph_def(graph_def, name='') + +sess = tf.Session() + # Feed the image_data as input to the graph and get first prediction +softmax_tensor = sess.graph.get_tensor_by_name('final_result:0') +print("loaded tensor") + +UPLOAD_FOLDER = '/tmp/' +ALLOWED_EXTENSIONS = set(['jpg', 'jpeg']) + +app = Flask(__name__) +app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER + +def allowed_file(filename): + return '.' in filename and \ + filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS + +@app.route("/", methods=['GET', 'POST']) +def index(): + if request.method == 'POST': + file = request.files['file'] + if file and allowed_file(file.filename): + filename = secure_filename(file.filename) + image_path =os.path.join(app.config['UPLOAD_FOLDER'], filename) + file.save(image_path) + # Read in the image_data + image_data = tf.gfile.FastGFile(image_path, 'rb').read() + predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data}) + + # Sort to show labels of first prediction in order of confidence + top_k = predictions[0].argsort()[-len(predictions[0]):][::-1] + + for node_id in top_k: + human_string = label_lines[node_id] + score = predictions[0][node_id] + print('%s (score = %.5f)' % (human_string, score)) + + return redirect(url_for('index')) + return """ + + Upload new File +

Upload new File

+
+

+ +

+

%s

+ """ % "
".join(os.listdir(app.config['UPLOAD_FOLDER'],)) + +if __name__ == "__main__": + app.run(host='0.0.0.0', port=5001, debug=True) diff --git a/pool/shard007/Python/0069697_main.py b/pool/shard007/Python/0069697_main.py new file mode 100644 index 0000000000000000000000000000000000000000..03d82554ac2cd90b12f7aa5ee87b055a87dc4936 --- /dev/null +++ b/pool/shard007/Python/0069697_main.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# +# === This file is part of Calamares - === +# +# Copyright 2014, Philip Müller +# Copyright 2014, Teo Mrnjavac +# Copyright 2017, Alf Gaida +# +# Calamares 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. +# +# Calamares 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 Calamares. If not, see . + +import libcalamares + + +def run(): + """ + Setup systemd services + """ + services = libcalamares.job.configuration['services'] + targets = libcalamares.job.configuration['targets'] + disable = libcalamares.job.configuration['disable'] + + # note that the "systemctl enable" and "systemctl disable" commands used + # here will work in a chroot; in fact, they are the only systemctl commands + # that support that, see: + # http://0pointer.de/blog/projects/changing-roots.html + + # enable services + for svc in services: + ec = libcalamares.utils.target_env_call( + ['systemctl', 'enable', '{}.service'.format(svc['name'])] + ) + + if ec != 0: + if svc['mandatory']: + return ("Cannot enable systemd service {}".format(svc['name']), + "systemctl enable call in chroot returned error code " + "{}".format(ec) + ) + else: + libcalamares.utils.debug( + "Cannot enable systemd service {}".format(svc['name']) + ) + libcalamares.utils.debug( + "systemctl enable call in chroot returned error code " + "{}".format(ec) + ) + + # enable targets + for tgt in targets: + ec = libcalamares.utils.target_env_call( + ['systemctl', 'enable', '{}.target'.format(tgt['name'])] + ) + + if ec != 0: + if tgt['mandatory']: + return ("Cannot enable systemd target {}".format(tgt['name']), + "systemctl enable call in chroot returned error code" + "{}".format(ec) + ) + else: + libcalamares.utils.debug( + "Cannot enable systemd target {}".format(tgt['name']) + ) + libcalamares.utils.debug( + "systemctl enable call in chroot returned error code " + "{}".format(ec) + ) + + for dbl in disable: + ec = libcalamares.utils.target_env_call( + ['systemctl', 'disable', '{}.service'.format(dbl['name'])] + ) + + if ec != 0: + if dbl['mandatory']: + return ("Cannot disable systemd service" + "{}".format(dbl['name']), + "systemctl disable call in chroot returned error code" + "{}".format(ec)) + else: + libcalamares.utils.debug( + "Cannot disable systemd service {}".format(dbl['name']) + ) + libcalamares.utils.debug( + "systemctl disable call in chroot returned error code " + "{}".format(ec) + ) + + return None diff --git a/pool/shard007/Python/0069701_NotInClanModule.py b/pool/shard007/Python/0069701_NotInClanModule.py new file mode 100644 index 0000000000000000000000000000000000000000..3ca0eb5a7fbc319e6df958f1714e5b9606908edc --- /dev/null +++ b/pool/shard007/Python/0069701_NotInClanModule.py @@ -0,0 +1,21 @@ +from cwbot.modules.BaseKmailModule import BaseKmailModule + + +class NotInClanModule(BaseKmailModule): + """ + A module that returns a kmail from somebody not in the clan. + + No configuration options. + """ + requiredCapabilities = ['kmail'] + _name = "nonclan" + + def __init__(self, manager, identity, config): + super(NotInClanModule, self).__init__(manager, identity, config) + + + def _processKmail(self, message): + if not self.parent.checkClan(message.uid): + return (self.newMessage(message.uid, "You're not in my clan.") + .addItems(message.items)) + return None diff --git a/pool/shard007/Python/0069703_views.py b/pool/shard007/Python/0069703_views.py new file mode 100644 index 0000000000000000000000000000000000000000..22a41af2c0a83ae2ec8ca08df60026b76368d2d5 --- /dev/null +++ b/pool/shard007/Python/0069703_views.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +########################################################################################## +# Developer: Luan,Jingchao Project: HuMaIN (http://humain.acis.ufl.edu) +# Description: +# Receive OCRopus segmentation service requests from user, call segmentation function +# and get the output, and then return the output or error info to user. +########################################################################################## +# Copyright 2017 Advanced Computing and Information Systems (ACIS) Lab - UF +# (https://www.acis.ufl.edu/) +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +########################################################################################## + +from __future__ import unicode_literals +from rest_framework.decorators import api_view +from rest_framework.response import Response +from rest_framework import status +from django.views.decorators.csrf import csrf_exempt +from django.http import HttpResponse, JsonResponse +from django.conf import settings +from django.shortcuts import render +from .segmentation import segmentation_exec +import sys, os, os.path, zipfile, StringIO +import logging + +reload(sys) +sys.setdefaultencoding('utf8') + +def index(request): + return render(request, 'index.html') + +@csrf_exempt +@api_view(['GET', 'POST']) +def segmentationView(request, format=None): + logger = logging.getLogger('segmentation') + if request.data.get('image') is None: + logger.error("Please upload only one image") + return Response("ERROR: Please upload an image", status=status.HTTP_400_BAD_REQUEST) + + ### Receive parameters set by user + parameters = request.data.dict() + del parameters['image'] # parameter 'image' will be processed later + keys = parameters.keys() + if 'usegauss' in keys: + keys.remove('usegauss') + for key in keys: + parameters[key] = float(parameters[key]) + + image_object = request.FILES['image'] + ### Call segmentation function + seg_result = segmentation_exec(image_object, parameters) + if not seg_result: # if output_list is empty + logger.error("sth wrong with segmentation") + return Response("ERROR: sth wrong with segmentation", status=status.HTTP_500_INTERNAL_SERVER_ERROR) + + ### Else return the segmented images in zip type + # Folder name in ZIP archive which contains the above files + imagename_base, ext = os.path.splitext(str(image_object)) + zip_dir = imagename_base+"_seg" + zip_name = "%s.zip" % zip_dir + strio = StringIO.StringIO() # Open StringIO to grab in-memory ZIP contents + zf = zipfile.ZipFile(strio, "w") # The zip compressor + + # Zip multiple image objects from memory + for key in seg_result: + # Save single-line image object in memory as png format + line_image_io = StringIO.StringIO() + seg_result[key].save(line_image_io, 'png') + zip_path = os.path.join(zip_dir, key) + zf.writestr(zip_path, line_image_io.getvalue()) + zf.close() + + # Grab ZIP file from in-memory, make response with correct MIME-type + response = HttpResponse(strio.getvalue(), content_type="application/x-zip") + # And correct content-disposition + response["Content-Disposition"] = 'attachment; filename=%s' % zip_name + + return response \ No newline at end of file diff --git a/pool/shard007/Python/0069704_bazel_api_test.py b/pool/shard007/Python/0069704_bazel_api_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e3d404c4f329eb6e8e22e60943e7eb1c36760061 --- /dev/null +++ b/pool/shard007/Python/0069704_bazel_api_test.py @@ -0,0 +1,157 @@ +# Lint as: python3 +# Copyright 2020 The Bazel Authors. All rights reserved. +# +# 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. +"""Tests for bazel_api.py.""" +import os +import unittest +from src.test.py.bazel import test_base +from tools.ctexplain.bazel_api import BazelApi +from tools.ctexplain.types import HostConfiguration +from tools.ctexplain.types import NullConfiguration + + +class BazelApiTest(test_base.TestBase): + + _bazel_api: BazelApi = None + + def setUp(self): + test_base.TestBase.setUp(self) + self._bazel_api = BazelApi(self.RunBazel) + self.ScratchFile('WORKSPACE') + self.CreateWorkspaceWithDefaultRepos('repo/WORKSPACE') + + def tearDown(self): + test_base.TestBase.tearDown(self) + + def testBasicCquery(self): + self.ScratchFile('testapp/BUILD', [ + 'filegroup(name = "fg", srcs = ["a.file"])', + ]) + res = self._bazel_api.cquery(['//testapp:all']) + success = res[0] + cts = res[2] + self.assertTrue(success) + self.assertEqual(len(cts), 1) + self.assertEqual(cts[0].label, '//testapp:fg') + self.assertIsNone(cts[0].config) + self.assertGreater(len(cts[0].config_hash), 10) + self.assertIn('PlatformConfiguration', cts[0].transitive_fragments) + + def testFailedCquery(self): + self.ScratchFile('testapp/BUILD', [ + 'filegroup(name = "fg", srcs = ["a.file"])', + ]) + (success, stderr, cts) = self._bazel_api.cquery(['//testapp:typo']) + self.assertFalse(success) + self.assertEqual(len(cts), 0) + self.assertIn("target 'typo' not declared in package 'testapp'", + os.linesep.join(stderr)) + + def testTransitiveFragmentsAccuracy(self): + self.ScratchFile('testapp/BUILD', [ + 'filegroup(name = "fg", srcs = ["a.file"])', + 'filegroup(name = "ccfg", srcs = [":ccbin"])', + 'cc_binary(name = "ccbin", srcs = ["ccbin.cc"])' + ]) + cts1 = self._bazel_api.cquery(['//testapp:fg'])[2] + self.assertNotIn('CppConfiguration', cts1[0].transitive_fragments) + cts2 = self._bazel_api.cquery(['//testapp:ccfg'])[2] + self.assertIn('CppConfiguration', cts2[0].transitive_fragments) + + def testGetTargetConfig(self): + self.ScratchFile('testapp/BUILD', [ + 'filegroup(name = "fg", srcs = ["a.file"])', + ]) + cts = self._bazel_api.cquery(['//testapp:fg'])[2] + config = self._bazel_api.get_config(cts[0].config_hash) + expected_fragments = ['PlatformConfiguration', 'JavaConfiguration'] + for exp in expected_fragments: + self.assertIn(exp, config.fragments.keys()) + core_options = config.options['CoreOptions'] + self.assertIsNotNone(core_options) + self.assertIn(('stamp', 'false'), core_options.items()) + + def testGetHostConfig(self): + self.ScratchFile('testapp/BUILD', [ + 'genrule(', + ' name = "g",', + ' srcs = [],', + ' cmd = "",', + ' outs = ["g.out"],', + ' tools = [":fg"])', + 'filegroup(name = "fg", srcs = ["a.file"])', + ]) + query = ['//testapp:fg', '--universe_scope=//testapp:g'] + cts = self._bazel_api.cquery(query)[2] + config = self._bazel_api.get_config(cts[0].config_hash) + self.assertIsInstance(config, HostConfiguration) + # We don't currently populate or read a host configuration's details. + self.assertEqual(len(config.fragments), 0) + self.assertEqual(len(config.options), 0) + + def testGetNullConfig(self): + self.ScratchFile('testapp/BUILD', [ + 'filegroup(name = "fg", srcs = ["a.file"])', + ]) + cts = self._bazel_api.cquery(['//testapp:a.file'])[2] + config = self._bazel_api.get_config(cts[0].config_hash) + self.assertIsInstance(config, NullConfiguration) + # Null configurations have no information by definition. + self.assertEqual(len(config.fragments), 0) + self.assertEqual(len(config.options), 0) + + def testConfigFragmentsMap(self): + self.ScratchFile('testapp/BUILD', [ + 'filegroup(name = "fg", srcs = ["a.file"])', + ]) + cts = self._bazel_api.cquery(['//testapp:fg'])[2] + fragments_map = self._bazel_api.get_config(cts[0].config_hash).fragments + self.assertIn('PlatformOptions', fragments_map['PlatformConfiguration']) + self.assertIn('ShellConfiguration$Options', + fragments_map['ShellConfiguration']) + + def testConfigWithDefines(self): + self.ScratchFile('testapp/BUILD', [ + 'filegroup(name = "fg", srcs = ["a.file"])', + ]) + cquery_args = ['//testapp:fg', '--define', 'a=b'] + cts = self._bazel_api.cquery(cquery_args)[2] + config = self._bazel_api.get_config(cts[0].config_hash) + user_defined_options = config.options['user-defined'] + self.assertIsNotNone(user_defined_options) + self.assertDictEqual(user_defined_options._dict, {'--define:a': 'b'}) + + def testConfigWithStarlarkFlags(self): + self.ScratchFile('testapp/defs.bzl', [ + 'def _flag_impl(settings, attr):', ' pass', 'string_flag = rule(', + ' implementation = _flag_impl,', + ' build_setting = config.string(flag = True)' + ')' + ]) + self.ScratchFile('testapp/BUILD', [ + 'load(":defs.bzl", "string_flag")', + 'string_flag(name = "my_flag", build_setting_default = "nada")', + 'filegroup(name = "fg", srcs = ["a.file"])', + ]) + cquery_args = ['//testapp:fg', '--//testapp:my_flag', 'algo'] + cts = self._bazel_api.cquery(cquery_args)[2] + config = self._bazel_api.get_config(cts[0].config_hash) + user_defined_options = config.options['user-defined'] + self.assertIsNotNone(user_defined_options) + self.assertDictEqual(user_defined_options._dict, + {'//testapp:my_flag': 'algo'}) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard007/Python/0069706_backup_database.py b/pool/shard007/Python/0069706_backup_database.py new file mode 100644 index 0000000000000000000000000000000000000000..29bf3869bd414b67fc5e8cf6f428f62304fb3f50 --- /dev/null +++ b/pool/shard007/Python/0069706_backup_database.py @@ -0,0 +1,71 @@ +from optparse import make_option +from subprocess import Popen, PIPE +from django.core.management.base import BaseCommand +from django.conf import settings +from django.core.mail import EmailMessage +import sys + +from socket import gethostname + +class Command(BaseCommand): + option_list = BaseCommand.option_list + ( + make_option('-d', '--database', choices=settings.DATABASES.keys(), default='default', help='Database to backup'), + + make_option('-o', '--output', choices=['file', 'stdout', 'email'], default='email', help='Output to file or stout or email'), + make_option('-f', '--filename', default='database.backup', help='File location to write to if output is file'), + + make_option('-s', '--subject', default='%s Database Backup' % settings.EMAIL_SUBJECT_PREFIX), + ) + help = 'Send email backups of a database' + + def handle(self, *emails, **options): + self.filename = options['filename'] if options['output'] == 'file' else None + self.file_content = None + self.file_written = False + + self.backup(options['database'], filename=self.filename) + + if options['output'] == 'stdout': + sys.stdout.write(self.file_content) + elif options['output'] == 'email': + if emails: + self.email(*emails, subject=options['subject'], filename=options['filename']) + elif options['output'] == 'file' and not self.file_written and self.file_content: + print 'write file' + + + def backup(self, database, *args, **kwargs): + if settings.DATABASES[database]['ENGINE'] in ['django.db.backends.postgresql_psycopg2']: + self.file_content = self.postgresql(database, *args, **kwargs) + + def postgresql(self, database, filename=None, cmd='pg_dump'): + cmd_args = [ + '--format', 'custom', + '--blobs', + '-U', settings.DATABASES[database]['USER'], + ] + if filename: + cmd_args.append('--file') + cmd_args.append(filename) + self.filename = filename + self.file_written = True + + pf = Popen([cmd] + cmd_args + [settings.DATABASES[database]['NAME']], + env = { + 'PGPASSWORD': settings.DATABASES[database]['PASSWORD'] + }, + stdout=PIPE + ) + return pf.communicate()[0] + + def email(self, *emails, **kwargs): + msg = EmailMessage( + subject=kwargs.get('subject', None), + to = list(emails), + ) + + if self.filename: + msg.attach_file(self.filename) + elif self.file_content: + msg.attach(kwargs.get('filename'), self.file_content) + msg.send() diff --git a/pool/shard007/Python/0069709_run-on-all.py b/pool/shard007/Python/0069709_run-on-all.py new file mode 100644 index 0000000000000000000000000000000000000000..890642ce9b252889b8d29942c54615ca466e971d --- /dev/null +++ b/pool/shard007/Python/0069709_run-on-all.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python +# We attempted to make this program work with both python2 and python3 +# -*-python-*- + +"""This script runs a command on all worker hosts of a Hillview cluster.""" +# pylint: disable=invalid-name + +from argparse import ArgumentParser, REMAINDER +from hillviewCommon import ClusterConfiguration, get_config, get_logger + +logger = get_logger("run-on-all") + +def execute_command_on_all(config, command): + """Executes command on all workers""" + assert isinstance(config, ClusterConfiguration) + message = "Executing `" + str(command) + "' on " + str(len(config.get_workers())) + " hosts" + logger.info(message) + lam = lambda rh: rh.run_remote_shell_command(command) + config.run_on_all_workers(lam) + +def main(): + """Main function""" + parser = ArgumentParser() + parser.add_argument("config", help="json cluster configuration file") + parser.add_argument("command", help="command to run", nargs=REMAINDER) + args = parser.parse_args() + config = get_config(parser, args) + command = " ".join(args.command) + execute_command_on_all(config, command) + +if __name__ == "__main__": + main() diff --git a/pool/shard007/Python/0069710_file_data_source.py b/pool/shard007/Python/0069710_file_data_source.py new file mode 100644 index 0000000000000000000000000000000000000000..9cbf78f0a7f8b4789589288fa6d3a40575f7c993 --- /dev/null +++ b/pool/shard007/Python/0069710_file_data_source.py @@ -0,0 +1,189 @@ +"""The base file related data source object from which all MayaVi data +sources derive. + +""" +# Author: Prabhu Ramachandran +# Copyright (c) 2005, Enthought, Inc. +# License: BSD Style. + +# Standard library imports. +import re +from os.path import split, join, isfile +from glob import glob + +# Enthought library imports. +from traits.api import List, Str, Instance, Int, Range +from traitsui.api import Group, Item, FileEditor +from apptools.persistence.state_pickler import set_state +from apptools.persistence.file_path import FilePath + +# Local imports +from mayavi.core.source import Source +from mayavi.core.common import handle_children_state + + +###################################################################### +# Utility functions. +###################################################################### +def get_file_list(file_name): + """ Given a file name, this function treats the file as a part of + a series of files based on the index of the file and tries to + determine the list of files in the series. The file name of a + file in a time series must be of the form 'some_name[0-9]*.ext'. + That is the integers at the end of the file determine what part of + the time series the file belongs to. The files are then sorted as + per this index.""" + + # The matching is done only for the basename of the file. + f_dir, f_base = split(file_name) + # Find the head and tail of the file pattern. + head = re.sub("[0-9]+[^0-9]*$", "", f_base) + tail = re.sub("^.*[0-9]+", "", f_base) + pattern = head+"[0-9]*"+tail + # Glob the files for the pattern. + _files = glob(join(f_dir, pattern)) + + # A simple function to get the index from the file. + def _get_index(f, head=head, tail=tail): + base = split(f)[1] + result = base.replace(head, '') + return float(result.replace(tail, '')) + + # Before sorting make sure the files in the globbed series are + # really part of a timeseries. This can happen in cases like so: + # 5_2_1.vtk and 5_2_1s.vtk will be globbed but 5_2_1s.vtk is + # obviously not a valid time series file. + files = [] + for x in _files: + try: + _get_index(x) + except ValueError: + pass + else: + files.append(x) + + # Sort the globbed files based on the index value. + def file_sort(x, y): + x1 = _get_index(x) + y1 = _get_index(y) + if x1 > y1: + return 1 + elif y1 > x1: + return -1 + else: + return 0 + + files.sort(file_sort) + return files + + +###################################################################### +# `FileDataSource` class. +###################################################################### +class FileDataSource(Source): + + # The version of this class. Used for persistence. + __version__ = 0 + + # The list of file names for the timeseries. + file_list = List(Str, desc='a list of files belonging to a time series') + + # The current time step (starts with 0). This trait is a dummy + # and is dynamically changed when the `file_list` trait changes. + # This is done so the timestep bounds are linked to the number of + # the files in the file list. + timestep = Range(value=0, + low='_min_timestep', + high='_max_timestep', + enter_set=True, auto_set=False, + desc='the current time step') + + base_file_name=Str('', desc="the base name of the file", + enter_set=True, auto_set=False, + editor=FileEditor()) + + # A timestep view group that may be included by subclasses. + time_step_group = Group(Item(name='file_path', style='readonly'), + Item(name='timestep', + defined_when='len(object.file_list) > 1') + ) + + ################################################## + # Private traits. + ################################################## + + # The current file name. This is not meant to be touched by the + # user. + file_path = Instance(FilePath, (), desc='the current file name') + + _min_timestep = Int(0) + _max_timestep = Int(0) + + ###################################################################### + # `object` interface + ###################################################################### + def __get_pure_state__(self): + d = super(FileDataSource, self).__get_pure_state__() + # These are obtained dynamically, so don't pickle them. + for x in ['file_list', 'timestep']: + d.pop(x, None) + return d + + def __set_pure_state__(self, state): + # Use the saved path to initialize the file_list and timestep. + fname = state.file_path.abs_pth + if not isfile(fname): + msg = 'Could not find file at %s\n'%fname + msg += 'Please move the file there and try again.' + raise IOError, msg + + self.initialize(fname) + # Now set the remaining state without touching the children. + set_state(self, state, ignore=['children', 'file_path']) + # Setup the children. + handle_children_state(self.children, state.children) + # Setup the children's state. + set_state(self, state, first=['children'], ignore=['*']) + + ###################################################################### + # `FileDataSource` interface + ###################################################################### + def initialize(self, base_file_name): + """Given a single filename which may or may not be part of a + time series, this initializes the list of files. This method + need not be called to initialize the data. + """ + self.base_file_name = base_file_name + + ###################################################################### + # Non-public interface + ###################################################################### + def _file_list_changed(self, value): + # Change the range of the timestep suitably to reflect new list. + n_files = len(self.file_list) + timestep = min(self.timestep, n_files) + self._max_timestep = max(n_files -1, 0) + if self.timestep == timestep: + self._timestep_changed(timestep) + else: + self.timestep = timestep + + def _file_list_items_changed(self, list_event): + self._file_list_changed(self.file_list) + + def _timestep_changed(self, value): + file_list = self.file_list + if len(file_list) > 0: + self.file_path = FilePath(file_list[value]) + else: + self.file_path = FilePath('') + + def _base_file_name_changed(self,value): + self.file_list = get_file_list(value) + if len(self.file_list) == 0: + self.file_list = [value] + try: + self.timestep = self.file_list.index(value) + except ValueError: + self.timestep = 0 + diff --git a/pool/shard007/Python/0069713_iOS_private.py b/pool/shard007/Python/0069713_iOS_private.py new file mode 100644 index 0000000000000000000000000000000000000000..a8af06e41f7043043e8ddeaaf8f9e1e76a38d0e1 --- /dev/null +++ b/pool/shard007/Python/0069713_iOS_private.py @@ -0,0 +1,225 @@ +#coding=utf-8 +''' +Created on 2015年10月27日 +iOS private api检查入口 +@author: atool +''' +import os, shutil +from utils import report_utils, utils +from dump import otool_utils, codesign_utils +from api import app_utils, api_utils +from db import api_dbs +# from app.utils import IpaParse +from app.utils import checkipa + +def get_executable_path(ipa_path, pid): + ''' + info: unzip ipa, get execute app path + ''' + if not os.path.exists(ipa_path): + #不存在,返回检查结果为空值 + return False + cur_dir = os.getcwd() + dest = os.path.join(cur_dir, 'tmp/' + pid) + if not os.path.exists(dest): + os.mkdir(dest) + app_path = app_utils.unzip_ipa(ipa_path, dest) #解压ipa,获得xxx.app目录路径 + app = app_utils.get_executable_file(app_path) + + return app + +#检查私有api,返回三个参数 +def check_private_api(app, pid): + strings = app_utils.get_app_strings(app, pid) #一般是app中的一些可打印文本 + #app中的私有库和公有库 .framework + private, public = otool_utils.otool_app(app) + print '=' * 15 + print 'private:', len(private) + print 'public', len(public) + print '=' * 15 + + dump_result = app_utils.get_dump_result(app) + app_varibles = app_utils.get_app_variables(dump_result, pid) #app自定义的一些方法,不需要检查 + left = strings - app_varibles #去除一些app中开发人员自定义的方法,剩余app中的一些字符串 + + app_methods = app_utils.get_app_methods(dump_result, pid) #dump-class分析出app中的类和方法名 + + app_apis = [] + for m in app_methods: + class_name = m["class"] if m["class"] != "ctype" else 'cur_app' + #if m["class"] != "ctype" else 'cur_app' + method_list = m["methods"] + m_type = m["type"] + for m in method_list: + tmp_api = {} + tmp_api['api_name'] = m + tmp_api['class_name'] = class_name + tmp_api['type'] = m_type + #tmp_api['header_file'] = '' + #tmp_api['sdk'] = '' + #tmp_api['framework'] = '' + app_apis.append(tmp_api) + + api_set = api_dbs.get_private_api_list(public) #数据库中的私有api,去除了whitelist白名单 + print '=' * 15 + print 'left app_varibles:', len(left) + print 'app_methods:', len(app_apis) + print 'private length:', len(api_set) + print '=' * 15 + inter_api = api_utils.intersection_list_and_api(left, api_set) # app中的api和数据库中的私有api取交集,获得app中的私有api关键字数据 + + methods_in_app, method_not_in = api_utils.intersection_api(app_apis, inter_api) #app中的私有方法 + + print '=' * 15 + print 'methods_in_app', len(methods_in_app) + print 'methods_not_in_app', len(method_not_in) + # for i in xrange(20): + # print methods_not_in_app[i] + print '=' * 15 + + + return methods_in_app, method_not_in, private + +#检查架构,返回架构数组 +def check_architectures(app): + arcs = app_utils.check_architectures(app) + return arcs + +#检查xcode ghost,返回bool +def check_xcode_ghost(app): + return app_utils.check_xcode_ghost(app) + +#检查info和provision文件,并获取建议和错误配置 +def check_app_info_and_provision(ipa): + return checkipa.process_ipa(ipa) + +#检查codesign信息 +def check_codesign(app): + return codesign_utils.codesignapp(app) + +#ipa的md5 +def get_file_md5(ipa): + return app_utils.file_md5(ipa) + +#检查单个的app,获得结果字典 +def check_ipa(ipa_path): + result = {} #每个app的检查结果 + pid = utils.get_unique_str() + print '1.', '+' * 10, 'get_file_md5' + result['md5'] = get_file_md5(ipa_path) + + print '2.', '+' * 10, 'check_app_info_and_provision' + rsts = check_app_info_and_provision(ipa_path) + for key in rsts.keys(): + result[key] = rsts[key] + #检查ios私有api + print '3.', '+' * 10, 'check_private_api' + app = get_executable_path(ipa_path, pid) + if not app: + #找不到math-o文件,说明不是正常的ipa,忽略 + return False + + methods_in_app, _, private = check_private_api(app, pid) + result['private_apis'] = methods_in_app + # result['private_apis_not'] = _ + result['private_frameworks'] = list(private) + #检查ipa 64支持情况 + print '4.', '+' * 10, 'check_architectures' + arcs = check_architectures(app) + result['arcs'] = arcs + if len(arcs) < 2: + result['error'].append({'label': 'Architecture:', + 'description': 'app may be not support 64-bit'}) + #检查ghost情况 + print '5.', '+' * 10, 'check_xcode_ghost' + ghost = check_xcode_ghost(app) + result['ghost'] = ghost + #检查codesign + print '6.', '+' * 10, 'check_private_api' + codesign = check_codesign(app) + result['codesign'] = codesign + + print '7.', '+' * 10, 'remove tmp files' + cur_dir = os.getcwd() #删除检查临时目录 + dest_tmp = os.path.join(cur_dir, 'tmp/' + pid) + # print 'tmp:', dest_tmp + if os.path.exists(dest_tmp): + shutil.rmtree(dest_tmp) + + return result + +def batch_check(app_folder, excel_path): + ''' + 批量检测多个ipa,并产生excel报告 + ''' + #遍历folder,找出.ipa文件 + if not app_folder or not excel_path: + return False + + check_results = [] + ipa_list = os.listdir(app_folder) + for ipa in ipa_list: + print 'start check :', ipa + if ipa.endswith('.ipa'): + ipa_path = os.path.join(app_folder, ipa) + #单个app的检查结果 + try: + r = check_ipa(ipa_path) + if r: + check_results.append(r) + except Exception, e: + print e + continue + + #将结果转化成excel报告 + report_utils.excel_report(check_results, excel_path) + return excel_path + +if __name__ == '__main__': + ####### + #check one app + # ipa_path = "/Users/summer-wj/code/svn/ljsg_for_netease_20150928_resign.ipa" + + # private_1 = open("tmp/private_1.txt", "w") + # private_2 = open("tmp/private_2.txt", "w") + # #将strings内容输出到文件中 + # pid = app_utils.get_unique_str() + # app = get_executable_path(ipa_path, pid) + # print app + # arcs = check_architectures(app) + # print arcs + # a, b, c = check_private_api(app, pid) + # print "=" * 50 + # print len(a), "Private Methods in App:" + # print "*" * 50 + # for aa in a: + # print aa + # print >>private_1, aa + + # print "=" * 50 + # print len(b), "Private Methods not in App, May in Framework Used:" + # print "*" * 50 + # for bb in b: + # print >>private_2, bb + + # print "=" * 50 + # print len(c), "Private Framework in App:" + # print "*" * 50 + + ########## + #test batch check ipa + cwd = os.getcwd() + excel_path = os.path.join(cwd, 'tmp/' + utils.get_unique_str() + '.xlsx') + # excel_path = os.path.join(cwd, 'tmp/test.xlsx') # for test + print excel_path + ipa_folder = '/Users/netease/Downloads/ipas/mg/' + # ipa_folder = '/Users/netease/Music/iTunes/iTunes Media/Mobile Applications/' + # ipa_folder = '/Users/netease/Music/iTunes/iTunes Media/' + print batch_check(ipa_folder, excel_path) + + ######### + #test check arcs + # app_path = '/Users/netease/Downloads/ipas/mg/Payload' + # app = app_utils.get_executable_file(app_path) + # print check_architectures(app) + diff --git a/pool/shard007/Python/0069718_ChangePasswordDlg.py b/pool/shard007/Python/0069718_ChangePasswordDlg.py new file mode 100644 index 0000000000000000000000000000000000000000..750479fa615e2166131a8c1fc7a36bc7f9685de0 --- /dev/null +++ b/pool/shard007/Python/0069718_ChangePasswordDlg.py @@ -0,0 +1,112 @@ +# +# Copyright 2001 - 2018 Ludek Smid [http://www.ospace.net/] +# +# This file is part of Outer Space. +# +# Outer Space 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. +# +# Outer Space 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 Outer Space; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +# + +import pygameui as ui +from osci import client, gdata, res +from ige import SecurityException + +class ChangePasswordDlg: + + def __init__(self, app): + self.app = app + self.createUI() + + def display(self, caller = None, message = None): + self.caller = caller + self.win.vOld.text = "" + self.win.vNew.text = "" + self.win.vConfirm.text = "" + self.win.show() + + def hide(self): + self.win.hide() + + def onChange(self, widget, action, data): + oldPassword = self.win.vOld.text + newPassword = self.win.vNew.text + confirmPassword = self.win.vConfirm.text + if newPassword != confirmPassword: + self.win.vMessage.text = _("Passwords do not match.") + self.win.vNew.text = "" + self.win.vConfirm.text = "" + return + self.win.hide() + try: + client.cmdProxy.changePassword(oldPassword, newPassword) + except SecurityException, e: + # failed + self.win.vMessage.text = _(e.args[0]) + self.win.show() + return + if self.caller: + self.caller.display(message = _("The password has been changed.")) + + def onCancel(self, widget, action, data): + self.win.hide() + if self.caller: + self.caller.display() + + def createUI(self): + w, h = gdata.scrnSize + self.win = ui.Window(self.app, + modal = 1, + movable = 0, + title = _('Change password'), + rect = ui.Rect((w - 324) / 2, (h - 104) / 2, 324, 104), + layoutManager = ui.SimpleGridLM(), + tabChange = True + ) + self.win.subscribeAction('*', self) + ui.Label(self.win, + text = _('Old password'), + align = ui.ALIGN_E, + layout = (0, 0, 6, 1) + ) + ui.Entry(self.win, id = 'vOld', + align = ui.ALIGN_W, + showChar = '*', + layout = (6, 0, 10, 1), + orderNo = 1 + ) + ui.Label(self.win, + text = _('New password'), + align = ui.ALIGN_E, + layout = (0, 1, 6, 1), + ) + ui.Entry(self.win, id = 'vNew', + align = ui.ALIGN_W, + showChar = '*', + layout = (6, 1, 10, 1), + orderNo = 2 + ) + ui.Label(self.win, + align = ui.ALIGN_E, + text = _('Confirm'), + layout = (0, 2, 6, 1), + ) + ui.Entry(self.win, id = 'vConfirm', + align = ui.ALIGN_W, + layout = (6, 2, 10, 1), + showChar = "*", + orderNo = 3 + ) + ui.Title(self.win, layout = (0, 3, 8, 1), id = 'vMessage', align = ui.ALIGN_W) + ui.TitleButton(self.win, layout = (8, 3, 4, 1), text = _('Cancel'), action = 'onCancel') + ui.TitleButton(self.win, layout = (12, 3, 4, 1), text = _('Apply'), action = 'onChange') diff --git a/pool/shard007/Python/0069719_window.py b/pool/shard007/Python/0069719_window.py new file mode 100644 index 0000000000000000000000000000000000000000..8cab771a0cc7058db5253b77519f7768765e38bc --- /dev/null +++ b/pool/shard007/Python/0069719_window.py @@ -0,0 +1,172 @@ +# Copyright (c) 2010 Arthur Mesh +# 2010 Christopher Nelson +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +import pygtk +pygtk.require('2.0') +import gtk + +from snmp.nms_accessor import NMSAccessor + +from widgets.treeview import TreeView +from widgets.textview import TextView + +class Window(gtk.Window): + """ + Top-level window of the application. + """ + + def delete_event(self, widget, event, data=None): + """ + Close the window and exit. + """ + gtk.main_quit() + return False + + def __init__(self): + """ + Create the top-level window and add children to it. + """ + gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL) + + self.scrolled = None + self.scrolled_text = None + self.treeview = None + self.textview = None + self.set_box = None + + self.set_title("Noname MIB 'Browser'") + self.set_size_request(640, 480) + self.connect('delete_event', self.delete_event) + + label = gtk.Label('Address: ') + self.inputbox = gtk.Entry() + self.hbox = gtk.HBox() + self.hbox.pack_start(label, expand = False) + self.hbox.pack_start(self.inputbox) + + self.login_box = gtk.HBox() + label = gtk.Label('Username: ') + self.login_box.pack_start(label, expand = False) + self.uname_box = gtk.Entry() + self.login_box.pack_start(self.uname_box) + label = gtk.Label('Password: ') + self.login_box.pack_start(label, expand = False) + self.passwd_box = gtk.Entry() + self.passwd_box.set_visibility(False) + self.login_box.pack_start(self.passwd_box) + button = gtk.Button('Login') + button.connect('clicked', self.login) + self.login_box.pack_start(button) + + self.vbox = gtk.VBox() + self.vbox.pack_start(self.hbox, expand=False) + self.vbox.pack_start(self.login_box, expand = False) + + self.add(self.vbox) + + self.show_all() + + def login(self, widget, data = None): + """ + Login to the application. + """ + # first, create the nms_accessor + self.nms_accessor = NMSAccessor(self.inputbox.get_text()) + # then, login + self.nms_accessor.login(self.uname_box.get_text(), + self.passwd_box.get_text()) + # then, set up the choice of devices to activate + self.combobox = gtk.combo_box_new_text() + combo_data = self.nms_accessor.get_devices() + for data in combo_data: + self.combobox.append_text(data) + self.combobox.set_active(1) + self.combobox.connect('changed', self.change_device) + + self.vbox.remove(self.login_box) + self.vbox.pack_start(self.combobox, expand = False) + + self.change_device(None) + + self.show_all() + + def change_device(self, widget, data = None): + """ + Change which device we're looking at. + """ + + if self.set_box is None: + self.set_box = gtk.HBox() + label = gtk.Label('OID: ') + self.set_box.pack_start(label, expand = False) + self.set_entry_oid = gtk.Entry() + self.set_box.pack_start(self.set_entry_oid) + label = gtk.Label('Value: ') + self.set_box.pack_start(label, expand = False) + self.set_entry_value = gtk.Entry() + self.set_box.pack_start(self.set_entry_value) + button = gtk.Button('Set') + button.connect('clicked', self.set_value) + self.set_box.pack_start(button, expand = False) + + self.vbox.pack_start(self.set_box, expand = False) + + + if self.scrolled is not None: + self.vbox.remove(self.scrolled) + if self.scrolled_text is not None: + self.vbox.remove(self.scrolled_text) + + self.scrolled = gtk.ScrolledWindow() + self.scrolled_text = gtk.ScrolledWindow() + + self.textview = TextView() + + self.treeview = TreeView(self.textview, + self.nms_accessor, + self.combobox.get_active_text()) + + if self.treeview is not None: + self.scrolled.remove(self.treeview) + self.scrolled.add_with_viewport(self.treeview) + if self.textview is not None: + self.scrolled_text.remove(self.textview) + self.scrolled_text.add_with_viewport(self.textview) + + self.vbox.pack_start(self.scrolled) + self.vbox.pack_start(self.scrolled_text) + + self.show_all() + + def set_value(self, widget, data = None): + """ + Set the value at the OID in self.set_entry_oid + """ + self.nms_accessor.set_value(self.combobox.get_active_text(), + self.set_entry_oid.get_text(), + self.set_entry_value.get_text()) + + def run(self): + """ + Run the application. + """ + gtk.main() + return diff --git a/pool/shard007/Python/0069720_watchdog.py b/pool/shard007/Python/0069720_watchdog.py new file mode 100644 index 0000000000000000000000000000000000000000..42a79d1fe4c855cc444f6ce2a985cfdaa0f25ec8 --- /dev/null +++ b/pool/shard007/Python/0069720_watchdog.py @@ -0,0 +1,232 @@ +#!/usr/bin/env python + +"""Alerta WatchDog script to monitor Alerta service""" +__author__ = "Mark Bradley (mbrad@github)" +__version__ = "0.8.1" + +import urllib, urllib2, sys, os, smtplib, time, socket +from email.mime.image import MIMEImage +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText + +# Monitor options +alertaURL = 'http://alerta.example.com:8080/alerta/management/healthcheck' +httptimeout = 5 +tko = 3 +retrytime = 10 +checkperiod = 600 +# Email Options +fromaddr = 'Alerta Watchdog ' +toaddr = ['admins@example.com'] +smtphost = 'localhost' +# PushOver.net Options +pushenable = False +pushurl = 'https://api.pushover.net/1/messages.json' +pushtoken = 'obtain-app-token-from-pushover' +pushuser = 'this-is-your-pushover-token' + + +class Event: + "Event class to construct an event object" + def __init__(self): + self.epoch = int(time.time()) + tt = time.gmtime(self.epoch) + self.human = '%02d/%02d/%02d %02d:%02d:%02d' % \ + (tt[2], tt[1], tt[0], tt[3], tt[4], tt[5]) + try: + request = urllib2.Request(alertaURL, None, { 'User-Agent' : 'python' }) + socket.setdefaulttimeout(httptimeout) + httpresponse = urllib2.urlopen(request, None, timeout = httptimeout) + self.code = httpresponse.getcode() + self.body = httpresponse.read() + httpresponse.close() + except urllib2.HTTPError, e: + self.code = e.code + self.body = e.read() + except urllib2.URLError, e: + self.code = 0 + self.body = str(e.reason) + except socket.timeout, e: + self.code = 0 + self.body = str(e.reason) + + +def _argvchk(): + if len(sys.argv) == 1: + return True + elif ('-h' or '--help') in sys.argv[1]: + print "\nThis daemon polls Alerta's Management URI remotely and determines if there is a problem.\n\t\ + Usage: %s (-f = foreground)\n" % ((sys.argv[0]).split('/')[-1]) + sys.exit(0) + elif '-f' in sys.argv[1]: + print "Debug Mode: Staying in foreground...\n" + return False + else: + print >>sys.stderr, "Error: Unknown Option" + sys.exit(1) + + +def dprint(msg): + if isdaemon == False: print msg + + +def mailalert(last, cache, typestr): + if pushcount > 3: + dprint('Info: Not sending Email notification - too many messages for event') + return + elif pushcount == 3: + suppnote = 'Further notifications will be suppressed.' + else: + suppnote = ' ' + msg = MIMEMultipart('alternative') + msg['Subject'] = "Alerta Service Notification" + msg['From'] = fromaddr + msg['To'] = ', '.join(toaddr) + if typestr == 'WARNING': + colour = 'ff8c00' + elif typestr == 'CRITICAL': + colour = 'ff0000' + elif typestr == 'OK': + colour = '00ff00' + text = """\ + Alerta state change: %s - Response: %s (Code: %d) + + TKO: %d + Soft Event logged at %s + Hard Event logged at %s + + Service Probed: %s + + %s + + Auto-generated by Alerta-WatchDog + + -- + + """ % (typestr, last.body, last.code, tko, cache.human, \ + last.human, alertaURL, suppnote) + html = """\ + + + +

+ Alerta state change: %s - Response: %s (Code: %d)
+
+ TKO: %d
+     Soft Event triggered at %s
+     Hard Event triggered at %s
+
+     Service Probed: %s

+

%s

+

Auto-generated by Alerta-WatchDog

+ -- + + + """ % (colour, typestr, last.body, last.code, tko, cache.human, \ + last.human, alertaURL, suppnote) + + textpart = MIMEText(text, 'plain') + htmlpart = MIMEText(html, 'html') + msg.attach(textpart) + msg.attach(htmlpart) + + s=smtplib.SMTP(smtphost) + s.sendmail(fromaddr, toaddr, msg.as_string()) + + dprint('\033[92mMAIL SENT\033[0m\n' + text) + + +def pushover(last, typestr): + if pushcount > 3: + dprint('Info: Not sending PushOver notification - too many messages for event') + return + elif pushenable == False: + dprint('Info: PushOver notifications disabled.') + return + pushmessage = 'State: %s Response: %s (%s)' % (typestr, last.body, last.code) + pushdata = urllib.urlencode({"token": pushtoken, "user": pushuser, "message": pushmessage}) + try: + pushrequest = urllib2.Request(pushurl, pushdata, { "Content-type": "application/x-www-form-urlencoded" }) + socket.setdefaulttimeout(httptimeout) + pushresponse = urllib2.urlopen(pushrequest, timeout = httptimeout) + except: + dprint('Error: Could not send data to Pushover') + + +def main(): + """Looping main function""" + global pushcount + pushcount = 1 + count = 1 + state = 'OK' + sleeptime = checkperiod + while 1: + dprint('Probing Alerta URI: %s' % (alertaURL)) + response = Event() + dprint('Probe Response: [ Code: %s | Body: %s | Epoch: %d ]' % \ + (response.code, response.body, response.epoch)) + dprint('\nCOUNT: %d' % (count)) + if response.code != 200: + dprint('Event Triggered') + if count == 1: + cache = response + dprint('Caching first event: [ Code: %d | Body: %s | Epoch: %d ]' % \ + (cache.code, cache.body, cache.epoch)) + if count == tko: + #Warnings + if response.body ==\ + 'HEARTBEAT_STALE': + state = 'WARNING' + dprint('State: \033[93mWARNING\033[0m') + mailalert(response, cache, state) + pushover(response, state) + pushcount += 1 + count = 0 # Reset for tko more tries. + sleeptime = checkperiod + dprint('\nRe-Probing in %d seconds...' % (sleeptime)) + time.sleep(sleeptime) + continue + else: + #Criticals + state = 'CRITICAL' + dprint('State: \033[91mCRITICAL\033[0m') + mailalert(response, cache, state) + pushover(response, state) + pushcount += 1 + count = 0 # Reset for tko more tries. + sleeptime = checkperiod + dprint('\nRe-Probing in %d seconds...' % (sleeptime)) + time.sleep(sleeptime) + continue + count += 1 + sleeptime = retrytime + elif response.code == 200: + dprint('State: \033[92mOK\033[0m') + if state != 'OK': + state = 'OK' + pushcount = 0 + mailalert(response, cache, state) + pushover(response, state) + sleeptime = checkperiod + count = 1 + dprint('\nRe-Probing in %d seconds...' % (sleeptime)) + time.sleep(sleeptime) + +if __name__ == '__main__': + isdaemon = _argvchk() + if isdaemon == True: + pid = os.fork() + if pid: + sys.exit(0) + else: + print 'Alerta WatchDog process started... (PID: %d)' % (os.getpid()) + os.close(2) + os.close(0) + os.close(1) + main() + sys.exit(0) + else: + print 'PID: %d' % (os.getpid()) + main() + +# vim: set ts=4 sw=4 et : diff --git a/pool/shard007/Python/0069723_q1.py b/pool/shard007/Python/0069723_q1.py new file mode 100644 index 0000000000000000000000000000000000000000..b0fd59eab0b91abe2cd1c71f9a31f520383a9cbc --- /dev/null +++ b/pool/shard007/Python/0069723_q1.py @@ -0,0 +1,32 @@ +#!/bin/bash/python +#grab urls and get all the links + +from bs4 import BeautifulSoup +import urllib2 + +fn = open("100url.list","r") + +for i, line in enumerate(fn): + try: + print i + f = open("100urls/%i.data" %i,'w') + hdr = { 'User-Agent' : 'Firefox 25.0' } + req = urllib2.Request(line, headers=hdr) + redditFile = urllib2.urlopen(req) + redditHtml = redditFile.read() + redditFile.close() + #downloads all the reference link + soup = BeautifulSoup(redditHtml) + redditAll = soup.find_all("a") + f.write('site:' + '\n') + f.write(line + '\n') + f.write('links:'+ '\n') + for links in soup.find_all('a'): + content = links.get('href') + print(content) + try: + f.write(content +'\n') + except: + f.close() + except: + pass diff --git a/pool/shard007/Python/0069725_init__.py b/pool/shard007/Python/0069725_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f8696876a94a524493921de4a831cdebacfe69fa --- /dev/null +++ b/pool/shard007/Python/0069725_init__.py @@ -0,0 +1,89 @@ +# Copyright 2016 Mycroft AI, Inc. +# +# This file is part of Mycroft Core. +# +# Mycroft Core 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. +# +# Mycroft Core 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 Mycroft Core. If not, see . + +from os.path import dirname + +from adapt.intent import IntentBuilder +from mycroft.skills.core import MycroftSkill +from mycroft.util.log import getLogger + +__author__ = 'chrisl8' +# Based on helloworld by eward + +LOG = getLogger(__name__) + +class SmallTalkSkill(MycroftSkill): + + def __init__(self): + super(SmallTalkSkill, self).__init__(name="SmallTalkSkill") + + def initialize(self): + self.load_data_files(dirname(__file__)) + + # thank_you_intent = IntentBuilder("ThankYouIntent").\ + # require("ThankYouKeyword").build() + # self.register_intent(thank_you_intent, self.handle_thank_you_intent) + # + # how_are_you_intent = IntentBuilder("HowAreYouIntent").\ + # require("HowAreYouKeyword").build() + # self.register_intent(how_are_you_intent, + # self.handle_how_are_you_intent) + + hi_intent = IntentBuilder("HiIntent").\ + require("HiKeyword").build() + self.register_intent(hi_intent, + self.handle_hi_intent) + + good_morning_intent = IntentBuilder("GoodMorningIntent"). \ + require("GoodMorningKeyword").build() + self.register_intent(good_morning_intent, + self.handle_good_morning_intent) + + do_you_have_my_glasses = IntentBuilder("GlassesIntent"). \ + require("GlassesKeyword").build() + self.register_intent(do_you_have_my_glasses, + self.handle_do_you_have_my_glasses) + + self.emitter.on('fallback_failure', self.handle_fallback) + + # def handle_thank_you_intent(self, message): + # self.speak_dialog("welcome") + # + # def handle_how_are_you_intent(self, message): + # self.speak_dialog("how.are.you") + + def handle_hi_intent(self, message): + self.speak_dialog("hi") + + def handle_good_morning_intent(self, message): + self.speak_dialog("good.morning") + + def handle_do_you_have_my_glasses(self, message): + self.speak_dialog("glasses") + + def handle_fallback(self, message): + utt = message.data.get('utterance') + LOG.debug("SmallTalk fallback attempt: " + utt) + self.speak_dialog("fallback", data={'phrase': utt}) + + + def stop(self): + pass + + +def create_skill(): + return SmallTalkSkill() diff --git a/pool/shard007/Python/0069728_helper.py b/pool/shard007/Python/0069728_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..8ab1b208298489e4618215f0b6b25d26cf59187e --- /dev/null +++ b/pool/shard007/Python/0069728_helper.py @@ -0,0 +1,28 @@ +import errno +import shutil +import tempfile + +class TempDirTest(object): + def setup(self): + self.tmp_dir = tempfile.mkdtemp() + + def teardown(self): + try: + shutil.rmtree(self.tmp_dir) + except OSError as ex: + if ex.errno != errno.ENOENT: + raise + +class _ANY(object): + "A helper object that compares equal to everything." + + def __eq__(self, other): + return True + + def __ne__(self, other): + return False + + def __repr__(self): + return '' + +ANY = _ANY() \ No newline at end of file diff --git a/pool/shard007/Python/0069733_throttled.py b/pool/shard007/Python/0069733_throttled.py new file mode 100644 index 0000000000000000000000000000000000000000..93dcc4fae9a78b79965e29b0fcaae9afb3b28632 --- /dev/null +++ b/pool/shard007/Python/0069733_throttled.py @@ -0,0 +1,52 @@ +import time + + + + +class Throttled(object): + def __init__(self, min_time_since_last_run_s=5): + """Used for simple throttled execution. + + Here's a simple example: + + @Throttled(1) + def lol(i): + print('epoch %d' % (i,), flush=True) + + for i in range(100000000): + lol(i) + + Above code will report the epoch every second. + + Here's another way: + + throttled = Throttled(1) + + + for i in range(100000000000): + if throttled.should_i_run(): + print('epoch %d' % (i,), flush=True) + """ + self.last_time = None + self.min_time_since_last_run_s = min_time_since_last_run_s + + + def should_i_run(self, min_time_since_last_run_s=None): + min_time_since_last_run_s = min_time_since_last_run_s or self.min_time_since_last_run_s + now = time.time() + if self.last_time is None or (now - self.last_time) > min_time_since_last_run_s: + self.last_time = now + return True + else: + return False + + def maybe_run(self, f, min_time_since_last_run_s=None): + if self.should_i_run(min_time_since_last_run_s): + return f() + else: + return None + + def __call__(self, f): + def wrapper(*args, **kwargs): + return self.maybe_run(lambda: f(*args, **kwargs)) + return wrapper diff --git a/pool/shard007/Python/0069734_titansoftv.py b/pool/shard007/Python/0069734_titansoftv.py new file mode 100644 index 0000000000000000000000000000000000000000..0f1fa667de6b9b01e49688ecdaaf71978f3d8d4f --- /dev/null +++ b/pool/shard007/Python/0069734_titansoftv.py @@ -0,0 +1,153 @@ +# coding=utf-8 +# URL: http://code.google.com/p/sickbeard +# Originally written for SickGear +# +# This file is part of SickRage. +# +# SickRage 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. +# +# SickRage 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 SickRage. If not, see . + +import urllib + +import generic +from sickbeard import logger +from sickbeard import tvcache +from sickbeard.helpers import mapIndexersToShow +from sickrage.helper.exceptions import AuthException + + +class TitansOfTVProvider(generic.TorrentProvider): + def __init__(self): + generic.TorrentProvider.__init__(self, 'TitansOfTV') + self.supportsBacklog = True + self.public = False + self.supportsAbsoluteNumbering = True + self.api_key = None + self.ratio = None + self.cache = TitansOfTVCache(self) + self.url = 'http://titansof.tv/api/torrents' + self.download_url = 'http://titansof.tv/api/torrents/%s/download?apikey=%s' + + def isEnabled(self): + return self.enabled + + def imageName(self): + return 'titansoftv.png' + + def seedRatio(self): + return self.ratio + + def _checkAuth(self): + if not self.api_key: + raise AuthException('Your authentication credentials for ' + self.name + ' are missing, check your config.') + + return True + + def _checkAuthFromData(self, data): + + if 'error' in data: + logger.log(u'Incorrect authentication credentials for ' + self.name + ' : ' + data['error'], + logger.DEBUG) + raise AuthException( + 'Your authentication credentials for ' + self.name + ' are incorrect, check your config.') + + return True + + def _doSearch(self, search_params, search_mode='eponly', epcount=0, age=0, epObj=None): + self._checkAuth() + results = [] + params = {} + self.headers.update({'X-Authorization': self.api_key}) + + if search_params: + params.update(search_params) + + search_url = self.url + '?' + urllib.urlencode(params) + logger.log(u'Search url: %s' % search_url) + + parsedJSON = self.getURL(search_url, json=True) # do search + + if not parsedJSON: + logger.log(u'No data returned from ' + self.name, logger.ERROR) + return results + + if self._checkAuthFromData(parsedJSON): + + try: + found_torrents = parsedJSON['results'] + except: + found_torrents = {} + + for result in found_torrents: + (title, url) = self._get_title_and_url(result) + + if title and url: + results.append(result) + + return results + + def _get_title_and_url(self, parsedJSON): + + title = parsedJSON['release_name'] + id = parsedJSON['id'] + url = self.download_url % (id, self.api_key) + + return title, url + + def _get_season_search_strings(self, ep_obj): + search_params = {'limit': 100} + + search_params['season'] = 'Season %02d' % ep_obj.scene_season + + if ep_obj.show.indexer == 1: + search_params['series_id'] = ep_obj.show.indexerid + elif ep_obj.show.indexer == 2: + tvdbid = mapIndexersToShow(ep_obj.show)[1] + if tvdbid: + search_params['series_id'] = tvdbid + + return [search_params] + + def _get_episode_search_strings(self, ep_obj, add_string=''): + + if not ep_obj: + return [{}] + + search_params = {'limit': 100} + + # Do a general name search for the episode, formatted like SXXEYY + search_params['episode'] = 'S%02dE%02d' % (ep_obj.scene_season, ep_obj.scene_episode) + + if ep_obj.show.indexer == 1: + search_params['series_id'] = ep_obj.show.indexerid + elif ep_obj.show.indexer == 2: + tvdbid = mapIndexersToShow(ep_obj.show)[1] + if tvdbid: + search_params['series_id'] = tvdbid + + return [search_params] + + +class TitansOfTVCache(tvcache.TVCache): + def __init__(self, provider): + tvcache.TVCache.__init__(self, provider) + + # At least 10 minutes between queries + self.minTime = 10 + + def _getRSSData(self): + search_params = {'limit': 100} + return self.provider._doSearch(search_params) + + +provider = TitansOfTVProvider() diff --git a/pool/shard007/Python/0069740_matchessourcefilter.py b/pool/shard007/Python/0069740_matchessourcefilter.py new file mode 100644 index 0000000000000000000000000000000000000000..80fffe795c0c7297c2daf81e9c6c53c778868247 --- /dev/null +++ b/pool/shard007/Python/0069740_matchessourcefilter.py @@ -0,0 +1,55 @@ +# +# Gramps - a GTK+/GNOME based genealogy program +# +# Copyright (C) 2002-2006 Donald N. Allingham +# Copyright (C) 2010 Benny Malengier +# Copyright (C) 2011 Tim G L Lyons +# +# 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. +# + +#------------------------------------------------------------------------- +# +# Standard Python modules +# +#------------------------------------------------------------------------- +from ....const import GRAMPS_LOCALE as glocale +_ = glocale.translation.gettext + +#------------------------------------------------------------------------- +# +# GRAMPS modules +# +#------------------------------------------------------------------------- +from .. import MatchesSourceFilterBase + +#------------------------------------------------------------------------- +# +# MatchesFilter +# +#------------------------------------------------------------------------- +class MatchesSourceFilter(MatchesSourceFilterBase): + """ + Rule that checks against another filter. + """ + + labels = [_('Source filter name:')] + name = _('Events with source matching the ') + description = _("Matches events with sources that match the " + "specified source filter name") + category = _('Citation/source filters') + + # we want to have this filter show source filters + namespace = 'Source' diff --git a/pool/shard007/Python/0069741_makeparsed.py b/pool/shard007/Python/0069741_makeparsed.py new file mode 100644 index 0000000000000000000000000000000000000000..ffe469d48f3f6efefdd62b30a1f946ab24045944 --- /dev/null +++ b/pool/shard007/Python/0069741_makeparsed.py @@ -0,0 +1,65 @@ +# Global modules +import os +# Third party modules +import pystache +# Local modules +from seleniumcrawler.filesystem import locate_sites + +template = '''from selenium import webdriver +from selenium.webdriver.firefox.firefox_profile import FirefoxProfile + +def get_profile(): + # get the Firefox profile object + firefoxProfile = FirefoxProfile() + # Disable CSS + firefoxProfile.set_preference('permissions.default.stylesheet', 2) + # Disable images + firefoxProfile.set_preference('permissions.default.image', 2) + # Disable Flash + firefoxProfile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', + 'false') + + return firefoxProfile + +def handle_link(link): + profile = get_profile() + + # Set the modified profile while creating the browser object + driver = webdriver.Firefox(profile) + driver.implicitly_wait(30) + driver.get(link) + +{{{code}}} + results = { + 'url': driver.current_url, + 'source': driver.page_source + } + driver.quit() + + return results +''' + +def parse_raw_script(name, directory, path): + f = open(path) + + codelines = [] + at_main_code = False + for line in f: + if at_main_code: + codelines.append(line[4:]) + if line.startswith(' def test_'): + at_main_code = True + elif line.startswith(' def') and at_main_code: + codelines = codelines[1:-2] + at_main_code = False + break + + fout = open(os.path.join(directory, name + '.py'), 'w') + code = ''.join(codelines) + data = {'code': code} + rendered = pystache.render(template, data) + fout.write(rendered) + +for site in locate_sites(): + parse_raw_script(site['name'], site['site_dir'], site['script_path']) + print "Parsed %s." % site['script_path'] diff --git a/pool/shard007/Python/0069751_contexts.py b/pool/shard007/Python/0069751_contexts.py new file mode 100644 index 0000000000000000000000000000000000000000..bea620cf4739e928c0a98defe6562bbf7d0636be --- /dev/null +++ b/pool/shard007/Python/0069751_contexts.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- + + +# Open Chord Charts -- Database of free chord charts +# By: Christophe Benz +# +# Copyright (C) 2012, 2013, 2014, 2015 Christophe Benz +# https://github.com/openchordcharts/ +# +# This file is part of Open Chord Charts. +# +# Open Chord Charts is free software; you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# Open Chord Charts 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . + + +"""Context loaded and saved in WSGI requests""" + + +from biryani.states import State + + +class Ctx(State): + env_keys = ('_node', '_user') + _ = lambda self, message: message + _node = None # Used by route functions to store model object matching id or slug in URL. + _user = UnboundLocalError + req = None + + def __init__(self, req=None): + if req is not None: + self.req = req + ctx_env = req.environ.get('open-chord-charts', {}) + for key in self.env_keys: + value = ctx_env.get(key) + if value is not None: + setattr(self, key, value) + + def node_del(self): + del self._node + if self.req is not None and self.req.environ.get('open-chord-charts') is not None \ + and '_node' in self.req.environ['open-chord-charts']: + del self.req.environ['open-chord-charts']['_node'] + + def node_get(self): + return self._node + + def node_set(self, node): + self._node = node + if self.req is not None: + self.req.environ.setdefault('open-chord-charts', {})['_node'] = node + + node = property(node_get, node_set, node_del) + + def user_del(self): + del self._user + if self.req is not None and self.req.environ.get('open-chord-charts') is not None \ + and '_user' in self.req.environ['open-chord-charts']: + del self.req.environ['open-chord-charts']['_user'] + + def user_get(self): + return self._user + + def user_set(self, user): + self._user = user + if self.req is not None: + self.req.environ.setdefault('open-chord-charts', {})['_user'] = user + + user = property(user_get, user_set, user_del) diff --git a/pool/shard007/Python/0069758_1217_conveniences.py b/pool/shard007/Python/0069758_1217_conveniences.py new file mode 100644 index 0000000000000000000000000000000000000000..f6020fdc1e9b6603286e2bb1fe6139b0a44980db --- /dev/null +++ b/pool/shard007/Python/0069758_1217_conveniences.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +''' +NPR 2017-12-17 +https://www.npr.org/2017/12/17/571421849/sunday-puzzle-capital-letters + +Think of a convenience introduced in the 19th century that is still around today. +Its name has two words. Take the first three letters of the first word and the +first letter of its second word, in order, to get a convenience introduced in the +21st century that serves a similar purpose. Their names are otherwise unrelated. +What two conveniences are these? +''' + +from nltk.corpus import wordnet as wn + +from nltk.tokenize import word_tokenize +from nltk import FreqDist + +import sys +sys.path.append('..') +from nprcommontools import get_hypernyms + +#%% +# "common" words from Wordnet +# We use words in example sentences +def_corpus = [] +for s in wn.all_synsets(): + for ex in s.examples(): + for w in word_tokenize(ex): + if w.isalpha(): + def_corpus.append(w.lower()) + +fdist = FreqDist(def_corpus) +common_words = set() +NUM_WORDS = 50000 +for word, frequency in fdist.most_common(NUM_WORDS): + # Keep only the best short words + if len(word) > 2 or word in ('a','i') or fdist[word] > 100: + common_words.add(word) + +#%% +four = set() +two_words = set() +for s in wn.all_synsets(): + if s.pos() == 'n': + for l in s.lemma_names(): + if l[0] != l[0].upper(): + if len(l) == 4 and '_' not in l and l in common_words: + four.add(l) + elif l.count('_') == 1 and l.split('_')[0] in common_words and l.split('_')[1] in common_words: + if 'product' in get_hypernyms(l): + two_words.add(l) + +#%% +for t in sorted(two_words): + w1,w2 = t.split('_') + if w1[:3] + w2[0] in four: + print t,w1[:3] + w2[0] + + diff --git a/pool/shard007/Python/0069761_ahlinux_to_ghost.py b/pool/shard007/Python/0069761_ahlinux_to_ghost.py new file mode 100644 index 0000000000000000000000000000000000000000..730155e6632a05b1964fb536acd0a95440dade4c --- /dev/null +++ b/pool/shard007/Python/0069761_ahlinux_to_ghost.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- + +import _env +import io +import json +import re +import time +from lib._db import get_collection +from config.config import CONFIG +from judge_upload import exist_or_insert +DB = CONFIG.MONGO.DATABASE + + +PAT = re.compile('[-#\w]+') + + +def find_first_tag(s): + m = PAT.search(s) + return m.group() if m else s + + +def remove_china_char(s): + if not s: + return s + return re.sub(ur"[\u4e00-\u9fa5]+", '', s) + + +def cur_timestamp(): + return int(time.time() * 1000) + + +USERS = [ + { + "id": 1, + "name": "jishushare", + "slug": "jishushare", + "email": "user@example.com", + "image": None, + "cover": None, + "bio": None, + "website": None, + "location": None, + "accessibility": None, + "status": "active", + "language": "zh_CN", + "meta_title": None, + "meta_description": None, + "last_login": None, + "created_at": 1283780649000, + "created_by": 1, + "updated_at": 1286958624000, + "updated_by": 1 + } +] + + +TAGS = [ + { + "id": 1, + "name": u'文章', + "slug": u'article', + "description": "" + } +] + + +def replace_post(post_data): + d = { + "id": 5, + "title": "my blog post title", + #"slug": "my-blog-post-title", + "markdown": "the *markdown* formatted post body", + #"html": "the html formatted post body", + "image": None, + "featured": 0, + "page": 0, + "status": "published", + "language": "zh_CN", + "meta_title": None, + "meta_description": None, + "author_id": 1, + "created_at": cur_timestamp(), + "created_by": 1, + "updated_at": cur_timestamp(), + "updated_by": 1, + "published_at": cur_timestamp(), + "published_by": 1 + } + d['id'] = int(post_data['source_url'].rsplit('/', 1)[1].split('.')[0]) + d['title'] = post_data['title'].strip() + if post_data['slug'] > 30: + d['slug'] = post_data['slug'][0:30] + d['markdown'] = post_data['content'].strip() + return d + + +def migrate(coll_name='article_pyhome', skip=0, limit=10): + res = { + "meta": { + "exported_on": cur_timestamp(), + "version": "003" + } + } + coll = get_collection(DB, coll_name) + + posts = [] + posts_tags = [] + slug_set = set() + + for doc in coll.find().skip(skip).limit(limit): + title = doc.get('title') + slug = title.lower().strip() + + if slug and (slug not in slug_set): + slug_set.add(slug) + doc['slug'] = slug + + if not exist_or_insert(slug): + doc_id = doc.get('_id') + post_id = int(doc['source_url'].rsplit('/', 1)[1].split('.')[0]) + + posts.append(replace_post(doc)) + posts_tags.append( + {"tag_id": 1, "post_id": post_id} + ) + + data = { + "posts": posts, + "tags": TAGS, + "posts_tags": posts_tags, + "users": USERS + } + res["data"] = data + return res + + +def tag_migrate(limit=10): + res = { + "meta": { + "exported_on": cur_timestamp(), + "version": "003" + } + } + coll = get_collection(DB, 'article') + + posts = [] + tags_id_map = {} + posts_tags = [] + tag_id = 1000 + index = 0 + + for doc in coll.find().batch_size(1000): + #print(doc.get('title')) + index += 1 + if index > limit: + break + + posts.append(replace_post(doc)) + post_id = int(doc['source_url'].rsplit('/', 1)[1].split('.')[0]) + tag_list = doc.get('tag_list') + tag = tag_list[0] if tag_list else '' + tag = remove_china_char(tag) + if tag: + save_tag = tag.replace(' ', '-').lower() + save_tag = find_first_tag(save_tag) + if len(save_tag) > 10: + posts_tags.append( + {"tag_id": 1, "post_id": post_id} + ) + continue + + if save_tag not in tags_id_map: + tag_id += 1 + TAGS.append({ + "id": tag_id, + "name": save_tag, + "slug": save_tag, + "description": "" + }) + tags_id_map[save_tag] = tag_id + posts_tags.append( + {"tag_id": tags_id_map[save_tag], "post_id": post_id} + ) + else: + posts_tags.append( + {"tag_id": tags_id_map[save_tag], "post_id": post_id} + ) + + data = { + "posts": posts, + "tags": TAGS, + "posts_tags": posts_tags, + "users": USERS + } + res["data"] = data + return res + + +def test(): + print(find_first_tag('正则表达式指南')) + + +def incr_migrate(coll_name, limit): + coll = get_collection(DB, coll_name) + all_cnt = coll.find().count() + start = 0 + index = 0 + + while start < all_cnt: + res = migrate(coll_name, start, limit) + filename = str(index) + '_article.json' + # print(json.dumps(res, indent=4)) + with io.open(filename, 'w+', encoding='utf8') as outfile: + data = json.dumps(res, ensure_ascii=False, + encoding='utf8', indent=4) + outfile.write(unicode(data)) + + index += 1 + start += limit + + +def main(): + import sys + try: + cnt = int(sys.argv[1]) + except: + cnt = 300 + res = migrate('ahlinux_pyhome', 0, 500) + print(json.dumps(res, indent=4)) + + +if __name__ == '__main__': + #main() + incr_migrate('ahlinux_pyhome', limit=500) diff --git a/pool/shard007/Python/0069765_init__.py b/pool/shard007/Python/0069765_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0aa358ba45c4ed6d92c24b59a51c95fbbfe7df97 --- /dev/null +++ b/pool/shard007/Python/0069765_init__.py @@ -0,0 +1,35 @@ +"""Quokka CMS!""" + +from pathlib import Path +from quokka.core.app import QuokkaApp +from quokka.core import configure_extensions, configure_extension +from quokka.core.flask_dynaconf import configure_dynaconf + + +def create_app_base(test=False, ext_list=None, **settings): + """Creates basic app only with extensions provided in ext_list + useful for testing.""" + + app = QuokkaApp('quokka') + if settings: + app.config.update(settings) + configure_dynaconf(app) + + if test or app.config.get('TESTING'): + app.testing = True + + app.static_folder = Path.cwd() / Path('static') + # Path(app.config['PROJECT_ROOT']) + + if ext_list: + for ext in ext_list: + configure_extension(ext, app=app) + + return app + + +def create_app(test=False, **settings): + """Creates full app with all extensions loaded""" + app = create_app_base(test=test, **settings) + configure_extensions(app) + return app diff --git a/pool/shard007/Python/0069768_electrostatics_example.py b/pool/shard007/Python/0069768_electrostatics_example.py new file mode 100644 index 0000000000000000000000000000000000000000..576bd644129f51d5d9f4903cbec3512c855739a1 --- /dev/null +++ b/pool/shard007/Python/0069768_electrostatics_example.py @@ -0,0 +1,226 @@ +''' +# This script is an example of calculation of long range interactions +# (Coulomb interaction) using the Ewald summation and the P3M methods. +# +# Initially, the simple cubic structure is generated in order to represent the +# NaCl crystal. Then the energy and forces are calculated and compared using both +# the Ewald summation and the P3M. At the end the Madelung constant of NaCl crystal +# is calculated. +# +# At the moment there is only metallic surrounding media is possible. + +# Parameters: + +# Ewald summation: + alpha = 1.112583061 (Ewald parameter) + rspacecutoff = 4.9 (the cutoff in real space) + kspacecutoff = 30 (the cutoff in reciprocal space) + +# P3M: + M = (16, 16, 16) (mesh) + P = 7 (charge assignment order) +''' + +# The script itself +import mpi4py.MPI as MPI +import espressopp +from espressopp import Real3D + +# initial parameters +N = 16 # number of particles on lattice site +num_particles = N**3 # total number of particles +rho = 0.03 # number density of particles, number of particles devided by volume + +# creating a cubic NaCl crystal +#print 'Creating a simple cubic structure...' +x, y, z, Lx, Ly, Lz = espressopp.tools.lattice.createCubic(num_particles, rho, False) + +# creating the system box +box = (Lx, Ly, Lz) +print 'System box size: ', box +print 'Number of particles = ', num_particles + +# Ewald summation parameters +#alphaEwald = 1.112583061 # alpha - Ewald parameter +alphaEwald = 0.660557 +rspacecutoff = 4.9 # rspacecutoff - the cutoff in real space +kspacecutoff = 30 # kspacecutoff - the cutoff in reciprocal space + +print 'Ewald parameters:' +print 'alfa=%f, rcutoff=%f, kcutoff=%d' % (alphaEwald, rspacecutoff, kspacecutoff) + +# P3M parameters +M = espressopp.Int3D(64, 64, 64) +P = 7 +#alphaP3M = 1.112583061 # alpha - Ewald parameter +alphaP3M = 0.660557 + +print 'P3M parameters:' +print 'Mesh=', M,', charge assignment order=%d, alphaP3M=%lf' % ( P, alphaP3M) + +# a skin for Verlet list +skin = 0.2 + +# Coulomb prefactor parameters +bjerrumlength = 1.0 +temperature = 1.0 +coulomb_prefactor = bjerrumlength * temperature + +nodeGrid = espressopp.tools.decomp.nodeGrid(MPI.COMM_WORLD.size) +cellGrid = espressopp.tools.decomp.cellGrid(box, nodeGrid, rspacecutoff, skin) + +print '' +print 'density = %.4f' % (rho) +print 'NodeGrid = %s' % (nodeGrid,) +print 'CellGrid = %s' % (cellGrid,) +print '' + +''' + Below two systems for Ewald summation and PPPM methods will be created. +''' + +####################################################################################### +# system for Ewald +####################################################################################### + +systemEwald = espressopp.System() +systemEwald.rng = espressopp.esutil.RNG() +systemEwald.bc = espressopp.bc.OrthorhombicBC(systemEwald.rng, box) +systemEwald.skin = skin +systemEwald.storage = espressopp.storage.DomainDecomposition(systemEwald, nodeGrid, cellGrid) + +####################################################################################### +# system for PPPM +####################################################################################### + +systemPPPM = espressopp.System() +systemPPPM.rng = espressopp.esutil.RNG() +systemPPPM.bc = espressopp.bc.OrthorhombicBC(systemPPPM.rng, box) +systemPPPM.skin = skin +systemPPPM.storage = espressopp.storage.DomainDecomposition(systemPPPM, nodeGrid, cellGrid) + +####################################################################################### + +# adding particles +props = ['id', 'pos', 'type', 'q'] +new_particles = [] +countX = countY = countZ = 0 +for i in range(0, num_particles): + + # charge should be accordingly to NaCl crystall + charge = pow(-1, countX + countY + countZ) + part = [ i, Real3D(x[i], y[i], z[i]), 0, charge ] + new_particles.append(part) + + countX += 1 + if countX >= N: + countX = 0 + countY += 1 + if countY >= N: + countY = 0 + countZ += 1 + +# adding particles to Ewald system +systemEwald.storage.addParticles(new_particles, *props) +systemEwald.storage.decompose() + +# adding particles to PPPM system +systemPPPM.storage.addParticles(new_particles, *props) +systemPPPM.storage.decompose() + +## potentials and interactions ## + +# setting a Verlet list +vlEwald = espressopp.VerletList(systemEwald, rspacecutoff) +vlPPPM = espressopp.VerletList(systemPPPM, rspacecutoff) + +# real space interaction for Ewald system +# R space part of electrostatic interaction +coulombR_potEwald = espressopp.interaction.CoulombRSpace(coulomb_prefactor, alphaEwald, rspacecutoff) +# creating an interaction based on the Verlet list +coulombR_intEwald = espressopp.interaction.VerletListCoulombRSpace(vlEwald) +# setting the potential for the interaction between particles of type 0 and 0 +coulombR_intEwald.setPotential(type1=0, type2=0, potential = coulombR_potEwald) +# adding the interaction to the system +systemEwald.addInteraction(coulombR_intEwald) + +# real space interaction for PPPM system +# R space part of electrostatic interaction +coulombR_potP3M = espressopp.interaction.CoulombRSpace(coulomb_prefactor, alphaP3M, rspacecutoff) +# creating an interaction based on the Verlet list +coulombR_intPPPM = espressopp.interaction.VerletListCoulombRSpace(vlPPPM) +# setting the potential for the interaction between particles of type 0 and 0 +coulombR_intPPPM.setPotential(type1=0, type2=0, potential = coulombR_potP3M) +# adding the interaction to the system +systemPPPM.addInteraction(coulombR_intPPPM) + +# K space part of electrostatic interaction +ewaldK_pot = espressopp.interaction.CoulombKSpaceEwald(systemEwald, coulomb_prefactor, alphaEwald, kspacecutoff) +# creating an interaction based on the Cell list for all particle interaction and potential in K space +ewaldK_int = espressopp.interaction.CellListCoulombKSpaceEwald(systemEwald.storage, ewaldK_pot) +# adding the interaction to the system +systemEwald.addInteraction(ewaldK_int) + +# PPPM system +p3m_pot = espressopp.interaction.CoulombKSpaceP3M( systemPPPM, coulomb_prefactor, alphaP3M, M, P, rspacecutoff) +# creating the interaction based on the Cell list for all particle interaction and potential in K space +p3m_int = espressopp.interaction.CellListCoulombKSpaceP3M(systemPPPM.storage, p3m_pot) +# adding the interaction to the system +systemPPPM.addInteraction(p3m_int) + +### Integrators for Ewald and PPPM +# creating the integrator which based on the Verlet algorithm +integratorEwald = espressopp.integrator.VelocityVerlet(systemEwald) +# seting the time step (it is not important here) +integratorEwald.dt = 0.0001 +# nothing will be changed in system, just forces will be calculated ones +integratorEwald.run(0) + +# creating the integrator which based on the Verlet algorithm +integratorPPPM = espressopp.integrator.VelocityVerlet(systemPPPM) +# seting the time step (it is not important here) +integratorPPPM.dt = 0.0001 +# nothing will be changed in system, just forces will be calculated ones +integratorPPPM.run(0) + +# printing the particle id and force difference (x,y,z) for first 6 particles +print ('\n Difference between forces calculated by Ewald summation and PPPM (first 6 particles)') +print ('%3s %20s %20s %20s\n' % ('id', 'dfx', 'dfy', 'dfz')) + +#sock = espressopp.tools.vmd.connect(systemPPPM) +#espressopp.tools.vmd.imd_positions(systemPPPM, sock) + +print_N = min(num_particles, 20) + +for j in range(0, print_N): + print ( '%3d %3.17f %3.17f %3.17f' % (j, \ + abs(systemEwald.storage.getParticle(j).f.x - systemPPPM.storage.getParticle(j).f.x), \ + abs(systemEwald.storage.getParticle(j).f.y - systemPPPM.storage.getParticle(j).f.y), \ + abs(systemEwald.storage.getParticle(j).f.z - systemPPPM.storage.getParticle(j).f.z)) ) + + print 'force:', systemPPPM.storage.getParticle(j).f, ' ', systemEwald.storage.getParticle(j).f + + +# calculating the R space part of electrostatic energy +energyEwaldR = coulombR_intEwald.computeEnergy() +# calculating the K space part of electrostatic energy +energyEwaldK = ewaldK_int.computeEnergy() +# total energy (Ewald summation) +enTotEwald = energyEwaldR + energyEwaldK + +# calculating the R space part of electrostatic energy +energyPPPMR = coulombR_intPPPM.computeEnergy() +# calculating the K space part of electrostatic energy +energyPPPMK = p3m_int.computeEnergy() +# total energy (PPPM) +enTotPPPM = energyPPPMR + energyPPPMK + + +# printing the total energy and the difference +print 'Energy (Ewald summation): %5.16f Energy (PPPM): %5.16f\n' % (enTotEwald, enTotPPPM) +print 'The difference in energy (Ewald - PPPM): %5.16f\n' % (enTotEwald-enTotPPPM) + +a = 2 * pow( Lx*Ly*Lz / num_particles , 1./3. ) +madelung_NaCl = -1.747564594633182190636212035544397403481 +print ("Madelung constant is: %14.10f\n" % (enTotEwald/num_particles * a)) +print (" error: %e\n\n" % ( abs( abs( enTotPPPM/num_particles * a) - abs(madelung_NaCl)))) diff --git a/pool/shard007/Python/0069771_ledongli.py b/pool/shard007/Python/0069771_ledongli.py new file mode 100644 index 0000000000000000000000000000000000000000..898205af471f935dedac19d6bb3ac8924f2fd321 --- /dev/null +++ b/pool/shard007/Python/0069771_ledongli.py @@ -0,0 +1,117 @@ +#coding: utf-8 + +#date: 刷微信步数 + +#usage: edit steps and ledongli's uid(u need to download this app) .That would be ok .Good luck. ^_^ + +import requests + +import sys + +import json + +import datetime + +import time + +def isnum(value): + + try: + + temp = int(value) + + except Exception, e: + + return False + + else: + + return True + +# like 2015-09-25 00:00:00 converts to unix time stamp + +def formatDate(): + + nowtime = datetime.datetime.now() + + date = time.strftime('%Y-%m-%d') + + strtemp_date = date + ' 00:00:00' + + ledongli_date = time.strptime(strtemp_date, '%Y-%m-%d %H:%M:%S') + + finaldate = time.mktime(ledongli_date) # rusult is 1443456000.0(float type), but still need to format to 1443456000 + + finaldate = int(finaldate) + + return finaldate + +def main(steps, uid): + + if not isnum(steps): + + print 'param error. steps must be an integer.' + + url = 'http://pl.api.ledongli.cn/xq/io.ashx' + + fake_headers = { + + 'User-Agent' : 'le dong li/5.4 (iPhone; iOS 9.1; Scale/2.00)', + + 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8', + + 'Accept-Encoding': 'gzip' + + } + + keycontentjson = [ + + { + + "date": formatDate(), + "calories": 0, + "activeValue": 108, + "steps": steps, + "pm2d5": 0, + "duration": 0, + "distance": 0, + "report": "[]" + + } + + ] + + # key is a str type + + # key must be a json data convert to string + + key = json.dumps(keycontentjson) + + param = { + + 'action': 'profile', + + 'pc': '29e39ed274ea8e7a50f8a83abf1239faca843022', + + 'cmd': 'updatedaily', + + 'uid': uid, + + 'list': key, + 'v' : '5.4%20ios', + 'vc' : '540%20ios' + } + + r = requests.post(url, data = param, headers = fake_headers) + + print r.text + + print '_kazakhsoft曰:装逼成功' + +if __name__ == '__main__': + + steps = 98801 + + uid = '39082958' + + main(steps, uid) \ No newline at end of file diff --git a/pool/shard007/Python/0069776_demo.py b/pool/shard007/Python/0069776_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..6ed3a239929a1ffbf267ffe7a997e2daa1776768 --- /dev/null +++ b/pool/shard007/Python/0069776_demo.py @@ -0,0 +1,46 @@ +from kivy.app import App +from kivy.clock import Clock +from kivy.graphics import Color, Ellipse, Line +from kivy.uix.widget import Widget + +from control import Control +from simulation import Simulation + +from control import PIXELS_PER_INCH + +class PlateWidget(Widget): + def setup_simulation(self): + self.sim = Simulation(Control(), (0,0)) + + def render(self, dt): + with self.canvas: + self.sim.step() + self.canvas.clear() + Color(.5, .5, .5) + x = (self.sim.center_axis[0] * PIXELS_PER_INCH)+400-4 + y = (self.sim.center_axis[1] * PIXELS_PER_INCH)+300-4 + Ellipse(pos=(x,y), size=(9, 9)) + + Color(1, 1, 0) + for p in self.sim.tool_history: + x = ((p[0]*1) * PIXELS_PER_INCH)+400-1 + y = ((p[1]*1) * PIXELS_PER_INCH)+300-1 + Ellipse(pos=(x,y), size=(3, 3)) + + Color(1,0,0) + x = (self.sim.tool_position[0] * PIXELS_PER_INCH)+400-2 + y = (self.sim.tool_position[1] * PIXELS_PER_INCH)+300-2 + Ellipse(pos=(x,y), size=(5, 5)) + +class DemoApp(App): + def build(self): + w = PlateWidget() + w.setup_simulation() + + # Schedule simulation step + event = Clock.schedule_interval(w.render, 1 / 60.) + + return w + +if __name__ == '__main__': + DemoApp().run() \ No newline at end of file diff --git a/pool/shard007/Python/0069777_navigation.py b/pool/shard007/Python/0069777_navigation.py new file mode 100644 index 0000000000000000000000000000000000000000..5eb0f5e6217c574bc9565198379d7099834c6962 --- /dev/null +++ b/pool/shard007/Python/0069777_navigation.py @@ -0,0 +1,52 @@ +class Navigation(object): + def __init__(self): + self.children = [] + + +class Element(object): + pass + + +class Link(Element): + def __init__(self, route, text, icon=None, **args): + self.route = route + self.text = text + self.icon = icon + self.args = args + + +class Menu(Element): + def __init__(self, text, children, icon=None, **args): + self.text = text + self.args = args + self.icon = icon + self.children = children + + +class Divider(Element): + pass + + +# Dictionary to hold navigation instances. Gets added to each request. +navigation = { + "navbar-left": Navigation(), + "acp": Navigation(), +} + + +def configure(config): + config.add_request_method(lambda x: navigation, "navigation", reify=True) + + def add_link(config, nav="navbar-left", **args): + if nav not in navigation: + navigation[nav] = Navigation() + navigation[nav].children.append(Link(**args)) + config.add_directive("add_navigation_link", add_link, action_wrap=False) + + def add_menu(config, nav="navbar-left", **args): + if nav not in navigation: + navigation[nav] = Navigation() + navigation[nav].children.append(Menu(**args)) + config.add_directive("add_navigation_menu", add_menu, action_wrap=False) + + config.add_navigation_link(nav="acp", icon="dashboard", route="admin.dashboard", text="Dashboard") diff --git a/pool/shard007/Python/0069785_sensor_energymeter.py b/pool/shard007/Python/0069785_sensor_energymeter.py new file mode 100644 index 0000000000000000000000000000000000000000..9c56ec6577c04718b2ae829a2acf0189fbc90055 --- /dev/null +++ b/pool/shard007/Python/0069785_sensor_energymeter.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python2 + +""" +sensor_power.py: Current and Voltage sensor driver + +This sensor driver collects current and voltage measurements from external arduino board. +""" + +__author__ = "Daniel Mazzer" +__copyright__ = "Copyright 2016, NORS project" +__credits__ = "" +__license__ = "MIT" +__maintainer__ = "Daniel Mazzer" +__email__ = "dmazzer@gmail.com" + +import signal +import serial + +from genericsensor.genericsensor import Nors_GenericSensor + +from grovepi import * + +from norsutils.logmsgs.logger import Logger + +from serial_ports import serial_ports + +logger = Logger('debug') +logger.log("SENSOR - Dual phase power meter", 'info') + +class RealSensor(Nors_GenericSensor): + def __init__(self): + + self.sensor_name = 'PWRMTR' + self.message = {} + + if self.connect_to_energy_meter() == True: + super(RealSensor, self).__init__( + gs_name = self.sensor_name, + gs_id = 'bdeb5806-a9a2-11e6-a119-080027bc22fd', + gs_description = 'Dual phase power meter', + gs_interface = None, + gs_read_interval = 60) + else: + logger.log('Energy meter device was not found on serial ports', 'error') + raise SystemExit('Exiting') + + + def SensorRead(self): + if self.ser.inWaiting() > 0 : + msg = self.ser.readline() + measures = self.msg_parse(msg) +# if measures is None: +# self.ser.flushInput() +# self.ser.flushOutput() + + logger.log(str(measures), 'debug') + return measures + else: + return None + + def SensorDataProcessing(self,sensor_data): + return sensor_data + + def connect_to_energy_meter(self): + logger.log('Searching serial ports','info') + ports = serial_ports() + for port in ports: + try: + logger.log('Trying ' + str(port),'info') + self.ser = serial.Serial(port, 115200, timeout=10) + retry = 100 + while retry > 0: + logger.log('Countdown ' + str(retry),'info') + self.ser.flushInput() + self.ser.flushOutput() + self.ser.write('#') +# time.sleep(2) + check_em = self.ser.read() + if check_em == '!': + logger.log('Success on port ' + str(port),'info') + return True + retry = retry-1 +# time.sleep(2) + + except (serial.SerialException) as e: + return False + + return False + + def msg_parse(self, msg): + msg_p = msg.split() + + # checking message parsing result using list size + if len(msg_p) != 6: + return None + + measure = {} + # for python 3 use: + # measure['channel'] = int(str(msg_p[0]).replace("b'@", "").replace("'", "")) + channel = int(str(msg_p[0]).replace("@", "")) + if (channel != 1) and (channel != 2): + return None + + measure['channel'] = channel + measure['real_power'] = float(msg_p[1]) + measure['apparent_power'] = float(msg_p[2]) + measure['Vrms'] = float(msg_p[3]) + measure['Irms'] = float(msg_p[4]) + measure['power_factor'] = float(msg_p[5]) +# return {str(channel): measure} + + return self.msg_agregate(measure) + + def msg_agregate(self, msg): +# print(msg) + if msg['channel'] == 1: + self.message = {'ch1': msg} +# print('canal1') + return None + if msg['channel'] == 2: + self.message['ch2'] = msg +# print('canal2') + return self.message + +if __name__ == '__main__': + sensor = RealSensor() + + + def do_exit(sig, stack): + raise SystemExit('Exiting') + + signal.signal(signal.SIGINT, do_exit) + signal.signal(signal.SIGUSR1, do_exit) + + signal.pause() + + diff --git a/pool/shard007/Python/0069789_gather_domain_token_stats.py b/pool/shard007/Python/0069789_gather_domain_token_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..472b447e9cabd45dd01e2c585d2d3895ab732d16 --- /dev/null +++ b/pool/shard007/Python/0069789_gather_domain_token_stats.py @@ -0,0 +1,129 @@ +#!/usr/bin/python +# +# Copyright 2014 Google Inc. All Rights Reserved. +# +# 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. + +"""Gather token information for a whole domain and show some stats. + +This may be a large task given many domains > 20k users. Therefore, +this script requires some form of perisistence. Likely, this script +will get interrupted by quota constraints and need to be resumed +so progress should be tracked. + +Overall, enough data should be collected to show 3 primary stats: + 1. List the domains the are most frequently issued tokens. + 2. List the users most frequently authorizing token access. + 3. Show a map of users to client_ids (to allow for revocation). + +Tool to show usage of Admin SDK Directory APIs. + +APIs Used: + Admin SDK Directory API: user management + Experimental Google Apps 3-legged OAuth Token Management API. +""" + +import sys + +# setup_path required to allow imports from component dirs (e.g. utils) +# and lib (where the OAuth and Google API Python Client modules reside). +import setup_path # pylint: disable=unused-import,g-bad-import-order + +from admin_sdk_directory_api import tokens_api +from utils import admin_api_tool_errors +from utils import auth_helper +from utils import common_flags +from utils import log_utils +from utils import token_report_utils +from utils import user_iterator + + +def AddFlags(arg_parser): + """Handle command line flags unique to this script. + + Args: + arg_parser: object from argparse.ArgumentParser() to accumulate flags. + """ + common_flags.DefineAppsDomainFlagWithDefault(arg_parser) + common_flags.DefineForceFlagWithDefaultFalse(arg_parser) + common_flags.DefineVerboseFlagWithDefaultFalse(arg_parser) + + arg_parser.add_argument('--first_n', type=int, default=0, + help=('Gather tokens for the first n users in the ' + 'domain.')) + arg_parser.add_argument('--resume', '-r', action='store_true', default=False, + help='Resume an interrupted gather command.') + + +def main(argv): + """A script to test Apps Security APIs: summarizing oauth2 tokens.""" + flags = common_flags.ParseFlags(argv, + 'Gather token status for entire domain.', + AddFlags) + # Tracks stats for each domain-scope: + # { + # (scope1, domain1): [user1, user2, ...], + # (scope2, domain1): [user1, user3, ...], + # (scope1, domain2): [user4, user5, ...], + # (scope3, domain3): [user6, user7, ...], + # } + # Issue domains (e.g.twitter.com) are the domains to whom the token was + # issued and scopes reflect the data accessed. + # + # This is simple to minimize memory footprint. Later processing of this data + # structure will report most frequent: issue domains, scopes and users. + token_stats = {} + + if not flags.resume: + # Early check if file exists and not --force. + filename_path = token_report_utils.WriteTokensIssuedJson(token_stats, + flags.force) + else: + token_stats = token_report_utils.GetTokenStats() + + http = auth_helper.GetAuthorizedHttp(flags) + apps_security_api = tokens_api.TokensApiWrapper(http) + + iterator_purpose = 'collection' # Used to tag iterator progress data. + + # The user list holds a tuple for each user of: email, id, full_name + # (e.g. 'larry', '112351558298938768732', 'Larry Summon'). + print 'Scanning domain users for %s' % iterator_purpose + for user in user_iterator.StartUserIterator(http, iterator_purpose, flags): + user_email, user_id, checkpoint = user + try: + token_list = apps_security_api.GetTokensForUser(user_id) + except admin_api_tool_errors.AdminAPIToolTokenRequestError as e: + # This suggests an unexpected response from the apps security api. + # As much detail as possible is provided by the raiser. + sys.stdout.write('%80s\r' % '') # Clear the previous entry. + sys.stdout.flush() + log_utils.LogError('Unable to get user tokens.', e) + sys.exit(1) + + for token in token_list: + # Save lists of users with tokens. + for scope in token['scopes']: + stat_key = token_report_utils.PackStatKey(token['clientId'], scope) + token_stats.setdefault(stat_key, []) + token_stats[stat_key].append(user_email) + + if checkpoint: + # Save progress every n users. + filename_path = token_report_utils.WriteTokensIssuedJson( + token_stats, overwrite_ok=True) + print 'Token report written: %s' % filename_path + + +if __name__ == '__main__': + main(sys.argv[1:]) diff --git a/pool/shard007/Python/0069790_p240_search_a_2d_matrix_ii.py b/pool/shard007/Python/0069790_p240_search_a_2d_matrix_ii.py new file mode 100644 index 0000000000000000000000000000000000000000..d1d44c28e0e378d4c0c42edf0ebbc62ccb48bc42 --- /dev/null +++ b/pool/shard007/Python/0069790_p240_search_a_2d_matrix_ii.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +# author: Fei Gao +# +# Search A 2d Matrix Ii + +# Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: +# Integers in each row are sorted in ascending from left to right. +# Integers in each column are sorted in ascending from top to bottom. +# For example, +# Consider the following matrix: +# [ +# [1, 4, 7, 11, 15], +# [2, 5, 8, 12, 19], +# [3, 6, 9, 16, 22], +# [10, 13, 14, 17, 24], +# [18, 21, 23, 26, 30] +# ] +# Given target = 5, return true. +# Given target = 20, return false. +# Subscribe to see which companies asked this question + + +class Solution(object): + def searchMatrix(self, matrix, target): + """ + :type matrix: List[List[int]] + :type target: int + :rtype: bool + """ + + def search(row1, row2, col1, col2): + """Search target in sub matrix[row1:row2][col1:col2]""" + # zero elements + if row1 >= row2 or col1 >= col2: + return False + if matrix[row1][col1] == target: + return True + # target less than up-left corner + if target < matrix[row1][col1]: + return False + # target greater than low-right corner + if target > matrix[row2 - 1][col2 - 1]: + return False + row3 = (row1 + row2 + 1) // 2 + col3 = (col1 + col2 + 1) // 2 + # print(row1, row3, row2, col1, col3, col2) + result = (search(row1, row3, col1, col3) + or search(row1, row3, col3, col2) + or search(row3, row2, col1, col3) + or search(row3, row2, col3, col2)) + # print(row1, row2, col1, col2, result) + return result + + return search(0, len(matrix), 0, len(matrix[0])) + + +def main(): + solver = Solution() + tests = [ + ([ + [1, 4, 7, 11, 15], + [2, 5, 8, 12, 19], + [3, 6, 9, 16, 22], + [10, 13, 14, 17, 24], + [18, 21, 23, 26, 30] + ], 5), + ([ + [1, 4, 7, 11, 15], + [2, 5, 8, 12, 19], + [3, 6, 9, 16, 22], + [10, 13, 14, 17, 24], + [18, 21, 23, 26, 30] + ], 20) + ] + for test in tests: + print(test) + print(' ->') + result = solver.searchMatrix(*test) + print(result) + print('~' * 10) + pass + + +if __name__ == '__main__': + main() + pass diff --git a/pool/shard007/Python/0069793_test_http_spider.py b/pool/shard007/Python/0069793_test_http_spider.py new file mode 100644 index 0000000000000000000000000000000000000000..cfc7a6ee33bed7119d986cf934cbcf53f620091c --- /dev/null +++ b/pool/shard007/Python/0069793_test_http_spider.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +# coding=utf-8 + +import unittest + +import httpretty + +from pycon2015.http_spider import get_url_data + + +class HttpSpiderTestCase(unittest.TestCase): + + @unittest.skip('Fuck GFW') + def test_get_url_data_impossible_in_china(self): + url_data = get_url_data('http://www.google.com/') + + self.assertEqual(url_data['status_code'], 200) + self.assertEqual(url_data['encoding'], 'utf-8') + + @httpretty.activate + def test_get_url_data(self): + url = 'http://www.google.com/' + httpretty.register_uri( + httpretty.GET, url, body='Fake Google', status=200 + ) + url_data = get_url_data(url) + + self.assertEqual(url_data['status_code'], 200) + self.assertEqual(url_data['encoding'], 'utf-8') diff --git a/pool/shard007/Python/0069798_test_ftp.py b/pool/shard007/Python/0069798_test_ftp.py new file mode 100644 index 0000000000000000000000000000000000000000..943cc1da6d8d2bbdd8c89f5354f120738ea08dba --- /dev/null +++ b/pool/shard007/Python/0069798_test_ftp.py @@ -0,0 +1,179 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# 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. +import io +import unittest +from unittest import mock + +from airflow.providers.ftp.hooks import ftp as fh + + +class TestFTPHook(unittest.TestCase): + def setUp(self): + super().setUp() + self.path = '/some/path' + self.conn_mock = mock.MagicMock(name='conn') + self.get_conn_orig = fh.FTPHook.get_conn + + def _get_conn_mock(hook): + hook.conn = self.conn_mock + return self.conn_mock + + fh.FTPHook.get_conn = _get_conn_mock + + def tearDown(self): + fh.FTPHook.get_conn = self.get_conn_orig + super().tearDown() + + def test_close_conn(self): + ftp_hook = fh.FTPHook() + ftp_hook.get_conn() + ftp_hook.close_conn() + + self.conn_mock.quit.assert_called_once_with() + + def test_list_directory(self): + with fh.FTPHook() as ftp_hook: + ftp_hook.list_directory(self.path) + + self.conn_mock.cwd.assert_called_once_with(self.path) + self.conn_mock.nlst.assert_called_once_with() + + def test_create_directory(self): + with fh.FTPHook() as ftp_hook: + ftp_hook.create_directory(self.path) + + self.conn_mock.mkd.assert_called_once_with(self.path) + + def test_delete_directory(self): + with fh.FTPHook() as ftp_hook: + ftp_hook.delete_directory(self.path) + + self.conn_mock.rmd.assert_called_once_with(self.path) + + def test_delete_file(self): + with fh.FTPHook() as ftp_hook: + ftp_hook.delete_file(self.path) + + self.conn_mock.delete.assert_called_once_with(self.path) + + def test_rename(self): + from_path = '/path/from' + to_path = '/path/to' + with fh.FTPHook() as ftp_hook: + ftp_hook.rename(from_path, to_path) + + self.conn_mock.rename.assert_called_once_with(from_path, to_path) + self.conn_mock.quit.assert_called_once_with() + + def test_mod_time(self): + self.conn_mock.sendcmd.return_value = '213 20170428010138' + + path = '/path/file' + with fh.FTPHook() as ftp_hook: + ftp_hook.get_mod_time(path) + + self.conn_mock.sendcmd.assert_called_once_with('MDTM ' + path) + + def test_mod_time_micro(self): + self.conn_mock.sendcmd.return_value = '213 20170428010138.003' + + path = '/path/file' + with fh.FTPHook() as ftp_hook: + ftp_hook.get_mod_time(path) + + self.conn_mock.sendcmd.assert_called_once_with('MDTM ' + path) + + def test_get_size(self): + self.conn_mock.size.return_value = 1942 + + path = '/path/file' + with fh.FTPHook() as ftp_hook: + ftp_hook.get_size(path) + + self.conn_mock.size.assert_called_once_with(path) + + def test_retrieve_file(self): + _buffer = io.StringIO('buffer') + with fh.FTPHook() as ftp_hook: + ftp_hook.retrieve_file(self.path, _buffer) + self.conn_mock.retrbinary.assert_called_once_with('RETR path', _buffer.write) + + def test_retrieve_file_with_callback(self): + func = mock.Mock() + _buffer = io.StringIO('buffer') + with fh.FTPHook() as ftp_hook: + ftp_hook.retrieve_file(self.path, _buffer, callback=func) + self.conn_mock.retrbinary.assert_called_once_with('RETR path', func) + + def test_connection_success(self): + with fh.FTPHook() as ftp_hook: + status, msg = ftp_hook.test_connection() + assert status is True + assert msg == 'Connection successfully tested' + + def test_connection_failure(self): + self.conn_mock = mock.MagicMock(name='conn_mock', side_effect=Exception('Test')) + fh.FTPHook.get_conn = self.conn_mock + with fh.FTPHook() as ftp_hook: + status, msg = ftp_hook.test_connection() + assert status is False + assert msg == 'Test' + + +class TestIntegrationFTPHook(unittest.TestCase): + def setUp(self): + super().setUp() + from airflow.models import Connection + from airflow.utils import db + + db.merge_conn( + Connection(conn_id='ftp_passive', conn_type='ftp', host='localhost', extra='{"passive": true}') + ) + + db.merge_conn( + Connection(conn_id='ftp_active', conn_type='ftp', host='localhost', extra='{"passive": false}') + ) + + def _test_mode(self, hook_type, connection_id, expected_mode): + hook = hook_type(connection_id) + conn = hook.get_conn() + conn.set_pasv.assert_called_once_with(expected_mode) + + @mock.patch("ftplib.FTP") + def test_ftp_passive_mode(self, mock_ftp): + from airflow.providers.ftp.hooks.ftp import FTPHook + + self._test_mode(FTPHook, "ftp_passive", True) + + @mock.patch("ftplib.FTP") + def test_ftp_active_mode(self, mock_ftp): + from airflow.providers.ftp.hooks.ftp import FTPHook + + self._test_mode(FTPHook, "ftp_active", False) + + @mock.patch("ftplib.FTP_TLS") + def test_ftps_passive_mode(self, mock_ftp): + from airflow.providers.ftp.hooks.ftp import FTPSHook + + self._test_mode(FTPSHook, "ftp_passive", True) + + @mock.patch("ftplib.FTP_TLS") + def test_ftps_active_mode(self, mock_ftp): + from airflow.providers.ftp.hooks.ftp import FTPSHook + + self._test_mode(FTPSHook, "ftp_active", False) diff --git a/pool/shard007/Python/0069799_bin2obj.py b/pool/shard007/Python/0069799_bin2obj.py new file mode 100644 index 0000000000000000000000000000000000000000..f12084948387070a6370e24c2f978f3bbd0e5670 --- /dev/null +++ b/pool/shard007/Python/0069799_bin2obj.py @@ -0,0 +1,187 @@ +from lar import * +from scipy import * +import json +import scipy +import numpy as np +import time as tm +import gc +import struct + +# ------------------------------------------------------------ +# Logging & Timer +# ------------------------------------------------------------ + +logging_level = 2; + +# 0 = no_logging +# 1 = few details +# 2 = many details +# 3 = many many details + +def log(n, l): + + if __name__=="__main__" and n <= logging_level: + for s in l: + print "Log:", s; + +timer = 1; + +timer_last = tm.time() + +def timer_start(s): + + global timer_last; + if __name__=="__main__" and timer == 1: + print "Timer start:", s; + timer_last = tm.time(); + +def timer_stop(): + + global timer_last; + if __name__=="__main__" and timer == 1: + print "Timer stop :", tm.time() - timer_last; + +# ------------------------------------------------------------ +# Configuration parameters +# ------------------------------------------------------------ + +nx = ny = nz = 64 +log(1, ["nx, ny, nz = " + str(nx) + "," + str(ny) + "," + str(nz)]); + +chunksize = nx * ny + nx * nz + ny * nz + 3 * nx * ny * nz +log(1, ["chunksize = " + str(chunksize)]); +# chunksize = 798720 (nx=ny=nz=64) + +MAX_CHUNKS = 64 #1024 +log(1, ["MAX_CHUNKS = " + str(MAX_CHUNKS)]); + +# ------------------------------------------------------------ + +def ind(x,y,z): return x + (nx+1) * (y + (ny+1) * (z)) + +def invertIndex(nx,ny,nz): + nx,ny,nz = nx+1,ny+1,nz+1 + def invertIndex0(offset): + a0, b0 = offset / nx, offset % nx + a1, b1 = a0 / ny, a0 % ny + a2, b2 = a1 / nz, a1 % nz + return b0,b1,b2 + return invertIndex0 + +# Construction of vertex coordinates (nx * ny * nz) +# ------------------------------------------------------------ + +timer_start("V"); + +V = [[x,y,z] for z in range(nz+1) for y in range(ny+1) for x in range(nx+1) ] + +timer_stop(); +log(3, ["V = " + str(V)]); + +# Construction of FV relation (nx * ny * nz) +# ------------------------------------------------------------ + +FV = [] + +timer_start("v2coords"); + +v2coords = invertIndex(nx,ny,nz) + +timer_stop(); + +timer_start("h"); + +for h in range(len(V)): + x,y,z = v2coords(h) + if (x < nx) and (y < ny): FV.append([h,ind(x+1,y,z),ind(x,y+1,z),ind(x+1,y+1,z)]) + if (x < nx) and (z < nz): FV.append([h,ind(x+1,y,z),ind(x,y,z+1),ind(x+1,y,z+1)]) + if (y < ny) and (z < nz): FV.append([h,ind(x,y+1,z),ind(x,y,z+1),ind(x,y+1,z+1)]) + +timer_stop(); +log(3, ["FV = " + str(FV)]); + +# ------------------------------------------------------------ + +out = [] +file = open("output.bin", "rb") + +fileVertex = open("outputVtx.obj", "w") +fileFaces = open("outputFaces.obj", "w") + +vertex_count = 1 +old_vertex_count = vertex_count +count = 0 + +for i in range(MAX_CHUNKS): + + count += 1 + + zStart = struct.unpack('>I', file.read(4))[0] + xStart = struct.unpack('>I', file.read(4))[0] + yStart = struct.unpack('>I', file.read(4))[0] + + log(1, ["zStart, xStart, yStart = " + str(zStart) + "," + str(xStart) + "," + str(yStart)]); +# zStart, xStart, yStart = LISTA_OFFSET[i].astype(float64) + + LISTA_VETTORI2 = np.zeros(chunksize,dtype=int32); + + temp = file.read(chunksize); + + timer_start("LISTA_VETTORI2 " + str(i)); + i = 0 + while (i < chunksize): + if (temp[i] == '\x01'): + LISTA_VETTORI2[i] = 1; + i = i + 1; + timer_stop(); + + timer_start("objectBoundaryChain "); + l = len(LISTA_VETTORI2) + objectBoundaryChain = scipy.sparse.csr_matrix(LISTA_VETTORI2.reshape((l,1))) + timer_stop(); + + timer_start("csrChainToCellList " + str(i)); + b2cells = csrChainToCellList(objectBoundaryChain) + timer_stop(); + + timer_start("MKPOLS " + str(i)); + + for f in b2cells: + old_vertex_count = vertex_count + + for vtx in FV[f]: + fileVertex.write("v ") + fileVertex.write(str(V[vtx][0] + xStart)) + fileVertex.write(" ") + fileVertex.write(str(V[vtx][1] + yStart)) + fileVertex.write(" ") + fileVertex.write(str(V[vtx][2] + zStart)) + fileVertex.write("\n") + vertex_count = vertex_count + 1 + + fileFaces.write("f ") + fileFaces.write(str(old_vertex_count + 0)) + fileFaces.write(" ") + fileFaces.write(str(old_vertex_count + 1)) + fileFaces.write(" ") + fileFaces.write(str(old_vertex_count + 3)) + fileFaces.write("\n") + + fileFaces.write("f ") + fileFaces.write(str(old_vertex_count + 0)) + fileFaces.write(" ") + fileFaces.write(str(old_vertex_count + 3)) + fileFaces.write(" ") + fileFaces.write(str(old_vertex_count + 2)) + fileFaces.write("\n") + + timer_stop(); + + if count == MAX_CHUNKS: + timer_start("VIEW(STRUCT(out))"); + timer_stop(); + +file.close() +fileVertex.close() +fileFaces.close() + diff --git a/pool/shard007/Python/0069800_stap_gen_code.py b/pool/shard007/Python/0069800_stap_gen_code.py new file mode 100644 index 0000000000000000000000000000000000000000..afbdbbd1161791fc5c87f66be31976d5e5b41af8 --- /dev/null +++ b/pool/shard007/Python/0069800_stap_gen_code.py @@ -0,0 +1,77 @@ +#!/usr/bin/python + +# Copyright (C) 2014 Red Hat Inc. +# +# This file is part of systemtap, and is free software. You can +# redistribute it and/or modify it under the terms of the GNU General +# Public License (GPL); either version 2, or (at your option) any +# later version. + +import os +import sys +from config_opts import config_opts + +def gen_files(dir, subset): + f = open('%s/probes.stp' % dir, 'w') + + # Output the script + i = 0 + while i < len(subset): + print >>f, ("global called%d" % (i)) + i += 1 + print >>f, "probe begin(-1)" + print >>f, "{" + i = 0 + while i < len(subset): + print >>f, ("\tcalled%d <<< 0" % (i)) + i += 1 + print >>f, "}" + i = 0 + while i < len(subset): + print >>f, ("probe kernel.function(\"%s\").call { called%d <<< 1 }" % (subset[i], i)) + i += 1 + print >>f, "probe end" + print >>f, "{" + i = 0 + while i < len(subset): + print >>f, ("\tprintf(\"%%d %s\\n\", @sum(called%d))" % (subset[i], i)) + i += 1 + print >>f, "\tprintf(\"probe_module unloaded\\n\")" + print >>f, "}" + f.close() + +def gen_module(): + f = open(config_opts['probes_current']) + probes = f.readlines() + f.close() + if len(probes) == 0: + print >>sys.stderr, ("Error: no probe points in %s" + % config_opts['probes_current']) + return -1 + + # Cleanup each probe by stripping whitespace + i = 0 + while i < len(probes): + probes[i] = probes[i].rstrip() + i += 1 + + # Generate necessary files + gen_files(os.getcwd(), probes) + + # Try to build the module + os.system('rm -f ./probe_module.ko') + + cmd = "stap -g --suppress-handler-errors --suppress-time-limits -vp4 -m probe_module probes.stp >build.log 2>&1" + print "Running", cmd + rc = os.system(cmd) + if os.WEXITSTATUS(rc) != 0: + print >>sys.stderr, "Error: stap failed, see build.log for details" + return -1 + return 0 + +def main(): + rc = gen_module() + sys.exit(rc) + +if __name__ == "__main__": + main() diff --git a/pool/shard007/Python/0069804_ro.py b/pool/shard007/Python/0069804_ro.py new file mode 100644 index 0000000000000000000000000000000000000000..e8238d8b7265ac56b2220fe5960120ca34328882 --- /dev/null +++ b/pool/shard007/Python/0069804_ro.py @@ -0,0 +1,71 @@ +############################################################################## +# +# Copyright (c) 2003 Zope Foundation and Contributors. +# All Rights Reserved. +# +# This software is subject to the provisions of the Zope Public License, +# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. +# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED +# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS +# FOR A PARTICULAR PURPOSE. +# +############################################################################## +"""Compute a resolution order for an object and its bases + +$Id: ro.py 110536 2010-04-06 02:59:44Z tseaver $ +""" +__docformat__ = 'restructuredtext' + + +def ro(object): + """Compute a "resolution order" for an object + """ + return mergeOrderings([_flatten(object)]) + +def mergeOrderings(orderings, seen=None): + """Merge multiple orderings so that within-ordering order is preserved + + Orderings are constrained in such a way that if an object appears + in two or more orderings, then the suffix that begins with the + object must be in both orderings. + + For example: + + >>> _mergeOrderings([ + ... ['x', 'y', 'z'], + ... ['q', 'z'], + ... [1, 3, 5], + ... ['z'] + ... ]) + ['x', 'y', 'q', 1, 3, 5, 'z'] + + """ + + if seen is None: + seen = {} + result = [] + orderings.reverse() + for ordering in orderings: + ordering = list(ordering) + ordering.reverse() + for o in ordering: + if o not in seen: + seen[o] = 1 + result.append(o) + + result.reverse() + return result + +def _flatten(ob): + result = [ob] + i = 0 + for ob in iter(result): + i += 1 + # The recursive calls can be avoided by inserting the base classes + # into the dynamically growing list directly after the currently + # considered object; the iterator makes sure this will keep working + # in the future, since it cannot rely on the length of the list + # by definition. + result[i:i] = ob.__bases__ + return result diff --git a/pool/shard007/Python/0069812_web_views_test.py b/pool/shard007/Python/0069812_web_views_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e0e6ebef9e1143b1cce621ee49cbb0ca2048cfc8 --- /dev/null +++ b/pool/shard007/Python/0069812_web_views_test.py @@ -0,0 +1,94 @@ +from cStringIO import StringIO +import unittest + +import mock +from PyPDF2 import PdfFileReader + +from logic import reminder_service +from testing import test_base +from testing import test_data +from util import ids +from views import web_views +assert web_views # Silence pyflakes + +pelosi = test_data.RepData.nancy_pelosi + +class WebViewsTest(test_base.DatabaseWithTestdataTest): + def test_heartbeat(self): + resp = self.client.get('/') + self.assertEqual(200, resp.status_code) + resp = self.client.get('/district/%s' % test_data.DistrictData.wy00.district_code) + self.assertEqual(200, resp.status_code) + resp = self.client.get('/compose/%s' % pelosi.rep_id) + self.assertEqual(200, resp.status_code) + + resp = self.client.get('/robots.txt') + self.assertEqual(200, resp.status_code) + resp = self.client.get('/sitemap.txt') + self.assertEqual(200, resp.status_code) + + def test_generate_letter_pdf(self): + resp = self.client.post('/letter', data=dict( + rep_id=str(pelosi.rep_id), + body='hello world', + name_and_address='Bob Smith\nSan Francisco, CA', + include_address_page='1')) + self.assertEqual(200, resp.status_code) + self.assertEqual('application/pdf', resp.headers.get('Content-Type')) + self.assertIsNotNone(resp.data) + + pdf_reader = PdfFileReader(StringIO(resp.data)) + self.assertEqual(2, pdf_reader.getNumPages()) + + def test_generate_letter_pdf_without_address_page(self): + resp = self.client.post('/letter', data=dict( + rep_id=str(pelosi.rep_id), + body='hello world', + name_and_address='Bob Smith\nSan Francisco, CA', + include_address_page='0')) + self.assertEqual(200, resp.status_code) + self.assertEqual('application/pdf', resp.headers.get('Content-Type')) + self.assertIsNotNone(resp.data) + + pdf_reader = PdfFileReader(StringIO(resp.data)) + self.assertEqual(1, pdf_reader.getNumPages()) + + @mock.patch('app.app.logger.error') + def test_generate_letter_with_invalid_params(self, mock_log_error): + resp = self.client.post('/letter', data=dict( + rep_id='-1', + body='hello world', + name_and_address='Bob Smith\nSan Francisco, CA', + include_address_page='1')) + self.assertEqual(400, resp.status_code) + mock_log_error.assert_called_once() + + @mock.patch.object(reminder_service.ReminderServiceImpl, 'update') + def test_reminder_unsubscribe(self, mock_update): + resp = self.client.get('/reminder/unsubscribe?email=foo@foo.com&token=blah') + self.assertEqual(200, resp.status_code) + mock_update.assert_called_once() + update_req = mock_update.call_args[0][0] + self.assertEqual('foo@foo.com', update_req.email) + self.assertEqual('blah', update_req.token) + self.assertEqual('UNSUBSCRIBED', update_req.status) + + def test_get_issue_page(self): + issue_data = test_data.IssueData.issue1 + resp = self.client.get('/issue/%s' % ids.public_id(issue_data.issue_id)) + self.assertEqual(200, resp.status_code) + + def test_create_issue_page(self): + resp = self.client.get('/issue/create') + self.assertEqual(200, resp.status_code) + + def test_edit_issue_page(self): + issue_data = test_data.IssueData.issue1 + resp = self.client.get('/issue/%s/edit?token=issuetoken' % + ids.public_id(issue_data.issue_id)) + self.assertEqual(200, resp.status_code) + self.assertTrue('issuetoken' in resp.data) + self.assertTrue(issue_data.description in resp.data) + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard007/Python/0069816_urls.py b/pool/shard007/Python/0069816_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..145936af5b19bd546adae9742b3fbc4732f1723d --- /dev/null +++ b/pool/shard007/Python/0069816_urls.py @@ -0,0 +1,167 @@ +from django.contrib.auth.decorators import login_required +from django.shortcuts import redirect +from django.urls import re_path +from django.views.generic import TemplateView + +from dados.dbdata import STATE_NAME + +# local +from .views import ( + AboutPageView, + AlertaGeoJSONView, + AlertaMainView, + AlertaMRJPageView, + AlertaMunicipioPageView, + AlertaStateView, + ChartsMainView, + DataPublicServicesPageView, + DetailsPageView, + GeoJsonView, + GeoTiffView, + JoininPageView, + ReportCityView, + ReportStateView, + ReportView, + SinanCasesView, + TeamPageView, + get_municipio, +) + + +def redirect_alerta_dengue(request, state): + return redirect('dados:alerta_uf', state=state, disease='dengue') + + +def redirect_alert_rio_dengue(request): + return redirect('dados:mrj', disease='dengue') + + +def redirect_alert_city_dengue(request, geocodigo): + return redirect( + 'dados:alerta_cidade', geocodigo=geocodigo, disease='dengue' + ) + + +app_name = "dados" + +state_abbv = '|'.join(state for state in STATE_NAME.keys()) + +__disease = '(?Pdengue|chikungunya|zika)' +__state_abbv = f'(?P{state_abbv})' +__geocode = r'(?P\d{7})' +__geocode_ = r'(?P\d{7})' +__year = r'(?P\d{4})' +__month = r'(?P\d{2})' +__day = r'(?P\d{2})' +__e_week = r'(?P\d{2})' +__year_week = r'(?P\d{6})' + +__report_type = '(?Pcity|state)' + + +urlpatterns = [ + re_path(r'^$', AlertaMainView.as_view(), name='main'), + re_path( + r'^chartshome/{}$'.format(__state_abbv), + ChartsMainView.as_view(), + name='chartshome', + ), + re_path(r'^informacoes/$', AboutPageView.as_view(), name='about'), + re_path(r'^equipe/$', TeamPageView.as_view(), name='team'), + re_path(r'^participe/$', JoininPageView.as_view(), name='joinin'), + re_path( + r'^services/(?Pmaps|api)?$', + DataPublicServicesPageView.as_view(), + name="data_public_services", + ), + re_path( + r'^services/(?Pmaps|tutorial)?$', + DataPublicServicesPageView.as_view(), + name="data_public_services", + ), + re_path( + r'^services/(?Pmaps|tutorial)/(?PR)$', + DataPublicServicesPageView.as_view( + template_name="services_tutorial_R.html" + ), + name='services_tutorial_R', + ), + re_path( + r'^tutorial_api_r/', + TemplateView.as_view( + template_name="components/tutorial/notebook-API-R-en.html" + ), + name='tutorial_api_R', + ), + re_path( + r'^services/(?Pmaps|tutorial)/(?PPython)$', + DataPublicServicesPageView.as_view( + template_name="services_tutorial_Python.html" + ), + name='services_tutorial_Python', + ), + re_path( + r'^tutorial_api_python/', + TemplateView.as_view( + template_name="components/tutorial/notebook-API-Python-en.html" + ), + name='tutorial_api_python', + ), + re_path( + r'^services/(?Pmaps|api)/(?Pdoc)$', + DataPublicServicesPageView.as_view(), + name="data_public_services_type", + ), + re_path(r'^alerta/%s[/]?$' % __state_abbv, redirect_alerta_dengue), + re_path( + r'^alerta/%s/%s$' % (__state_abbv, __disease), + AlertaStateView.as_view(), + name='alerta_uf', + ), + re_path(r'^alerta/rio/$', redirect_alert_rio_dengue), + re_path( + r'^alerta/rio/%s$' % __disease, AlertaMRJPageView.as_view(), name='mrj' + ), + re_path(r'^alerta/%s[/]?$' % __geocode, redirect_alert_city_dengue), + re_path( + r'^alerta/%s/%s$' % (__geocode, __disease), + AlertaMunicipioPageView.as_view(), + name='alerta_cidade', + ), + re_path(r'^alerta-detalhado/$', DetailsPageView.as_view(), name='home'), + re_path( + r'^alertageoJSON/$', + login_required(AlertaGeoJSONView.as_view()), + name='alerta-layer', + ), + re_path(r'^getcity/$', get_municipio, name='get_city'), + re_path( + r'^sinan/(\d{4})/(\d{1,2})', SinanCasesView.as_view(), name='sinan' + ), + re_path( + r'^geotiff/%s/%s/$' % (__geocode, __disease), + GeoTiffView.as_view(), + name='geotiff', + ), + re_path( + r'^geojson/%s/%s/$' % (__geocode, __disease), + GeoJsonView.as_view(), + name='geojson', + ), + re_path(r'^report/$', ReportView.as_view(), name='report'), + re_path( + r'^report/{}/{}$'.format(__state_abbv, __report_type), + ReportView.as_view(), + name='report_filter', + ), + re_path( + r'^report/{}/{}/{}$'.format(__state_abbv, __geocode_, __year_week), + ReportCityView.as_view(), + name='report_city', + ), + re_path( + r'^report/{}/{}$'.format(__state_abbv, __year_week), + ReportStateView.as_view(), + name='report_state', + ), +] diff --git a/pool/shard007/Python/0069818_test_abstract_protein.py b/pool/shard007/Python/0069818_test_abstract_protein.py new file mode 100644 index 0000000000000000000000000000000000000000..a1de246ea9017e7ca47eb2100335f8b08f99fb95 --- /dev/null +++ b/pool/shard007/Python/0069818_test_abstract_protein.py @@ -0,0 +1,56 @@ +from helpers.filters import Filter +from view_testing import ViewTest + + +class TestAbstractProteinView(ViewTest): + + def view_module(self): + from website.views import abstract_protein + return abstract_protein + + def test_are_filter_managers_graceful(self): + from views import ProteinView, SequenceView, NetworkView + from views.abstract_protein import GracefulFilterManager + + graceful_views = [SequenceView, ProteinView, NetworkView] + for view in graceful_views: + assert issubclass(view.filter_class, GracefulFilterManager) + + def test_graceful_manager(self): + from website.views.abstract_protein import GracefulFilterManager + + class Target: + __name__ = 'TestModel' + + class Request: + method = 'GET' + + def __init__(self, args): + self.args = args + + class TestViewFilters(GracefulFilterManager): + + def __init__(self, request): + + filters = [ + Filter( + Target(), 'property', comparators=['in'], + choices=['Value1', "Value2, corrected"], + multiple=True + ) + ] + super().__init__(filters) + self.update_from_request(request) + + test_request = Request({ + 'filters': "TestModel.property:in:Value1,Value2,'Value2, corrected'" + }) + TestViewFilters(test_request) + with self.assert_flashes( + content='Value2 does not occur in property for this protein and therefore it was left out.', + category='warning' + ): + test_request = Request({ + 'filters': "TestModel.property:in:Value1,Value2,'Value2, corrected'" + }) + TestViewFilters(test_request) diff --git a/pool/shard007/Python/0069820_storage.py b/pool/shard007/Python/0069820_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..03eac8df895cf2ec677e231ccfcebfc225c9b720 --- /dev/null +++ b/pool/shard007/Python/0069820_storage.py @@ -0,0 +1,78 @@ +import os + +from django.conf import settings +from django.core.exceptions import ImproperlyConfigured +from django.utils.functional import cached_property + +from django_tenants import utils +from django_tenants.files.storage import TenantFileSystemStorage + + +class TenantStaticFilesStorage(TenantFileSystemStorage): + """ + Implementation that extends core Django's StaticFilesStorage for multi-tenant setups. + + The defaults for ``location`` and ``base_url`` are ``STATIC_ROOT`` and ``STATIC_URL``. + + """ + def _clear_cached_properties(self, setting, **kwargs): + """Reset setting based property values.""" + super()._clear_cached_properties(settings, **kwargs) + + if setting == 'MULTITENANT_RELATIVE_STATIC_ROOT': + self.__dict__.pop('relative_static_root', None) + + @cached_property + def relative_static_root(self): + try: + return os.path.join(settings.STATIC_ROOT, settings.MULTITENANT_RELATIVE_STATIC_ROOT) + except AttributeError: + # MULTITENANT_RELATIVE_STATIC_ROOT is an optional setting. Use the default of just appending + # the tenant schema_name to STATIC_ROOT if no configuration value is provided + try: + return settings.STATIC_ROOT + except AttributeError: + raise ImproperlyConfigured("You're using the staticfiles app " + "without having set the STATIC_ROOT " + "setting to a filesystem path.") + + @cached_property + def relative_static_url(self): + url = settings.STATIC_URL + rewrite_on = False + + try: + if settings.REWRITE_STATIC_URLS is True: + rewrite_on = True + try: + multitenant_relative_url = settings.MULTITENANT_RELATIVE_STATIC_ROOT + except AttributeError: + # MULTITENANT_RELATIVE_STATIC_ROOT is an optional setting. Use the default of just appending + # the tenant schema_name to STATIC_ROOT if no configuration value is provided + multitenant_relative_url = "%s" + + url = "/" + "/".join(s.strip("/") for s in [url, multitenant_relative_url]) + "/" + + except AttributeError: + # REWRITE_STATIC_URLS not set - ignore + pass + + return rewrite_on, url + + @property # Not cached like in parent class + def base_location(self): + return self._value_or_setting(self._location, utils.parse_tenant_config_path(self.relative_static_root)) + + @property # Not cached like in parent class + def base_url(self): + rewrite_on, relative_tenant_url = self.relative_static_url + if rewrite_on: + relative_tenant_url = utils.parse_tenant_config_path(relative_tenant_url) + + if not relative_tenant_url.endswith('/'): + relative_tenant_url += '/' + + if self._base_url is not None and not self._base_url.endswith('/'): + self._base_url += '/' + + return self._value_or_setting(self._base_url, relative_tenant_url) diff --git a/pool/shard007/Python/0069824_Hello.py b/pool/shard007/Python/0069824_Hello.py new file mode 100644 index 0000000000000000000000000000000000000000..3b4fe7575a2b52b52ee713820fa9e47c2404a72c --- /dev/null +++ b/pool/shard007/Python/0069824_Hello.py @@ -0,0 +1,247 @@ +# +# Autogenerated by Thrift Compiler (0.13.0) +# +# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING +# +# options string: py +# + +from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException +from thrift.protocol.TProtocol import TProtocolException +from thrift.TRecursive import fix_spec + +import sys +import logging +from .ttypes import * +from thrift.Thrift import TProcessor +from thrift.transport import TTransport +all_structs = [] + + +class Iface(object): + def hi(self, test_data): + """ + Parameters: + - test_data + + """ + pass + + +class Client(Iface): + def __init__(self, iprot, oprot=None): + self._iprot = self._oprot = iprot + if oprot is not None: + self._oprot = oprot + self._seqid = 0 + + def hi(self, test_data): + """ + Parameters: + - test_data + + """ + self.send_hi(test_data) + return self.recv_hi() + + def send_hi(self, test_data): + self._oprot.writeMessageBegin('hi', TMessageType.CALL, self._seqid) + args = hi_args() + args.test_data = test_data + args.write(self._oprot) + self._oprot.writeMessageEnd() + self._oprot.trans.flush() + + def recv_hi(self): + iprot = self._iprot + (fname, mtype, rseqid) = iprot.readMessageBegin() + if mtype == TMessageType.EXCEPTION: + x = TApplicationException() + x.read(iprot) + iprot.readMessageEnd() + raise x + result = hi_result() + result.read(iprot) + iprot.readMessageEnd() + if result.success is not None: + return result.success + raise TApplicationException(TApplicationException.MISSING_RESULT, "hi failed: unknown result") + + +class Processor(Iface, TProcessor): + def __init__(self, handler): + self._handler = handler + self._processMap = {} + self._processMap["hi"] = Processor.process_hi + self._on_message_begin = None + + def on_message_begin(self, func): + self._on_message_begin = func + + def process(self, iprot, oprot): + (name, type, seqid) = iprot.readMessageBegin() + if self._on_message_begin: + self._on_message_begin(name, type, seqid) + if name not in self._processMap: + iprot.skip(TType.STRUCT) + iprot.readMessageEnd() + x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' % (name)) + oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid) + x.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() + return + else: + self._processMap[name](self, seqid, iprot, oprot) + return True + + def process_hi(self, seqid, iprot, oprot): + args = hi_args() + args.read(iprot) + iprot.readMessageEnd() + result = hi_result() + try: + result.success = self._handler.hi(args.test_data) + msg_type = TMessageType.REPLY + except TTransport.TTransportException: + raise + except TApplicationException as ex: + logging.exception('TApplication exception in handler') + msg_type = TMessageType.EXCEPTION + result = ex + except Exception: + logging.exception('Unexpected exception in handler') + msg_type = TMessageType.EXCEPTION + result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error') + oprot.writeMessageBegin("hi", msg_type, seqid) + result.write(oprot) + oprot.writeMessageEnd() + oprot.trans.flush() + +# HELPER FUNCTIONS AND STRUCTURES + + +class hi_args(object): + """ + Attributes: + - test_data + + """ + + + def __init__(self, test_data=None,): + self.test_data = test_data + + def read(self, iprot): + if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: + iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 1: + if ftype == TType.STRING: + self.test_data = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() + + def write(self, oprot): + if oprot._fast_encode is not None and self.thrift_spec is not None: + oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) + return + oprot.writeStructBegin('hi_args') + if self.test_data is not None: + oprot.writeFieldBegin('test_data', TType.STRING, 1) + oprot.writeString(self.test_data.encode('utf-8') if sys.version_info[0] == 2 else self.test_data) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() + + def validate(self): + return + + def __repr__(self): + L = ['%s=%r' % (key, value) + for key, value in self.__dict__.items()] + return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + + def __ne__(self, other): + return not (self == other) +all_structs.append(hi_args) +hi_args.thrift_spec = ( + None, # 0 + (1, TType.STRING, 'test_data', 'UTF8', None, ), # 1 +) + + +class hi_result(object): + """ + Attributes: + - success + + """ + + + def __init__(self, success=None,): + self.success = success + + def read(self, iprot): + if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: + iprot._fast_decode(self, iprot, [self.__class__, self.thrift_spec]) + return + iprot.readStructBegin() + while True: + (fname, ftype, fid) = iprot.readFieldBegin() + if ftype == TType.STOP: + break + if fid == 0: + if ftype == TType.STRING: + self.success = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() + else: + iprot.skip(ftype) + else: + iprot.skip(ftype) + iprot.readFieldEnd() + iprot.readStructEnd() + + def write(self, oprot): + if oprot._fast_encode is not None and self.thrift_spec is not None: + oprot.trans.write(oprot._fast_encode(self, [self.__class__, self.thrift_spec])) + return + oprot.writeStructBegin('hi_result') + if self.success is not None: + oprot.writeFieldBegin('success', TType.STRING, 0) + oprot.writeString(self.success.encode('utf-8') if sys.version_info[0] == 2 else self.success) + oprot.writeFieldEnd() + oprot.writeFieldStop() + oprot.writeStructEnd() + + def validate(self): + return + + def __repr__(self): + L = ['%s=%r' % (key, value) + for key, value in self.__dict__.items()] + return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) + + def __eq__(self, other): + return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ + + def __ne__(self, other): + return not (self == other) +all_structs.append(hi_result) +hi_result.thrift_spec = ( + (0, TType.STRING, 'success', 'UTF8', None, ), # 0 +) +fix_spec(all_structs) +del all_structs + diff --git a/pool/shard007/Python/0069826_wiz_import_procurement_from_plan.py b/pool/shard007/Python/0069826_wiz_import_procurement_from_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..2dd8f7b2a1cd94d798aa5102bd1615b748d890cd --- /dev/null +++ b/pool/shard007/Python/0069826_wiz_import_procurement_from_plan.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# (c) 2015 Alfredo de la Fuente - AvanzOSC +# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html +from openerp import models, fields, api + + +class WizImportProcurementFromPlan(models.TransientModel): + + _name = 'wiz.import.procurement.from.plan' + + from_date = fields.Date(string='From Date') + to_date = fields.Date(string='to Date') + warehouse_id = fields.Many2one('stock.warehouse', string='Warehouse') + procurement_ids = fields.Many2many( + comodel_name="procurement.order", + relation="import_from_plan_procurement_rel", + column1="wiz_import_plan_id", column2="procurement_id", + string="Procurements") + + @api.model + def default_get(self, var_fields): + plan = self.env['procurement.plan'].browse( + self.env.context['active_id']) + return {'from_date': plan.from_date, + 'to_date': plan.to_date, + 'warehouse_id': plan.warehouse_id.id} + + @api.multi + @api.onchange('warehouse_id') + def onchange_warehouse_id(self): + self.ensure_one() + cond = [('warehouse_id', '=', self.warehouse_id.id), + ('state', 'not in', ('cancel', 'done')), + ('location_type', '=', 'internal'), + ('plan', '=', False)] + if self.from_date: + cond.append(('date_planned', '>=', self.from_date)) + if self.to_date: + cond.append(('date_planned', '<=', self.to_date)) + return {'domain': {'procurement_ids': cond}} + + @api.multi + def import_procurements(self): + self.ensure_one() + self.procurement_ids.write({'plan': self.env.context['active_id']}) + plan = self.env['procurement.plan'].browse( + self.env.context['active_id']) + if plan.procurement_ids: + sorted_procs = sorted(plan.procurement_ids, + key=lambda l: l.date_planned, reverse=True) + plan.to_date = sorted_procs[0].date_planned + plan.from_date = sorted_procs[len(sorted_procs)-1].date_planned + return True diff --git a/pool/shard007/Python/0069831_test_footer.py b/pool/shard007/Python/0069831_test_footer.py new file mode 100644 index 0000000000000000000000000000000000000000..2b76db6d9921881884efdcd3f41ccd7b6c43b960 --- /dev/null +++ b/pool/shard007/Python/0069831_test_footer.py @@ -0,0 +1,72 @@ +""" +Tests related to the basic footer-switching based off SITE_NAME to ensure +edx.org uses an edx footer but other instances use an Open edX footer. +""" + +import unittest + +from django.conf import settings +from django.test import TestCase +from django.test.utils import override_settings + +from openedx.core.djangoapps.theming.tests.test_util import with_comprehensive_theme + + +@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') +class TestFooter(TestCase): + """ + Tests for edx and OpenEdX footer + """ + shard = 1 + + SOCIAL_MEDIA_NAMES = [ + "facebook", + "google_plus", + "twitter", + "linkedin", + "tumblr", + "meetup", + "reddit", + "youtube", + ] + + SOCIAL_MEDIA_URLS = { + "facebook": "http://www.facebook.com/", + "google_plus": "https://plus.google.com/", + "twitter": "https://twitter.com/", + "linkedin": "http://www.linkedin.com/", + "tumblr": "http://www.tumblr.com/", + "meetup": "http://www.meetup.com/", + "reddit": "http://www.reddit.com/", + "youtube": "https://www.youtube.com/" + } + + @with_comprehensive_theme("edx.org") + def test_edx_footer(self): + """ + Verify that the homepage, when accessed at edx.org, has the edX footer + """ + resp = self.client.get('/') + self.assertEqual(resp.status_code, 200) + self.assertContains(resp, 'footer-edx-v3') + + def test_openedx_footer(self): + """ + Verify that the homepage, when accessed at something other than + edx.org, has the Open edX footer + """ + resp = self.client.get('/') + self.assertEqual(resp.status_code, 200) + self.assertContains(resp, 'footer-openedx') + + @with_comprehensive_theme("edx.org") + @override_settings( + SOCIAL_MEDIA_FOOTER_NAMES=SOCIAL_MEDIA_NAMES, + SOCIAL_MEDIA_FOOTER_URLS=SOCIAL_MEDIA_URLS + ) + def test_edx_footer_social_links(self): + resp = self.client.get('/') + for name, url in self.SOCIAL_MEDIA_URLS.iteritems(): + self.assertContains(resp, url) + self.assertContains(resp, settings.SOCIAL_MEDIA_FOOTER_DISPLAY[name]['title']) + self.assertContains(resp, settings.SOCIAL_MEDIA_FOOTER_DISPLAY[name]['icon']) diff --git a/pool/shard007/Python/0069835_app_lib.py b/pool/shard007/Python/0069835_app_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..ba038b8ce67c60be97674c83fe99f8e4fd50e05c --- /dev/null +++ b/pool/shard007/Python/0069835_app_lib.py @@ -0,0 +1,75 @@ +"""Class to set App lib directory for current version of Python""" +# standard library +import os +import sys + + +class AppLib: + """Set App Lib Directory""" + + def __init__(self): + """Initialize App properties.""" + self._lib_directories = None + + # All Python Version that will be searched + self.lib_major_version = f'lib_{sys.version_info.major}' + self.lib_minor_version = f'{self.lib_major_version}.{sys.version_info.minor}' + self.lib_micro_version = f'{self.lib_minor_version}.{sys.version_info.micro}' + + def find_lib_directory(self) -> str: + """Find the optimal lib directory.""" + lib_directory = None + if self.lib_micro_version in self.lib_directories: + lib_directory = self.lib_micro_version + elif self.lib_minor_version in self.lib_directories: + lib_directory = self.lib_minor_version + elif self.lib_major_version in self.lib_directories: + lib_directory = self.lib_major_version + else: + for lv in [self.lib_micro_version, self.lib_minor_version, self.lib_major_version]: + for d in self.lib_directories: + if lv in d: + lib_directory = d + break + else: + continue + break + return lib_directory + + @property + def lib_directories(self) -> list: + """Return all "lib_" directories.""" + if self._lib_directories is None: + self._lib_directories = [] + app_path = os.getcwd() + contents = os.listdir(app_path) + for c in contents: + # ensure content starts with lib, is directory, and is readable + if c.startswith('lib') and os.path.isdir(c) and (os.access(c, os.R_OK)): + self._lib_directories.append(c) + return sorted(self._lib_directories, reverse=True) + + def update_path(self) -> None: + """Update sys path to ensure all required modules can be found. + + All Apps must be able to access included modules, this method will ensure that the system + path has been updated to include the "cwd" and the proper "lib_" directories. + """ + lib_directory = self.find_lib_directory() + lib_latest = os.path.join(os.getcwd(), 'lib_latest') + + # insert the appropriate lib_directory into system path if found, otherwise insert + # lib_latest directory into the system Path. This entry will be bumped to index 1 + # after adding the current working directory. + if lib_directory is None: + lib_directory = lib_latest + sys.path.insert(0, os.path.join(os.getcwd(), lib_directory)) + + # insert the current working directory into the system Path for the App, ensuring that it is + # always the first entry in the list. + cwd = os.getcwd() + try: + sys.path.remove(cwd) + except ValueError: + pass + sys.path.insert(0, cwd) diff --git a/pool/shard007/Python/0069849_oss_fs_impl.py b/pool/shard007/Python/0069849_oss_fs_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..a54072d58889cf5cae9f611b06ceb3df19ed25f7 --- /dev/null +++ b/pool/shard007/Python/0069849_oss_fs_impl.py @@ -0,0 +1,107 @@ +# -*- coding: utf-8 -*- +from pyftpdlib.filesystems import FilesystemError +import oss2 + +import oss_file_operation +import defaults + +class OssFsImpl: + + def __init__(self, bucket_name, endpoint, access_id, access_key): + self.bucket_name = bucket_name + self.endpoint = endpoint + self.access_id = access_id + self.access_key = access_key + + self.bucket = oss2.Bucket(oss2.Auth(self.access_id, self.access_key), self.endpoint, self.bucket_name, app_name=defaults.app_name) + self.size_cache = {} + self.dir_cache = {} + + def is_bucket(self, path): + phyPath = path.rstrip('/') + index = phyPath.rfind('/') + if index == 0 and not self.is_root(path): + return True + return False + + def is_root(self, path): + return path == '/' + + def get_oss_bucket_name(self, path): + if self.is_root(path): + return u'/' + phyPath = path.rstrip('/') + index = phyPath.find('/', 1) + if index <= 0: + return phyPath[1:] + else: + return phyPath[1:index] + + def get_file_name(self, path): + if self.is_bucket(path): + return "" + if path == '/': + return u'/' + bucket = self.get_oss_bucket_name(path) + return path[len(bucket)+2:] + + def normalize_separate_char(self, path): + normalized_path_name = path.replace('\\', '/') + return normalized_path_name + + def get_bucket(self, path): + path = self.normalize_separate_char(path) + bucket_name = self.get_oss_bucket_name(path) + bucket = oss2.Bucket(oss2.Auth(self.access_id, self.access_key), self.endpoint, bucket_name, app_name=defaults.app_name) + return bucket + + def get_object(self, path): + path = self.normalize_separate_char(path) + object = self.get_file_name(path) + return object + + def get_file_operation_instance(self, path): + return oss_file_operation.OssFileOperation(self.get_bucket(path), self.get_object(path), self.size_cache, self.dir_cache) + + def open_read(self, path): + return self.get_file_operation_instance(path).open_read() + + def open_write(self, path): + return self.get_file_operation_instance(path) + + def mkdir(self, path): + return self.get_file_operation_instance(path).mkdir() + + def infopath(self, path): + return get_file_operation_instance(path).infopath() + + def listdir(self, path): + return self.get_file_operation_instance(path).listdir() + + def rmdir(self, path): + return self.get_file_operation_instance(path).rmdir() + + def remove(self, path): + return self.get_file_operation_instance(path).remove() + + def rename(self, path1, path2): + raise FilesystemError("method rename not implied") + + def getsize(self, path): + return self.get_file_operation_instance(path).getsize() + + def getmtime(self, path): + return self.get_file_operation_instance(path).getmtime() + + def isfile(self, path): + return self.get_file_operation_instance(path).isfile() + + def isdir(self, path): + path = self.normalize_separate_char(path) + if self.is_bucket(path): + return True + if self.is_root(path): + return True + return self.get_file_operation_instance(path).isdir() + def lexists(self, path): + return self.isfile(path) or self.isdir(path) diff --git a/pool/shard007/Python/0069854_makeTestFile.py b/pool/shard007/Python/0069854_makeTestFile.py new file mode 100644 index 0000000000000000000000000000000000000000..711a6e14e96e71cee746fe9ba1a28004513b2f1f --- /dev/null +++ b/pool/shard007/Python/0069854_makeTestFile.py @@ -0,0 +1,34 @@ +#!/usr/bin/pyhton + +import os +ls = os.linesep + +# get filename +fname = raw_input("input fname: ") + +while True: + if os.path.exists(fname): + print "Error: '%s' already exist" %fname + fname = raw_input("input fname: ") + else: + break + +#get file content(test) lines + +all = [] +print "\nEnter lines ('.' by itself to quit).\n" + +#loop until user terminates input +while True: + entry = raw_input('>') + if entry == '.': + break; + else: + all.append(entry) + +#write lines to file with proper line_endling +fobj = open(fname, 'w') +fobj.writelines(['%s%s' % (x, ls) for x in all]) +fobj.close() + +print 'DONE' diff --git a/pool/shard007/Python/0069869_base.py b/pool/shard007/Python/0069869_base.py new file mode 100644 index 0000000000000000000000000000000000000000..2d4dc1c3a7db5b99074a3f7da5c6f7cc3fda1ab8 --- /dev/null +++ b/pool/shard007/Python/0069869_base.py @@ -0,0 +1,57 @@ +# Copyright 2014 Tesora, Inc. +# All Rights Reserved. +# +# 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. +# + +import abc + +import six +from trove.guestagent.strategy import Strategy + + +@six.add_metaclass(abc.ABCMeta) +class Replication(Strategy): + """Base class for Replication Strategy implementation.""" + + __strategy_type__ = 'replication' + __strategy_ns__ = 'trove.guestagent.strategies.replication' + + def __init__(self, context): + self.context = context + super(Replication, self).__init__() + + @abc.abstractmethod + def get_master_ref(self, service, snapshot_info): + """Get reference to master site for replication strategy.""" + + @abc.abstractmethod + def snapshot_for_replication(self, context, service, location, + snapshot_info): + """Capture snapshot of master db.""" + + @abc.abstractmethod + def enable_as_master(self, service, snapshot_info): + """Configure underlying database to act as master for replication.""" + + @abc.abstractmethod + def enable_as_slave(self, service, snapshot): + """Configure underlying database as a slave of the given master.""" + + @abc.abstractmethod + def detach_slave(self, service): + """Turn off replication on a slave site.""" + + @abc.abstractmethod + def demote_master(self, service): + """Turn off replication on a master site.""" diff --git a/pool/shard007/Python/0069871_bignum.py b/pool/shard007/Python/0069871_bignum.py new file mode 100644 index 0000000000000000000000000000000000000000..010225bbcd686d617ecaef8017d0308d6949761b --- /dev/null +++ b/pool/shard007/Python/0069871_bignum.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +# +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. +"""Big number routines. + +This file is copied from python-bitcoinlib. +""" + +import struct + + +# generic big endian MPI format + +def bn_bytes(v, have_ext=False): + ext = 0 + if have_ext: + ext = 1 + return ((v.bit_length() + 7) // 8) + ext + + +def bn2bin(v): + s = bytearray() + i = bn_bytes(v) + while i > 0: + s.append((v >> ((i - 1) * 8)) & 0xff) + i -= 1 + return s + + +def bn2mpi(v): + have_ext = False + if v.bit_length() > 0: + have_ext = (v.bit_length() & 0x07) == 0 + + neg = False + if v < 0: + neg = True + v = -v + + s = struct.pack(b">I", bn_bytes(v, have_ext)) + ext = bytearray() + if have_ext: + ext.append(0) + v_bin = bn2bin(v) + if neg: + if have_ext: + ext[0] |= 0x80 + else: + v_bin[0] |= 0x80 + return s + ext + v_bin + + +# bitcoin-specific little endian format, with implicit size + + +def mpi2vch(s): + r = s[4:] # strip size + r = r[::-1] # reverse string, converting BE->LE + return r + + +def bn2vch(v): + return bytes(mpi2vch(bn2mpi(v))) diff --git a/pool/shard007/Python/0069873_test_soft_validation.py b/pool/shard007/Python/0069873_test_soft_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..2177bd76c93f201fd885561d5aa6922748fa25c6 --- /dev/null +++ b/pool/shard007/Python/0069873_test_soft_validation.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python +# +# spyne - Copyright (C) Spyne contributors. +# +# 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. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 +# + +# +# Most of the service tests are performed through the interop tests. +# + +import unittest + +from spyne.application import Application +from spyne.decorator import srpc +from spyne.error import ValidationError +from spyne.service import Service +from spyne.protocol.http import HttpRpc +from spyne.protocol.soap import Soap11 +from spyne.model.primitive import Integer +from spyne.model.primitive import String +from spyne.server import ServerBase +from spyne.server.wsgi import WsgiApplication + +from spyne import MethodContext +from spyne.server.wsgi import WsgiMethodContext + +Application.transport = 'test' + + +class TestValidationString(unittest.TestCase): + def test_min_len(self): + StrictType = String(min_len=3) + + self.assertEqual(StrictType.validate_string(StrictType, 'aaa'), True) + self.assertEqual(StrictType.validate_string(StrictType, 'a'), False) + + def test_max_len(self): + StrictType = String(max_len=3) + + self.assertEqual(StrictType.validate_string(StrictType, 'a'), True) + self.assertEqual(StrictType.validate_string(StrictType, 'aaa'), True) + self.assertEqual(StrictType.validate_string(StrictType, 'aaaa'), False) + + def test_pattern(self): + # Pattern match needs to be checked after the string is decoded, that's + # why we need to use validate_native here. + StrictType = String(pattern='[a-z]') + + self.assertEqual(StrictType.validate_native(StrictType, 'a'), True) + self.assertEqual(StrictType.validate_native(StrictType, 'a1'), False) + self.assertEqual(StrictType.validate_native(StrictType, '1'), False) + + +class TestValidationInteger(unittest.TestCase): + def test_lt(self): + StrictType = Integer(lt=3) + + self.assertEqual(StrictType.validate_native(StrictType, 2), True) + self.assertEqual(StrictType.validate_native(StrictType, 3), False) + + def test_le(self): + StrictType = Integer(le=3) + + self.assertEqual(StrictType.validate_native(StrictType, 2), True) + self.assertEqual(StrictType.validate_native(StrictType, 3), True) + self.assertEqual(StrictType.validate_native(StrictType, 4), False) + + def test_gt(self): + StrictType = Integer(gt=3) + + self.assertEqual(StrictType.validate_native(StrictType, 4), True) + self.assertEqual(StrictType.validate_native(StrictType, 3), False) + + def test_ge(self): + StrictType = Integer(ge=3) + + self.assertEqual(StrictType.validate_native(StrictType, 3), True) + self.assertEqual(StrictType.validate_native(StrictType, 2), False) + +class TestHttpRpcSoftValidation(unittest.TestCase): + def setUp(self): + class SomeService(Service): + @srpc(String(pattern='a')) + def some_method(s): + pass + @srpc(String(pattern='a', max_occurs=2)) + def some_other_method(s): + pass + + self.application = Application([SomeService], + in_protocol=HttpRpc(validator='soft'), + out_protocol=Soap11(), + name='Service', tns='tns', + ) + + + def __get_ctx(self, mn, qs): + server = WsgiApplication(self.application) + ctx = WsgiMethodContext(server, { + 'QUERY_STRING': qs, + 'PATH_INFO': '/%s' % mn, + 'REQUEST_METHOD': "GET", + 'SERVER_NAME': 'localhost', + }, 'some-content-type') + + ctx, = server.generate_contexts(ctx) + server.get_in_object(ctx) + + return ctx + + def test_http_rpc(self): + ctx = self.__get_ctx('some_method', 's=1') + self.assertEqual(ctx.in_error.faultcode, 'Client.ValidationError') + + ctx = self.__get_ctx('some_method', 's=a') + self.assertEqual(ctx.in_error, None) + + ctx = self.__get_ctx('some_other_method', 's=1') + self.assertEqual(ctx.in_error.faultcode, 'Client.ValidationError') + ctx = self.__get_ctx('some_other_method', 's=1&s=2') + self.assertEqual(ctx.in_error.faultcode, 'Client.ValidationError') + ctx = self.__get_ctx('some_other_method', 's=1&s=2&s=3') + self.assertEqual(ctx.in_error.faultcode, 'Client.ValidationError') + ctx = self.__get_ctx('some_other_method', 's=a&s=a&s=a') + self.assertEqual(ctx.in_error.faultcode, 'Client.ValidationError') + + ctx = self.__get_ctx('some_other_method', 's=a&s=a') + self.assertEqual(ctx.in_error, None) + ctx = self.__get_ctx('some_other_method', 's=a') + self.assertEqual(ctx.in_error, None) + ctx = self.__get_ctx('some_other_method', '') + self.assertEqual(ctx.in_error, None) + +class TestSoap11SoftValidation(unittest.TestCase): + def test_basic(self): + class SomeService(Service): + @srpc(String(pattern='a')) + def some_method(s): + pass + + application = Application([SomeService], + in_protocol=Soap11(validator='soft'), + out_protocol=Soap11(), + name='Service', tns='tns', + ) + server = ServerBase(application) + + ctx = MethodContext(server, MethodContext.SERVER) + ctx.in_string = [u""" + + + + OK + + + + """] + + ctx, = server.generate_contexts(ctx) + server.get_in_object(ctx) + + self.assertEqual(isinstance(ctx.in_error, ValidationError), True) + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard007/Python/0069877_project.py b/pool/shard007/Python/0069877_project.py new file mode 100644 index 0000000000000000000000000000000000000000..a762d6ccaec89023166f78d893b9ef465f47e2bc --- /dev/null +++ b/pool/shard007/Python/0069877_project.py @@ -0,0 +1,158 @@ +""" +sentry.models.project +~~~~~~~~~~~~~~~~~~~~~ + +:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details. +:license: BSD, see LICENSE for more details. +""" + +from django.conf import settings +from django.core.urlresolvers import reverse +from django.db import models +from django.db.models import F +from django.utils import timezone +from django.utils.translation import ugettext_lazy as _ + +from sentry.constants import ( + PLATFORM_TITLES, PLATFORM_LIST, STATUS_VISIBLE, STATUS_HIDDEN +) +from sentry.db.models import ( + Model, BoundedPositiveIntegerField, sane_repr +) +from sentry.db.models.utils import slugify_instance +from sentry.manager import ProjectManager +from sentry.utils.http import absolute_uri + + +class Project(Model): + """ + Projects are permission based namespaces which generally + are the top level entry point for all data. + + A project may be owned by only a single team, and may or may not + have an owner (which is thought of as a project creator). + """ + PLATFORM_CHOICES = tuple( + (p, PLATFORM_TITLES.get(p, p.title())) + for p in PLATFORM_LIST + ) + (('other', 'Other'),) + + slug = models.SlugField(null=True) + name = models.CharField(max_length=200) + owner = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="sentry_owned_project_set", null=True) + team = models.ForeignKey('sentry.Team', null=True) + public = models.BooleanField(default=False) + date_added = models.DateTimeField(default=timezone.now) + status = BoundedPositiveIntegerField(default=0, choices=( + (STATUS_VISIBLE, _('Visible')), + (STATUS_HIDDEN, _('Hidden')), + ), db_index=True) + platform = models.CharField(max_length=32, choices=PLATFORM_CHOICES, null=True) + + objects = ProjectManager(cache_fields=[ + 'pk', + 'slug', + ]) + + class Meta: + app_label = 'sentry' + db_table = 'sentry_project' + unique_together = (('team', 'slug'),) + + __repr__ = sane_repr('team_id', 'slug', 'owner_id') + + def __unicode__(self): + return u'%s (%s)' % (self.name, self.slug) + + def save(self, *args, **kwargs): + if not self.slug: + slugify_instance(self, self.name, team=self.team) + super(Project, self).save(*args, **kwargs) + + def get_absolute_url(self): + return absolute_uri(reverse('sentry-stream', args=[ + self.team.slug, self.slug])) + + def merge_to(self, project): + from sentry.models import ( + Group, GroupCountByMinute, GroupTag, Event, TagValue + ) + + if not isinstance(project, Project): + project = Project.objects.get_from_cache(pk=project) + + for group in Group.objects.filter(project=self): + try: + other = Group.objects.get( + project=project, + logger=group.logger, + culprit=group.culprit, + checksum=group.checksum, + ) + except Group.DoesNotExist: + group.update(project=project) + for model in (Event, GroupTag, GroupCountByMinute): + model.objects.filter(project=self, group=group).update(project=project) + else: + Event.objects.filter(group=group).update(group=other) + + for obj in GroupTag.objects.filter(group=group): + obj2, created = GroupTag.objects.get_or_create( + project=project, + group=group, + key=obj.key, + value=obj.value, + defaults={'times_seen': obj.times_seen} + ) + if not created: + obj2.update(times_seen=F('times_seen') + obj.times_seen) + + for obj in GroupCountByMinute.objects.filter(group=group): + obj2, created = GroupCountByMinute.objects.get_or_create( + project=project, + group=group, + date=obj.date, + defaults={ + 'times_seen': obj.times_seen, + 'time_spent_total': obj.time_spent_total, + 'time_spent_count': obj.time_spent_count, + } + ) + if not created: + obj2.update( + times_seen=F('times_seen') + obj.times_seen, + time_spent_total=F('time_spent_total') + obj.time_spent_total, + time_spent_count=F('time_spent_count') + obj.time_spent_count, + ) + + for fv in TagValue.objects.filter(project=self): + TagValue.objects.get_or_create(project=project, key=fv.key, value=fv.value) + fv.delete() + self.delete() + + def is_default_project(self): + return str(self.id) == str(settings.SENTRY_PROJECT) or str(self.slug) == str(settings.SENTRY_PROJECT) + + def get_tags(self): + from sentry.models import TagKey + + if not hasattr(self, '_tag_cache'): + tags = self.get_option('tags', None) + if tags is None: + tags = [ + t for t in TagKey.objects.all_keys(self) + if not t.startswith('sentry:') + ] + self._tag_cache = tags + return self._tag_cache + + # TODO: Make these a mixin + def update_option(self, *args, **kwargs): + from sentry.models import ProjectOption + + return ProjectOption.objects.set_value(self, *args, **kwargs) + + def get_option(self, *args, **kwargs): + from sentry.models import ProjectOption + + return ProjectOption.objects.get_value(self, *args, **kwargs) diff --git a/pool/shard007/Python/0069879_noprocess.py b/pool/shard007/Python/0069879_noprocess.py new file mode 100644 index 0000000000000000000000000000000000000000..6526f795090ff26453e9d18a92b206d603755128 --- /dev/null +++ b/pool/shard007/Python/0069879_noprocess.py @@ -0,0 +1,67 @@ +# Copyright (C) 2013 by Clearcode +# and associates (see AUTHORS). + +# This file is part of pytest-mysql. + +# pytest-mysql 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. + +# pytest-mysql 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 pytest-mysql. If not, see . +"""Process fixture factory for MySQL database.""" + +import os +from warnings import warn + +import pytest +from _pytest.fixtures import FixtureRequest + +from pytest_mysql.config import get_config +from pytest_mysql.executor_noop import NoopMySQLExecutor + + +def mysql_noproc(host=None, port=None, user=None): + """ + Process fixture factory for MySQL server. + + :param str host: hostname + :param int port: port name + :param str user: user name + :rtype: func + :returns: function which makes a redis process + + """ + + @pytest.fixture(scope="session") + def mysql_noproc_fixture(request: FixtureRequest): + """ + Process fixture for MySQL server. + + #. Get config. + + :param request: fixture request object + :rtype: pytest_dbfixtures.executors.TCPExecutor + :returns: tcp executor + + """ + config = get_config(request) + mysql_port = int(port or config["port"] or 3306) + mysql_host = host or config["host"] + mysql_user = user or config["user"] or "root" + + mysql_executor = NoopMySQLExecutor( + user=mysql_user, + host=mysql_host, + port=mysql_port, + ) + with mysql_executor: + yield mysql_executor + + return mysql_noproc_fixture diff --git a/pool/shard007/Python/0069885_41f6a59a61f2_database_options_for_sql_lab.py b/pool/shard007/Python/0069885_41f6a59a61f2_database_options_for_sql_lab.py new file mode 100644 index 0000000000000000000000000000000000000000..484d0935dd4210332b54edf12dd758dc28349ba4 --- /dev/null +++ b/pool/shard007/Python/0069885_41f6a59a61f2_database_options_for_sql_lab.py @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +"""database options for sql lab + +Revision ID: 41f6a59a61f2 +Revises: 3c3ffe173e4f +Create Date: 2016-08-31 10:26:37.969107 + +""" +from alembic import op +import sqlalchemy as sa + +# revision identifiers, used by Alembic. +revision = '41f6a59a61f2' +down_revision = '3c3ffe173e4f' + + +def upgrade(): + op.add_column('dbs', sa.Column('allow_ctas', sa.Boolean(), nullable=True)) + op.add_column( + 'dbs', sa.Column('expose_in_sqllab', sa.Boolean(), nullable=True)) + op.add_column( + 'dbs', + sa.Column('force_ctas_schema', sa.String(length=250), nullable=True)) + + +def downgrade(): + op.drop_column('dbs', 'force_ctas_schema') + op.drop_column('dbs', 'expose_in_sqllab') + op.drop_column('dbs', 'allow_ctas') diff --git a/pool/shard007/Python/0069886_class_service.py b/pool/shard007/Python/0069886_class_service.py new file mode 100644 index 0000000000000000000000000000000000000000..a825d6fa1570d26b30688585ac5a9d04cfd9ba28 --- /dev/null +++ b/pool/shard007/Python/0069886_class_service.py @@ -0,0 +1,61 @@ +# +# PyWO - Python Window Organizer +# Copyright 2010, Wojciech 'KosciaK' Pietrzok +# +# This file is part of PyWO. +# +# PyWO 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. +# +# PyWO 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 PyWO. If not, see . +# + +"""module_service.py - example of pywo.service plugin.""" + +import logging +import threading + +from pywo import services + + +__author__ = "Wojciech 'KosciaK' Pietrzok" + + +# NOTE: Use logger in 'pywo.services.*' hierarchy! +log = logging.getLogger('pywo.services.' + __name__) + + +class Clock(services.Service): + + def __init__(self): + self.timer = None + self.minutes = 0 + + def setup(self, config): + log.debug('Setting up clock') + self.minutes = 0 + self.timer = threading.Timer(60, self._show_time) + + def start(self): + log.info('Starting clock') + self.timer.start() + + def stop(self): + log.info('Stopping clock') + self.timer.cancel() + + def _show_time(self): + self.minutes += 1 + log.info('You are using PyWO for %s minute(s)' % self.minutes) + self.timer = threading.Timer(60, self._show_time) + self.timer.start() + + diff --git a/pool/shard007/Python/0069891_while_loop.py b/pool/shard007/Python/0069891_while_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..39817314a1cfd25652a248139cb77328556043ab --- /dev/null +++ b/pool/shard007/Python/0069891_while_loop.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 + +import sys + +if __name__ == '__main__': + a_str = sys.argv[1] + b_str = sys.argv[2] + a = int(a_str) + b = int(b_str) + while ( a <= b ): + print("a = " + str(a) + "(b=" + str(b) + ")") + a = a + 1 diff --git a/pool/shard007/Python/0069898_GlobalRRD.py b/pool/shard007/Python/0069898_GlobalRRD.py new file mode 100644 index 0000000000000000000000000000000000000000..ada665c679b34ea1466331e078d2a377c0f563e4 --- /dev/null +++ b/pool/shard007/Python/0069898_GlobalRRD.py @@ -0,0 +1,47 @@ +import os +import subprocess +from RRD import RRD, DS, RRA + +class GlobalRRD(RRD): + ds_list = [ + # Number of nodes available + DS('nodes', 'GAUGE', 120, 0, float('NaN')), + # Number of client available + DS('clients', 'GAUGE', 120, 0, float('NaN')), + ] + rra_list = [ + RRA('AVERAGE', 0.5, 1, 120), # 2 hours of 1 minute samples + RRA('AVERAGE', 0.5, 60, 744), # 31 days of 1 hour samples + RRA('AVERAGE', 0.5, 1440, 1780),# ~5 years of 1 day samples + ] + + def __init__(self, directory): + super().__init__(os.path.join(directory, "nodes.rrd")) + self.ensureSanity(self.ds_list, self.rra_list, step=60) + + def update(self, nodeCount, clientCount): + super().update({'nodes': nodeCount, 'clients': clientCount}) + + def graph(self, filename, timeframe): + args = ["rrdtool", 'graph', filename, + '-s', '-' + timeframe, + '-w', '1100', + '-h' '600', + 'DEF:nodes=' + self.filename + ':nodes:AVERAGE', + 'LINE1:nodes#F00:nodes\\l', + 'DEF:clients=' + self.filename + ':clients:AVERAGE', + 'LINE2:clients#00F:clients', + ] + subprocess.check_output(args) + + def graphMonthly(self, filename, timeframe): + args = ["rrdtool", 'graph', filename, + '-s', '-' + timeframe, + '-w', '4800', + '-h' '600', + 'DEF:nodes=' + self.filename + ':nodes:AVERAGE', + 'LINE1:nodes#F00:nodes\\l', + 'DEF:clients=' + self.filename + ':clients:AVERAGE', + 'LINE2:clients#00F:clients', + ] + subprocess.check_output(args) diff --git a/pool/shard007/Python/0069907_conf.py b/pool/shard007/Python/0069907_conf.py new file mode 100644 index 0000000000000000000000000000000000000000..90620340111d79c4d848234f550a55ba68d04a0c --- /dev/null +++ b/pool/shard007/Python/0069907_conf.py @@ -0,0 +1,275 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# steem_graph documentation build configuration file, created by +# sphinx-quickstart on Tue Jul 9 22:26:36 2013. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys +import os + +# If extensions (or modules to document with autodoc) are in another +# directory, add these directories to sys.path here. If the directory is +# relative to the documentation root, use os.path.abspath to make it +# absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# Get the project root dir, which is the parent dir of this +cwd = os.getcwd() +project_root = os.path.dirname(cwd) + +# Insert the project root dir as the first element in the PYTHONPATH. +# This lets us ensure that the source package is imported, and that its +# version is used. +sys.path.insert(0, project_root) + +import steem_graph + +# -- General configuration --------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'steem_graph' +copyright = u"2017, Marnee Dearman" + +# The version info for the project you're documenting, acts as replacement +# for |version| and |release|, also used in various other places throughout +# the built documents. +# +# The short X.Y version. +version = steem_graph.__version__ +# The full version, including alpha/beta/rc tags. +release = steem_graph.__version__ + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to +# some non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +#default_role = None + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + +# If true, keep warnings as "system message" paragraphs in the built +# documents. +#keep_warnings = False + + +# -- Options for HTML output ------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a +# theme further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as +# html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the +# top of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon +# of the docs. This file should be a Windows icon file (.ico) being +# 16x16 or 32x32 pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) +# here, relative to this directory. They are copied after the builtin +# static files, so a file named "default.css" will overwrite the builtin +# "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page +# bottom, using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names +# to template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. +# Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. +# Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages +# will contain a tag referring to it. The value of this option +# must be the base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'steem_graphdoc' + + +# -- Options for LaTeX output ------------------------------------------ + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + #'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + #'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + #'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass +# [howto/manual]). +latex_documents = [ + ('index', 'steem_graph.tex', + u'steem_graph Documentation', + u'Marnee Dearman', 'manual'), +] + +# The name of an image file (relative to this directory) to place at +# the top of the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings +# are parts, not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output ------------------------------------ + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'steem_graph', + u'steem_graph Documentation', + [u'Marnee Dearman'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ---------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'steem_graph', + u'steem_graph Documentation', + u'Marnee Dearman', + 'steem_graph', + 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' + +# If true, do not generate a @detailmenu in the "Top" node's menu. +#texinfo_no_detailmenu = False diff --git a/pool/shard007/Python/0069912_service.py b/pool/shard007/Python/0069912_service.py new file mode 100644 index 0000000000000000000000000000000000000000..daa072ea96cfae934ff8f4fc933578639e873977 --- /dev/null +++ b/pool/shard007/Python/0069912_service.py @@ -0,0 +1,66 @@ +"""ShortUrlApi API implemented using Google Cloud Endpoints.""" + +import appengine_config +import endpoints + +from endpoints import api_config +from protorpc import remote +from api import service_impl +from api.proto_api import CreateRequest +from api.proto_api import GetRequest +from api.proto_api import RegisterRequest +from api.proto_api import Response + +_AUTH_CONFIG = api_config.ApiAuth(allow_cookie_auth=True) + + +@endpoints.api(name='pgurin', version='v1', + description='Prediction Short URL API', + title='PGurin service', + auth=_AUTH_CONFIG, owner_name='PredictionGuru', + owner_domain='pgur.in') +class ShortUrlApi(remote.Service): + + """Class which defines pgurin API v1.""" + # pylint: disable=R0201 + @endpoints.method(RegisterRequest, Response, + path='register', name='pgur.register') + def register(self, request): + """ + Register device store url as well as default url in order to redirect, + if no local application found or desktop / someother device browser. + """ + success, reason, token = service_impl.register(request) + return Response(success=success, reason=reason, token=token) + + @endpoints.method(RegisterRequest, Response, + path='update', name='pgur.update') + def update(self, request): + """ + Update device store url as well as default url in order to redirect, + if no local application found or desktop / some other device browser. + """ + success, reason = service_impl.update(request) + return Response(success=success, reason=reason) + + @endpoints.method(CreateRequest, Response, + path='url/create', name='pgur.create') + def url_create(self, request): + """Create Short url from given details""" + success, reason, url_uid = service_impl.create(request) + if success: + short_url = appengine_config.WEBSITE + if request.is_claim: + short_url += 'claim/' + short_url += url_uid + return Response( + short_url=short_url, url_uid=url_uid, success=success) + return Response(success=success, reason=reason) + + @endpoints.method(GetRequest, Response, + path='get', name='pgur.get') + def get(self, request): + """Return data from given ip address or url id.""" + success, reason, data, url_uid = service_impl.get(request) + return Response( + success=success, reason=reason, data=data, url_uid=url_uid) diff --git a/pool/shard007/Python/0069915_lda_models.py b/pool/shard007/Python/0069915_lda_models.py new file mode 100644 index 0000000000000000000000000000000000000000..008faaacceebd728677082611b57e2ab41e4ffb0 --- /dev/null +++ b/pool/shard007/Python/0069915_lda_models.py @@ -0,0 +1,194 @@ +# coding=utf-8 +# Copyright 2022 The Google Research Authors. +# +# 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. + +"""Transformers for performing inference in the LDA generative model. +""" +from functools import partial + +from . import transformer +from . import util + +import flax +from flax.deprecated import nn +import jax +import jax.numpy as jnp +import jax.random + + +class Embedding(nn.Module): + + def apply(self, + inputs, + num_embeddings, + embedding_dim, + weight_init=nn.initializers.normal(stddev=1.0)): + """Applies Embedding module. + + Args: + inputs: input data + num_embeddings: The number of embedding vectors. + embedding_dim: The size of the embedding dimension. + weight_init: embedding initializer + Returns: + output: embedded input data + """ + embedding = self.param("embedding", (num_embeddings, embedding_dim), + weight_init) + if inputs.dtype not in [jnp.int32, jnp.int64, jnp.uint32, jnp.uint64]: + raise ValueError("Input type must be an integer or unsigned integer.") + return jnp.take(embedding, inputs, axis=0) + + +class SequenceEmbedding(nn.Module): + + def apply(self, + input_seq, + num_embeddings=3000, + embedding_dim=512, + weight_init=nn.initializers.normal(stddev=1.)): + embeddings = Embedding(input_seq, num_embeddings, embedding_dim, + weight_init=weight_init) + return jnp.sum(embeddings, axis=-2) + + +class LDATopicWordInferenceMachine(nn.Module): + + def apply(self, + documents, + topic_params, + num_topics=50, + vocab_size=30000, + num_heads=8, + num_encoders=6, + num_decoders=6, + qkv_dim=512, + embedding_dim=512, + activation_fn=flax.deprecated.nn.relu, + weight_init=jax.nn.initializers.xavier_uniform(), + embedding_init=jax.nn.initializers.normal(stddev=1.0)): + batch_size, num_documents, _ = documents.shape + + # [batch_size, num_documents, doc_length, embedding_dim] + doc_word_embeddings = Embedding( + documents, num_embeddings=vocab_size, embedding_dim=embedding_dim, + weight_init=embedding_init) + # [batch_size, num_documents, embedding_dim] + doc_embeddings = jnp.sum(doc_word_embeddings, axis=-2) + # out_topics will be [batch_size, num_topics, vocab_size] + out_raw_topic_params = transformer.EncoderDecoderTransformer( + doc_embeddings, + jnp.full([batch_size], num_documents), + jnp.full([batch_size], num_topics), + targets=topic_params, + target_dim=vocab_size, + max_input_length=num_documents, + max_target_length=num_topics, + num_heads=num_heads, + num_encoders=num_encoders, + qkv_dim=qkv_dim, + activation_fn=activation_fn, + weight_init=weight_init) + + # softmax the last dimension of the topic params to make each vector sum + # to one. + out_topic_params = jax.nn.softmax(out_raw_topic_params, axis=-1) + + return out_topic_params + + @classmethod + def loss(cls, params, key, documents, topic_params): + batch_size, num_topics, _ = topic_params.shape + pred_topic_params = cls.call( + params, documents, topic_params=topic_params) + + wasserstein_dist, _ = jax.vmap( + util.atomic_sinkhorn, in_axes=(0, None, 0, None, 0))( + topic_params, jnp.zeros(num_topics) - jnp.log(num_topics), + pred_topic_params, jnp.zeros(num_topics) - jnp.log(num_topics), + jax.random.split(key, num=batch_size)) + + return wasserstein_dist + + +class LDADocTopicInferenceMachine(nn.Module): + + def apply(self, + documents, + topic_params, + doc_topic_proportions, + num_topics=50, + vocab_size=30000, + num_heads=8, + num_encoders=6, + num_decoders=6, + qkv_dim=512, + embedding_dim=512, + activation_fn=flax.deprecated.nn.relu, + weight_init=jax.nn.initializers.xavier_uniform(), + embedding_init=jax.nn.initializers.normal(stddev=1.0)): + """ + Args: + documents: [batch_size, doc_length] integer Tensor. + topic_params: [batch_size, num_topics, vocab_size] float Tensor. + doc_topic_proportions: [batch_size, num_topics] float Tensor. + """ + + batch_size, doc_length = documents.shape + + embedding = Embedding.shared( + num_embeddings=vocab_size, embedding_dim=embedding_dim, + weight_init=embedding_init, name="word_embedding") + + # [batch_size, doc_length, embedding_dim] + doc_word_embeddings = embedding(documents) + + # embedded_topics will be [batch_size, num_topics, embedding_dim] + embedded_topics = flax.deprecated.nn.Dense( + topic_params, features=embedding_dim, kernel_init=weight_init) + + # concatenate the document and topic embeddings to produce + # [batch_size, document_length + num_topics, embedding_dim] + doc_topic_input = jnp.concatenate( + [doc_word_embeddings, embedded_topics], axis=1) + + # feed the doc_topic_input into a transformer to produce the + # [batch_size, num_topics, 1] document-topic proportions. + out_doc_topics = transformer.EncoderDecoderTransformer( + doc_topic_input, + jnp.full([batch_size], doc_length + num_topics), + jnp.full([batch_size], num_topics), + targets=doc_topic_proportions[Ellipsis, jnp.newaxis], + target_dim=1, + max_input_length=doc_length + num_topics, + max_target_length=num_topics, + num_heads=num_heads, + num_encoders=num_encoders, + qkv_dim=qkv_dim, + activation_fn=activation_fn, + weight_init=weight_init) + + return jnp.squeeze(out_doc_topics, axis=2) + + @classmethod + def loss(cls, params, key, documents, topic_params, doc_topic_proportions): + pred_doc_topic_proportions = cls.call( + params, documents, topic_params=topic_params, + doc_topic_proportions=doc_topic_proportions) + + pred_doc_topic_logprobs = jax.nn.log_softmax(pred_doc_topic_proportions, + axis=-1) + doc_topic_loss = util.categorical_kl(doc_topic_proportions, + pred_doc_topic_logprobs) + return doc_topic_loss diff --git a/pool/shard007/Python/0069922_projector.py b/pool/shard007/Python/0069922_projector.py new file mode 100644 index 0000000000000000000000000000000000000000..475f40568861b0aa1953c1968379cc17785bb11f --- /dev/null +++ b/pool/shard007/Python/0069922_projector.py @@ -0,0 +1,92 @@ +# -*- coding: utf-8 -*- +"""Utility class that projects variants from one transcript to another +via a common reference sequence. + +""" + +from __future__ import absolute_import, division, print_function, unicode_literals + +import copy + +import hgvs +import hgvs.alignmentmapper + + +class Projector(object): + """ + The Projector class implements liftover between two transcripts via a + common reference sequence. + + :param hdp: HGVS Data Provider Interface-compliant instance (see :class:`hgvs.dataproviders.interface.Interface`) + :param ref: string representing the common reference assembly (e.g., GRCh37.p10) + :param src_ac: string representing the source transcript accession (e.g., NM_000551.2) + :param dst_ac: string representing the destination transcript accession (e.g., NM_000551.3) + :param src_alt_aln_method: string representing the source transcript alignment method + :param dst_alt_aln_method: string representing the destination transcript alignment method + + This class assumes (and verifies) that the transcripts are on the same + strand. This assumption obviates some work in flipping sequence + variants twice unnecessarily. + """ + + def __init__(self, + hdp, + alt_ac, + src_ac, + dst_ac, + src_alt_aln_method=hgvs.global_config.mapping.alt_aln_method, + dst_alt_aln_method=hgvs.global_config.mapping.alt_aln_method): + self.hdp = hdp + self.alt_ac = alt_ac + self.src_tm = hgvs.alignmentmapper.AlignmentMapper(hdp, src_ac, alt_ac, src_alt_aln_method) + self.dst_tm = hgvs.alignmentmapper.AlignmentMapper(hdp, dst_ac, alt_ac, dst_alt_aln_method) + + def project_interval_forward(self, c_interval): + """ + project c_interval on the source transcript to the + destination transcript + + :param c_interval: an :class:`hgvs.interval.Interval` object on the source transcript + :returns: c_interval: an :class:`hgvs.interval.Interval` object on the destination transcript + """ + return self.dst_tm.g_to_c(self.src_tm.c_to_g(c_interval)) + + def project_interval_backward(self, c_interval): + """ + project c_interval on the destination transcript to the + source transcript + + :param c_interval: an :class:`hgvs.interval.Interval` object on the destination transcript + :returns: c_interval: an :class:`hgvs.interval.Interval` object on the source transcript + """ + return self.src_tm.g_to_c(self.dst_tm.c_to_g(c_interval)) + + def project_variant_forward(self, c_variant): + """ + project c_variant on the source transcript onto the destination transcript + + :param c_variant: an :class:`hgvs.sequencevariant.SequenceVariant` object on the source transcript + :returns: c_variant: an :class:`hgvs.sequencevariant.SequenceVariant` object on the destination transcript + """ + if c_variant.ac != self.src_tm.tx_ac: + raise RuntimeError("variant accession does not match that used to initialize " + + __name__) + new_c_variant = copy.deepcopy(c_variant) + new_c_variant.ac = self.dst_tm.tx_ac + new_c_variant.posedit.pos = self.project_interval_forward(c_variant.posedit.pos) + return new_c_variant + + def project_variant_backward(self, c_variant): + """ + project c_variant on the source transcript onto the destination transcript + + :param c_variant: an :class:`hgvs.sequencevariant.SequenceVariant` object on the source transcript + :returns: c_variant: an :class:`hgvs.sequencevariant.SequenceVariant` object on the destination transcript + """ + if c_variant.ac != self.dst_tm.tx_ac: + raise RuntimeError("variant accession does not match that used to initialize " + + __name__) + new_c_variant = copy.deepcopy(c_variant) + new_c_variant.ac = self.src_tm.tx_ac + new_c_variant.posedit.pos = self.project_interval_backward(c_variant.posedit.pos) + return new_c_variant diff --git a/pool/shard007/Python/0069931_common.py b/pool/shard007/Python/0069931_common.py new file mode 100644 index 0000000000000000000000000000000000000000..de423f2dd202115c5438da1234052e209a47813e --- /dev/null +++ b/pool/shard007/Python/0069931_common.py @@ -0,0 +1,55 @@ +import calendar + +import newrelic.agent +import requests +from dateutil import parser +from django.conf import settings + + +def make_request(url, method='GET', headers=None, timeout=30, **kwargs): + """A wrapper around requests to set defaults & call raise_for_status().""" + headers = headers or {} + headers['User-Agent'] = 'treeherder/{}'.format(settings.SITE_HOSTNAME) + # Work around bug 1305768. + if 'queue.taskcluster.net' in url: + headers['x-taskcluster-skip-cache'] = 'true' + response = requests.request(method, + url, + headers=headers, + timeout=timeout, + **kwargs) + + if response.history: + params = { + 'url': url, + 'redirects': len(response.history), + 'duration': sum(r.elapsed.total_seconds() for r in response.history) + } + newrelic.agent.record_custom_event('RedirectedRequest', params=params) + + response.raise_for_status() + return response + + +def fetch_json(url, params=None): + response = make_request(url, + params=params, + headers={'Accept': 'application/json'}) + return response.json() + + +def fetch_text(url): + response = make_request(url) + return response.text + + +def get_guid_root(guid): + """Converts a job_guid with endtime suffix to normal job_guid""" + if "_" in str(guid): + return str(guid).split("_", 1)[0] + return guid + + +def to_timestamp(datestr): + """Converts a date string to a UTC timestamp""" + return calendar.timegm(parser.parse(datestr).utctimetuple()) diff --git a/pool/shard007/Python/0069932_test_collection_provider_detail.py b/pool/shard007/Python/0069932_test_collection_provider_detail.py new file mode 100644 index 0000000000000000000000000000000000000000..fe49fd1337bc7362aa1a1222bc5a7197c730ad81 --- /dev/null +++ b/pool/shard007/Python/0069932_test_collection_provider_detail.py @@ -0,0 +1,67 @@ +import pytest + +from api.base.settings.defaults import API_BASE +from api_tests.providers.mixins import ProviderExistsMixin +from osf_tests.factories import ( + CollectionProviderFactory, +) + + +class TestPreprintProviderExists(ProviderExistsMixin): + provider_class = CollectionProviderFactory + + @pytest.fixture() + def fake_url(self): + return '/{}providers/collections/fake/'.format(API_BASE) + + @pytest.fixture() + def provider_url(self, provider): + return '/{}providers/collections/{}/'.format( + API_BASE, provider._id) + + @pytest.fixture() + def provider_url_two(self, provider_two): + return '/{}providers/collections/{}/'.format( + API_BASE, provider_two._id) + + @pytest.fixture() + def provider_list_url(self, provider): + return '/{}providers/collections/{}/submissions/'.format(API_BASE, provider._id) + + @pytest.fixture() + def provider_list_url_fake(self, fake_url): + return '{}submissions/'.format(fake_url) + + # This overrides the mixin to prevent not-yet-implemented behavior + # TODO [IN-153]: use mixin implmentation + def test_provider_exists(self, app, provider_url, fake_url, provider_list_url, provider_list_url_fake): + detail_res = app.get(provider_url) + assert detail_res.status_code == 200 + + licenses_res = app.get('{}licenses/'.format(provider_url)) + assert licenses_res.status_code == 200 + + #res = app.get(provider_list_url) + #assert res.status_code == 200 + + taxonomies_res = app.get('{}taxonomies/'.format(provider_url)) + assert taxonomies_res.status_code == 200 + + # test_preprint_provider_does_not_exist_returns_404 + detail_res = app.get(fake_url, expect_errors=True) + assert detail_res.status_code == 404 + + licenses_res = app.get( + '{}licenses/'.format(fake_url), + expect_errors=True) + assert licenses_res.status_code == 404 + + res = app.get( + provider_list_url_fake, + expect_errors=True) + assert res.status_code == 404 + + taxonomies_res = app.get( + '{}taxonomies/'.format(fake_url), + expect_errors=True) + assert taxonomies_res.status_code == 404 diff --git a/pool/shard007/Python/0069934_setfattr.py b/pool/shard007/Python/0069934_setfattr.py new file mode 100644 index 0000000000000000000000000000000000000000..4d499152986c395110028067fb005069aeb532d1 --- /dev/null +++ b/pool/shard007/Python/0069934_setfattr.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python +# +# attrz, (C) 2015 Harshavardhana. +# +# 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. + +import os +import sys +from optparse import OptionParser + +import xattr + +def convert(string): + tmp_string = string + if (string[0] == '0' and + (string[1] == 's' or + string[1] == 'S')): + tmp_string = string.strip('%s%s' % + (string[0], + string[1])) + return tmp_string.decode('base64') + + if (string[0] == '0' and + (string[1] == 'x' or + string[1] == 'X')): + tmp_string = string.split('%s%s' % + (string[0], + string[1])) + return tmp_string[1].decode('hex') + + return tmp_string + +if __name__ == '__main__': + usage = "usage: %prog [-n name] [-v value] [-x name]" + parser = OptionParser(usage=usage) + parser.add_option("-n", action="store", dest="name", type="string", + help="Specifies the name of the extended attribute to set.") + parser.add_option("-v", action="store", dest="value", type="string", + help="Specifies the new value of the extended attribute." + " There are three methods available for encoding the value." + " If the given string is enclosed in double quotes, the" + " inner string is treated as text. In that case," + " backslashes and double quotes have special meanings" + " and need to be escaped by a preceding backslash. Any" + " control characters can be encoded as a backslash" + " followed by three digits as its ASCII code in octal." + " If the given string begins with 0x or 0X, it expresses" + " a hexadecimal number. If the given string begins with" + " 0s or 0S, base64 encoding is expected.") + parser.add_option("-x", action="store", dest="xname", type="string", + help="Remove the named extended attribute entirely.") + + (option,args) = parser.parse_args() + if not args: + print ("Usage: setfattr {-n name} [-v value] file...") + print (" setfattr {-x name} file...") + print ("Try `setfattr --help' for more information.") + sys.exit(1) + + if option.name and option.xname: + print ("-n and -x are mutually exclusive...") + sys.exit(1) + + if option.name: + if option.value is None: + print ("-n option requires -v value...") + + args[0] = os.path.abspath(args[0]) + + if option.name and option.value: + try: + xattr.setxattr(args[0], option.name, convert(option.value)) + except Exception as err: + print (err) + sys.exit(1) + + if option.xname: + try: + xattr.removexattr(args[0], option.xname) + except Exception as err: + print (err) + sys.exit(1) diff --git a/pool/shard007/Python/0069935_persons.py b/pool/shard007/Python/0069935_persons.py new file mode 100644 index 0000000000000000000000000000000000000000..57b94d4bb232c10926999f4ab1f9f0081eadb4d2 --- /dev/null +++ b/pool/shard007/Python/0069935_persons.py @@ -0,0 +1,108 @@ +# This file is part of Indico. +# Copyright (C) 2002 - 2019 CERN +# +# Indico is free software; you can redistribute it and/or +# modify it under the terms of the MIT License; see the +# LICENSE file for more details. + +from __future__ import unicode_literals + +from indico.core.db.sqlalchemy import PyIntEnum, db +from indico.modules.events.models.persons import PersonLinkBase +from indico.util.locators import locator_property +from indico.util.string import format_repr, return_ascii +from indico.util.struct.enum import IndicoEnum + + +class AuthorType(int, IndicoEnum): + none = 0 + primary = 1 + secondary = 2 + + @classmethod + def get_highest(cls, *types): + if any(t == cls.primary for t in types): + return cls.primary + elif any(t == cls.secondary for t in types): + return cls.secondary + else: + return cls.none + + +class ContributionPersonLink(PersonLinkBase): + """Association between EventPerson and Contribution.""" + + __tablename__ = 'contribution_person_links' + __auto_table_args = {'schema': 'events'} + person_link_backref_name = 'contribution_links' + person_link_unique_columns = ('contribution_id',) + object_relationship_name = 'contribution' + + contribution_id = db.Column( + db.Integer, + db.ForeignKey('events.contributions.id'), + index=True, + nullable=False + ) + is_speaker = db.Column( + db.Boolean, + nullable=False, + default=False + ) + author_type = db.Column( + PyIntEnum(AuthorType), + nullable=False, + default=AuthorType.none + ) + + # relationship backrefs: + # - contribution (Contribution.person_links) + + @property + def is_submitter(self): + if not self.contribution: + raise Exception("No contribution to check submission rights against") + return self.person.has_role('submit', self.contribution) + + @property + def is_author(self): + return self.author_type != AuthorType.none + + @locator_property + def locator(self): + return dict(self.contribution.locator, person_id=self.id) + + @return_ascii + def __repr__(self): + return format_repr(self, 'id', 'person_id', 'contribution_id', is_speaker=False, author_type=AuthorType.none, + _text=self.full_name) + + +class SubContributionPersonLink(PersonLinkBase): + """Association between EventPerson and SubContribution.""" + + __tablename__ = 'subcontribution_person_links' + __auto_table_args = {'schema': 'events'} + person_link_backref_name = 'subcontribution_links' + person_link_unique_columns = ('subcontribution_id',) + object_relationship_name = 'subcontribution' + + # subcontribution persons are always speakers and never authors + # we provide these attributes to make subcontribution links + # compatible with contribution links + is_speaker = True + author_type = AuthorType.none + + subcontribution_id = db.Column( + db.Integer, + db.ForeignKey('events.subcontributions.id'), + index=True, + nullable=False + ) + + # relationship backrefs: + # - subcontribution (SubContribution.person_links) + + @return_ascii + def __repr__(self): + return format_repr(self, 'id', 'person_id', 'subcontribution_id', _text=self.full_name) diff --git a/pool/shard007/Python/0069938_0001_initial.py b/pool/shard007/Python/0069938_0001_initial.py new file mode 100644 index 0000000000000000000000000000000000000000..5563592ba5194abde953df19dee2610c16aac591 --- /dev/null +++ b/pool/shard007/Python/0069938_0001_initial.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.2 on 2017-06-30 15:12 +from __future__ import unicode_literals + +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Event', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('type', models.IntegerField(choices=[(0, 'Unknown'), (1, 'Message'), (2, 'Join'), (3, 'Leave')], default=0)), + ('source', models.CharField(max_length=100)), + ('source_raw', models.CharField(max_length=100)), + ('target', models.CharField(max_length=100)), + ('target_raw', models.CharField(max_length=100)), + ('sent', models.DateTimeField()), + ('received', models.DateTimeField()), + ('text', models.TextField()), + ], + ), + migrations.CreateModel( + name='Screen', + fields=[ + ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('title', models.CharField(max_length=100)), + ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), + ], + ), + ] diff --git a/pool/shard007/Python/0069939_decorators.py b/pool/shard007/Python/0069939_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..6f6b48a95575b6d35e3efaa66cd5b0a30d00c617 --- /dev/null +++ b/pool/shard007/Python/0069939_decorators.py @@ -0,0 +1,48 @@ +""" Decorators used by failedloginblocker """ + +from .models import FailedAttempt +from .exceptions import LoginBlockedError + + +def monitor_login(auth_func): + """ + Function that decorates Django authenticate() function with one that + tracks failed logins and blocks further attempts based on a threshold + """ + + if hasattr(auth_func, '__PROTECT_FAILED_LOGINS__'): + # avoiding multiple decorations + return auth_func + + def decorate(*args, **kwargs): + """ Wrapper for Django authenticate function """ + user = kwargs.get('username', '') + if not user: + raise ValueError('username must be supplied by the \ + authentication function for FailedLoginBlocker to operate') + + try: + fa = FailedAttempt.objects.get(username=user) + if fa.recent_failure(): + if fa.too_many_failures(): + raise LoginBlockedError() + else: + # the block interval is over, reset the count + fa.failures = 0 + fa.save() + except FailedAttempt.DoesNotExist: + fa = None + + result = auth_func(*args, **kwargs) + if result: + # the authentication was successful + return result + # authentication failed + fa = fa or FailedAttempt(username=user, failures=0) + fa.failures += 1 + fa.save() + # return with unsuccessful auth + return None + + decorate.__PROTECT_FAILED_LOGINS__ = True + return decorate diff --git a/pool/shard007/Python/0069943_0004_auto_20161211_0309.py b/pool/shard007/Python/0069943_0004_auto_20161211_0309.py new file mode 100644 index 0000000000000000000000000000000000000000..51c9ebf60e95937903e9bd2c2019750d783982d2 --- /dev/null +++ b/pool/shard007/Python/0069943_0004_auto_20161211_0309.py @@ -0,0 +1,23 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.10.4 on 2016-12-11 03:09 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('user', '0003_post'), + ] + + operations = [ + migrations.DeleteModel( + name='Post', + ), + migrations.AddField( + model_name='user', + name='bio', + field=models.CharField(default='', max_length=255), + ), + ] diff --git a/pool/shard007/Python/0069945_forms.py b/pool/shard007/Python/0069945_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..7f98e5b73f73fa5e99a600d2f7331586f0eb9af1 --- /dev/null +++ b/pool/shard007/Python/0069945_forms.py @@ -0,0 +1,29 @@ +from django import forms + +from .models import SnoopedElection +from elections.models import ModerationHistory, ModerationStatus, ModerationStatuses + + +class ReviewElectionForm(forms.ModelForm): + class Meta: + model = SnoopedElection + fields = ["status"] + widgets = {"status": forms.widgets.RadioSelect()} + + +class ModerationHistoryForm(forms.ModelForm): + class Meta: + model = ModerationHistory + fields = ["status"] + widgets = {"status": forms.widgets.RadioSelect()} + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.fields["status"].queryset = ModerationStatus.objects.filter( + short_label__in=[ + ModerationStatuses.approved.value, + ModerationStatuses.suggested.value, + ModerationStatuses.rejected.value, + ] + ) + self.fields["status"].empty_label = None diff --git a/pool/shard007/Python/0069950_config.py b/pool/shard007/Python/0069950_config.py new file mode 100644 index 0000000000000000000000000000000000000000..c6e09e1af9cd9a9e3570c46bae5b0e564a37af24 --- /dev/null +++ b/pool/shard007/Python/0069950_config.py @@ -0,0 +1,32 @@ +# +# This loads the configuration +# +import os +try: + #Attempt Python 2 ConfigParser setup + import ConfigParser + config = ConfigParser.ConfigParser() + from ConfigParser import NoOptionError +except ImportError: + #Attempt Python 3 ConfigParser setup + import configparser + config = configparser.ConfigParser() + from configparser import NoOptionError + +# This is the default configuration file that always needs to be present. +default_file = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'defaults.cfg')) + +# These files are optional +# This specifies configurations that are typically specific to the machine (it is found alongside the GPy installation). +local_file = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..', 'installation.cfg')) + +# This specifies configurations specific to the user (it is found in the user home directory) +home = os.getenv('HOME') or os.getenv('USERPROFILE') or '' +user_file = os.path.join(home,'.config','GPy', 'user.cfg') + +# Read in the given files. +config.readfp(open(default_file)) +config.read([local_file, user_file]) + +if not config: + raise ValueError("No configuration file found at either " + user_file + " or " + local_file + " or " + default_file + ".") diff --git a/pool/shard007/Python/0069952_readonly_disk.py b/pool/shard007/Python/0069952_readonly_disk.py new file mode 100644 index 0000000000000000000000000000000000000000..a2d05471f6650941e0f16c016f605887c1e5fbb3 --- /dev/null +++ b/pool/shard007/Python/0069952_readonly_disk.py @@ -0,0 +1,74 @@ +import logging, re +from autotest.client.shared import error +from virttest import utils_test, aexpect, env_process + + +@error.context_aware +def run_readonly_disk(test, params, env): + """ + KVM reboot test: + 1) Log into a guest with virtio data disk + 2) Format the disk and copy file to it + 3) Stop the guest and boot up it again with the data disk set to readonly + 4) Try to copy file to the data disk + 5) Try to copy file from the data disk + + @param test: QEMU test object + @param params: Dictionary with the test parameters + @param env: Dictionary with test environment. + """ + error.context("Try to log into guest.", logging.info) + vm = env.get_vm(params["main_vm"]) + vm.verify_alive() + timeout = float(params.get("login_timeout", 240)) + session = vm.wait_for_login(timeout=timeout) + + create_partition_cmd = params.get("create_partition_cmd") + format_cmd = params.get("format_cmd") + copy_cmd = params.get("copy_cmd") + src_file = params.get("src_file") + disk_letter = params.get("disk_letter") + + #update the cdrom letter for winutils + cdrom_chk_cmd = "echo list volume > cmd && echo exit >>" + cdrom_chk_cmd += " cmd && diskpart /s cmd" + + vols = re.findall("\s+([A-Z])\s+.*CDFS.*\n", + session.cmd_output(cdrom_chk_cmd)) + if vols: + src_file = re.sub("WIN_UTIL", vols[0], src_file) + else: + raise error.TestError("Can not find winutils in guest.") + + filen = 0 + error.context("Format the disk and copy file to it", logging.info) + session.cmd(create_partition_cmd) + session.cmd(format_cmd) + dst_file = disk_letter + ":\\" + str(filen) + session.cmd(copy_cmd % (src_file, dst_file)) + filen += 1 + + msg = "Stop the guest and boot up it again with the data disk" + msg += " set to readonly" + error.context(msg, logging.info) + session.close() + vm.destroy() + data_img = params.get("images").split()[-1] + params["image_readonly_%s" % data_img] = "yes" + params["force_create_image_%s" % data_img] = "no" + env_process.preprocess(test, params, env) + + vm = env.get_vm(params["main_vm"]) + vm.verify_alive() + session = vm.wait_for_login(timeout=timeout) + + try: + error.context("Try to write to the readonly disk", logging.info) + dst_file_readonly = disk_letter + ":\\" + str(filen) + session.cmd(copy_cmd % (src_file, dst_file_readonly)) + raise error.TestFail("Write in readonly disk should failed.") + except aexpect.ShellCmdError: + error.context("Try to read from the readonly disk", logging.info) + session.cmd(copy_cmd % (dst_file, "C:\\")) + + session.close() diff --git a/pool/shard007/Python/0069954_api_version.py b/pool/shard007/Python/0069954_api_version.py new file mode 100644 index 0000000000000000000000000000000000000000..3470b513fc9a7db8faf8263776c4205da44bcd25 --- /dev/null +++ b/pool/shard007/Python/0069954_api_version.py @@ -0,0 +1,30 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- + +from enum import Enum + + +class RemoteRenderingApiVersion(str, Enum): + """Remote Rendering API versions supported by this package""" + + #: This is the default version + V2021_01_01 = "2021-01-01" + + +def validate_api_version(api_version): + # type: (str) -> None + """Raise ValueError if api_version is invalid """ + if not api_version: + return + + try: + api_version = RemoteRenderingApiVersion(api_version) + except ValueError: + raise ValueError( + "Unsupported API version '{}'. Please select from:\n{}".format( + api_version, ", ".join(v.value for v in RemoteRenderingApiVersion) + ) + ) diff --git a/pool/shard007/Python/0069955_plot.py b/pool/shard007/Python/0069955_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..a5038c01128c9bff6b5ee69f2d71155eeab4d40d --- /dev/null +++ b/pool/shard007/Python/0069955_plot.py @@ -0,0 +1,57 @@ + + +import sys +import os +import numpy +import glob +import matplotlib.pyplot as mp +args = sys.argv + +#protip: combine strings to specify path to data and filename +datadir = args[1] + +def capturefname(datadir): + os.chdir(datadir) + fnames = glob.glob('*csv') + print(fnames) + return fnames + + +#import data +def impdat(datadir,csvfile): + fname = datadir + '/' + csvfile + data = numpy.loadtxt(fname, delimiter=',') + return data + +def setupgraph(data): + fig = mp.figure(figsize=(10.0, 3.0)) + axes1 = fig.add_subplot(1,3,1) + axes2 = fig.add_subplot(1,3,2) + axes3 = fig.add_subplot(1,3,3) + + axes1.set_ylabel('avg') + axes2.set_ylabel('max') + axes3.set_ylabel('min') + + axes1.plot(data.mean(axis=0)) + axes2.plot(data.max(axis=0)) + axes3.plot(data.min(axis=0)) + + fig.tight_layout() + return fig + + + +def save_figure(fig,figfname): + mp.savefig(figfname + 'jpg') + return + + +fnames = capturefname(datadir) +for i in fnames: + csvfile = i + print(csvfile) + data = impdat(datadir,csvfile) + fig = setupgraph(data) + #mp.show(fig) + save_figure(fig) diff --git a/pool/shard007/Python/0069960_deluge_tracker_rename.py b/pool/shard007/Python/0069960_deluge_tracker_rename.py new file mode 100644 index 0000000000000000000000000000000000000000..8df5d22c284d766e8d138a7b3c14461df93e5631 --- /dev/null +++ b/pool/shard007/Python/0069960_deluge_tracker_rename.py @@ -0,0 +1,72 @@ +import os +import sys +import platform +import shutil +import pickle +import argparse +import re +from sets import Set +import time + +parser = argparse.ArgumentParser(description="Find and replace tracker urls in a Deluge torrents.state") +parser.add_argument( + "orig_tracker", + help="The original tracker regular expression url (with n possible groups) to be replaced." + " i.e. https://tracker.t411.ai/(\w+)/announce", + type=str +) +parser.add_argument( + "new_tracker", + help="The new tracker url to replace the original one with \\n where n is the group number from orig_tracker." + " i.e. http://tracker.t411.al/\\1/announce", + type=str +) +args = parser.parse_args() + +if platform.system() in ('Windows', 'Microsoft'): + state_file_path = os.path.join(os.environ.get('APPDATA'), 'deluge', 'state', 'torrents.state') + deluge_dir = os.path.join(os.environ['ProgramFiles'], 'Deluge') + if os.path.isdir(deluge_dir): + sys.path.append(deluge_dir) + for item in os.listdir(deluge_dir): + if item.endswith(('.egg', '.zip')): + sys.path.append(os.path.join(deluge_dir, item)) +else: + state_file_path = os.path.expanduser('~/.config/deluge/state/torrents.state') + +print("State file : {}".format(state_file_path)) +print("Replace '{}' with '{}'".format(args.orig_tracker, args.new_tracker)) +state_file = open(state_file_path, 'rb') +state = pickle.load(state_file) +state_file.close() + +state_updated = Set() +state_not_updated = Set() + +for torrent in state.torrents: + for tracker in torrent.trackers: + new_string, number_of_subs_made = re.subn(args.orig_tracker, args.new_tracker, tracker['url']) + if number_of_subs_made: + tracker['url'] = new_string + state_updated.add(new_string) + else: + state_not_updated.add(new_string) + +if state_updated: + shutil.copyfile(state_file_path, "{}.{}.old".format(state_file_path, time.time())) + state_file = open(state_file_path, 'wb') + pickle.dump(state, state_file) + state_file.close() + + print("\nState Updated : {}".format(len(state_updated))) + for state in state_updated: + print(state) + + print("\nState NOT Updated : {}".format(len(state_not_updated))) + for state in state_not_updated: + print(state) +else: + print("Nothing to do ...") + print("\nState NOT Updated : {}".format(len(state_not_updated))) + for state in state_not_updated: + print(state) diff --git a/pool/shard007/Python/0069965_urls.py b/pool/shard007/Python/0069965_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..b04472814e6b7cbafd3225bfe26affcc8baf0d34 --- /dev/null +++ b/pool/shard007/Python/0069965_urls.py @@ -0,0 +1,152 @@ +from django.conf import settings +from django.conf.urls import include, patterns, url +from django.db.transaction import non_atomic_requests + +import waffle +from piston.resource import Resource + +from olympia.addons.urls import ADDON_ID +from olympia.api import authentication, handlers, views, views_drf + +API_CACHE_TIMEOUT = getattr(settings, 'API_CACHE_TIMEOUT', 500) + + +# Wrap class views in a lambda call so we get an fresh instance of the class +# for thread-safety. +def class_view(cls): + return lambda *args, **kw: cls()(*args, **kw) + + +# Regular expressions that we use in our urls. +type_regexp = '/(?P[^/]*)' +limit_regexp = '/(?P\d*)' +platform_regexp = '/(?P\w*)' +version_regexp = '/(?P[^/]*)' +compat_mode = '(?:/(?P(?:strict|normal|ignore)))?' + + +def build_urls(base, appendages): + """ + Many of our urls build off each other: + e.g. + /search/:query + /search/:query/:type + . + . + /search/:query/:type/:limit/:platform/:version + /search/:query/:type/:limit/:platform/:version/:compatMode + """ + urls = [base] + for i in range(len(appendages)): + urls.append(base + ''.join(appendages[:i + 1])) + + return urls + + +base_search_regexp = r'search/(?P[^/]+)' +appendages = [type_regexp, limit_regexp, platform_regexp, version_regexp, + compat_mode] +search_regexps = build_urls(base_search_regexp, appendages) + +base_list_regexp = r'list' +appendages.insert(0, '/(?P[^/]+)') +list_regexps = build_urls(base_list_regexp, appendages) +ad = {'authentication': authentication.AMOOAuthAuthentication(two_legged=True)} + + +class SwitchToDRF(object): + """ + Waffle switch to move from Piston to DRF. + """ + def __init__(self, resource_name, with_handler=False, with_viewset=False, + only_detail=False): + self.resource_name = resource_name + self.with_handler = with_handler + self.with_viewset = with_viewset + self.only_detail = only_detail + + @non_atomic_requests + def __call__(self, *args, **kwargs): + if waffle.switch_is_active('drf'): + if self.with_viewset: + actions = {} + view_name = self.resource_name + 'ViewSet' + if self.only_detail: + actions = { + 'get': 'retrieve', + 'put': 'update', + 'delete': 'delete', + } + else: + actions = { + 'get': 'retrieve', + 'post': 'create', + } + return (getattr(views_drf, view_name).as_view(actions) + (*args, **kwargs)) + else: + view_name = self.resource_name + 'View' + return getattr(views_drf, view_name).as_view()(*args, **kwargs) + else: + if self.with_handler: + handler = getattr(handlers, self.resource_name + 'Handler') + return Resource(handler=handler, **ad)(*args, **kwargs) + else: + return (class_view(getattr(views, self.resource_name + 'View')) + (*args, **kwargs)) + + +api_patterns = patterns( + '', + # Addon_details + url('addon/%s$' % ADDON_ID, SwitchToDRF('AddonDetail'), + name='api.addon_detail'), + url(r'^get_language_packs$', SwitchToDRF('Language'), + name='api.language'),) + +for regexp in search_regexps: + api_patterns += patterns( + '', + url(regexp + '/?$', SwitchToDRF('Search'), name='api.search')) + +for regexp in list_regexps: + api_patterns += patterns( + '', + url(regexp + '/?$', SwitchToDRF('List'), name='api.list')) + +piston_patterns = patterns( + '', + url(r'^user/$', SwitchToDRF('User', with_handler=True), name='api.user'), + url(r'^addons/$', + SwitchToDRF('Addons', with_handler=True, with_viewset=True), + name='api.addons'), + url(r'^addon/%s$' % ADDON_ID, + SwitchToDRF('Addons', with_handler=True, with_viewset=True, + only_detail=True), + name='api.addon'), + url(r'^addon/%s/versions$' % ADDON_ID, + SwitchToDRF('Versions', with_handler=True, with_viewset=True), + name='api.versions'), + url(r'^addon/%s/version/(?P\d+)$' % ADDON_ID, + SwitchToDRF('Versions', with_handler=True, with_viewset=True, + only_detail=True), + name='api.version'), +) + +urlpatterns = patterns( + '', + # Redirect api requests without versions + url('^((?:addon|search|list)/.*)$', views.redirect_view), + + # Piston + url(r'^2/', include(piston_patterns)), + url(r'^1.5/search_suggestions/', views.search_suggestions), + # Append api_version to the real api views + url(r'^(?P\d+|\d+.\d+)/search/guid:(?P.*)', + views.guid_search), + url(r'^(?P\d+|\d+.\d+)/', include(api_patterns)), + url(r'^v3/accounts/', include('olympia.accounts.urls')), + url(r'^v3/addons/', include('olympia.addons.api.urls')), + url(r'^v3/', include('olympia.signing.urls')), + url(r'^v3/statistics/', include('olympia.stats.api_urls')), +) diff --git a/pool/shard007/Python/0069968_pr_latency.py b/pool/shard007/Python/0069968_pr_latency.py new file mode 100644 index 0000000000000000000000000000000000000000..5d635835e54340520251a07e2b52adb47b65f069 --- /dev/null +++ b/pool/shard007/Python/0069968_pr_latency.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python +# Copyright 2017 gRPC authors. +# +# 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. + +"""Measure the time between PR creation and completion of all tests. + +You'll need a github API token to avoid being rate-limited. See +https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line/ + +This script goes over the most recent 100 pull requests. For PRs with a single +commit, it uses the PR's creation as the initial time; othewise, it uses the +date of the last commit. This is somewhat fragile, and imposed by the fact that +GitHub reports a PR's updated timestamp for any event that modifies the PR (e.g. +comments), not just the addition of new commits. + +In addition, it ignores latencies greater than five hours, as that's likely due +to a manual re-run of tests. +""" + +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import json +import logging +import pprint +import urllib2 + +from datetime import datetime, timedelta + +logging.basicConfig(format='%(asctime)s %(message)s') + +PRS = 'https://api.github.com/repos/grpc/grpc/pulls?state=open&per_page=100' +COMMITS = 'https://api.github.com/repos/grpc/grpc/pulls/{pr_number}/commits' + + +def gh(url): + request = urllib2.Request(url) + if TOKEN: + request.add_header('Authorization', 'token {}'.format(TOKEN)) + response = urllib2.urlopen(request) + return response.read() + + +def print_csv_header(): + print('pr,base_time,test_time,latency_seconds,successes,failures,errors') + + +def output(pr, base_time, test_time, diff_time, successes, failures, errors, mode='human'): + if mode == 'human': + print("PR #{} base time: {} UTC, Tests completed at: {} UTC. Latency: {}." + "\n\tSuccesses: {}, Failures: {}, Errors: {}".format( + pr, base_time, test_time, diff_time, successes, failures, errors)) + elif mode == 'csv': + print(','.join([str(pr), str(base_time), + str(test_time), str(int((test_time-base_time).total_seconds())), + str(successes), str(failures), str(errors)])) + + +def parse_timestamp(datetime_str): + return datetime.strptime(datetime_str, '%Y-%m-%dT%H:%M:%SZ') + + +def to_posix_timestamp(dt): + return str((dt - datetime(1970, 1, 1)).total_seconds()) + + +def get_pr_data(): + latest_prs = json.loads(gh(PRS)) + res = [{'number': pr['number'], + 'created_at': parse_timestamp(pr['created_at']), + 'updated_at': parse_timestamp(pr['updated_at']), + 'statuses_url': pr['statuses_url']} + for pr in latest_prs] + return res + + +def get_commits_data(pr_number): + commits = json.loads(gh(COMMITS.format(pr_number=pr_number))) + return {'num_commits': len(commits), + 'most_recent_date': parse_timestamp(commits[-1]['commit']['author']['date'])} + + +def get_status_data(statuses_url, system): + status_url = statuses_url.replace('statuses', 'status') + statuses = json.loads(gh(status_url + '?per_page=100')) + successes = 0 + failures = 0 + errors = 0 + latest_datetime = None + if not statuses: return None + if system == 'kokoro': string_in_target_url = 'kokoro' + elif system == 'jenkins': string_in_target_url = 'grpc-testing' + for status in statuses['statuses']: + if not status['target_url'] or string_in_target_url not in status['target_url']: continue # Ignore jenkins + if status['state'] == 'pending': return None + elif status['state'] == 'success': successes += 1 + elif status['state'] == 'failure': failures += 1 + elif status['state'] == 'error': errors += 1 + if not latest_datetime: + latest_datetime = parse_timestamp(status['updated_at']) + else: + latest_datetime = max(latest_datetime, parse_timestamp(status['updated_at'])) + # First status is the most recent one. + if any([successes, failures, errors]) and sum([successes, failures, errors]) > 15: + return {'latest_datetime': latest_datetime, + 'successes': successes, + 'failures': failures, + 'errors': errors} + else: return None + + +def build_args_parser(): + import argparse + parser = argparse.ArgumentParser() + parser.add_argument('--format', type=str, choices=['human', 'csv'], + default='human', + help='Output format: are you a human or a machine?') + parser.add_argument('--system', type=str, choices=['jenkins', 'kokoro'], + required=True, help='Consider only the given CI system') + parser.add_argument('--token', type=str, default='', + help='GitHub token to use its API with a higher rate limit') + return parser + + +def main(): + import sys + global TOKEN + args_parser = build_args_parser() + args = args_parser.parse_args() + TOKEN = args.token + if args.format == 'csv': print_csv_header() + for pr_data in get_pr_data(): + commit_data = get_commits_data(pr_data['number']) + # PR with a single commit -> use the PRs creation time. + # else -> use the latest commit's date. + base_timestamp = pr_data['updated_at'] + if commit_data['num_commits'] > 1: + base_timestamp = commit_data['most_recent_date'] + else: + base_timestamp = pr_data['created_at'] + last_status = get_status_data(pr_data['statuses_url'], args.system) + if last_status: + diff = last_status['latest_datetime'] - base_timestamp + if diff < timedelta(hours=5): + output(pr_data['number'], base_timestamp, last_status['latest_datetime'], + diff, last_status['successes'], last_status['failures'], + last_status['errors'], mode=args.format) + + +if __name__ == '__main__': + main() diff --git a/pool/shard007/Python/0069970_trueprp.py b/pool/shard007/Python/0069970_trueprp.py new file mode 100644 index 0000000000000000000000000000000000000000..4dd2db8b9be4da20e971823c31db28fafbfd737c --- /dev/null +++ b/pool/shard007/Python/0069970_trueprp.py @@ -0,0 +1,96 @@ +import os +import hashlib +import struct + +class TruePRP(object): + + @classmethod + def _key_rand(cls, key, i): + """ + Generate a random number deterministically from the key in the range + 0 <= n <= i. Outputs for independent i are not correlated in any way. + """ + + return struct.unpack('= StarSystem.max_planets: + raise Exception + self.__planets[counter + 1] = planet + + @planets.deleter + def planets(self): + pass + + @property + def administrator(self): + return self.__administrator + + @administrator.setter + def administrator(self, admin): + if self.color == 'black': + raise Exception + self.__administrator = admin + + @administrator.deleter + def administrator(self): + self.administrator = None + + @property + def name(self): + return self.__name + + @name.setter + def name(self, name): + if name in StarSystem._systems: + raise Exception + if self.__name: + StarSystem._systems.discard(self.name) + StarSystem._systems.add(name) + self.__name = name + + @name.deleter + def name(self): + pass diff --git a/pool/shard007/Python/0069987_forms.py b/pool/shard007/Python/0069987_forms.py new file mode 100644 index 0000000000000000000000000000000000000000..05795db9e558848b3b7e90036d90420715b90282 --- /dev/null +++ b/pool/shard007/Python/0069987_forms.py @@ -0,0 +1,133 @@ +from __future__ import unicode_literals +from future.builtins import int + +from collections import defaultdict + +from django import forms +from django.utils.safestring import mark_safe +from django.utils.translation import activate, get_language, ugettext_lazy as _ +from django.template.defaultfilters import urlize + +from zhiliao.conf import settings, registry +from zhiliao.conf.models import Setting + +if settings.USE_MODELTRANSLATION: + from django.utils.datastructures import SortedDict + from modeltranslation.utils import build_localized_fieldname + + +FIELD_TYPES = { + bool: forms.BooleanField, + int: forms.IntegerField, + float: forms.FloatField, +} + + +class SettingsForm(forms.Form): + """ + Form for settings - creates a field for each setting in + ``mezzanine.conf`` that is marked as editable. + """ + + def __init__(self, *args, **kwargs): + super(SettingsForm, self).__init__(*args, **kwargs) + # Create a form field for each editable setting's from its type. + active_language = get_language() + for name in sorted(registry.keys()): + setting = registry[name] + if setting["editable"]: + field_class = FIELD_TYPES.get(setting["type"], forms.CharField) + if settings.USE_MODELTRANSLATION and setting["translatable"]: + for code in SortedDict(settings.LANGUAGES): + try: + activate(code) + except: + pass + else: + self._init_field(setting, field_class, name, code) + else: + self._init_field(setting, field_class, name) + activate(active_language) + + def _init_field(self, setting, field_class, name, code=None): + """ + Initialize a field wether it is built with a custom name for a + specific translation language or not. + """ + kwargs = { + "label": setting["label"] + ":", + "required": setting["type"] in (int, float), + "initial": getattr(settings, name), + "help_text": self.format_help(setting["description"]), + } + if setting["choices"]: + field_class = forms.ChoiceField + kwargs["choices"] = setting["choices"] + field_instance = field_class(**kwargs) + code_name = ('_modeltranslation_' + code if code else '') + self.fields[name + code_name] = field_instance + css_class = field_class.__name__.lower() + field_instance.widget.attrs["class"] = css_class + if code: + field_instance.widget.attrs["class"] += " modeltranslation" + + def __iter__(self): + """ + Calculate and apply a group heading to each field and order by + the heading. + """ + fields = list(super(SettingsForm, self).__iter__()) + group = lambda field: field.name.split("_", 1)[0].title() + misc = _("Miscellaneous") + groups = defaultdict(int) + for field in fields: + groups[group(field)] += 1 + for (i, field) in enumerate(fields): + setattr(fields[i], "group", group(field)) + if groups[fields[i].group] == 1: + fields[i].group = misc + return iter(sorted(fields, key=lambda x: (x.group == misc, x.group))) + + def save(self): + """ + Save each of the settings to the DB. + """ + active_language = get_language() + for (name, value) in self.cleaned_data.items(): + if name not in registry: + name, code = name.rsplit('_modeltranslation_', 1) + else: + code = None + setting_obj, created = Setting.objects.get_or_create(name=name) + if settings.USE_MODELTRANSLATION: + if registry[name]["translatable"]: + try: + activate(code) + except: + pass + finally: + setting_obj.value = value + activate(active_language) + else: + # Duplicate the value of the setting for every language + for code in SortedDict(settings.LANGUAGES): + setattr(setting_obj, + build_localized_fieldname('value', code), + value) + else: + setting_obj.value = value + setting_obj.save() + + def format_help(self, description): + """ + Format the setting's description into HTML. + """ + for bold in ("``", "*"): + parts = [] + if description is None: + description = "" + for i, s in enumerate(description.split(bold)): + parts.append(s if i % 2 == 0 else "%s" % s) + description = "".join(parts) + description = urlize(description, autoescape=False) + return mark_safe(description.replace("\n", "
")) diff --git a/pool/shard007/Python/0069989_logs.py b/pool/shard007/Python/0069989_logs.py new file mode 100644 index 0000000000000000000000000000000000000000..ae53e2d5a17fa492fb9d0bd84f14304f9378adbc --- /dev/null +++ b/pool/shard007/Python/0069989_logs.py @@ -0,0 +1,223 @@ +# Copyright 2014 Google Inc. All Rights Reserved. + +# 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. + + +"""Logging mechanisms for use in OpenHTF. + +There are two types of logs within OpenHTF, framework logs, and test logs. +Framework logs are logs that are not included in test record output, while +test logs are. Framework logs are typically internal to OpenHTF, and are +only interesting when debugging weird framework behavior. + +Test logs are primarily generated by test authors, and are included in test +record output. The preferred way to do this is via the 'test' first parameter +passed to test phases: + + def MyLoggingPhase(test): + test.logger.info('My log line') + +In order to facilitate adding logs to the test record output from places +outside the test phase (without forcing the author to pass the logger object +around), a user can directly use a logger instance assocated with the Test's +output TestRecord. This is accessible via the get_record_logger_for function +in this module, which take's a Test's UID and returns a Python Logger: + + import logging + from openhtf.util import logs + + class MyHelperClass(object): + def __init__(self) + self.test_uid = '' + + def MyRandomMethod(self): + logs.get_record_logger_for(self.test_uid).info( + 'Log this to currently running test.') + + def MyPhase(test, helper): + helper.MyRandomMethod() + + if __name__ == '__main__': + helper = MyHelperClass() + my_test = openhtf.Test(MyPhase.with_args(helper=helper)) + helper.test_uid = my_test.uid + my_test.Excute() + +Framework logs are by default output only to stderr at a warning level. They +can be additionally logged to a file (with a different level) via the +--log-file and --log-file-level flags. The --quiet flag may be set to suppress +all framework log output to stderr. The --verbosity flag may be used to set +the log level threshold for framework logs output to stderr. + +Test record logs are by default output to stdout at a debug level. There is +no way to change this, if you don't like it redirect stdout to /dev/null. +""" + +import argparse +import collections +import logging +import os +import re +import sys +import traceback + +from openhtf import util +from openhtf.util import argv +from openhtf.util import functions + + +DEFAULT_LEVEL = 'warning' +DEFAULT_LOGFILE_LEVEL = 'warning' +QUIET = False +LOGFILE = None + +LEVEL_CHOICES = ['debug', 'info', 'warning', 'error', 'critical'] +ARG_PARSER = argv.ModuleParser() +ARG_PARSER.add_argument( + '--verbosity', default=DEFAULT_LEVEL, choices=LEVEL_CHOICES, + action=argv.StoreInModule, target='%s.DEFAULT_LEVEL' % __name__, + help='Console log verbosity level (stderr).') +ARG_PARSER.add_argument( + '--quiet', action=argv.StoreInModule, target='%s.QUIET' % __name__, + proxy=argparse._StoreTrueAction, help="Don't output logs to stderr.") +ARG_PARSER.add_argument( + '--log-file', action=argv.StoreInModule, target='%s.LOGFILE' % __name__, + help='Filename to output logs to, if any.') +ARG_PARSER.add_argument( + '--log-file-level', default=DEFAULT_LOGFILE_LEVEL, choices=LEVEL_CHOICES, + action=argv.StoreInModule, target='%s.DEFAULT_LOGFILE_LEVEL' % __name__, + help='Logging verbosity level for log file output.') + +LOGGER_PREFIX = 'openhtf' +RECORD_LOGGER = '.'.join((LOGGER_PREFIX, 'test_record')) + +_LOGONCE_SEEN = set() + +LogRecord = collections.namedtuple( + 'LogRecord', 'level logger_name source lineno timestamp_millis message') + + +def get_record_logger_for(test_uid): + return logging.getLogger('.'.join((RECORD_LOGGER, test_uid))) + + +def initialize_record_logger(test_uid, test_record, notify_update): + logger = get_record_logger_for(test_uid) + # All record loggers have a shared parent that's separately configured, so + # we want to propagate to that logger. + logger.propagate = True + logger.setLevel(logging.DEBUG) + # Just in case, make sure we don't have any extra handlers hanging around. + logger.handlers = [RecordHandler(test_record, notify_update)] + return logger + + +def log_once(log_func, msg, *args, **kwargs): + """"Logs a message only once.""" + if msg not in _LOGONCE_SEEN: + log_func(msg, *args, **kwargs) + # Only check the message since it's likely from the source code so lifespan + # is long and no copies are made. + _LOGONCE_SEEN.add(msg) + + +class MacAddressLogFilter(logging.Filter): + """A filter which redacts mac addresses if it sees one.""" + + MAC_REPLACE_RE = re.compile(r""" + ((?:[\dA-F]{2}:){3}) # 3-part prefix, f8:8f:ca means google + (?:[\dA-F]{2}(:|\b)){3} # the remaining octets + """, re.IGNORECASE | re.VERBOSE) + MAC_REPLACEMENT = r'\1' + + def __init__(self): + super(MacAddressLogFilter, self).__init__() + + def filter(self, record): + if self.MAC_REPLACE_RE.search(record.getMessage()): + # Update all the things to have no mac address in them + record.msg = self.MAC_REPLACE_RE.sub(self.MAC_REPLACEMENT, record.msg) + record.args = tuple([ + self.MAC_REPLACE_RE.sub(self.MAC_REPLACEMENT, str(arg)) + if isinstance(arg, basestring) + else arg for arg in record.args]) + return True + + +# We use one shared instance of this, it has no internal state. +MAC_FILTER = MacAddressLogFilter() + + +class RecordHandler(logging.Handler): + """A handler to save logs to an HTF TestRecord.""" + + def __init__(self, test_record, notify_update): + super(RecordHandler, self).__init__(level=logging.DEBUG) + self._test_record = test_record + self._notify_update = notify_update + self.addFilter(MAC_FILTER) + + def emit(self, record): + """Save a logging.LogRecord to our test record. + + LogRecords carry a significant amount of information with them including the + logger name and level information. This allows us to be a little clever + about what we store so that filtering can occur on the client. + + Args: + record: A logging.LogRecord to log. + """ + message = record.getMessage() + if record.exc_info: + message += '\n' + ''.join(traceback.format_exception( + *record.exc_info)) + message = message.decode('utf8', 'replace') + + log_record = LogRecord( + record.levelno, record.name, os.path.basename(record.pathname), + record.lineno, int(record.created * 1000), message + ) + self._test_record.log_records.append(log_record) + self._notify_update() + + +@functions.call_once +def setup_logger(): + """Configure logging for OpenHTF.""" + record_logger = logging.getLogger(RECORD_LOGGER) + record_logger.propagate = False + record_logger.setLevel(logging.DEBUG) + record_logger.addHandler(logging.StreamHandler(stream=sys.stdout)) + + logger = logging.getLogger(LOGGER_PREFIX) + logger.propagate = False + logger.setLevel(logging.DEBUG) + formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') + if LOGFILE: + try: + cur_time = str(util.time_millis()) + file_handler = logging.FileHandler('%s.%s' % (LOGFILE, cur_time)) + file_handler.setFormatter(formatter) + file_handler.setLevel(DEFAULT_LOGFILE_LEVEL.upper()) + file_handler.addFilter(MAC_FILTER) + logger.addHandler(file_handler) + except IOError as exception: + print ('Failed to set up log file due to error: %s. ' + 'Continuing anyway.' % exception) + + if not QUIET: + console_handler = logging.StreamHandler(stream=sys.stderr) + console_handler.setFormatter(formatter) + console_handler.setLevel(DEFAULT_LEVEL.upper()) + console_handler.addFilter(MAC_FILTER) + logger.addHandler(console_handler) diff --git a/pool/shard007/Python/0069990_test_pdbparams.py b/pool/shard007/Python/0069990_test_pdbparams.py new file mode 100644 index 0000000000000000000000000000000000000000..810d63edadf6624f427ad5de5d0981c23e9e18b3 --- /dev/null +++ b/pool/shard007/Python/0069990_test_pdbparams.py @@ -0,0 +1,146 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2014-2019 khalim19 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import absolute_import, division, print_function, unicode_literals +from future.builtins import * + +import unittest + +from ... import constants as pgconstants + +from ...setting import pdbparams as pdbparams_ +from ...setting import settings as settings_ + +from . import stubs_group + + +class TestCreateParams(unittest.TestCase): + + def setUp(self): + self.file_ext_setting = settings_.FileExtensionSetting( + "file_extension", default_value="png", display_name="File extension") + self.unregistrable_setting = settings_.IntSetting( + "num_exported_layers", default_value=0, pdb_type=settings_.SettingPdbTypes.none) + self.coordinates_setting = settings_.ArraySetting( + "coordinates", + default_value=(1.0, 5.0, 10.0), + element_type=settings_.SettingTypes.float, + element_default_value=0.0) + + self.settings = stubs_group.create_test_settings_hierarchical() + + def test_create_params_single_param(self): + params = pdbparams_.create_params(self.file_ext_setting) + param = params[0] + + self.assertTrue(len(param), 3) + self.assertEqual(param[0], settings_.SettingPdbTypes.string) + self.assertEqual( + param[1], "file-extension".encode(pgconstants.GIMP_CHARACTER_ENCODING)) + self.assertEqual( + param[2], "File extension".encode(pgconstants.GIMP_CHARACTER_ENCODING)) + + def test_create_params_invalid_argument(self): + with self.assertRaises(TypeError): + pdbparams_.create_params([self.file_ext_setting]) + + def test_create_multiple_params(self): + params = pdbparams_.create_params( + self.file_ext_setting, self.coordinates_setting, self.settings) + + self.assertTrue(len(params), 3 + len(self.settings)) + + self.assertEqual( + params[0], + (self.file_ext_setting.pdb_type, + self.file_ext_setting.pdb_name.encode(pgconstants.GIMP_CHARACTER_ENCODING), + self.file_ext_setting.description.encode(pgconstants.GIMP_CHARACTER_ENCODING))) + + # Array length parameter + self.assertEqual(params[1][0], settings_.SettingPdbTypes.int32) + + self.assertEqual( + params[2], + (self.coordinates_setting.pdb_type, + self.coordinates_setting.pdb_name.encode(pgconstants.GIMP_CHARACTER_ENCODING), + self.coordinates_setting.description.encode(pgconstants.GIMP_CHARACTER_ENCODING))) + + for param, setting in zip(params[3:], self.settings.walk()): + self.assertEqual( + param, + (setting.pdb_type, + setting.pdb_name.encode(pgconstants.GIMP_CHARACTER_ENCODING), + setting.description.encode(pgconstants.GIMP_CHARACTER_ENCODING))) + + def test_create_params_with_unregistrable_setting(self): + params = pdbparams_.create_params(self.unregistrable_setting) + self.assertEqual(params, []) + + +class TestIterArgs(unittest.TestCase): + + def setUp(self): + self.settings = stubs_group.create_test_settings_hierarchical() + self.args = ["png", False, "replace"] + + def test_iter_args_number_of_args_equals_number_of_settings(self): + self.assertListEqual( + list(pdbparams_.iter_args(self.args, list(self.settings.walk()))), + self.args) + + def test_iter_args_number_of_args_is_less_than_number_of_settings(self): + self.assertListEqual( + list(pdbparams_.iter_args(self.args[:-1], list(self.settings.walk()))), + self.args[:-1]) + + def test_iter_args_number_of_args_is_more_than_number_of_settings(self): + self.assertListEqual( + list(pdbparams_.iter_args(self.args, list(self.settings.walk())[:-1])), + self.args[:-1]) + + def test_iter_args_with_array_setting(self): + coordinates_setting = settings_.ArraySetting( + "coordinates", + default_value=(1.0, 5.0, 10.0), + element_type=settings_.SettingTypes.float, + element_default_value=0.0) + + self.settings.add([coordinates_setting]) + self.args.extend([3, (20.0, 50.0, 40.0)]) + + self.assertListEqual( + list(pdbparams_.iter_args(self.args, list(self.settings.walk()))), + self.args[:-2] + [self.args[-1]]) + + +class TestListParamValues(unittest.TestCase): + + def setUp(self): + self.settings = stubs_group.create_test_settings_hierarchical() + + def test_list_param_values(self): + param_values = pdbparams_.list_param_values([self.settings]) + self.assertEqual( + param_values[0], self.settings["main/file_extension"].value) + self.assertEqual( + param_values[1], self.settings["advanced/only_visible_layers"].value) + self.assertEqual( + param_values[2], self.settings["advanced/overwrite_mode"].value) + + def test_list_param_values_ignore_run_mode(self): + param_values = pdbparams_.list_param_values( + [settings_.IntSetting("run_mode", 0), self.settings]) + self.assertEqual(len(param_values), len(list(self.settings.walk()))) diff --git a/pool/shard007/Python/0069991_test_snapshot_details.py b/pool/shard007/Python/0069991_test_snapshot_details.py new file mode 100644 index 0000000000000000000000000000000000000000..c8a59eea3aa8d1ba5b8bed26cf5e12c91559734b --- /dev/null +++ b/pool/shard007/Python/0069991_test_snapshot_details.py @@ -0,0 +1,67 @@ +from changes.config import db +from changes.models import ProjectOption, Snapshot, SnapshotStatus +from changes.testutils import APITestCase + + +class SnapshotDetailsTest(APITestCase): + def test_simple(self): + project = self.create_project() + snapshot = self.create_snapshot(project) + + path = '/api/0/snapshots/{0}/'.format(snapshot.id) + + resp = self.client.get(path) + assert resp.status_code == 200 + data = self.unserialize(resp) + assert data['id'] == snapshot.id.hex + assert data['project']['id'] == project.id.hex + assert data['build'] is None + + +class UpdateSnapshotTest(APITestCase): + def setUp(self): + super(UpdateSnapshotTest, self).setUp() + self.project = self.create_project() + self.snapshot = self.create_snapshot(self.project) + self.path = '/api/0/snapshots/{0}/'.format(self.snapshot.id.hex) + + def test_simple(self): + for status in ('active', 'failed', 'invalidated'): + resp = self.client.post(self.path, data={ + 'status': status, + }) + + assert resp.status_code == 200 + data = self.unserialize(resp) + assert data['id'] == self.snapshot.id.hex + assert data['status']['id'] == status + db.session.expire(self.snapshot) + + snapshot = Snapshot.query.get(self.snapshot.id) + assert snapshot.status == SnapshotStatus[status] + + def test_invalid_status(self): + resp = self.client.post(self.path, data={ + 'status': 'invalid_status', + }) + assert resp.status_code == 400 + + def test_set_current(self): + for status in ('failed', 'invalidated', 'active'): + resp = self.client.post(self.path, data={ + 'status': status, + 'set_current': True, + }) + + options = dict(db.session.query( + ProjectOption.name, ProjectOption.value + ).filter( + ProjectOption.project == self.project, + )) + + if status == 'active': + assert resp.status_code == 200 + assert options.get('snapshot.current') == self.snapshot.id.hex + else: + assert resp.status_code == 400 + assert options.get('snapshot.current') != self.snapshot.id.hex diff --git a/pool/shard007/Python/0069993_test_exec_anatomy.py b/pool/shard007/Python/0069993_test_exec_anatomy.py new file mode 100644 index 0000000000000000000000000000000000000000..d58a61217b718e14874805408000378837093630 --- /dev/null +++ b/pool/shard007/Python/0069993_test_exec_anatomy.py @@ -0,0 +1,50 @@ +# -*- coding: utf-8 -*- +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. + +import libear +import unittest + +import os.path +import subprocess +import json + + +def run(source_dir, target_dir): + def execute(cmd): + return subprocess.check_call(cmd, + cwd=target_dir, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT) + + execute(['cmake', source_dir]) + execute(['make']) + + result_file = os.path.join(target_dir, 'result.json') + expected_file = os.path.join(target_dir, 'expected.json') + execute(['intercept-build', '--cdb', result_file, './exec', + expected_file]) + return (expected_file, result_file) + + +class ExecAnatomyTest(unittest.TestCase): + def assertEqualJson(self, expected, result): + def read_json(filename): + with open(filename) as handler: + return json.load(handler) + + lhs = read_json(expected) + rhs = read_json(result) + for item in lhs: + self.assertTrue(rhs.count(item)) + for item in rhs: + self.assertTrue(lhs.count(item)) + + def test_all_exec_calls(self): + this_dir, _ = os.path.split(__file__) + source_dir = os.path.normpath(os.path.join(this_dir, '..', 'exec')) + with libear.TemporaryDirectory() as tmp_dir: + expected, result = run(source_dir, tmp_dir) + self.assertEqualJson(expected, result) diff --git a/pool/shard007/Python/0069995_common.py b/pool/shard007/Python/0069995_common.py new file mode 100644 index 0000000000000000000000000000000000000000..b1269b5aac605b7a89510a7d8b120abc59cee5ad --- /dev/null +++ b/pool/shard007/Python/0069995_common.py @@ -0,0 +1,56 @@ +# # +# Copyright 2009-2019 Ghent University +# +# This file is part of EasyBuild, +# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), +# with support of Ghent University (http://ugent.be/hpc), +# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), +# Flemish Research Foundation (FWO) (http://www.fwo.be/en) +# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). +# +# https://github.com/easybuilders/easybuild +# +# EasyBuild 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 v2. +# +# EasyBuild 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 EasyBuild. If not, see . +# # +""" +Dispatch function for container packages + +:author: Shahzeb Siddiqui (Pfizer) +:author: Kenneth Hoste (HPC-UGent) +:author: Mohamed Abidi (Bright Computing) +""" +from easybuild.base import fancylogger +from easybuild.tools.build_log import EasyBuildError +from easybuild.tools.config import build_option +from easybuild.tools.containers.docker import DockerContainer # noqa +from easybuild.tools.containers.singularity import SingularityContainer # noqa + +_log = fancylogger.getLogger('tools.containers.common') # pylint: disable=C0103 + + +def containerize(easyconfigs): + """ + Generate container recipe + (optionally) image + """ + _log.experimental("support for generating container recipes and images (--containerize/-C)") + + container_type = build_option('container_type') + + _log.info("Creating %s container", container_type) + + try: + klass = globals()["%sContainer" % container_type.capitalize()] + except KeyError: + raise EasyBuildError("Unknown container type specified: %s", container_type) + + klass(easyconfigs).generate() diff --git a/pool/shard007/Python/0069996_solitarywave.py b/pool/shard007/Python/0069996_solitarywave.py new file mode 100644 index 0000000000000000000000000000000000000000..e97bf213bdac13438f38cd49e62f63f7495937e2 --- /dev/null +++ b/pool/shard007/Python/0069996_solitarywave.py @@ -0,0 +1,83 @@ +# Copyright (C) 2013 Columbia University in the City of New York and others. +# +# Please see the AUTHORS file in the main source directory for a full list +# of contributors. +# +# This file is part of TerraFERMA. +# +# TerraFERMA 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. +# +# TerraFERMA 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 TerraFERMA. If not, see . + +"""python class for calculating solitary waves profiles +""" + +__author__ = "Marc Spiegelman (mspieg@ldeo.columbia.edu)" +__date__ = "15 Oct 2011 22:01:49" +__copyright__ = "Copyright (C) 2010 Marc Spiegelman" +__license__ = "GNU LGPL Version 2.1" + +from numpy import * +from scipy.interpolate import interp1d +import sys + +from magmasinc import solwave_mck, solwave_con, solwave_m1, solwave_gen +from sinc_eo import sincinterp_e + +class SolitaryWave: + """ class for calculating and evaluating solitary wave profiles from Simpson + magmasinc library + """ + + def __init__(self, c,n,m,d,N): + """initialize radial solitary wave profile fc(r) using PySolwave Routines + + c: wavespeed + n: permeability exponent + m: bulk viscosity exponent + d: wave dimension + N: number of collocation points + """ + + # calculate profiles checking for special cases + if m == 1: + if n == 2: + r, f = solwave_con(c, d, N) + else: + r, f = solwave_m1(c,n, d, N) + else: + if n == 3: + r, f = solwave_mck(c, d, N) + else: + r, f = solwave_gen(c, n, m, d, N) + + self.r = r + self.f = f + self.finterp = interp1d(r,f, kind='cubic', fill_value=1.0) + + def eval(self,r): + """ use sincinterp_e to return porosity at radius r""" + + f = sincinterp_e(self.r, self.f - 1.0, r) + 1.0 + return f + + + def interp(self,r): + """ use scipy interp1d cubic interpolation to return values""" + return self.finterp(r) + + + + + + + diff --git a/pool/shard007/Python/0069998_HostList.py b/pool/shard007/Python/0069998_HostList.py new file mode 100644 index 0000000000000000000000000000000000000000..f1dce5b9c3c1e5aade26e1292198041c6a1fb2e1 --- /dev/null +++ b/pool/shard007/Python/0069998_HostList.py @@ -0,0 +1,24 @@ +from HostManager import HostManager +from Host import Host + +class HostList: + + def __init__(self): + self.hosts = [] + fm = HostManager(address) + for e in fm.getArray(): + self.hosts.append(Host(e)) + def getSize(self): + return len(self.hosts) + def checkHostUp(self, index): + return self.hosts[index].isUp() + def checkHostsUp(self): + results = [] + for i in range(0, self.getSize()): + results.append(self.checkHostUp(i)) + return results + def getHostNames(self): + results = [] + for e in self.hosts: + results.append(e.getHostName()) + return results diff --git a/pool/shard007/Python/0070000_init__.py b/pool/shard007/Python/0070000_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..44f3c4e7b3e3ced745b805d817c6a980085fbe7a --- /dev/null +++ b/pool/shard007/Python/0070000_init__.py @@ -0,0 +1,234 @@ +# Copyright (c) 2006, John X. Gilman + +# This software is distributed under the new BSD Open Source License. +# +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# (1) Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# +# (2) Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and or other materials provided with the distribution. +# +# (3) Neither the name of the University of California, Lawrence Berkeley +# National Laboratory, U.S. Dept. of Energy nor the names of its contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. + +"""Database access. In biological parlance, a 'database' is an organized +collection of biological data. + + -- Dbxref - A database cross-reference, a resource identifier. + -- DataSource - A source of biological data. + -- databases - A list of standard databases. + +Usage: + ref = Dbxref("Swiss-Prot:P12345") + data = ref. + +""" + +import re +import urllib + +from corebio.data import data_stream +from corebio.utils import update, stdrepr + + + + +__all__ = ['Dbxref','DataSource', 'default_registry', + 'astral', 'scop' ] + +_dbxref = re.compile(r'\s*(?:/db_xref\s*=\s*\")?(\w+):(\w+)\"?\s*') + +class Dbxref(object) : + + """A database cross-reference, a kind of Universal Resource Name (URN) used + to locate information in biological databases. + + -- database - the name of the database + -- identifier - the internal identifier of the related information + according to the naming conventions of the cross-referenced + database. + + Examples: + + cross reference to GDB identifier: /db_xref="GDB:39999" + cross reference to Swiss-Prot entry: /db_xref="Swiss-Prot:P12345" + + Refs: + http://www.ncbi.nlm.nih.gov/collab/db_xref.html + http://www.ebi.ac.uk/cgi-bin/emblfetch + http://www.expasy.org/cgi-bin/lists?dbxref.txt + """ + + __slots__ = ["database", "identifier"] + + def __init__(self, ref, identifier=None) : + """ Dbxref('/db_xref="GDB:39999"') + Dbxref("GDB:39999") + Dbxref('GDB','39999') + """ + if identifier: + self.database = ref + self.identifier = identifier + return + m = _dbxref.match(ref) + if m is None : + raise ValueError, "Cannot parse database cross-reference." + self.database = m.group(1) + self.identifier = m.group(2) + + def __repr__(self) : + return "Dbxref(%s, %s)" %(self.database, self.identifier) + + def __str__(self) : + return "%s:%s" %(self.database, self.identifier) + + def datasource(self, registry = None) : + if registry is None: registry = default_registry + database = self.database.lower() + if not (database in registry) : + raise ValueError, "Unknown database: %s" % self.database + return registry[database] + + def data_url(self) : + return self.datasource().data_url(self.identifier) + + def data_stream(self) : + return self.datasource().data_stream(self.identifier) + + def data_string(self) : + return self.datasource().data_string(self.identifier) + + +class DataSource(object) : + """A collection of indexed biological data. + + Attributes: + -- name - The name of the database. + -- abbrev - Standard abrreviation + -- alt_abbrev - A list of alternative abrreviations or names. + -- url - Main URL of the database. + -- resource_url - The URL of individual database resources, e.g. + 'biocyc.org/getid?id=%s', where '%s' is replaced by the + resource identifier. + -- parser - A function that can convert raw data into an object. + -- description - Description of the type of biological data in this + database. E.g. ''Organism-specific gene databases' + """ + __slots__=['abbrev', 'alt_abbrev', 'name', + 'url', 'resource_url', 'parser', 'description'] + + def __init__(self, **kwarg) : + for s in self.__slots__ : setattr(self, s, None) + update(self, **kwarg) + + def __repr__(self) : + return stdrepr(self) + + def data_url(self, identifier) : + url = self.resource_url + if url is None : + raise ValueError, "Cannot resolve resource." + url = url % identifier # Fixme + return url + + def data_stream(self, identifier) : + url = self.data_url(identifier) + return urllib.urlopen(url) + + def data_string(self, identifier) : + return self.data_stream(identifier).read() + + def data_object(self, identifier) : + parser = self.parser + if parser == None : + raise ValueError, "No parser for resource." + stream = self.data_stream(identifier) + return parser(stream) + + + +def _build_default_registry() : + registry = dict() + + # Parse database specifications from standard 'dbxref' file. + ds = _read_dbxref( data_stream('dbxref.txt') ) + + ds.append(DataSource( + name= 'Swiss-Prot', + abbrev = 'swissprot', + alt_abbrev = ('uniprotkb', 'uniprot'), + url = 'http://ca.expasy.org/sprot/', + resource_url = 'http://www.expasy.ch/cgi-bin/get-sprot-raw.pl?%s', + description='Protein knowledgebase', + ) ) + + for d in ds : + registry[d.abbrev.lower() ] = d + if d.alt_abbrev : + for alt in d.alt_abbrev : + registry[alt.lower()] = ds + return registry + + +def _read_dbxref(stream) : + """ Read the dbxref file and return a list of datasources.""" + namemap = dict(Abbrev = 'abbrev', + Name = 'name', + Server = 'url', + Db_URL = 'resource_url', + Cat = 'description' + ) + + ds_list = [] + attr = None + ds = None + + for line in stream : + if len(line)<8 : continue + typeof = line[0:6].strip() + content = line[8:].strip() + + if typeof=='Abbrev' : # New record + ds = DataSource() + ds_list.append(ds) + + if content == 'None' : continue # No data + + if ds is None : continue # No record started + + if typeof == '' : # Continuation line + if not attr is None : + content = getattr(ds, attr) +' '+ content + setattr(ds, attr, content) + else : + attr = None + if typeof in namemap: + attr = namemap[typeof] + if attr == 'resource_url' or attr=='url' : + content = ''.join(('http://',content)) + + setattr(ds, attr, content) + + return ds_list + + +default_registry = _build_default_registry() diff --git a/pool/shard007/Python/0070001_urls.py b/pool/shard007/Python/0070001_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..16044de6f46a12401e161bb9d88b14c9f2cc8acf --- /dev/null +++ b/pool/shard007/Python/0070001_urls.py @@ -0,0 +1,15 @@ +""" +URLs for mobile API +""" +from django.conf.urls import patterns, url, include + +from .users.views import my_user_info + +# Additionally, we include login URLs for the browseable API. +urlpatterns = patterns( + '', + url(r'^users/', include('mobile_api.users.urls')), + url(r'^my_user_info', my_user_info), + url(r'^video_outlines/', include('mobile_api.video_outlines.urls')), + url(r'^course_info/', include('mobile_api.course_info.urls')), +) diff --git a/pool/shard007/Python/0070003_clock_resolution.py b/pool/shard007/Python/0070003_clock_resolution.py new file mode 100644 index 0000000000000000000000000000000000000000..17993cd8603ef2447ccc65a2fdd2741e6b7565a6 --- /dev/null +++ b/pool/shard007/Python/0070003_clock_resolution.py @@ -0,0 +1,72 @@ +import time + +try: + from time import timeout_time +except ImportError: + from time import time as timeout_time + +def compute_resolution(func): + resolution = None + points = 0 + timeout = timeout_time() + 1.0 + previous = func() + while timeout_time() < timeout or points < 3: + for loop in range(10): + t1 = func() + t2 = func() + dt = t2 - t1 + if 0 < dt: + break + else: + dt = t2 - previous + if dt <= 0.0: + continue + if resolution is not None: + resolution = min(resolution, dt) + else: + resolution = dt + points += 1 + previous = func() + return resolution + +def format_duration(dt): + if dt >= 1e-3: + return "%.0f ms" % (dt * 1e3) + if dt >= 1e-6: + return "%.0f us" % (dt * 1e6) + else: + return "%.0f ns" % (dt * 1e9) + +def test_clock(name, func): + print("%s:" % name) + resolution = compute_resolution(func) + print("- resolution in Python: %s" % format_duration(resolution)) + + +clocks = ['clock', 'perf_counter', 'process_time'] +if hasattr(time, 'monotonic'): + clocks.append('monotonic') +clocks.append('time') +for name in clocks: + func = getattr(time, name) + test_clock("%s()" % name, func) + info = time.get_clock_info(name) + print("- implementation: %s" % info.implementation) + print("- resolution: %s" % format_duration(info.resolution)) + +clock_ids = [name for name in dir(time) if name.startswith("CLOCK_")] +clock_ids.sort() +for clock_id_text in clock_ids: + clock_id = getattr(time, clock_id_text) + name = 'clock_gettime(%s)' % clock_id_text + def gettime(): + return time.clock_gettime(clock_id) + try: + gettime() + except OSError as err: + print("%s failed: %s" % (name, err)) + continue + test_clock(name, gettime) + resolution = time.clock_getres(clock_id) + print("- announced resolution: %s" % format_duration(resolution)) + diff --git a/pool/shard007/Python/0070006_multivariatenormal.py b/pool/shard007/Python/0070006_multivariatenormal.py new file mode 100644 index 0000000000000000000000000000000000000000..919ec8d78988230733ba0d831db7e615294399d8 --- /dev/null +++ b/pool/shard007/Python/0070006_multivariatenormal.py @@ -0,0 +1,103 @@ +''' +Created on Jun 30, 2014 + +@author: jonaswallin +''' +import copy as cp +import numpy as np + +import pickle + + +class multivariatenormal(object): + ''' + Class for sampling from a Multivariate normal distribution on the form + f(X| Y, \Sigma, \mu_p, \Sigma_p) \propto N(Y; X, \Sigma) N(X; \mu_p, \Sigma_p) + ''' + + def pickle(self, filename): + """ + store object in file + """ + f = file(filename, 'wb') + pickle.dump(self, f, pickle.HIGHEST_PROTOCOL) + f.close() + + @staticmethod + def unpickle(filename): + """ + load object from file + use: + + object = multivariatenormal.unpickle(filename) + """ + with file(filename, 'rb') as f: + return pickle.load(f) + + def __init__(self, param = None ,prior = None): + ''' + prior: + prior['mu'] = np.array(dim=1) + prior['Sigma'] = np.array(dim=2) + ''' + self.prior = None + self.param = None + self.Y = None + if prior != None: + self.set_prior(prior) + + if param != None: + self.set_parameter(param) + + def set_prior(self,prior): + """ + + """ + self.mu_p = np.zeros_like(prior['mu']) + self.mu_p[:] = prior['mu'][:] + self.Sigma_p = np.zeros_like(prior['Sigma']) + self.Sigma_p[:] = prior['Sigma'][:] + self.Q_p = np.linalg.inv(self.Sigma_p) + self.Q_pmu_p = np.dot(self.Q_p,self.mu_p) + self.d = self.Q_pmu_p.shape[0] + + def set_parameter(self, parameter): + """ + parameter should be a dictonray with 'Sigma' + + """ + self.Sigma = np.zeros_like(parameter['Sigma']) + self.Sigma[:] = parameter['Sigma'][:] + self.Q = np.linalg.inv(self.Sigma) + self.d = self.Q.shape[0] + + def set_data(self, Y): + """ + Y - (nxd) numpy vector + """ + self.Y = np.zeros_like(Y) + self.Y[:] = Y[:] + self.sumY = np.sum(Y,0) + self.n = Y.shape[0] + + def sample(self): + """ + return X + """ + if self.Y != None: + mu_sample = self.Q_pmu_p + np.dot(self.Sigma, self.sumY) + Sigma_sample = self.Q_p + self.n * self.Q + else: + mu_sample = self.Q_pmu_p + Sigma_sample = self.Q_p + + R = np.linalg.cholesky(Sigma_sample) + X = np.linalg.solve(R, mu_sample) + X = np.linalg.solve(R.T, X + np.random.randn(self.d)) + self.X = np.zeros_like(X) + self.X[:] = X[:] + return X + + + + diff --git a/pool/shard007/Python/0070010_base.py b/pool/shard007/Python/0070010_base.py new file mode 100644 index 0000000000000000000000000000000000000000..33f72c355297411f2ff6b8322c4a99e858cdd8d5 --- /dev/null +++ b/pool/shard007/Python/0070010_base.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- + +from configparser import ConfigParser +from functools import wraps +import pickle +import logging + +############################## +# logging relevance +############################## + +def get_log(name=None): + logger = logging.getLogger(name) + handler = logging.StreamHandler() + formatter = logging.Formatter( + '%(asctime)s %(name)-12s %(levelname)-8s %(message)s') + handler.setFormatter(formatter) + logger.addHandler(handler) + logger.setLevel(logging.DEBUG) + return logger + +############################## +# redis relevance +############################## + +def redis_login(): + cfg = ConfigParser() + cfg.read('config.ini') + info = { + 'host': cfg.get('redis', 'host'), + 'port': cfg.getint('redis', 'port'), + 'password': cfg.get('redis', 'password') + } + return info + +def push(func): + @wraps(func) + def dec(redis, key, objects): + if not (isinstance(objects, tuple) or isinstance(objects, list)): + objects = [objects] + serialization = list() + for obj in objects: + serialization.append(pickle.dumps(obj)) + pipe = redis.pipeline() + func(pipe, key, serialization) + pipe.execute() + return dec + +# list operation +@push +def rpush(redis, key, objects): + for obj in objects: + redis.rpush(key, obj) + +def blpop(redis, key, timeout=30): + serialization = redis.blpop(key, timeout=timeout) + if serialization: + return pickle.loads(serialization[1]) + +# set operation +@push +def sadd(redis, key, objects): + for obj in objects: + redis.sadd(key, obj) + +def srandmember(redis, key): + serialization = redis.srandmember(key) + if serialization: + return pickle.loads(serialization) + +############################## +# string relevance +############################## + +def preprocess(func): + @wraps(func) + def dec(*args): + args = list(args) + if not (isinstance(args[0], tuple) or isinstance(args[0], list)): + args[0] = [args[0]] + lst = func(*args) + return lst + return dec + +@preprocess +def strip(strings, chars=None): + if strings: + return list(map(lambda string: string.strip(chars), strings)) + +def split_pop(string, sep=None, char=None, maxsplit=-1, index=0): + if not string: + return None + items = string.split(sep) + items.pop(index) + for item in items: + try: + items.remove(char) + except: + return items \ No newline at end of file diff --git a/pool/shard007/Python/0070024_test_general.py b/pool/shard007/Python/0070024_test_general.py new file mode 100644 index 0000000000000000000000000000000000000000..88909a09cfc6075aaceacd1ce8091209c94f9e9f --- /dev/null +++ b/pool/shard007/Python/0070024_test_general.py @@ -0,0 +1,44 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +general tests for string behavior. If these fail, +lots of tests that use string interpolation will +error because of the string interpolation. + +This is a good catch for people writing a test +with a buggy print statement. + +Then again, there's always pylint. + +Thank You Py2/3 compatibility problems... + +""" +from __future__ import absolute_import +from __future__ import print_function +from __future__ import unicode_literals +from ..utils.timing import TimedTestCase + + +class test_general(TimedTestCase): + + def test_interpolate(self): + """Interpolate two strings...""" + self.threshold = .1 + n = "one" + key = "two" + print(('interpolate (%s) %s' % (n, key))) + + def test_typing(self): + """Interpolate a number...""" + self.threshold = .1 + n = 1 + key = "two" + print(('interpolate (%s) %s' % (n, key))) + + def test_named(self): + """Interpolate with named keys...""" + self.threshold = .1 + n = 1 + key = "two" + print(('one (%(name)s) %(key)s' % {'name': n, 'key': key})) + # def test_numbered(self): diff --git a/pool/shard007/Python/0070025_json.py b/pool/shard007/Python/0070025_json.py new file mode 100644 index 0000000000000000000000000000000000000000..bdff2f599849ff374e3b2b380c4134635cc838ab --- /dev/null +++ b/pool/shard007/Python/0070025_json.py @@ -0,0 +1,53 @@ +# +# Copyright © 2012–2022 Michal Čihař +# +# This file is part of Weblate +# +# 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 . +# + + +from django.utils.translation import gettext_lazy as _ + +from weblate.addons.base import StoreBaseAddon +from weblate.addons.forms import JSONCustomizeForm + + +class JSONCustomizeAddon(StoreBaseAddon): + name = "weblate.json.customize" + verbose = _("Customize JSON output") + description = _( + "Allows adjusting JSON output behavior, for example indentation or sorting." + ) + settings_form = JSONCustomizeForm + compat = { + "file_format": { + "json", + "json-nested", + "webextension", + "i18next", + "arb", + "go-i18n-json", + } + } + + def store_post_load(self, translation, store): + config = self.instance.configuration + style = config.get("style", "spaces") + indent = int(config.get("indent", 4)) + if style == "spaces": + store.store.dump_args["indent"] = indent + else: + store.store.dump_args["indent"] = "\t" * indent + store.store.dump_args["sort_keys"] = bool(int(config.get("sort_keys", 0))) diff --git a/pool/shard007/Python/0070028_is_palindrome.py b/pool/shard007/Python/0070028_is_palindrome.py new file mode 100644 index 0000000000000000000000000000000000000000..025d9289e77def9fe9ea2a95250bb43875913ade --- /dev/null +++ b/pool/shard007/Python/0070028_is_palindrome.py @@ -0,0 +1,15 @@ +def is_palindrome(s): + return s == s[::-1] + +def is_palindrome2(s): + n = len(s) + for i in range(n/2 + 1): + if s[i] != s[n - i - 1]: + return False + return True + +if __name__ == '__main__': + # print is_palindrome('Michael') + # print is_palindrome('racecar') + print is_palindrome2('Michael') + print is_palindrome2('racecar') diff --git a/pool/shard007/Python/0070031_ProjectColumn.py b/pool/shard007/Python/0070031_ProjectColumn.py new file mode 100644 index 0000000000000000000000000000000000000000..244a3184b3b2c3f389a775bc8769243a26f349d6 --- /dev/null +++ b/pool/shard007/Python/0070031_ProjectColumn.py @@ -0,0 +1,175 @@ +# -*- coding: utf-8 -*- + +############################ Copyrights and license ############################ +# # +# Copyright 2018 bbi-yggy # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub 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. # +# # +# PyGithub 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 PyGithub. If not, see . # +# # +################################################################################ + +import github.GithubObject +import github.Project +import github.ProjectCard + +from . import Consts + + +class ProjectColumn(github.GithubObject.CompletableGithubObject): + """ + This class represents Project Columns. The reference can be found here http://developer.github.com/v3/projects/columns + """ + + def __repr__(self): + return self.get__repr__({"name": self._name.value}) + + @property + def cards_url(self): + """ + :type: string + """ + return self._cards_url.value + + @property + def created_at(self): + """ + :type: datetime.datetime + """ + return self._created_at.value + + @property + def id(self): + """ + :type: integer + """ + return self._id.value + + @property + def name(self): + """ + :type: string + """ + return self._name.value + + @property + def node_id(self): + """ + :type: string + """ + return self._node_id.value + + @property + def project_url(self): + """ + :type: string + """ + return self._project_url.value + + @property + def updated_at(self): + """ + :type: datetime.datetime + """ + return self._updated_at.value + + @property + def url(self): + """ + :type: string + """ + return self._url.value + + def get_cards(self, archived_state=github.GithubObject.NotSet): + """ + :calls: `GET /projects/columns/:column_id/cards `_ + :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.ProjectCard.ProjectCard` + :param archived_state: string + """ + assert archived_state is github.GithubObject.NotSet or isinstance( + archived_state, str + ), archived_state + + url_parameters = dict() + if archived_state is not github.GithubObject.NotSet: + url_parameters["archived_state"] = archived_state + + return github.PaginatedList.PaginatedList( + github.ProjectCard.ProjectCard, + self._requester, + self.url + "/cards", + url_parameters, + {"Accept": Consts.mediaTypeProjectsPreview}, + ) + + def create_card( + self, + note=github.GithubObject.NotSet, + content_id=github.GithubObject.NotSet, + content_type=github.GithubObject.NotSet, + ): + """ + :calls: `POST /projects/columns/:column_id/cards `_ + :param note: string + :param content_id: integer + :param content_type: string + """ + post_parameters = {} + if isinstance(note, str): + assert content_id is github.GithubObject.NotSet, content_id + assert content_type is github.GithubObject.NotSet, content_type + post_parameters = {"note": note} + else: + assert note is github.GithubObject.NotSet, note + assert isinstance(content_id, int), content_id + assert isinstance(content_type, str), content_type + post_parameters = {"content_id": content_id, "content_type": content_type} + + import_header = {"Accept": Consts.mediaTypeProjectsPreview} + headers, data = self._requester.requestJsonAndCheck( + "POST", self.url + "/cards", headers=import_header, input=post_parameters + ) + return github.ProjectCard.ProjectCard( + self._requester, headers, data, completed=True + ) + + def _initAttributes(self): + self._cards_url = github.GithubObject.NotSet + self._created_at = github.GithubObject.NotSet + self._id = github.GithubObject.NotSet + self._name = github.GithubObject.NotSet + self._node_id = github.GithubObject.NotSet + self._project_url = github.GithubObject.NotSet + self._updated_at = github.GithubObject.NotSet + self._url = github.GithubObject.NotSet + + def _useAttributes(self, attributes): + if "cards_url" in attributes: # pragma no branch + self._cards_url = self._makeStringAttribute(attributes["cards_url"]) + if "created_at" in attributes: # pragma no branch + self._created_at = self._makeDatetimeAttribute(attributes["created_at"]) + if "id" in attributes: # pragma no branch + self._id = self._makeIntAttribute(attributes["id"]) + if "name" in attributes: # pragma no branch + self._name = self._makeStringAttribute(attributes["name"]) + if "node_id" in attributes: # pragma no branch + self._node_id = self._makeStringAttribute(attributes["node_id"]) + if "project_url" in attributes: # pragma no branch + self._project_url = self._makeStringAttribute(attributes["project_url"]) + if "updated_at" in attributes: # pragma no branch + self._updated_at = self._makeDatetimeAttribute(attributes["updated_at"]) + if "url" in attributes: # pragma no branch + self._url = self._makeStringAttribute(attributes["url"]) diff --git a/pool/shard007/Python/0070032_request.py b/pool/shard007/Python/0070032_request.py new file mode 100644 index 0000000000000000000000000000000000000000..77592521c6c3c3c90ec689d836e1477d89d9867b --- /dev/null +++ b/pool/shard007/Python/0070032_request.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +#import requests +#r = requests.get('http://letiantian.me/') +#print(r.text) + +import gevent +from gevent import monkey +monkey.patch_socket() + +import urllib2 + +urls = ['http://letiantian.me/'] * 10 + +def get_content(url): + data = urllib2.urlopen(url).read() + return data + +#for url in urls: +# get_content(url) + +jobs = [gevent.spawn(get_content, url) for url in urls] +gevent.joinall(jobs) + + diff --git a/pool/shard007/Python/0070039_picking.py b/pool/shard007/Python/0070039_picking.py new file mode 100644 index 0000000000000000000000000000000000000000..603e815fc10ca0ed2cbda38ae1523e0c6f584f9f --- /dev/null +++ b/pool/shard007/Python/0070039_picking.py @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2004-2010 Tiny SPRL (). +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## + +import time +from openerp.report import report_sxw + +class picking(report_sxw.rml_parse): + def __init__(self, cr, uid, name, context): + super(picking, self).__init__(cr, uid, name, context=context) + self.localcontext.update({ + 'time': time, + 'get_product_desc': self.get_product_desc, + }) + def get_product_desc(self, move_line): + desc = move_line.product_id.name + if move_line.product_id.default_code: + desc = '[' + move_line.product_id.default_code + ']' + ' ' + desc + return desc + +for suffix in ['', '.in', '.out']: + report_sxw.report_sxw('report.stock.picking.list' + suffix, + 'stock.picking' + suffix, + 'addons/stock/report/picking.rml', + parser=picking) +# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/pool/shard007/Python/0070042_blogPostDAO.py b/pool/shard007/Python/0070042_blogPostDAO.py new file mode 100644 index 0000000000000000000000000000000000000000..db6b0dff0a432c0c90203f1d85e35aab8e375a97 --- /dev/null +++ b/pool/shard007/Python/0070042_blogPostDAO.py @@ -0,0 +1,164 @@ +__author__ = 'aje' + + +# +# Copyright (c) 2008 - 2013 10gen, Inc. +# +# 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. +# +# + +import sys +import re +import datetime +import time +from bson.objectid import ObjectId + + +# The Blog Post Data Access Object handles interactions with the Posts collection +class BlogPostDAO: + + # constructor for the class + def __init__(self, database): + self.db = database + self.posts = database.posts + + # inserts the blog entry and returns a permalink for the entry + def insert_entry(self, title, post, comments, tags_array, author, userid, group, period, opend): + print "inserting blog entry", title, post + + # fix up the permalink to not include whitespace + + exp = re.compile('\W') # match anything not alphanumeric + whitespace = re.compile('\s') + temp_title = whitespace.sub("_",title) + permalink = exp.sub('', temp_title) + + # Build a new post + post = {"group": group, + "title": title, + "open": opend, + "author": author, + "userid":userid, + "price": int(post), + "permalink":permalink, + "tags": tags_array, + "comments": comments, + "date": datetime.datetime.utcnow(), + "period":period} + + # now insert the post + try: + # XXX HW 3.2 Work Here to insert the post + print "Inserting the post", post + self.posts.insert(post) + except: + print "Error inserting post" + print "Unexpected error:", sys.exc_info()[0] + return permalink + + # returns an array of num_posts posts, reverse ordered + def get_posts(self, group, period, demo_mode): + + cursor = [] # Placeholder so blog compiles before you make your changes + + # XXX HW 3.2 Work here to get the posts + for i in range(10):print period + l = [] + if demo_mode: + cursor=self.posts.find({'period':period, 'open':1}).sort('price',-1) + else: + cursor=self.posts.find({'group': group, 'period':period, 'open':1}).sort('price',-1) + for post in cursor: + post['date'] =str(time.time()) # fix up date + post['id']=str(post['_id']); + post['price'] = str(post['price']) + if 'tags' not in post: + post['tags'] = [] # fill it in if its not there already + if 'comments' not in post: + post['comments'] = [] + post["_id"]=str(post['_id']); + if 'period' not in post: + post['period'] = 0 + else: + post['period']=str(post['period']); + l.append(post) + return l + + + # find a post corresponding to a particular permalink + def get_post_by_permalink(self, permalink): + + post = None + # XXX Work here to retrieve the specified post + post=self.posts.find_one({'permalink':permalink}) + print post; + if post is not None: + # fix up date + post['date'] = post['date'].strftime("%A, %B %d %Y at %I:%M%p") + + return post + + def get_post_by_id(self, id): + + post = None + #Work here to retrieve the specified post + post=self.posts.find_one({'_id':ObjectId(id)}) + print post; + if post is not None: + # fix up date + post['date'] = post['date'].strftime("%A, %B %d %Y at %I:%M%p") + + return post + + def accept_call(self, id, accepter_id): + call=self.get_post_by_id(id) + + call["open"]=False; + call['accepted']=accepter_id + self.posts.update({'_id':call['_id']}, {"$set": call}, upsert=False) + + def computer_accept(self, id): + call = self.get_put_by_id(id) + call["open"] = False; + call['accepted'] = -1 + self.posts.update({'_id':call['_id']}, {"$set": call}, upsert=False) + + # add a comment to a particular blog post + def add_comment(self, id, name, email, body, commentId): + + comment = {'author': name, 'body': body, 'id':commentId} + print comment; + if (email != ""): + comment['email'] = email + + try: + last_error = {'n':-1} # this is here so the code runs before you fix the next line + # XXX HW 3.3 Work here to add the comment to the designated post + post=self.posts.find_one({'_id':ObjectId(id)}) + post['comments'].append(comment); + self.posts.save(post) + return last_error['n'] # return the number of documents updated + + except: + print "Could not update the collection, error" + print "Unexpected error:", sys.exc_info()[0] + return 0 + + + + + + + + diff --git a/pool/shard007/Python/0070043_make_submission.py b/pool/shard007/Python/0070043_make_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..03fd01cdd66125145171f40d687ae7ab22a3fce6 --- /dev/null +++ b/pool/shard007/Python/0070043_make_submission.py @@ -0,0 +1,63 @@ +""" +make_submission.py +Transforms the class probabilities (csv) into lists of recommendations +Params: +RESULTS_FILENAME +SUBMIT_FILENAME +""" + +import argparse +parser = argparse.ArgumentParser() +parser.add_argument("results_filename") +parser.add_argument("submit_filename") +parser.add_argument('-d', '--dataset', default="./df.csv") +parser.add_argument('-m', '--month', type=int, default=17) +args = parser.parse_args() + +import time +import numpy as np +import pandas as pd + +DATASET = args.dataset or "./df.csv" +MONTH = args.month or 17 +RESULTS_FILENAME = args.results_filename +SUBMIT_FILENAME = args.submit_filename +print(time.strftime("%H:%M:%S", time.localtime())) +res = pd.read_csv(RESULTS_FILENAME, header=None) +PRODUCT_LABELS = [ + "ind_ahor_fin_ult1","ind_aval_fin_ult1","ind_cco_fin_ult1","ind_cder_fin_ult1","ind_cno_fin_ult1","ind_ctju_fin_ult1", + "ind_ctma_fin_ult1","ind_ctop_fin_ult1","ind_ctpp_fin_ult1","ind_deco_fin_ult1","ind_deme_fin_ult1","ind_dela_fin_ult1", + "ind_ecue_fin_ult1","ind_fond_fin_ult1","ind_hip_fin_ult1","ind_plan_fin_ult1","ind_pres_fin_ult1","ind_reca_fin_ult1", + "ind_tjcr_fin_ult1","ind_valo_fin_ult1","ind_viv_fin_ult1","ind_nomina_ult1","ind_nom_pens_ult1","ind_recibo_ult1"] + +NUM_CLASSES = len(PRODUCT_LABELS) +K_VAL = 7 +iter_csv = pd.read_csv(DATASET, iterator=True, chunksize=1000000) +lastdf = pd.concat([chunk[chunk["t"] == MONTH] for chunk in iter_csv]) +lastdf = pd.concat([lastdf["id"], lastdf.iloc[:,-NUM_CLASSES:]], axis=1) + +res = res.merge(lastdf, left_on=0, right_on="id", how="left", copy=False).as_matrix() +print("y_all_sum = ", (res[:,1:NUM_CLASSES+1] > 0.0).sum(0)) +print("y_new_sum = ", ((res[:,1:NUM_CLASSES+1] > 0.0) & (res[:,NUM_CLASSES+2:] == 0)).sum(0)) + +y_recom_sum = [0] * NUM_CLASSES +ixs_recommendation_rows = [] +for row in res: + row_id = int(row[0]) + row_prev = row[NUM_CLASSES+2:] + row = row[1:NUM_CLASSES+1] + row_boolean = (row > 0.0) + row_boolean_ixs = np.where(row_boolean)[0] + row_previous_ixs = np.where(row_prev >= 1.0)[0] + row_boolean_ixs = np.setdiff1d(row_boolean_ixs, row_previous_ixs) + row_boolean_vals = row[row_boolean_ixs] + row_recommendations_ixs = row_boolean_ixs[np.argsort(row_boolean_vals)[::-1]] + for c in row_recommendations_ixs.tolist()[:K_VAL]: + y_recom_sum[c] += 1 + ixs_recommendation_rows.append( str(row_id) + "," + ' '.join( list(map(lambda x: PRODUCT_LABELS[x], row_recommendations_ixs.tolist())) ) ) + +print("y_recom_sum = ", y_recom_sum) +with open(SUBMIT_FILENAME, 'w', newline='') as f: + f.write( '\r\n'.join(["ncodpers,added_products"] + ixs_recommendation_rows) ) + +print(time.strftime("%H:%M:%S", time.localtime())) diff --git a/pool/shard007/Python/0070044_extraction_test_topblock.py b/pool/shard007/Python/0070044_extraction_test_topblock.py new file mode 100644 index 0000000000000000000000000000000000000000..373a473758353fe9c98b4c9534d6cf1681c85c8c --- /dev/null +++ b/pool/shard007/Python/0070044_extraction_test_topblock.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python +################################################## +# Gnuradio Python Flow Graph +# Title: Extraction Test Topblock +# Generated: Thu Jun 26 13:00:39 2014 +################################################## + +from gnuradio import analog +from gnuradio import blocks +from gnuradio import eng_notation +from gnuradio import gr +from gnuradio.eng_option import eng_option +from gnuradio.filter import firdes +from optparse import OptionParser + +class extraction_test_topblock(gr.top_block): + + def __init__(self): + gr.top_block.__init__(self, "Extraction Test Topblock") + + ################################################## + # Variables + ################################################## + self.value = value = 0.5 + self.length = length = 100 + + ################################################## + # Blocks + ################################################## + self.blocks_vector_sink_x_0 = blocks.vector_sink_f(1) + self.blocks_head_0 = blocks.head(gr.sizeof_float*1, int(length)) + self.analog_const_source_x_0 = analog.sig_source_f(0, analog.GR_CONST_WAVE, 0, 0, value) + + ################################################## + # Connections + ################################################## + self.connect((self.analog_const_source_x_0, 0), (self.blocks_head_0, 0)) + self.connect((self.blocks_head_0, 0), (self.blocks_vector_sink_x_0, 0)) + + + + def get_value(self): + return self.value + + def set_value(self, value): + self.value = value + self.analog_const_source_x_0.set_offset(self.value) + + def get_length(self): + return self.length + + def set_length(self, length): + self.length = length + self.blocks_head_0.set_length(int(self.length)) + +if __name__ == '__main__': + parser = OptionParser(option_class=eng_option, usage="%prog: [options]") + (options, args) = parser.parse_args() + tb = extraction_test_topblock() + tb.start() + tb.wait() diff --git a/pool/shard007/Python/0070046_raritan.py b/pool/shard007/Python/0070046_raritan.py new file mode 100644 index 0000000000000000000000000000000000000000..696eda06529faa9b8888391f2ba7784fcb608156 --- /dev/null +++ b/pool/shard007/Python/0070046_raritan.py @@ -0,0 +1,151 @@ +import telnetlib +import os +import sys +import re +import cmd +from smap import actuate, driver +from smap.util import periodicSequentialCall + +# TODO: put in some code to reconnect in the case of dead telnet session + +CONSOLE_PROMPT='clp:/->' + +class ConsoleClient(cmd.Cmd): + """Simple Console Client in Python. This allows for readline functionality.""" + + def connect_to_console(self, host, port): + """Can throw an IOError if telnet connection fails.""" + self.console = telnetlib.Telnet(host, port) + self.console.read_until('Login:') + self.console.write('admin\r\n') + print 'login' + self.console.read_until('Password:') + print 'password' + self.console.write('ucberkeley\r\n') + print 'wait' + self.status() + + def read_from_console(self): + """Read from console until prompt is found (no more data to read) + Will throw EOFError if the console is closed. + """ + read_data = self.console.read_until(CONSOLE_PROMPT) + return self.strip_console_prompt(read_data) + + def strip_console_prompt(self,data_received): + """Strip out the console prompt if present""" + if data_received.startswith(CONSOLE_PROMPT): + return data_received.partition(CONSOLE_PROMPT)[2] + else: + #The banner case when you first connect + if data_received.endswith(CONSOLE_PROMPT): + return data_received.partition(CONSOLE_PROMPT)[0] + else: + return data_received + + def status(self): + command = 'show -d properties=powerState /system1/outlet*' + return self.run_console_command(command) + + def setstate(self, outletnum, state): + if state == 1 or state == 'on': + command = 'set /system1/outlet{0} powerState=on'.format(outletnum) + elif state == 0 or state == 'off': + command = 'set /system1/outlet{0} powerState=off'.format(outletnum) + return self.run_console_command(command) + + def getstate(self, outletnum): + command = 'show -d properties=powerState /system1/outlet'+str(outletnum) + out = self.run_console_command(command) + return out + + def run_console_command(self,line): + self.console.write(line + '\r\n') + data_recved = self.read_from_console() + return self.strip_console_prompt(data_recved) + + def do_EOF(self, line): + try: + self.console.write("quit\n") + self.console.close() + except IOError: + pass + return True + + def do_help(self,line): + """The server already has it's own help command. Use that""" + self.run_console_command("help\n") + + def do_quit(self, line): + return self.do_EOF(line) + + def default(self, line): + """Allow a command to be sent to the console.""" + self.run_console_command(line) + + def emptyline(self): + """Don't send anything to console on empty line.""" + pass + + +class Raritan(driver.SmapDriver): + + def setup(self, opts): + self.tz = opts.get('Metadata/Timezone', None) + self.username = opts.get('username','admin') + self.password = opts.get('password','ucberkeley') + self.ip = opts.get('ip','192.168.1.150') + self.port = int(opts.get('port',23)) + self.console = ConsoleClient() + self.console.connect_to_console(self.ip, self.port) + self.rate = float(opts.get('rate', 1)) + self.add_timeseries('/outlet1/state', 'On/Off', data_type='long', timezone=self.tz) + self.add_timeseries('/outlet2/state', 'On/Off', data_type='long', timezone=self.tz) + self.add_timeseries('/outlet3/state', 'On/Off', data_type='long', timezone=self.tz) + self.add_timeseries('/outlet4/state', 'On/Off', data_type='long', timezone=self.tz) + self.add_timeseries('/outlet5/state', 'On/Off', data_type='long', timezone=self.tz) + self.add_timeseries('/outlet6/state', 'On/Off', data_type='long', timezone=self.tz) + + self.add_actuator('/outlet1/state_act', 'On/Off', OnOffActuator(outlet=1, console=self.console)) + self.add_actuator('/outlet2/state_act', 'On/Off', OnOffActuator(outlet=2, console=self.console)) + self.add_actuator('/outlet3/state_act', 'On/Off', OnOffActuator(outlet=3, console=self.console)) + self.add_actuator('/outlet4/state_act', 'On/Off', OnOffActuator(outlet=4, console=self.console)) + self.add_actuator('/outlet5/state_act', 'On/Off', OnOffActuator(outlet=5, console=self.console)) + self.add_actuator('/outlet6/state_act', 'On/Off', OnOffActuator(outlet=6, console=self.console)) + + + def start(self): + periodicSequentialCall(self.read).start(self.rate) + + + def read(self): + status = self.console.status() + try: + tmp = status.index('/system1/outlet*') + newstates = status[tmp+len('/system1/outlet*'):].strip().split('\r\n\r\n') + except: + newstates = status + for i,newstate in enumerate(newstates): + if i >= 6: break + source = re.compile(r'(^[a-z/0-9]+)').findall(newstate) + val = re.compile(r'powerState is ([12])').findall(newstate) + if val: + self.add('/outlet{0}/state'.format(i+1), int(val[0])) + +class RaritanActuator(actuate.SmapActuator): + def __init__(self, **opts): + self.console = opts.get('console') + self.outlet = opts.get('outlet') + + def get_state(self, request): + return 0 + #return self.console.getstate(self.outlet) + + def set_state(self, request, state): + return self.console.setstate(self.outlet, state) + +class OnOffActuator(RaritanActuator, actuate.BinaryActuator): + def __init__(self, **opts): + actuate.BinaryActuator.__init__(self) + RaritanActuator.__init__(self, **opts) + diff --git a/pool/shard007/Python/0070049_PanelLightExample.py b/pool/shard007/Python/0070049_PanelLightExample.py new file mode 100644 index 0000000000000000000000000000000000000000..6c2be24089b0426ec854781cc6abd45df0e616cc --- /dev/null +++ b/pool/shard007/Python/0070049_PanelLightExample.py @@ -0,0 +1,42 @@ + +from muntjac.api import VerticalLayout, Panel, Label, Button + +from muntjac.ui.button import IClickListener +from muntjac.ui.themes import Reindeer + + +class PanelLightExample(VerticalLayout, IClickListener): + + def __init__(self): + super(PanelLightExample, self).__init__() + + self.setSpacing(True) + self.setSpacing(True) + + # Panel 1 - with caption + self._panel = Panel('This is a light Panel') + self._panel.setStyleName(Reindeer.PANEL_LIGHT) + self._panel.setHeight('200px') # we want scrollbars + # let's adjust the panels default layout (a VerticalLayout) + layout = self._panel.getContent() + layout.setMargin(True) # we want a margin + layout.setSpacing(True) + # and spacing between components + self.addComponent(self._panel) + + # Let's add a few rows to provoke scrollbars: + for _ in range(20): + l = Label('The quick brown fox jumps over the lazy dog.') + self._panel.addComponent(l) + + # Caption toggle: + b = Button('Toggle caption') + b.addListener(self, IClickListener) + self.addComponent(b) + + + def buttonClick(self, event): + if self._panel.getCaption() is None: + self._panel.setCaption('This is a light Panel') + else: + self._panel.setCaption(None) diff --git a/pool/shard007/Python/0070053_StateSpace2D.py b/pool/shard007/Python/0070053_StateSpace2D.py new file mode 100644 index 0000000000000000000000000000000000000000..db9a74374cdc4f9b43f7821082d76d8dee2aade5 --- /dev/null +++ b/pool/shard007/Python/0070053_StateSpace2D.py @@ -0,0 +1,50 @@ +import random +import numpy as np +from StateSpace import States + + + +class StateSpace2D: + """ + Empty continuous 2D plane + """ + def __init__(self, width, height): + self.width = width + self.height = height + self.width2 = width/2 + self.height2 = height/2 + random.seed() + + def random_state(self): + """ + Generate a valid random state + :return: + """ + randx = random.uniform(-1,1) * self.width2 + randy = random.uniform(-1,1) * self.height2 + return States.Point2D(randx, randy) + + def intermediate_state(self, source, target, step_size): + """ + Find an intermediate state a @step_size away from source to target + :param source: Source state + :param target: Target state + :param step_size: Size of the step to take towards target + :return: The intermediate state + """ + delta = target - source + delta /= np.linalg.norm(delta) + state = source.vec + delta * step_size + return States.Point2D(state[0], state[1]) + + def distance(self, source, target): + return np.linalg.norm(target - source) + + def is_state_valid(self, state): + if ((state.x >= -self.width2) and (state.x <= self.width2) and + (state.y >= -self.height2) and (state.y <= self.height2)): + return True + return False + + def is_transition_valid(self, source, goal): + return True diff --git a/pool/shard007/Python/0070054_0002_auto_20151216_0201.py b/pool/shard007/Python/0070054_0002_auto_20151216_0201.py new file mode 100644 index 0000000000000000000000000000000000000000..1db370fe87f10f9cf5651c0086fecc84609c4155 --- /dev/null +++ b/pool/shard007/Python/0070054_0002_auto_20151216_0201.py @@ -0,0 +1,35 @@ +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ("teryt_tree", "0001_initial"), + ] + + operations = [ + migrations.AlterModelOptions( + name="category", + options={"verbose_name": "Category", "verbose_name_plural": "Categories"}, + ), + migrations.AlterModelOptions( + name="jednostkaadministracyjna", + options={ + "verbose_name": "Unit of administrative division", + "verbose_name_plural": "Units of administrative division", + }, + ), + migrations.AlterField( + model_name="category", + name="level", + field=models.IntegerField( + db_index=True, + choices=[(1, "voivodeship"), (2, "county"), (3, "community")], + ), + ), + migrations.AlterField( + model_name="jednostkaadministracyjna", + name="updated_on", + field=models.DateField(verbose_name="Updated date"), + ), + ] diff --git a/pool/shard007/Python/0070056_ex14.py b/pool/shard007/Python/0070056_ex14.py new file mode 100644 index 0000000000000000000000000000000000000000..7d5075d85ccf0c855424a32940f560009ddc9124 --- /dev/null +++ b/pool/shard007/Python/0070056_ex14.py @@ -0,0 +1,20 @@ +# Getting user input and Passing it along + +from sys import argv + +k=__name__ +name=input('\nWhat\'s your name,please..?\n>') + +print('Hi {0},Am running from {1}'.format(name,k)) +print('--->I\'d like to ask thee a few Questions.') +likes=input('\nDo you really like Me..?\n>') + +lives=input('Where do you live..?\n>') +comp=input('What make of a comp are you using..?\n>') + +print(''' +SO you said {0} about liking me. +You live in {1}. Not sure where that is. +And you have {2} computer. +Thanks {3}. +'''.format(likes,lives,comp,name)) diff --git a/pool/shard007/Python/0070058_batch_recommend.py b/pool/shard007/Python/0070058_batch_recommend.py new file mode 100644 index 0000000000000000000000000000000000000000..015a0b4ccdf96b511db26e1b8800e05472b40dd5 --- /dev/null +++ b/pool/shard007/Python/0070058_batch_recommend.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +""" Gets candidate product recommendations for all users in the database and + save them to file. + + Command-line parameters: + *environment* - The db host name. + + *n_recommendations* - The intended number of recommendations. + + *algorithm* - The algorithm to be used. + + Example of usage + + ``python recommend.py development 10 UBCF`` + + **Output** + + Returns a JSON object as follows: + {"products": a map {user: {product_id : {"score" : score, "rank", + rank}}}, "success": "true"}, if recommendation ran fine; {"message": + "some error message", "success": "false"}, otherwise. + + Notice that the returned map of recommendations is not ordered. This is + not an issue, since the recommendations *must* be ordered anyway after + querying the database for satellite data. +""" + +import sys +import traceback + +from barbante.utils.profiling import profile +import barbante.utils.logging as barbante_logging +from barbante.context import init_session +from barbante.context.context_manager import new_context + + +log = barbante_logging.get_logger(__name__) + + +@profile +def recommend_products_all_users(env, count_recommendations, algorithm): + result = {} + session = init_session(env) + + all_users = session.data_proxy.fetch_all_user_ids() + done = 0 + for user_id in all_users: + session = init_session(env, user_id, algorithm=algorithm) + recommender = session.get_recommender() + recommendations = recommender.recommend(count_recommendations) + result[user_id] = recommendations + done += 1 + if done % 1000 == 0: + log.debug("Processed %d users." % done) + + return result + + +def map_to_csv(recommendations_map, separator, n_recommendations): + csv_as_list = [] + for user_id in recommendations_map: + scores_by_product = recommendations_map[user_id] + product_tuples = [] + for product_id in scores_by_product: + product_tuple = (scores_by_product[product_id]["rank"], product_id) + product_tuples += [product_tuple] + sorted_product_tuples = sorted(product_tuples) + row = [str(user_id)] + for product_tuple in sorted_product_tuples: + row += [str(product_tuple[1])] + row_as_string = separator.join(row) + csv_as_list += [row_as_string] + csv = "USER" + separator + for i in range(n_recommendations): + csv += "PRODUCT_" + str(i + 1) + if i < n_recommendations - 1: + csv += separator + csv += "\n" + "\n".join(csv_as_list) + return csv + + +def main(argv): + if len(argv) == 0: + return {"success": False, "message": "You must specify the environment, the number of " + "recommendations and the algorithm."} + try: + # command-line arguments + export_to_csv = False + if argv[0] == "--csv": + export_to_csv = True + del (argv[0]) + env = argv[0] + count_recommendations = int(argv[1]) + algorithm = argv[2] + + results = recommend_products_all_users(env, count_recommendations, algorithm) + + except Exception: + log.exception('Exception on {0}:'.format(__name__)) + return {"success": False, "message": traceback.format_exc()} + + if export_to_csv: + return map_to_csv(results, ";", count_recommendations) + else: + if results is not None: + return_json = {"success": True, "products": results} + return return_json + else: + msg = "No recommendations" + log.error(msg) + return {"success": False, "message": msg} + + +if __name__ == '__main__': + with new_context(): + print(main(sys.argv[1:])) diff --git a/pool/shard007/Python/0070061_links.py b/pool/shard007/Python/0070061_links.py new file mode 100644 index 0000000000000000000000000000000000000000..67cdbacb89aa0fa2e337e00e78bd64a325bcf911 --- /dev/null +++ b/pool/shard007/Python/0070061_links.py @@ -0,0 +1,48 @@ +from collections import OrderedDict + +from flask import Blueprint, current_app as app, url_for, redirect + +from ..domain import Text + + +blueprint = Blueprint('links', __name__, url_prefix="/") + + +@blueprint.route("") +def get_without_text(key): + template = app.template_service.find(key) + if template.key != key: + return redirect(url_for(".get_without_text", key=template.key)) + + text = Text(template.default or '_') + return redirect(url_for(".get", key=key, path=text.path)) + + +@blueprint.route("/", endpoint='get') +def get_with_text(key, path): + """Get links for generated images.""" + template = app.template_service.find(key) + if template.key != key: + return redirect(url_for(".get", key=template.key, path=path)) + + text = Text(path) + if text.path != path: + return redirect(url_for(".get", key=key, path=text.path)) + + data = OrderedDict() + data['direct'] = OrderedDict() + visible_url = url_for('image.get', key=key, path=path, _external=True) + data['direct']['visible'] = visible_url + code = app.link_service.encode(key, path) + masked_url = url_for('image.get_encoded', code=code, _external=True) + data['direct']['masked'] = masked_url + data['markdown'] = OrderedDict() + data['markdown']['visible'] = "![{k}]({u})".format(k=key, u=visible_url) + data['markdown']['masked'] = "![{k}]({u})".format(k=key, u=masked_url) + return data + + +@blueprint.route("_") +def get_encoded(code): + key, path = app.link_service.decode(code) + return redirect(url_for('.get', key=key, path=path)) diff --git a/pool/shard007/Python/0070064_views.py b/pool/shard007/Python/0070064_views.py new file mode 100644 index 0000000000000000000000000000000000000000..0a012068ede11679372da24ccadf8b02df001aca --- /dev/null +++ b/pool/shard007/Python/0070064_views.py @@ -0,0 +1,55 @@ +import datetime + +from django.http.response import HttpResponse + +from rest_framework import status +from rest_framework.response import Response +from rest_framework.views import APIView + +from .controllers.mandadas_controller import MandadaController +from .serializers import MandadaSerializer + + +def index(request): + return HttpResponse('hello') + + +class MandadasView(APIView): + + @staticmethod + def get(request, init_date=None, end_date=None, user_id=None, + user_email=None): + status_code = status.HTTP_204_NO_CONTENT + data = {} + error = False + init_date = init_date or request.query_params.get('init_date') + end_date = end_date or request.query_params.get('end_date') + if init_date and end_date: + try: + init_date = datetime.datetime.strptime(init_date, '%Y-%m-%d') + end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d') + except ValueError: + status_code = status.HTTP_400_BAD_REQUEST + error = True + init_date = None + end_date = None + else: + end_date = end_date + datetime.timedelta(days=1) + + user_id = user_id or request.query_params.get('user_id') + user_email = user_email or request.query_params.get('user_email') + + mandadas_controller = MandadaController( + init_date=init_date, + end_date=end_date, + user_email=user_email, + user_id=user_id + ) + mandadas = mandadas_controller.run_query() + if mandadas.exists() and not error: + serializer = MandadaSerializer(mandadas, many=True) + status_code = status.HTTP_200_OK + data['data'] = serializer.data + + data['count'] = mandadas.count() + return Response(data, status=status_code) diff --git a/pool/shard007/Python/0070068_scheduler_test.py b/pool/shard007/Python/0070068_scheduler_test.py new file mode 100644 index 0000000000000000000000000000000000000000..bd4837bb2dc6b6a005b26d9f35aecb1c7b82d6a7 --- /dev/null +++ b/pool/shard007/Python/0070068_scheduler_test.py @@ -0,0 +1,181 @@ +# Screen scheduler test classes. +# +# This file is part of Simpleline Text UI library. +# +# Copyright (C) 2020 Red Hat, Inc. +# +# Simpleline 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. +# +# Simpleline 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 Simpleline. If not, see . +# +# Author(s): Jiri Konecny +# + +import unittest + +from unittest import mock + +from simpleline.event_loop.main_loop import MainLoop +from simpleline.render.screen import UIScreen +from simpleline.render.screen_scheduler import ScreenScheduler +from simpleline.render.screen_stack import ScreenStack, ScreenStackEmptyException + + +class Scheduler_TestCase(unittest.TestCase): + + def setUp(self): + self.stack = None + self.scheduler = None + + def create_scheduler_with_stack(self): + self.stack = ScreenStack() + self.scheduler = ScreenScheduler(event_loop=mock.MagicMock(), scheduler_stack=self.stack) + + def pop_last_item(self, remove=True): + return self.stack.pop(remove) + + def test_create_scheduler(self): + scheduler = ScreenScheduler(MainLoop()) + self.assertTrue(isinstance(scheduler._screen_stack, ScreenStack)) # pylint: disable=protected-access + + def test_scheduler_quit_screen(self): + def test_callback(): + pass + scheduler = ScreenScheduler(MainLoop()) + self.assertEqual(scheduler.quit_screen, None) + scheduler.quit_screen = test_callback + self.assertEqual(scheduler.quit_screen, test_callback) + + def test_nothing_to_render(self): + self.create_scheduler_with_stack() + + self.assertTrue(self.scheduler.nothing_to_render) + self.assertTrue(self.stack.empty()) + + self.scheduler.schedule_screen(UIScreen()) + self.assertFalse(self.scheduler.nothing_to_render) + self.assertFalse(self.stack.empty()) + + def test_schedule_screen(self): + self.create_scheduler_with_stack() + + screen = UIScreen() + self.scheduler.schedule_screen(screen) + test_screen = self.pop_last_item(False) + self.assertEqual(test_screen.ui_screen, screen) + self.assertEqual(test_screen.args, None) # empty field - no arguments + self.assertFalse(test_screen.execute_new_loop) + + # Schedule another screen, new one will be added to the bottom of the stack + new_screen = UIScreen() + self.scheduler.schedule_screen(new_screen) + # Here should still be the old screen + self.assertEqual(self.pop_last_item().ui_screen, screen) + # After removing the first we would find the second screen + self.assertEqual(self.pop_last_item().ui_screen, new_screen) + + def test_replace_screen_with_empty_stack(self): + self.create_scheduler_with_stack() + + with self.assertRaises(ScreenStackEmptyException): + self.scheduler.replace_screen(UIScreen()) + + def test_replace_screen(self): + self.create_scheduler_with_stack() + + old_screen = UIScreen() + screen = UIScreen() + self.scheduler.schedule_screen(old_screen) + self.scheduler.replace_screen(screen) + self.assertEqual(self.pop_last_item(False).ui_screen, screen) + + new_screen = UIScreen() + self.scheduler.replace_screen(new_screen) + self.assertEqual(self.pop_last_item().ui_screen, new_screen) + # The old_screen was replaced so the stack is empty now + self.assertTrue(self.stack.empty()) + + def test_replace_screen_with_args(self): + self.create_scheduler_with_stack() + + old_screen = UIScreen() + screen = UIScreen() + self.scheduler.schedule_screen(old_screen) + self.scheduler.replace_screen(screen, "test") + test_screen = self.pop_last_item() + self.assertEqual(test_screen.ui_screen, screen) + self.assertEqual(test_screen.args, "test") + # The old_screen was replaced so the stack is empty now + self.assertTrue(self.stack.empty()) + + def test_switch_screen_with_empty_stack(self): + self.create_scheduler_with_stack() + + screen = UIScreen() + self.scheduler.push_screen(screen) + self.assertEqual(self.pop_last_item().ui_screen, screen) + + def test_switch_screen(self): + self.create_scheduler_with_stack() + + screen = UIScreen() + new_screen = UIScreen() + + self.scheduler.schedule_screen(screen) + self.scheduler.push_screen(new_screen) + + test_screen = self.pop_last_item() + self.assertEqual(test_screen.ui_screen, new_screen) + self.assertEqual(test_screen.args, None) + self.assertEqual(test_screen.execute_new_loop, False) + + # We popped the new_screen so the old screen should stay here + self.assertEqual(self.pop_last_item().ui_screen, screen) + self.assertTrue(self.stack.empty()) + + def test_switch_screen_with_args(self): + self.create_scheduler_with_stack() + + screen = UIScreen() + self.scheduler.push_screen(screen, args="test") + self.assertEqual(self.pop_last_item(False).ui_screen, screen) + self.assertEqual(self.pop_last_item().args, "test") + + @mock.patch('simpleline.render.screen_scheduler.ScreenScheduler._draw_screen') + def test_switch_screen_modal_empty_stack(self, _): + self.create_scheduler_with_stack() + + screen = UIScreen() + self.scheduler.push_screen_modal(screen) + self.assertEqual(self.pop_last_item().ui_screen, screen) + + @mock.patch('simpleline.render.screen_scheduler.ScreenScheduler._draw_screen') + def test_switch_screen_modal(self, _): + self.create_scheduler_with_stack() + + screen = UIScreen() + new_screen = UIScreen() + self.scheduler.schedule_screen(screen) + self.scheduler.push_screen_modal(new_screen) + + test_screen = self.pop_last_item() + self.assertEqual(test_screen.ui_screen, new_screen) + self.assertEqual(test_screen.args, None) + self.assertEqual(test_screen.execute_new_loop, True) + + @mock.patch('simpleline.render.screen_scheduler.ScreenScheduler._draw_screen') + def test_switch_screen_modal_with_args(self, _): + self.create_scheduler_with_stack() + + screen = UIScreen() + self.scheduler.push_screen_modal(screen, args="test") + self.assertEqual(self.pop_last_item(False).ui_screen, screen) diff --git a/pool/shard007/Python/0070078_manager.py b/pool/shard007/Python/0070078_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..b72a71e8b6ff3bd1e29d2d5c776b1c3d5b7b8d5d --- /dev/null +++ b/pool/shard007/Python/0070078_manager.py @@ -0,0 +1,227 @@ +# *************************************************************************** +# * Copyright (c) 2019 Bernd Hahnebach * +# * Copyright (c) 2020 Sudhanshu Dubey * +# * * +# * This file is part of the FreeCAD CAx development system. * +# * * +# * This program is free software; you can redistribute it and/or modify * +# * it under the terms of the GNU Lesser General Public License (LGPL) * +# * as published by the Free Software Foundation; either version 2 of * +# * the License, or (at your option) any later version. * +# * for detail see the LICENCE text file. * +# * * +# * 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 Library General Public License for more details. * +# * * +# * You should have received a copy of the GNU Library General Public * +# * License along with this program; if not, write to the Free Software * +# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * +# * USA * +# * * +# *************************************************************************** + +import FreeCAD + + +# ************************************************************************************************ +# setup and run examples by Python + +# TODO: use method from examples gui to collect all examples in run_all method +# FreeCAD Gui update between the examples would makes sense too + +""" +# setup all examples +from femexamples.manager import * +setup_all() + + +# run all examples +from femexamples.manager import * +run_all() + + +# one special example +from femexamples.manager import run_example as run + +doc = run("boxanalysis_static") +doc = run("boxanalysis_frequency") + +""" + + +def run_all(): + run_example("boxanalysis_frequency", run_solver=True) + run_example("boxanalysis_static", run_solver=True) + run_example("buckling_lateraltorsionalbuckling", run_solver=True) + run_example("buckling_platebuckling", run_solver=True) + run_example("ccx_buckling_flexuralbuckling", run_solver=True) + run_example("ccx_cantilever_faceload", run_solver=True) + run_example("ccx_cantilever_hexa20faceload", run_solver=True) + run_example("ccx_cantilever_nodeload", run_solver=True) + run_example("ccx_cantilever_prescribeddisplacement", run_solver=True) + run_example("constraint_contact_shell_shell", run_solver=True) + run_example("constraint_contact_solid_solid", run_solver=True) + run_example("constraint_section_print", run_solver=True) + run_example("constraint_selfweight_cantilever", run_solver=True) + run_example("constraint_tie", run_solver=True) + run_example("constraint_transform_beam_hinged", run_solver=True) + run_example("elmer_nonguitutorial01_eigenvalue_of_elastic_beam", run_solver=True) + run_example("equation_electrostatics_capacitance_two_balls", run_solver=True) + run_example("equation_electrostatics_electricforce_elmer_nongui6", run_solver=True) + run_example("frequency_beamsimple", run_solver=True) + run_example("material_multiple_bendingbeam_fiveboxes", run_solver=True) + run_example("material_multiple_bendingbeam_fivefaces", run_solver=True) + run_example("material_multiple_tensionrod_twoboxes", run_solver=True) + run_example("material_nl_platewithhole", run_solver=True) + run_example("rc_wall_2d", run_solver=True) + run_example("square_pipe_end_twisted_edgeforces", run_solver=True) + run_example("square_pipe_end_twisted_nodeforces", run_solver=True) + run_example("thermomech_bimetall", run_solver=True) + run_example("thermomech_flow1d", run_solver=True) + run_example("thermomech_spine", run_solver=True) + + +def setup_all(): + run_example("boxanalysis_frequency") + run_example("boxanalysis_static") + run_example("buckling_lateraltorsionalbuckling") + run_example("buckling_platebuckling") + run_example("ccx_buckling_flexuralbuckling") + run_example("ccx_cantilever_faceload") + run_example("ccx_cantilever_hexa20faceload") + run_example("ccx_cantilever_nodeload") + run_example("ccx_cantilever_prescribeddisplacement") + run_example("constraint_contact_shell_shell") + run_example("constraint_contact_solid_solid") + run_example("constraint_section_print") + run_example("constraint_selfweight_cantilever") + run_example("constraint_tie") + run_example("constraint_transform_beam_hinged") + run_example("elmer_nonguitutorial01_eigenvalue_of_elastic_beam") + run_example("equation_electrostatics_capacitance_two_balls") + run_example("equation_electrostatics_electricforce_elmer_nongui6") + run_example("frequency_beamsimple") + run_example("material_multiple_bendingbeam_fiveboxes") + run_example("material_multiple_bendingbeam_fivefaces") + run_example("material_multiple_tensionrod_twoboxes") + run_example("material_nl_platewithhole") + run_example("rc_wall_2d") + run_example("square_pipe_end_twisted_edgeforces") + run_example("square_pipe_end_twisted_nodeforces") + run_example("thermomech_bimetall") + run_example("thermomech_flow1d") + run_example("thermomech_spine") + + +def run_analysis(doc, base_name, filepath="", run_solver=False): + + from os.path import join, exists + from os import makedirs + from tempfile import gettempdir as gettmp + + # recompute + doc.recompute() + + # print(doc.Objects) + # print([obj.Name for obj in doc.Objects]) + + # filepath + if filepath == "": + filepath = join(gettmp(), "FEM_examples") + if not exists(filepath): + makedirs(filepath) + + # find the first solver + # thus ATM only one solver per analysis is supported + from femtools.femutils import is_derived_from + for m in doc.Analysis.Group: + if is_derived_from(m, "Fem::FemSolverObjectPython"): + solver = m + break + + # a file name is needed for the besides dir to work + save_fc_file = join(filepath, (base_name + ".FCStd")) + FreeCAD.Console.PrintMessage( + "Save FreeCAD file for {} analysis to {}\n.".format(base_name, save_fc_file) + ) + doc.saveAs(save_fc_file) + + # get analysis workig dir + from femtools.femutils import get_beside_dir + working_dir = get_beside_dir(solver) + + # run analysis + from femsolver.run import run_fem_solver + if run_solver is True: + run_fem_solver(solver, working_dir) + + # save doc once again with results + doc.save() + + +def run_example(example, solver=None, base_name=None, run_solver=False): + + from importlib import import_module + module = import_module("femexamples." + example) + if not hasattr(module, "setup"): + FreeCAD.Console.PrintError("Setup method not found in {}\n".format(example)) + return None + + if solver is None: + doc = getattr(module, "setup")() + else: + doc = getattr(module, "setup")(solvertype=solver) + + if base_name is None: + base_name = example + if solver is not None: + base_name += "_" + solver + run_analysis(doc, base_name, run_solver=run_solver) + doc.recompute() + + return doc + + +# ************************************************************************************************ +# helper used from examples +def init_doc(doc=None): + if doc is None: + doc = FreeCAD.newDocument() + return doc + + +def get_meshname(): + # needs to be "Mesh" to work with unit tests + return "Mesh" + + +def get_header(information): + return """{name} + +{information}""".format(name=information["name"], information=print_info_dict(information)) + + +def print_info_dict(information): + the_text = "" + for k, v in information.items(): + value_text = "" + if isinstance(v, list): + for j in v: + value_text += "{}, ".format(j) + value_text = value_text.rstrip(", ") + else: + value_text = v + the_text += "{} --> {}\n".format(k, value_text) + # print(the_text) + return the_text + + +def add_explanation_obj(doc, the_text): + text_obj = doc.addObject("App::TextDocument", "Explanation_Report") + text_obj.Text = the_text + text_obj.setPropertyStatus("Text", "ReadOnly") # set property editor readonly + if FreeCAD.GuiUp: + text_obj.ViewObject.ReadOnly = True # set editor view readonly + return text_obj diff --git a/pool/shard007/Python/0070082_shared_resources.py b/pool/shard007/Python/0070082_shared_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..5dad2341bb0db47984b439b7499274856d402df7 --- /dev/null +++ b/pool/shard007/Python/0070082_shared_resources.py @@ -0,0 +1,210 @@ +# This code is licensed under the MIT License (see LICENSE file for details) + +import contextlib +import atexit +import sys +import pkg_resources +import signal + +import numpy +from PyQt5 import Qt +import sip + +_QAPPLICATION = None +def init_qapplication(icon_resource_path=(__name__, 'icon.svg')): + global _QAPPLICATION + if _QAPPLICATION is None: + assert Qt.QApplication.instance() is None + pre_qapp_initialization() + _QAPPLICATION = Qt.QApplication([]) + post_qapp_initialization() + + if icon_resource_path is not None: + iconfile = pkg_resources.resource_filename(*icon_resource_path) + _QAPPLICATION.setWindowIcon(Qt.QIcon(iconfile)) + + try: + # are we running in IPython? + import IPython + ipython = IPython.get_ipython() # only not None if IPython is currently running + except ModuleNotFoundError: + ipython = None + + if ipython is not None: + # If iPython is running, turn on the GUI integration + ipython.enable_gui('qt5') + # QApplication.aboutToQuit is not emitted when exiting via IPython + # so register a handler to do so + atexit.register(_emit_about_to_quit) + + else: + # install signal handlers so that Qt can be interrupted by control-c to quit + def sigint_handler(*args): + """Handler for the SIGINT signal.""" + Qt.QApplication.quit() + signal.signal(signal.SIGINT, sigint_handler) + # now arrange for the QT event loop to allow the python interpreter to + # run occasionally. Otherwise it never runs, and hence the signal handler + # would never get called. + timer = Qt.QTimer() + timer.start(100) + # add a no-op callback for timeout. What's important is that the python interpreter + # gets a chance to run so it can see the signal and call the handler. + timer.timeout.connect(lambda: None) + _QAPPLICATION._timer = timer + return _QAPPLICATION + + +MSAA_SAMPLE_COUNT = 2 +SWAP_INTERVAL = 0 +GL_QSURFACE_FORMAT = None +def pre_qapp_initialization(): + Qt.QApplication.setAttribute(Qt.Qt.AA_ShareOpenGLContexts) + sip.setdestroyonexit(False) + + global GL_QSURFACE_FORMAT + assert GL_QSURFACE_FORMAT is None + GL_QSURFACE_FORMAT = Qt.QSurfaceFormat() + GL_QSURFACE_FORMAT.setRenderableType(Qt.QSurfaceFormat.OpenGL) + GL_QSURFACE_FORMAT.setVersion(2, 1) + GL_QSURFACE_FORMAT.setProfile(Qt.QSurfaceFormat.CompatibilityProfile) + GL_QSURFACE_FORMAT.setSwapBehavior(Qt.QSurfaceFormat.DoubleBuffer) + GL_QSURFACE_FORMAT.setStereo(False) + GL_QSURFACE_FORMAT.setSwapInterval(SWAP_INTERVAL) + GL_QSURFACE_FORMAT.setSamples(MSAA_SAMPLE_COUNT) + GL_QSURFACE_FORMAT.setRedBufferSize(8) + GL_QSURFACE_FORMAT.setGreenBufferSize(8) + GL_QSURFACE_FORMAT.setBlueBufferSize(8) + GL_QSURFACE_FORMAT.setAlphaBufferSize(8) + Qt.QSurfaceFormat.setDefaultFormat(GL_QSURFACE_FORMAT) + +OFFSCREEN_SURFACE = None +OFFSCREEN_CONTEXT = None +def post_qapp_initialization(): + global OFFSCREEN_SURFACE, OFFSCREEN_CONTEXT + assert OFFSCREEN_SURFACE is None + OFFSCREEN_SURFACE = Qt.QOffscreenSurface() + OFFSCREEN_SURFACE.setFormat(GL_QSURFACE_FORMAT) + OFFSCREEN_SURFACE.create() + OFFSCREEN_CONTEXT = Qt.QOpenGLContext() + OFFSCREEN_CONTEXT.setShareContext(Qt.QOpenGLContext.globalShareContext()) + OFFSCREEN_CONTEXT.setFormat(GL_QSURFACE_FORMAT) + OFFSCREEN_CONTEXT.create() + +def _emit_about_to_quit(): + # With IPython's Qt event loop integration installed, the Qt.QApplication.aboutToQuit signal is not emitted + # when the Python interpreter exits. However, we must do certain things before last-pass garbage collection + # at interpreter exit time in order to avoid segfaulting, and these things are done in response to the + # Qt.QApplication.aboutToQuit signal. Fortunately, we can cause Qt.QApplication.aboutToQuit emission + # ourselves. Doing so at exit time prompts our cleanup routines, avoiding segfault upon exit. + app = Qt.QApplication.instance() + if app is None: + return + app.aboutToQuit.emit() + +def offscreen_context(): + estack = contextlib.ExitStack() + if Qt.QOpenGLContext.currentContext() is None: + estack.callback(OFFSCREEN_CONTEXT.doneCurrent) + OFFSCREEN_CONTEXT.makeCurrent(OFFSCREEN_SURFACE) + return estack + + +_NEXT_QGRAPHICSITEM_USERTYPE = Qt.QGraphicsItem.UserType +def generate_unique_qgraphicsitem_type(): + """Returns a value to return from QGraphicsItem.type() overrides (which help + Qt and PyQt return objects of the right type from any call returning QGraphicsItem + references; for details see http://www.riverbankcomputing.com/pipermail/pyqt/2015-January/035302.html + and https://bugreports.qt.io/browse/QTBUG-45064) + + This function will not return the same value twice and should be + used to generate type values for all custom item classes that may + have instances in the same scene.""" + global _NEXT_QGRAPHICSITEM_USERTYPE + _NEXT_QGRAPHICSITEM_USERTYPE += 1 + return _NEXT_QGRAPHICSITEM_USERTYPE + + +_QGL_CACHE = {} +def QGL(): + current_thread = Qt.QThread.currentThread() + if current_thread is None: + # We are probably being called by a destructor being called by an at-exit cleanup routine, but too much + # Qt infrastructure has already been torn down for whatever is calling us to complete its cleanup. + return + context = Qt.QOpenGLContext.currentContext() + if context is None: + raise RuntimeError('There is no current OpenGL context.') + assert current_thread is context.thread() + # Attempt to return cache entry, a Qt.QOpenGLVersionFunctions object... + try: + return _QGL_CACHE[context] + except KeyError: + pass + # There is no entry for the current OpenGL context in our cache. Acquire, cache, and return a + # Qt.QOpenGLVersionFunctions object. + try: + QGL = context.versionFunctions() + if QGL is None: + # Some platforms seem to need version profile specification + vp = Qt.QOpenGLVersionProfile() + vp.setProfile(Qt.QSurfaceFormat.CompatibilityProfile) + vp.setVersion(2, 1) + QGL = context.versionFunctions(vp) + except ImportError: + # PyQt5 v5.4.0 and v5.4.1 provide access to OpenGL functions up to OpenGL 2.0, but we have made + # an OpenGL 2.1 context. QOpenGLContext.versionFunctions(..) will, by default, attempt to return + # a wrapper around QOpenGLFunctions2_1, which has failed in the try block above. Therefore, + # we fall back to explicitly requesting 2.0 functions. We don't need any of the C _GL 2.1 + # constants or calls, anyway - these address non-square shader uniform transformation matrices and + # specification of sRGB texture formats, neither of which we use. + vp = Qt.QOpenGLVersionProfile() + vp.setProfile(Qt.QSurfaceFormat.CompatibilityProfile) + vp.setVersion(2, 0) + QGL = context.versionFunctions(vp) + if QGL is None: + raise RuntimeError('Failed to retrieve QOpenGL.') + if not QGL.initializeOpenGLFunctions(): + raise RuntimeError('Failed to initialize OpenGL wrapper namespace.') + _QGL_CACHE[context] = QGL + # TODO: is below really not necessary? + context.aboutToBeDestroyed.connect(lambda c=context: _QGL_CACHE.pop(c)) + return QGL + +class _GlQuad: + def __init__(self): + if Qt.QOpenGLContext.currentContext() is None: + raise RuntimeError("A QOpenGLContext must be current when a _GlQuad is instantiated.") + self.vao = Qt.QOpenGLVertexArrayObject() + self.vao.create() + vao_binder = Qt.QOpenGLVertexArrayObject.Binder(self.vao) + quad = numpy.array([1.1, -1.1, + -1.1, -1.1, + -1.1, 1.1, + 1.1, 1.1], dtype=numpy.float32) + self.buffer = Qt.QOpenGLBuffer(Qt.QOpenGLBuffer.VertexBuffer) + self.buffer.create() + self.buffer.bind() + try: + self.buffer.setUsagePattern(Qt.QOpenGLBuffer.StaticDraw) + self.buffer.allocate(quad.ctypes.data, quad.nbytes) + finally: + # Note: the following release call is essential. Without it, if a QPainter is active, QPainter will never work for + # again for the widget with the active painter! + self.buffer.release() + # Qt.QApplication.instance().aboutToQuit.connect(self._on_about_to_quit) + + # def _on_about_to_quit(self): + # with offscreen_context(): + # self.vao.destroy() + # self.vao = None + # self.buffer.destroy() + # self.buffer = None + +_GL_QUAD = None +def GL_QUAD(): + global _GL_QUAD + if _GL_QUAD is None: + _GL_QUAD = _GlQuad() + return _GL_QUAD + diff --git a/pool/shard007/Python/0070084_server.py b/pool/shard007/Python/0070084_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a49d9e1cf1884f6ffe9f90166d3d742d22b5d056 --- /dev/null +++ b/pool/shard007/Python/0070084_server.py @@ -0,0 +1,158 @@ +import global_data as g +from util import * +import sys +import time +import select +import socket +import Queue +import os +from input_handler import HandleUserInput +import random +import hashlib +import json +import threading +import atexit, signal + +class Connection: + def __init__(self, g_data): + self.auth = False + self.queue = Queue.Queue() + self.g_data = g_data + self.attached = False + + +def GDatas(): + abs_prefix = os.path.join(os.path.dirname(__file__), "../data") + with open(abs_prefix + '/config.json','r') as f: + conf = json.load(f) + host = conf['host'] if 'host' in conf else 'localhost' + port = conf['port'] if 'port' in conf else 10001 + g_datas = [] + for i in xrange(len(conf["bots"])): + if "skip" in conf["bots"][i] and conf["bots"][i]: + continue + g_datas.append(g.GlobalData(g_data = None if len(g_datas) == 0 else g_datas[0], conf=conf["bots"][i], dbHost=conf["dbHost"])) + g_datas[-1].TraceInfo("Initialized!") + for i in xrange(len(g_datas)): + if g_datas[i].invalid: + g_datas[-1].TraceWarn("g_data INVALID!") + assert False + assert len(g_datas) != 0 + return g_datas + +def StartServer(): + + abs_prefix = os.path.join(os.path.dirname(__file__), "../data") + with open(abs_prefix + '/config.json','r') as f: + conf = json.load(f) + host = conf['host'] if 'host' in conf else 'localhost' + port = conf['port'] if 'port' in conf else 10001 + + + server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + server.setblocking(0) + + g_datas = GDatas() + + sys.excepthook = exceptionTrace + + + server_address = (host, port) + server.bind(server_address) + server.listen(5) + + g_datas[0].TraceInfo("Starting up Tiara Boom Server on %s, port %s!" % server_address) + + inputs = [server] + outputs = [] + + cons = {} + + while inputs: + + for g_data in g_datas: + g_data.SocialLogic().Act() + + ############# Begin server stuff ################## + readable, writable, exceptional = select.select(inputs, outputs, inputs, 60) + for s in readable: + if s in exceptional: + continue + if s is server: + connection, client_address = s.accept() + g_datas[0].TraceInfo('new connection from %s:%s' % client_address) + connection.setblocking(0) + inputs.append(connection) + cons[connection] = Connection(g_datas[0]) + else: + data = s.recv(1024) + data = data.strip() + if data and not data in ["quit","_upgrade","_kill"]: + if cons[s].auth: + cons[s].g_data.TraceInfo('received "%s" from %s' % (data, s.getpeername())) + cons[s].queue.put(HandleUserInput(cons[s].g_data, data)) + elif not cons[s].attached: # we haven't yet decided who to assign you to + if data in [g_data.myName for g_data in g_datas]: + this_bot = [g_data for g_data in g_datas if data == g_data.myName][0] + this_bot.TraceDebug("received hi message") + cons[s].attached = True + cons[s].g_data = this_bot + cons[s].pad = random.randrange(0,2**32) + cons[s].queue.put(str(cons[s].pad)) + else: # you're assigned a bot but not authorized + h = hashlib.sha256(str(cons[s].pad)) + h.update(cons[s].g_data.password) + if data == h.hexdigest(): + cons[s].auth = True + cons[s].queue.put("welcome") + cons[s].g_data.TraceInfo('%s:%s entered the password' % s.getpeername()) + else: + cons[s].queue.put("password denied") + cons[s].g_data.TraceInfo('%s:%s failed the password' % s.getpeername()) + if s not in outputs: + outputs.append(s) + elif not data or data == "quit" or not cons[s].auth: + try: + cons[s].g_data.TraceInfo('closing %s:%s' % s.getpeername()) + except Exception as e: + cons[s].g_data.TraceInfo("closing, cant get peer name") + if s in outputs: + outputs.remove(s) + inputs.remove(s) + s.close() + del cons[s] + elif data == "_upgrade": + s.close() + server.close() + os.system("git pull --rebase origin master") + os.execl(sys.executable, sys.executable, * sys.argv) + else: + assert data == "_kill" + s.close() + server.close() + cons[s].g_data.TraceInfo("Recieved _kill, going down NOW") + assert False + for s in writable: + if s in exceptional: + continue + try: + next_msg = cons[s].queue.get_nowait() + except Exception as e: + if s in outputs: + outputs.remove(s) + else: + cons[s].g_data.TraceInfo('sending "%s" to %s' % (next_msg[:min(50,len(next_msg))], s.getpeername())) + s.send(next_msg) + for s in exceptional: + try: + cons[s].g_data.TraceInfo('closing %s:%s' % s.getpeername()) + except Exception as e: + pass + inputs.remove(s) + if s in outputs: + outputs.remove(s) + s.close() + del cons[s] + + diff --git a/pool/shard007/Python/0070085_region.py b/pool/shard007/Python/0070085_region.py new file mode 100644 index 0000000000000000000000000000000000000000..c1f906dc6294333348d3dea4f685cd06518d3003 --- /dev/null +++ b/pool/shard007/Python/0070085_region.py @@ -0,0 +1,174 @@ +# -*- coding: utf-8 -*- +import logging +import os +import time +import requests +from qiniu import compat +from qiniu import utils + +UC_HOST = 'https://uc.qbox.me' # 获取空间信息Host + + +class Region(object): + """七牛上传区域类 + + 该类主要内容上传区域地址。 + + """ + + def __init__( + self, + up_host=None, + up_host_backup=None, + io_host=None, + host_cache={}, + home_dir=None, + scheme="http"): + """初始化Zone类""" + self.up_host, self.up_host_backup, self.io_host, self.home_dir = up_host, up_host_backup, io_host, home_dir + self.host_cache = host_cache + self.scheme = scheme + + def get_up_host_by_token(self, up_token, home_dir): + ak, bucket = self.unmarshal_up_token(up_token) + if home_dir is None: + home_dir = os.getcwd() + up_hosts = self.get_up_host(ak, bucket, home_dir) + return up_hosts[0] + + def get_up_host_backup_by_token(self, up_token, home_dir): + ak, bucket = self.unmarshal_up_token(up_token) + if home_dir is None: + home_dir = os.getcwd() + up_hosts = self.get_up_host(ak, bucket, home_dir) + if (len(up_hosts) <= 1): + up_host = up_hosts[0] + else: + up_host = up_hosts[1] + return up_host + + def get_io_host(self, ak, bucket, home_dir): + if self.io_host: + return self.io_host + if home_dir is None: + home_dir = os.getcwd() + bucket_hosts = self.get_bucket_hosts(ak, bucket, home_dir) + io_hosts = bucket_hosts['ioHosts'] + return io_hosts[0] + + def get_up_host(self, ak, bucket, home_dir): + bucket_hosts = self.get_bucket_hosts(ak, bucket, home_dir) + up_hosts = bucket_hosts['upHosts'] + return up_hosts + + def unmarshal_up_token(self, up_token): + token = up_token.split(':') + if (len(token) != 3): + raise ValueError('invalid up_token') + + ak = token[0] + policy = compat.json.loads( + compat.s( + utils.urlsafe_base64_decode( + token[2]))) + + scope = policy["scope"] + bucket = scope + if (':' in scope): + bucket = scope.split(':')[0] + + return ak, bucket + + def get_bucket_hosts(self, ak, bucket, home_dir): + key = self.scheme + ":" + ak + ":" + bucket + + bucket_hosts = self.get_bucket_hosts_to_cache(key, home_dir) + if (len(bucket_hosts) > 0): + return bucket_hosts + + hosts = {} + hosts.update({self.scheme: {}}) + + hosts[self.scheme].update({'up': []}) + hosts[self.scheme].update({'io': []}) + + if self.up_host is not None: + hosts[self.scheme]['up'].append(self.scheme + "://" + self.up_host) + + if self.up_host_backup is not None: + hosts[self.scheme]['up'].append( + self.scheme + "://" + self.up_host_backup) + + if self.io_host is not None: + hosts[self.scheme]['io'].append(self.scheme + "://" + self.io_host) + + if len(hosts[self.scheme]) == 0 or self.io_host is None: + hosts = compat.json.loads(self.bucket_hosts(ak, bucket)) + else: + # 1 year + hosts['ttl'] = int(time.time()) + 31536000 + try: + scheme_hosts = hosts[self.scheme] + except KeyError: + raise KeyError( + "Please check your BUCKET_NAME! The UpHosts is %s" % + hosts) + bucket_hosts = { + 'upHosts': scheme_hosts['up'], + 'ioHosts': scheme_hosts['io'], + 'deadline': int(time.time()) + hosts['ttl'] + } + home_dir = "" + self.set_bucket_hosts_to_cache(key, bucket_hosts, home_dir) + return bucket_hosts + + def get_bucket_hosts_to_cache(self, key, home_dir): + ret = [] + if (len(self.host_cache) == 0): + self.host_cache_from_file(home_dir) + + if self.host_cache == {}: + return ret + + if (not (key in self.host_cache)): + return ret + + if (self.host_cache[key]['deadline'] > time.time()): + ret = self.host_cache[key] + + return ret + + def set_bucket_hosts_to_cache(self, key, val, home_dir): + self.host_cache[key] = val + self.host_cache_to_file(home_dir) + return + + def host_cache_from_file(self, home_dir): + if home_dir is not None: + self.home_dir = home_dir + path = self.host_cache_file_path() + if not os.path.isfile(path): + return None + with open(path, 'r') as f: + try: + bucket_hosts = compat.json.load(f) + self.host_cache = bucket_hosts + except Exception as e: + logging.error(e) + f.close() + return + + def host_cache_file_path(self): + return os.path.join(self.home_dir, ".qiniu_pythonsdk_hostscache.json") + + def host_cache_to_file(self, home_dir): + path = self.host_cache_file_path() + with open(path, 'w') as f: + compat.json.dump(self.host_cache, f) + f.close() + + def bucket_hosts(self, ak, bucket): + url = "{0}/v1/query?ak={1}&bucket={2}".format(UC_HOST, ak, bucket) + ret = requests.get(url) + data = compat.json.dumps(ret.json(), separators=(',', ':')) + return data diff --git a/pool/shard007/Python/0070086_calculator.py b/pool/shard007/Python/0070086_calculator.py new file mode 100644 index 0000000000000000000000000000000000000000..eac506a7a20716edebf88c441de92ac89f3a26aa --- /dev/null +++ b/pool/shard007/Python/0070086_calculator.py @@ -0,0 +1,134 @@ +from __future__ import division +__kupfer_name__ = _("Calculator") +__kupfer_actions__ = ("Calculate", ) +__description__ = _("Calculate expressions starting with '='") +__version__ = "" +__author__ = "Ulrik Sverdrup " + + +import cmath +import math + +from kupfer.objects import Source, Action, TextLeaf +from kupfer import pretty + + +class IgnoreResultException (Exception): + pass + +class KupferSurprise (float): + """kupfer + + cleverness to the inf**inf + """ + def __call__(self, *args): + from kupfer import utils, version + utils.show_url(version.WEBSITE) + raise IgnoreResultException + +class DummyResult (object): + def __unicode__(self): + return u"" + +class Help (object): + """help() + + Show help about the calculator + """ + def __call__(self): + import textwrap + + from kupfer import uiutils + + environment = make_environment(last_result=DummyResult()) + docstrings = [] + for attr in sorted(environment): + if attr != "_" and attr.startswith("_"): + continue + val = environment[attr] + if not callable(val): + docstrings.append(u"%s = %s" % (attr, val)) + continue + try: + docstrings.append(val.__doc__) + except AttributeError: + pass + formatted = [] + maxlen = 72 + left_margin = 4 + for docstr in docstrings: + # Wrap the description and align continued lines + docsplit = docstr.split("\n", 1) + if len(docsplit) < 2: + formatted.append(docstr) + continue + wrapped_lines = textwrap.wrap(docsplit[1].strip(), + maxlen - left_margin) + wrapped = (u"\n" + u" "*left_margin).join(wrapped_lines) + formatted.append("%s\n %s" % (docsplit[0], wrapped)) + uiutils.show_text_result("\n\n".join(formatted), _("Calculator")) + raise IgnoreResultException + + def __complex__(self): + return self() + +def make_environment(last_result=None): + "Return a namespace for the calculator's expressions to be executed in." + environment = dict(vars(math)) + environment.update(vars(cmath)) + # define some constants missing + if last_result is not None: + environment["_"] = last_result + environment["help"] = Help() + environment["kupfer"] = KupferSurprise("inf") + # make the builtins inaccessible + environment["__builtins__"] = {} + return environment + +def format_result(res): + cres = complex(res) + parts = [] + if cres.real: + parts.append(u"%s" % cres.real) + if cres.imag: + parts.append(u"%s" % complex(0, cres.imag)) + return u"+".join(parts) or u"%s" % res + +class Calculate (Action): + # since it applies only to special queries, we can up the rank + rank_adjust = 10 + def __init__(self): + Action.__init__(self, _("Calculate")) + self.last_result = None + + def has_result(self): + return True + def activate(self, leaf): + expr = leaf.object.lstrip("= ") + + # try to add missing parantheses + brackets_missing = expr.count("(") - expr.count(")") + if brackets_missing > 0: + expr += ")"*brackets_missing + environment = make_environment(self.last_result) + + pretty.print_debug(__name__, "Evaluating", repr(expr)) + try: + result = eval(expr, environment) + resultstr = format_result(result) + self.last_result = result + except IgnoreResultException: + return + except Exception, exc: + pretty.print_error(__name__, type(exc).__name__, exc) + resultstr = unicode(exc) + return TextLeaf(resultstr) + + def item_types(self): + yield TextLeaf + def valid_for_item(self, leaf): + text = leaf.object + return text and text.startswith("=") + + def get_description(self): + return None diff --git a/pool/shard007/Python/0070087_xmlrpcdispatcher.py b/pool/shard007/Python/0070087_xmlrpcdispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..4f2986230e5ca68ee8f706a91af8d750c055dea1 --- /dev/null +++ b/pool/shard007/Python/0070087_xmlrpcdispatcher.py @@ -0,0 +1,30 @@ +from flask import request + +class XMLRPCDispatcher(object): + """Please see documentation in FlaskXMLRPC.""" + def __init__(self, log): + self._log = log + + def requestCertificate(self): + """Retrieve the certificate which the client has sent.""" + # get it from the request"s environment + if request.environ.has_key("CLIENT_RAW_CERT"): # check nginx + return request.environ["CLIENT_RAW_CERT"] + if request.environ.has_key("SSL_CLIENT_CERT"): # check apache + return request.environ["SSL_CLIENT_CERT"] + return None + + def _dispatch(self, method, params): + self._log.info("Called: <%s>" % (method)) + try: + meth = getattr(self, "%s" % (method)) + except AttributeError, e: + self._log.warning("Client called unknown method: <%s>" % (method)) + raise e + + try: + return meth(*params) + except Exception, e: + # TODO check if the exception has already been logged + self._log.exception("Call to known method <%s> failed!" % (method)) + raise e diff --git a/pool/shard007/Python/0070088_yahoo.py b/pool/shard007/Python/0070088_yahoo.py new file mode 100644 index 0000000000000000000000000000000000000000..36f62409808d0b9d5e694888ff85a1e5427027ea --- /dev/null +++ b/pool/shard007/Python/0070088_yahoo.py @@ -0,0 +1,90 @@ +""" +----------------- +YAHOO SYNC ENGINE +----------------- + +Yahoo is an IMAP backend with no CONDSTORE support. This may eventually be +our default generic IMAP implementation, but for now it's easier to develop +the backend separately. + +Yahoo does not provide server-side threading, so we have to thread messages +ourselves. Currently we make each message its own thread. + +Yahoo does not currently support synchronizing flag changes. (We plan to add +support for this later, but a lack of CONDSTORE makes it tricky / slow.) + +""" +from inbox.crispin import retry_crispin +from inbox.models.util import reconcile_message +from inbox.models.backends.imap import ImapThread +from inbox.mailsync.backends.imap import (account, base_poll, imap_poll_update, + resync_uids_from, base_initial_sync, + imap_initial_sync, ImapSyncMonitor) + + +PROVIDER = 'yahoo' +SYNC_MONITOR_CLS = 'YahooSyncMonitor' + + +class YahooSyncMonitor(ImapSyncMonitor): + def __init__(self, account_id, namespace_id, email_address, provider, + heartbeat=1, poll_frequency=30): + self.folder_state_handlers = { + 'initial': initial_sync, + 'initial uidinvalid': resync_uids_from('initial'), + 'poll': poll, + 'poll uidinvalid': resync_uids_from('poll'), + 'finish': lambda c, s, l, f, st: 'finish', + } + + ImapSyncMonitor.__init__(self, account_id, namespace_id, email_address, + provider, heartbeat=1, + poll_frequency=poll_frequency) + + +@retry_crispin +def poll(conn_pool, db_session, log, folder_name, shared_state): + with conn_pool.get() as crispin_client: + return base_poll(crispin_client, db_session, log, folder_name, + shared_state, imap_poll_update, create_yahoo_message) + + +@retry_crispin +def initial_sync(conn_pool, db_session, log, folder_name, shared_state): + with conn_pool.get() as crispin_client: + return base_initial_sync(crispin_client, db_session, log, folder_name, + shared_state, imap_initial_sync, + create_yahoo_message) + + +def create_yahoo_message(db_session, log, acct, folder, msg): + """ Yahoo-specific message creation logic. + + Returns + ------- + new_uid: inbox.models.backends.imap.ImapUid + New db object, which links to new Message and Block objects through + relationships. All new objects are uncommitted. + """ + assert acct is not None and acct.namespace is not None + + new_uid = account.create_imap_message(db_session, log, acct, folder, msg) + + if new_uid: + new_uid = add_yahoo_attrs(db_session, log, new_uid, msg.flags, + folder, msg.created) + return new_uid + + +def add_yahoo_attrs(db_session, log, new_uid, flags, folder, created): + """ Yahoo-specific post-create-message bits.""" + with db_session.no_autoflush: + new_uid.message.thread = ImapThread.from_yahoo_message( + db_session, new_uid.account.namespace, new_uid.message) + new_uid.update_imap_flags(flags) + + if folder in ('draft', 'sent') and not created and new_uid.message.inbox_uid: + reconcile_message(db_session, log, new_uid.message.inbox_uid, + new_uid.message) + + return new_uid diff --git a/pool/shard007/Python/0070090_models.py b/pool/shard007/Python/0070090_models.py new file mode 100644 index 0000000000000000000000000000000000000000..863c86163fc78007bd5ae02756442c230ef1aee1 --- /dev/null +++ b/pool/shard007/Python/0070090_models.py @@ -0,0 +1,155 @@ +from django.core.validators import MinLengthValidator +from django.db import models +from django.utils.encoding import python_2_unicode_compatible +from jsonfield import JSONField + +from treeherder.model.models import (MachinePlatform, + OptionCollection, + Repository) + +SIGNATURE_HASH_LENGTH = 40L + + +@python_2_unicode_compatible +class PerformanceFramework(models.Model): + + name = models.SlugField(max_length=255L, unique=True) + + class Meta: + db_table = 'performance_framework' + + def __str__(self): + return self.name + + +@python_2_unicode_compatible +class PerformanceSignature(models.Model): + + signature_hash = models.CharField(max_length=SIGNATURE_HASH_LENGTH, + validators=[ + MinLengthValidator(SIGNATURE_HASH_LENGTH) + ], + db_index=True) + + repository = models.ForeignKey(Repository, null=True) # null=True only temporary, until we update old entries + framework = models.ForeignKey(PerformanceFramework) + platform = models.ForeignKey(MachinePlatform) + option_collection = models.ForeignKey(OptionCollection) + suite = models.CharField(max_length=80L) + test = models.CharField(max_length=80L, blank=True) + lower_is_better = models.BooleanField(default=True) + last_updated = models.DateTimeField(db_index=True, null=True) # null=True only temporary, until we update old entries + + # extra properties to distinguish the test (that don't fit into + # option collection for whatever reason) + extra_properties = JSONField(max_length=1024) + + class Meta: + db_table = 'performance_signature' + # make sure there is only one signature per repository with a + # particular set of properties + unique_together = ('repository', 'framework', 'platform', + 'option_collection', 'suite', 'test', + 'last_updated') + # make sure there is only one signature of any hash per + # repository (same hash in different repositories is allowed) + unique_together = ('repository', 'signature_hash') + + def __str__(self): + return self.signature_hash + + +@python_2_unicode_compatible +class PerformanceDatum(models.Model): + + repository = models.ForeignKey(Repository) + job_id = models.PositiveIntegerField(db_index=True) + result_set_id = models.PositiveIntegerField(db_index=True) + signature = models.ForeignKey(PerformanceSignature) + value = models.FloatField() + push_timestamp = models.DateTimeField(db_index=True) + + class Meta: + db_table = 'performance_datum' + index_together = [('repository', 'signature', 'push_timestamp'), + ('repository', 'job_id'), + ('repository', 'result_set_id')] + unique_together = ('repository', 'job_id', 'result_set_id', + 'signature', 'push_timestamp') + + def save(self, *args, **kwargs): + super(PerformanceDatum, self).save(*args, **kwargs) # Call the "real" save() method. + if not self.signature.last_updated or (self.signature.last_updated < + self.push_timestamp): + self.signature.last_updated = self.push_timestamp + self.signature.save() + + def __str__(self): + return "{} {}".format(self.value, self.push_timestamp) + + +@python_2_unicode_compatible +class PerformanceAlertSummary(models.Model): + ''' + A summarization of performance alerts + + A summary of "alerts" that the performance numbers for a specific + repository have changed at a particular time. + + See also the :ref:`PerformanceAlert` class below. + ''' + id = models.AutoField(primary_key=True) + repository = models.ForeignKey(Repository) + prev_result_set_id = models.PositiveIntegerField() + result_set_id = models.PositiveIntegerField() + + last_updated = models.DateTimeField(db_index=True) + + class Meta: + db_table = "performance_alert_summary" + unique_together = ('repository', 'prev_result_set_id', 'result_set_id') + + def __str__(self): + return "{} {}".format(self.repository, self.result_set_id) + + +@python_2_unicode_compatible +class PerformanceAlert(models.Model): + ''' + A single performance alert + + An individual "alert" that the numbers in a specific performance + series have consistently changed level at a specific time. + + An alert is always a member of an alert summary, which groups all + the alerts associated with a particular result set and repository + together. In many cases at Mozilla, the original alert summary is not + correct, so we allow reassigning it to a different (revised) summary. + ''' + id = models.AutoField(primary_key=True) + summary = models.ForeignKey(PerformanceAlertSummary, + related_name='alerts') + revised_summary = models.ForeignKey(PerformanceAlertSummary, + related_name='revised_alerts', + null=True) + series_signature = models.ForeignKey(PerformanceSignature) + is_regression = models.BooleanField() + amount_pct = models.FloatField( + help_text="Amount in percentage that series has changed") + amount_abs = models.FloatField( + help_text="Absolute amount that series has changed") + prev_value = models.FloatField( + help_text="Previous value of series before change") + new_value = models.FloatField( + help_text="New value of series after change") + t_value = models.FloatField( + help_text="t value out of analysis indicating confidence " + "that change is 'real'") + + class Meta: + db_table = "performance_alert" + unique_together = ('summary', 'series_signature') + + def __str__(self): + return "{} {} {}%".format(self.summary, self.series_signature, + self.amount_pct) diff --git a/pool/shard007/Python/0070096_templatecell.py b/pool/shard007/Python/0070096_templatecell.py new file mode 100644 index 0000000000000000000000000000000000000000..53d1b90af5a44dfbb07e7e5ae56c05371e0dc5da --- /dev/null +++ b/pool/shard007/Python/0070096_templatecell.py @@ -0,0 +1,232 @@ +#!/usr/bin/env python +""" +Copyright (C) 2012 Computational Neuroscience Group, NMBU. + +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. + +""" + +import os +import posixpath +import sys +import neuron +from LFPy import Cell + + +class TemplateCell(Cell): + + """ + ``LFPy.Cell`` like class allowing use of NEURON templates with some + limitations. + + This takes all the same parameters as the Cell class, but requires three + more template related parameters ``templatefile``, ``templatename`` and + ``templateargs`` + + Parameters + ---------- + morphology : str + path to morphology file + templatefile : str + File with cell template definition(s) + templatename : str + Cell template-name used for this cell object + templateargs : str + Parameters provided to template-definition + v_init : float + Initial membrane potential. Default to -65. + Ra : float + axial resistance. Defaults to 150. + cm : float + membrane capacitance. Defaults to 1.0 + passive : bool + Passive mechanisms are initialized if True. Defaults to True + passive_parameters : dict + parameter dictionary with values for the passive membrane mechanism in + NEURON ('pas'). The dictionary must contain keys 'g_pas' and 'e_pas', + like the default: passive_parameters=dict(g_pas=0.001, e_pas=-70) + extracellular : bool + switch for NEURON's extracellular mechanism. Defaults to False + dt: float + Simulation time step. Defaults to 2**-4 + tstart : float + initialization time for simulation <= 0 ms. Defaults to 0. + tstop : float + stop time for simulation > 0 ms. Defaults to 100. + nsegs_method : 'lambda100' or 'lambda_f' or 'fixed_length' or None + nseg rule, used by NEURON to determine number of compartments. + Defaults to 'lambda100' + max_nsegs_length : float or None + max segment length for method 'fixed_length'. Defaults to None + lambda_f : int + AC frequency for method 'lambda_f'. Defaults to 100 + d_lambda : float + parameter for d_lambda rule. Defaults to 0.1 + delete_sections : bool + delete pre-existing section-references. Defaults to True + custom_code : list or None + list of model-specific code files ([.py/.hoc]). Defaults to None + custom_fun : list or None + list of model-specific functions with args. Defaults to None + custom_fun_args : list or None + list of args passed to custom_fun functions. Defaults to None + pt3d : bool + use pt3d-info of the cell geometries switch. Defaults to False + celsius : float or None + Temperature in celsius. If nothing is specified here + or in custom code it is 6.3 celcius + verbose : bool + verbose output switch. Defaults to False + + Examples + -------- + + >>> import LFPy + >>> cellParameters = { + >>> 'morphology' : '', + >>> 'templatefile' : '' + >>> 'templatename' : 'templatename' + >>> 'templateargs' : None + >>> 'v_init' : -65, + >>> 'cm' : 1.0, + >>> 'Ra' : 150, + >>> 'passive' : True, + >>> 'passive_parameters' : {'g_pas' : 0.001, 'e_pas' : -65.}, + >>> 'dt' : 2**-3, + >>> 'tstart' : 0, + >>> 'tstop' : 50, + >>> } + >>> cell = LFPy.TemplateCell(**cellParameters) + >>> cell.simulate() + + See also + -------- + Cell + NetworkCell + """ + + def __init__(self, + templatefile='LFPyCellTemplate.hoc', + templatename='LFPyCellTemplate', + templateargs=None, + verbose=False, + **kwargs): + if "win32" in sys.platform and isinstance(templatefile, str): + templatefile = templatefile.replace(os.sep, posixpath.sep) + self.templatefile = templatefile + self.templatename = templatename + self.templateargs = templateargs + self.verbose = verbose + + if not hasattr(neuron.h, 'd_lambda'): + neuron.h.load_file('stdlib.hoc', 'String') # NEURON std. library + neuron.h.load_file('import3d.hoc') # import 3D morphology lib + + # load the cell template specification + # check if templatename exist in neuron.h namespace: + if hasattr(neuron.h, self.templatename): + if self.verbose: + print('template %s exist already' % self.templatename) + else: + if isinstance(self.templatefile, str): + neuron.h.load_file(self.templatefile) + elif isinstance(self.templatefile, list): + for template in self.templatefile: + if "win32" in sys.platform: + template = template.replace(os.sep, posixpath.sep) + neuron.h.load_file(template) + + # initialize the parent Cell object + super().__init__(**kwargs) + + def _load_geometry(self): + """Load the morphology-file in NEURON""" + # the python cell object we are loading the morphology into: + self.template = getattr(neuron.h, self.templatename)(self.templateargs) + + # perform a test if the morphology is already loaded: + seccount = 0 + for sec in self.template.all: + seccount += 1 + if seccount == 0: + # import the morphology, try and determine format + fileEnding = self.morphology.split('.')[-1] + + if not fileEnding == 'hoc' or fileEnding == 'HOC': + # create objects for importing morphologies of different + # formats + if fileEnding == 'asc' or fileEnding == 'ASC': + Import = neuron.h.Import3d_Neurolucida3() + if not self.verbose: + Import.quiet = 1 + elif fileEnding == 'swc' or fileEnding == 'SWC': + Import = neuron.h.Import3d_SWC_read() + elif fileEnding == 'xml' or fileEnding == 'XML': + Import = neuron.h.Import3d_MorphML() + else: + raise ValueError( + '%s not a recognised morphology format' + % self.morphology).with_traceback( + 'Should be either .hoc, .asc, .swc, .xml') + + # assuming now that morphology file is the correct format + try: + Import.input(self.morphology) + except BaseException: + if not hasattr(neuron, 'neuroml'): + raise Exception( + 'Can not import, try and copy the ' + + 'nrn/share/lib/python/neuron/neuroml ' + + 'folder into %s' % + neuron.__path__[0]) + else: + raise Exception( + 'something wrong with file, see output') + try: + imprt = neuron.h.Import3d_GUI(Import, 0) + except BaseException: + raise Exception('See output, try to correct the file') + + # instantiate the cell object + if fileEnding == 'xml' or fileEnding == 'XML': + # can not currently assign xml to cell template + try: + imprt.instantiate(self.template) + except BaseException: + raise Exception("this xml file is not supported") + else: + imprt.instantiate(self.template) + + else: + neuron.h.execute( + "xopen(\"%s\")" % + self.morphology, self.template) + + # set shapes and create sectionlists + neuron.h.define_shape() + self._create_sectionlists() + + def _create_sectionlists(self): + """Create section lists for different kinds of sections""" + + self.allsecnames = [] + for sec in self.template.all: + self.allsecnames.append(sec.name()) + + self.allseclist = self.template.all + + # list of soma sections, assuming it is named on the format "soma*" + self.nsomasec = 0 + self.somalist = neuron.h.SectionList() + for sec in self.allseclist: + if 'soma' in sec.name(): + self.somalist.append(sec=sec) + self.nsomasec += 1 diff --git a/pool/shard007/Python/0070102_tex.py b/pool/shard007/Python/0070102_tex.py new file mode 100644 index 0000000000000000000000000000000000000000..ad435075fe40d64432b35420f9baaca99d339c4c --- /dev/null +++ b/pool/shard007/Python/0070102_tex.py @@ -0,0 +1,164 @@ +#!/bin/env python + +from __future__ import absolute_import + +import collections +from PyTeX import error, utilities +from PyTeX.lexer import Token +import re + +# Character Escaping + +ESC_MAP = {r'&' : r'\\&', r'%' : r'\\%', r'$' : r'\\$', r'#' : r'\\#', r'_' : r'\\_', r'{' : r'\\{', r'}' : r'\\{', r'~' : r'\\~', r'^' : r'\\^', r'<' : r'\\<', r'>' : r'\\>'} +REV_ESC_MAP = {value : key for key, value in ESC_MAP.items()} +SUB_DICT = {r'\\\\' : r'\n'} + +# Regular Expression Patterns +regex = collections.namedtuple('regex', ['name', 'pattern']) + +P_START_GEN = regex('BeginGeneric', re.compile(r'\\begin\{\w+\}')) +P_COMMENT = regex('Comment', re.compile(r'%.+\n', flags=re.I)) +P_END_ARG = regex('EndArgument', re.compile(r'\}')) +P_END_GEN = regex('EndGeneric', re.compile(r'\\end\{\w+\}')) +P_END_OPT = regex('EndOption', re.compile(r'\]')) +P_ESCAPED = regex('Escaped', re.compile(r'|'.join(REV_ESC_MAP.keys()))) +P_FUNCTION = regex('Function', re.compile(r'\\[\w\*]+')) +P_INV_FUNCTION = regex('InverseFunction', re.compile(r'\{\s*?\\em[a-z0-9\s\.]+?\}')) +# P_ITEM = regex('Item', re.compile(r'\\item')) +P_MATH = regex('Math', re.compile(r'\$')) +P_NEWLINE = regex('Newline', re.compile(r'\n|\\\\')) +P_SECTION = regex('Section', re.compile(r'\\section\*?')) +P_SUBSECTION = regex('Subsection', re.compile(r'\\subsection')) +P_START_ARG = regex('StartArgument', re.compile(r'\{')) +P_START_OPT = regex('StartOption', re.compile(r'\[')) +P_TEXT = regex('Text', re.compile(r'[\w/:~+`\'\,\.\(\)=&@\*\-]+', flags=re.I)) + +REGEX_LIST = [P_COMMENT, P_NEWLINE, P_SECTION, P_SUBSECTION, P_MATH, P_ESCAPED, P_INV_FUNCTION, P_START_GEN, P_END_GEN, P_FUNCTION, P_START_ARG, P_START_OPT, P_END_ARG, P_END_OPT, P_TEXT] + + +class Parser(object): + + def __init__(self, lexer): + self.lexer = lexer + self.current = None + + def next(self): + item = next(self.lexer) + if item.name == 'Escaped': + self.current = Token(REV_ESC_MAP['\\'+item.data], 'Text') + else: + self.current = item + + def __parse_comment__(self): + result = {self.current.name : self.current.data} + self.next() + return result + + def __parse_text__(self): + result = self.current.data + while self.current.name == 'Text': + self.next() + if self.current.name == 'Text': + result += ' ' + self.current.data + if self.current.name == 'Newline': + self.next() + if self.current.name == 'Text': + result += self.current.data + else: + return result + return result + + def __parse_options__(self): + while self.current.name not in ['EndOption']: + self.next() + if self.current.name == 'Text': + result = self.__parse_text__() + self.next() + return result.split(',') + + def __parse_arguments__(self): + while self.current.name not in ['EndArgument']: + self.next() + result = self.__recursive_parse__(['EndArgument']) + self.next() + return result + + def __parse_function__(self): + command = re.search(r'\w+', self.current.data).group() + result = {'arguments' : [], 'options' : []} + self.next() + while self.current.name in ['StartOption', 'StartArgument']: + if self.current.name == 'StartOption': + result['options'] += self.__parse_options__() + elif self.current.name == 'StartArgument': + result['arguments'] += self.__parse_arguments__() + result = utilities.del_empty_keys(result) + return {command : result} + + def __parse_inverse__(self): + match = re.search(r'(?:\{)(?P\\\w+)(?P[a-z0-9\.\s]+?)(?:\})', self.current.data) + command = match.group('command') + result = {'arguments' : match.group('data')} + self.next() + return {command : result} + + def __parse_math__(self): + self.next() + result = {'equation' : self.__recursive_parse__(['Math'])} + self.next() + return result + + def __parse_object__(self): + result = {'options':[]} + command = self.current.name.replace('Begin', '') + condition = [self.current.name.replace('Begin', 'End')] + self.next() + if self.current.name == 'StartOption': + result['options'] += self.__parse_options__() + result['data'] = (self.__recursive_parse__(condition)) + if self.current.name in condition: + self.next() + else: + raise error.TeXError(error.SYNTAX.format(self.current.name, condition)) + result = utilities.del_empty_keys(result) + return {command : result} + + def __parse_section__(self, conditions): + command = re.search(r'\w+', self.current.data).group() + result = {'data' : []} + self.next() + result['name'] = self.__parse_arguments__() + result['data'] = self.__recursive_parse__(conditions) + result = utilities.del_empty_keys(result) + return {command : result} + + def __recursive_parse__(self, condition): + result = [] + while self.current.name not in condition: + if self.current.name == 'Comment': + result.append(self.__parse_comment__()) + elif self.current.name == 'Section': + result.append(self.__parse_section__(['Section', 'Enddocument'])) + elif self.current.name == 'Subsection': + result.append(self.__parse_section__(['Section', 'Subsection', 'Enddocument'])) + elif self.current.name == 'Text': + result.append(self.__parse_text__()) + elif self.current.name == 'Math': + result.append(self.__parse_math__()) + elif 'Begin' in self.current.name: + result.append(self.__parse_object__()) + elif self.current.name == 'InverseFunction': + result.append(self.__parse_inverse__()) + elif self.current.name == 'Function': + result.append(self.__parse_function__()) + elif self.current.name == 'StartArgument': + result.append(self.__parse_arguments__()) + elif self.current.name == 'Newline': + self.next() + else: + raise error.TeXError(error.SYNTAX.format(self.current.name, condition)) + return result + + def parse(self): + self.next() + return self.__recursive_parse__(condition=['EOF']) diff --git a/pool/shard007/Python/0070103_updatefeed.py b/pool/shard007/Python/0070103_updatefeed.py new file mode 100644 index 0000000000000000000000000000000000000000..bdb89e060759a9682f2284b59392c2707b6e3049 --- /dev/null +++ b/pool/shard007/Python/0070103_updatefeed.py @@ -0,0 +1,38 @@ +__author__ = '@abhinavbom a.k.a darkl0rd' + +import urllib2 +import urlparse +import re +import os +import time +from lib.feeds import * +from lib.parse import * + +def gather(): + if not os.path.exists('intel'): + os.mkdir('intel') + os.chdir('.\\intel') + #print os.getcwd() + print "Starting feed update process" + counter = 0 + ioc_list = [] + timestr = time.strftime("%Y%m%d-%H%M%S") + for source in OSINT_IP.iteritems(): + if not os.path.exists(str(source[0])): + os.mkdir(str(source[0])) + print os.getcwd() + os.chdir(str(source[0])) + print source[0] + name = str(source[0]) +"_" + timestr + ".txt" + print name + print "Building database" + file = open(name, 'a+') + r = requests.get(str(source[1]), + headers=create_basic_headers(), + proxies={'http': HTTP_PROXY, 'https': HTTPS_PROXY}) + for line in r: + if line.startswith("/") or line.startswith('\n') or line.startswith("#"): + pass + else: + file.write(line+'\n') + os.chdir("..") diff --git a/pool/shard007/Python/0070110_main__.py b/pool/shard007/Python/0070110_main__.py new file mode 100644 index 0000000000000000000000000000000000000000..d9ded4e77abb9d83d750634defa62b9c335a144a --- /dev/null +++ b/pool/shard007/Python/0070110_main__.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 + +import argparse +import collections +import json +import os +import subprocess +import sys + +from artificialproject.field_generators import GenerationFailedException +from artificialproject.file_path_generator import FilePathGenerator +from artificialproject.target_generator import Context, TargetGenerator + + +def get_transitive_deps(top_target_name, targets_by_name): + visited = set([top_target_name]) + to_process = [top_target_name] + while to_process: + target_name = to_process.pop() + target = targets_by_name[target_name] + for dep in target[".all_deps"]: + if dep not in visited: + to_process.append(dep) + visited.add(dep) + return visited + + +def target_has_output(target): + type = target["buck.type"] + if type in ["java_library", "android_library"]: + srcs = target.get("srcs", []) + return len(srcs) != 0 + return True + + +def main(): + parser = argparse.ArgumentParser(description="Generate artificial Buck project.") + parser.add_argument( + "--input-repo", default=".", help="Path to the repository to analyze." + ) + parser.add_argument( + "--input-target", required=True, help="Name of the target to analyze." + ) + parser.add_argument( + "--output-repo", required=True, help="Output path for generated repository." + ) + parser.add_argument( + "--output-repo-size", + type=int, + required=True, + help="Approximate number of targets to generate.", + ) + args = parser.parse_args() + args.input_target = ( + subprocess.check_output( + ["buck", "targets", args.input_target], cwd=args.input_repo + ) + .decode("utf8") + .strip("\n") + ) + project_data_json = subprocess.check_output( + [ + "buck", + "query", + "deps({})".format(args.input_target), + "--output-attributes", + ".*", + ], + cwd=args.input_repo, + ) + project_data = json.loads(project_data_json.decode("utf8")) + targets_by_name = {} + gen_targets_by_type = collections.defaultdict(list) + gen_targets_with_output_by_type = collections.defaultdict(list) + file_path_generator = FilePathGenerator() + file_path_generator.analyze_project_data(project_data) + context = Context( + project_data, + targets_by_name, + gen_targets_by_type, + gen_targets_with_output_by_type, + args.output_repo, + file_path_generator, + ) + target_generator = TargetGenerator(context) + for target_name, target_data in project_data.items(): + target_generator.add_sample(target_data) + + try: + os.makedirs(args.output_repo) + except FileExistsError: + print("Output repository already exists.", file=sys.stderr) + return 1 + with open(os.path.join(args.output_repo, ".buckconfig"), "w"): + pass + + rejected = 0 + count = 0 + target_size = args.output_repo_size + candidates = [] + while True: + try: + target = target_generator.generate() + except GenerationFailedException: + rejected += 1 + continue + count += 1 + target_name = "//" + target["buck.base_path"] + ":" + target["name"] + gen_targets_by_type[target["buck.type"]].append(target_name) + if target_has_output(target): + gen_targets_with_output_by_type[target["buck.type"]].append(target_name) + targets_by_name[target_name] = target + if count % 100 == 0: + try: + target = target_generator.generate( + force_type=project_data[args.input_target]["buck.type"] + ) + except GenerationFailedException: + continue + target_name = "//" + target["buck.base_path"] + ":" + target["name"] + targets_by_name[target_name] = target + transitive_deps = len(get_transitive_deps(target_name, targets_by_name)) + del targets_by_name[target_name] + candidates.append((transitive_deps, target)) + candidates.sort(key=lambda c: c[0]) + MIN_CANDIDATES = 100 + candidates = candidates[-MIN_CANDIDATES:] + progress = 0 + if len(candidates) >= MIN_CANDIDATES: + progress = candidates[0][0] + else: + progress += len(candidates) - MIN_CANDIDATES + progress_field_width = len(str(target_size)) + 1 + print( + "\rProgress: {:{width}} / {} ".format( + progress, target_size, width=progress_field_width + ), + end="", + flush=True, + file=sys.stderr, + ) + if len(candidates) >= MIN_CANDIDATES and candidates[0][0] >= target_size: + target = candidates[0][1] + gen_targets_by_type[target["buck.type"]].append(target["name"]) + targets_by_name[target["name"]] = target + generated_top_target = target + break + print(file=sys.stderr) + print("Rejection rate: {:.2%}".format(1.0 * rejected / count), file=sys.stderr) + + print( + "Top target: //{}:{}".format( + generated_top_target["buck.base_path"], generated_top_target["name"] + ), + file=sys.stderr, + ) + + targets_by_base_path = collections.defaultdict(list) + for target in targets_by_name.values(): + targets_by_base_path[target["buck.base_path"]].append(target) + + for base_path, targets in targets_by_base_path.items(): + buck_file_path = os.path.join(args.output_repo, base_path, "BUCK") + os.makedirs(os.path.dirname(buck_file_path), exist_ok=True) + with open(buck_file_path, "w") as buck_file: + for target in targets: + buck_file.write("{}(\n".format(target["buck.type"])) + for key in target: + if "." not in key: + buck_file.write(" {}={!r},\n".format(key, target[key])) + buck_file.write(")\n\n") + + return 0 + + +sys.exit(main()) diff --git a/pool/shard007/Python/0070113_app.py b/pool/shard007/Python/0070113_app.py new file mode 100644 index 0000000000000000000000000000000000000000..271a3d94c2e7d4212dc71a8b3c952003c9d4c20a --- /dev/null +++ b/pool/shard007/Python/0070113_app.py @@ -0,0 +1,16 @@ +#!/usr/bin/env python + +import os +from food_service import FoodService + +# Application entrypoint: +if __name__ == '__main__': + app = FoodService(url_conf=os.path.abspath('./config/location.ini'), + db_conf=os.path.abspath('./config/db.ini')) + + try: + # Run every 24 hours. + app.run_schedule(interval=24) + except KeyboardInterrupt or SystemExit: + print("\nStopping...") + app.stop() diff --git a/pool/shard007/Python/0070119_XendCheckpoint.py b/pool/shard007/Python/0070119_XendCheckpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..63d5821a005aef71d9a2a2f897f94197bf815bdb --- /dev/null +++ b/pool/shard007/Python/0070119_XendCheckpoint.py @@ -0,0 +1,227 @@ +# Copyright (C) 2005 Christian Limpach +# Copyright (C) 2005 XenSource Ltd + +# This file is subject to the terms and conditions of the GNU General +# Public License. See the file "COPYING" in the main directory of +# this archive for more details. + +import os +import re +import string +import sxp +import threading +from struct import pack, unpack, calcsize + +from xen.util.xpopen import xPopen3 + +import xen.util.auxbin + +import xen.lowlevel.xc + +import balloon +from XendError import XendError +from XendLogging import log + + +SIGNATURE = "LinuxGuestRecord" +XC_SAVE = "xc_save" +XC_RESTORE = "xc_restore" + + +sizeof_int = calcsize("i") +sizeof_unsigned_long = calcsize("L") + + +xc = xen.lowlevel.xc.xc() + + +def write_exact(fd, buf, errmsg): + if os.write(fd, buf) != len(buf): + raise XendError(errmsg) + +def read_exact(fd, size, errmsg): + buf = '' + while size != 0: + str = os.read(fd, size) + if not len(str): + log.error("read_exact: EOF trying to read %d (buf='%s')" % \ + (size, buf)) + raise XendError(errmsg) + size = size - len(str) + buf = buf + str + return buf + + + +def save(fd, dominfo, live): + write_exact(fd, SIGNATURE, "could not write guest state file: signature") + + config = sxp.to_string(dominfo.sxpr()) + + domain_name = dominfo.getName() + # Rename the domain temporarily, so that we don't get a name clash if this + # domain is migrating (live or non-live) to the local host. Doing such a + # thing is useful for debugging. + dominfo.setName('migrating-' + domain_name) + + try: + write_exact(fd, pack("!i", len(config)), + "could not write guest state file: config len") + write_exact(fd, config, "could not write guest state file: config") + + # xc_save takes three customization parameters: maxit, max_f, and + # flags the last controls whether or not save is 'live', while the + # first two further customize behaviour when 'live' save is + # enabled. Passing "0" simply uses the defaults compiled into + # libxenguest; see the comments and/or code in xc_linux_save() for + # more information. + cmd = [xen.util.auxbin.pathTo(XC_SAVE), str(xc.handle()), str(fd), + str(dominfo.getDomid()), "0", "0", str(int(live)) ] + log.debug("[xc_save]: %s", string.join(cmd)) + + def saveInputHandler(line, tochild): + log.debug("In saveInputHandler %s", line) + if line == "suspend": + log.debug("Suspending %d ...", dominfo.getDomid()) + dominfo.shutdown('suspend') + dominfo.waitForShutdown() + log.info("Domain %d suspended.", dominfo.getDomid()) + tochild.write("done\n") + tochild.flush() + log.debug('Written done') + + forkHelper(cmd, fd, saveInputHandler, False) + + dominfo.destroyDomain() + + except Exception, exn: + log.exception("Save failed on domain %s (%d).", domain_name, + dominfo.getDomid()) + try: + dominfo.setName(domain_name) + except: + log.exception("Failed to reset the migrating domain's name") + raise Exception, exn + + +def restore(xd, fd): + signature = read_exact(fd, len(SIGNATURE), + "not a valid guest state file: signature read") + if signature != SIGNATURE: + raise XendError("not a valid guest state file: found '%s'" % + signature) + + l = read_exact(fd, sizeof_int, + "not a valid guest state file: config size read") + vmconfig_size = unpack("!i", l)[0] + vmconfig_buf = read_exact(fd, vmconfig_size, + "not a valid guest state file: config read") + + p = sxp.Parser() + p.input(vmconfig_buf) + if not p.ready: + raise XendError("not a valid guest state file: config parse") + + vmconfig = p.get_val() + + dominfo = xd.restore_(vmconfig) + + store_port = dominfo.getStorePort() + console_port = dominfo.getConsolePort() + + assert store_port + assert console_port + + try: + l = read_exact(fd, sizeof_unsigned_long, + "not a valid guest state file: pfn count read") + nr_pfns = unpack("L", l)[0] # native sizeof long + if nr_pfns > 16*1024*1024: # XXX + raise XendError( + "not a valid guest state file: pfn count out of range") + + balloon.free(xc.pages_to_kib(nr_pfns)) + + cmd = map(str, [xen.util.auxbin.pathTo(XC_RESTORE), + xc.handle(), fd, dominfo.getDomid(), nr_pfns, + store_port, console_port]) + log.debug("[xc_restore]: %s", string.join(cmd)) + + handler = RestoreInputHandler() + + forkHelper(cmd, fd, handler.handler, True) + + if handler.store_mfn is None or handler.console_mfn is None: + raise XendError('Could not read store/console MFN') + + dominfo.unpause() + + dominfo.completeRestore(handler.store_mfn, handler.console_mfn) + + return dominfo + except: + dominfo.destroy() + raise + + +class RestoreInputHandler: + def __init__(self): + self.store_mfn = None + self.console_mfn = None + + + def handler(self, line, _): + m = re.match(r"^(store-mfn) (\d+)$", line) + if m: + self.store_mfn = int(m.group(2)) + else: + m = re.match(r"^(console-mfn) (\d+)$", line) + if m: + self.console_mfn = int(m.group(2)) + + +def forkHelper(cmd, fd, inputHandler, closeToChild): + child = xPopen3(cmd, True, -1, [fd, xc.handle()]) + + if closeToChild: + child.tochild.close() + + thread = threading.Thread(target = slurp, args = (child.childerr,)) + thread.start() + + try: + try: + while 1: + line = child.fromchild.readline() + if line == "": + break + else: + line = line.rstrip() + log.debug('%s', line) + inputHandler(line, child.tochild) + + thread.join() + + except IOError, exn: + raise XendError('Error reading from child process for %s: %s' % + (cmd, exn)) + finally: + child.fromchild.close() + child.childerr.close() + if not closeToChild: + child.tochild.close() + + status = child.wait() + if status >> 8 == 127: + raise XendError("%s failed: popen failed" % string.join(cmd)) + elif status != 0: + raise XendError("%s failed" % string.join(cmd)) + + +def slurp(infile): + while 1: + line = infile.readline() + if line == "": + break + else: + log.error('%s', line.strip()) diff --git a/pool/shard007/Python/0070120_1_ecos.py b/pool/shard007/Python/0070120_1_ecos.py new file mode 100644 index 0000000000000000000000000000000000000000..f77649651d8ea38d94039102482a6e5a67f2b053 --- /dev/null +++ b/pool/shard007/Python/0070120_1_ecos.py @@ -0,0 +1,56 @@ +import datetime + +def main(j, args, params, tags, tasklet): + page = args.page + modifier = j.portal.tools.html.getPageModifierGridDataTables(page) + + filters = dict() + for tag, val in args.tags.tags.items(): + val = args.getTag(tag) + if tag == 'from' and val: + filters['from_'] = {'name': 'lasttime', 'value': j.data.time.getEpochAgo(val), 'eq': 'gte'} + elif tag == 'to' and val: + filters['to'] = {'name': 'lasttime', 'value': j.data.time.getEpochAgo(val), 'eq': 'lte'} + elif val: + if j.data.types.int.checkString(val): + val = j.data.types.int.fromString(val) + filters[tag] = val + fieldnames = ['Time', 'Grid ID', 'Node ID', 'App Name', 'Error Message', 'Type', 'Level', 'Occurences', 'Job ID'] + + def errormessage(row, field): + if row[field]: + return "

%s" % row[field] + + def makeTime(row, field): + time = modifier.makeTime(row, field) + return '[%s|error condition?id=%s]' % (time, row['id']) + + def makeJob(row, field): + jid = row[field] + if not jid: + return 'N/A' + return '[Details|job?id=%s]' % (jid) + + def level(row, field): + value = row[field] + return "%s (%s)" % (j.errorconditionhandler.getLevelName(value), value) + + def appName(row, field): + return row[field].split(':')[-1] + + nidstr = '[%(nid)s|grid node?nid=%(nid)s&gid=%(gid)s]' + + fieldids = ["lasttime", "gid", "nid", "appname", "errormessage", 'type', 'level', 'occurrences', "jid"] + fieldvalues = [makeTime, 'gid', nidstr, appName, errormessage, 'type', level, 'occurrences', makeJob] + tableid = modifier.addTableForModel('system', 'errorcondition', fieldids, fieldnames, fieldvalues, filters) + modifier.addSearchOptions('#%s' % tableid) + modifier.addSorting('#%s' % tableid, 0, 'desc') + + + params.result = page + + return params + + +def match(j, args, params, tags, tasklet): + return True diff --git a/pool/shard007/Python/0070121_rs.py b/pool/shard007/Python/0070121_rs.py new file mode 100644 index 0000000000000000000000000000000000000000..bfa6ead95320aaf975a7f306314af3eb90ad06dc --- /dev/null +++ b/pool/shard007/Python/0070121_rs.py @@ -0,0 +1,45 @@ +#!/usr/bin/python +from socket import * +from sys import argv +import os +import sys, time, string, struct +from time import sleep +import time +import math + +proto = 5000 +s = socket(AF_PACKET,SOCK_RAW,proto) +s.bind(("eth2",proto)) +#s.bind(("eth5",proto)) +ifName,ifProto,pktType,hwType,hwAddr = s.getsockname() +srcAddr = hwAddr # My mac addr +dstAddr = "\x00\x15\x17\x1c\xd8\x66" +#dstAddr = "\x00\x15\x17\x1e\x03\x02" + +def run_server(): + file = open("file1.txt", "rb") + filename="file1.txt" + statinfo = os.stat(filename) #get information + fsize = statinfo.st_size #get size of file + total_pckts=0 + i=0 + for line in file: + i=i+1 + line=line.rstrip() + payload_size = len(line) + if payload_size == 0: + break + packet_number = "%05d" % i # packet number 3 bytes + payload_size_str = "%03d" % payload_size + proto_str = "%05d" % proto + packet = str(packet_number) + str(payload_size_str) + line + total_pckts=total_pckts+1 + # make raw packet with router as dest mac + txFrame = struct.pack("!6s6sh",dstAddr,srcAddr,proto) + packet + print "Tx: " + packet + s.send(txFrame)# send it + print "Number of packets sent---> ", total_pckts + s.close() + +if __name__=="__main__": + run_server() diff --git a/pool/shard007/Python/0070122_structure_hierarchical_multilabel_classification.py b/pool/shard007/Python/0070122_structure_hierarchical_multilabel_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..a675a6b6ded1a47d50264985e854c0a44faef58b --- /dev/null +++ b/pool/shard007/Python/0070122_structure_hierarchical_multilabel_classification.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python + +""" +This examples shows how to use HierarchicalMultilabelModel for hierarchical +multi-label classification. The data used: +[1] Image CLEF 2007 competition for annotation of X-Ray images. + http://kt.ijs.si/DragiKocev/PhD/resources/doku.php?id=hmc_classification#imageclef07d +""" + +import shogun as sg +import numpy as np +import time + + +train_file_name = '../../../data/multilabel/image_clef_train.arff' +test_file_name = '../../../data/multilabel/image_clef_test.arff' + +parameter_list = [[train_file_name, test_file_name]] + + +def get_taxonomy(labels): + """ + Converting the labels to shogun compatible format + (i.e. 0, 1, ... num_classes - 1) and getting taxonomy of the labels + """ + labels = labels.split(',') + num_labels = len(labels) + # taking the root label into consideration + num_labels += 1 + shogun_labels = dict() + taxonomy = np.zeros(num_labels, dtype=np.int32) + # considering the root_label node index to be 0 + taxonomy[0] = -1 + for i, label in enumerate(labels): + shogun_labels[label] = i + 1 + try: + parent_label = label[:-2] + parent_idx = labels.index(parent_label) + 1 + taxonomy[i + 1] = parent_idx + except ValueError: + taxonomy[i + 1] = 0 + return shogun_labels, taxonomy + + +def get_data_sample(data_sample, shogun_labels): + """ + Extracting features and labels from a single row of data + """ + data = data_sample.split(',') + features = np.array(data[:-1], dtype=np.float64) + labs = data[-1].split('@') + # adding the root label + labels = np.zeros(len(labs) + 1, dtype=np.int32) + labels[0] = 0 + for i, label in enumerate(labs): + labels[i + 1] = shogun_labels[label] + labels.sort() + + return features, labels + + +def get_data(data, shogun_labels): + """ + Creating features and labels from the data samples + """ + num_samples = len(data) + # considering the root label + num_classes = len(shogun_labels) + 1 + labels = sg.MultilabelSOLabels(num_samples, num_classes) + + for i, data_sample in enumerate(data): + feats, labs = get_data_sample(data_sample, shogun_labels) + try: + features = np.c_[features, feats] + except NameError: + features = feats + labels.set_sparse_label(i, labs) + + return sg.create_features(features), labels + + +def get_features_labels(input_file): + """ + Creating features and labels from the input file (train/test file) + """ + train_file_lines = list(map(lambda x: x.strip(), input_file.readlines())) + + all_labels = list(filter(lambda x: 'hierarchical' in x.strip(), + train_file_lines))[0].split()[-1] + + shogun_labels, taxonomy = get_taxonomy(all_labels) + + data_index = train_file_lines.index('@DATA') + features, labels = get_data(train_file_lines[data_index + 1:], + shogun_labels) + + return features, labels, taxonomy + + +def structure_hierarchical_multilabel_classification(train_file_name, + test_file_name): + train_file = open(train_file_name) + test_file = open(test_file_name) + + train_features, train_labels, train_taxonomy = get_features_labels( + train_file) + + # TODO: fix HierarchicalMultilabelModel initialisation + model = sg.create_structured_model("HierarchicalMultilabelModel", + features=train_features, + labels=train_labels, + taxonomy=train_taxonomy) + sgd = sg.create_machine("StochasticSOSVM", model=model, labels=train_labels) + # t1 = time.time() + # sgd.train() + # print('>>> Took %f time for training' % (time.time() - t1)) + + # test_features, test_labels, test_taxonomy = get_features_labels(test_file) + # assert(test_taxonomy.all() == train_taxonomy.all()) + + # evaluator = sg.create_evaluation("StructuredAccuracy") + # outlabel = sgd.apply(test_features) + + # print('>>> Accuracy of classification = %f' % evaluator.evaluate( + # outlabel, test_labels)) + +if __name__ == '__main__': + print('Hierarchical Multilabel Classification') + structure_hierarchical_multilabel_classification(*parameter_list[0]) diff --git a/pool/shard007/Python/0070123_filesystem.py b/pool/shard007/Python/0070123_filesystem.py new file mode 100644 index 0000000000000000000000000000000000000000..f3fa23b9eb7a5bdfe74efa4fd196cba9be25c1d6 --- /dev/null +++ b/pool/shard007/Python/0070123_filesystem.py @@ -0,0 +1,44 @@ +# +# @BEGIN LICENSE +# +# Psi4: an open-source quantum chemistry software package +# +# Copyright (c) 2007-2022 The Psi4 Developers. +# +# The copyrights for code used from other parties are included in +# the corresponding files. +# +# This file is part of Psi4. +# +# Psi4 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, version 3. +# +# Psi4 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 Psi4; if not, write to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +# +# @END LICENSE +# + +import os + + +def join_path(prefix, *args): + path = str(prefix) + for elt in args: + path = os.path.join(path, str(elt)) + return path + + +def ancestor(dir, n=1): + """Get the nth ancestor of a directory.""" + parent = os.path.abspath(dir) + for i in range(n): + parent = os.path.dirname(parent) + return parent diff --git a/pool/shard007/Python/0070127_reset_gids.py b/pool/shard007/Python/0070127_reset_gids.py new file mode 100644 index 0000000000000000000000000000000000000000..21e25cec949b6c191b676fe6936aa4cdd83d82a4 --- /dev/null +++ b/pool/shard007/Python/0070127_reset_gids.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python +# -*- coding:utf-8 -*- + +import types + +from sfa.storage.model import * +from sfa.storage.alchemy import * +from sfa.trust.gid import create_uuid +from sfa.trust.hierarchy import Hierarchy +from sfa.util.xrn import Xrn +from sfa.trust.certificate import Certificate, Keypair, convert_public_key + +def fix_users(): + s=global_dbsession + hierarchy = Hierarchy() + users = s.query(RegRecord).filter_by(type="user") + for record in users: + record.gid = "" + if not record.gid: + uuid = create_uuid() + pkey = Keypair(create=True) + pub_key=getattr(record,'reg_keys',None) + if len(pub_key) > 0: + # use only first key in record + if pub_key and isinstance(pub_key, types.ListType): pub_key = pub_key[0] + pub_key = pub_key.key + pkey = convert_public_key(pub_key) + urn = Xrn (xrn=record.hrn, type='user').get_urn() + email=getattr(record,'email',None) + gid_object = hierarchy.create_gid(urn, uuid, pkey, email = email) + gid = gid_object.save_to_string(save_parents=True) + record.gid = gid + s.commit() + +if __name__ == '__main__': + fix_users() diff --git a/pool/shard007/Python/0070150_views.py b/pool/shard007/Python/0070150_views.py new file mode 100644 index 0000000000000000000000000000000000000000..e663235463ce0278dcb98cd6176dffa589dac02b --- /dev/null +++ b/pool/shard007/Python/0070150_views.py @@ -0,0 +1,104 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +from django.core.urlresolvers import reverse +from django.core.urlresolvers import reverse_lazy +from django.utils.translation import ugettext_lazy as _ + +from horizon import exceptions +from horizon import forms +from horizon import tabs +from horizon.utils import memoized + +from openstack_dashboard import api + +from openstack_dashboard.dashboards.project.volumes \ + .snapshots import forms as vol_snapshot_forms +from openstack_dashboard.dashboards.project.volumes \ + .snapshots import tables as vol_snapshot_tables +from openstack_dashboard.dashboards.project.volumes \ + .snapshots import tabs as vol_snapshot_tabs + + +class UpdateView(forms.ModalFormView): + form_class = vol_snapshot_forms.UpdateForm + form_id = "update_snapshot_form" + modal_header = _("Edit Snapshot") + template_name = 'project/volumes/snapshots/update.html' + submit_label = _("Save Changes") + submit_url = "horizon:project:volumes:snapshots:update" + success_url = reverse_lazy("horizon:project:volumes:index") + page_title = _("Edit Snapshot") + + @memoized.memoized_method + def get_object(self): + snap_id = self.kwargs['snapshot_id'] + try: + self._object = api.cinder.volume_snapshot_get(self.request, + snap_id) + except Exception: + msg = _('Unable to retrieve volume snapshot.') + url = reverse('horizon:project:volumes:index') + exceptions.handle(self.request, msg, redirect=url) + return self._object + + def get_context_data(self, **kwargs): + context = super(UpdateView, self).get_context_data(**kwargs) + context['snapshot'] = self.get_object() + args = (self.kwargs['snapshot_id'],) + context['submit_url'] = reverse(self.submit_url, args=args) + return context + + def get_initial(self): + snapshot = self.get_object() + return {'snapshot_id': self.kwargs["snapshot_id"], + 'name': snapshot.name, + 'description': snapshot.description} + + +class DetailView(tabs.TabView): + tab_group_class = vol_snapshot_tabs.SnapshotDetailTabs + template_name = 'horizon/common/_detail.html' + page_title = "{{ snapshot.name|default:snapshot.id }}" + + def get_context_data(self, **kwargs): + context = super(DetailView, self).get_context_data(**kwargs) + snapshot = self.get_data() + table = vol_snapshot_tables.VolumeSnapshotsTable(self.request) + context["snapshot"] = snapshot + context["url"] = self.get_redirect_url() + context["actions"] = table.render_row_actions(snapshot) + context["page_title"] = _("Volume Snapshot Details: " + "%(snapshot_name)s") % {'snapshot_name': + snapshot.name} + return context + + @memoized.memoized_method + def get_data(self): + try: + snapshot_id = self.kwargs['snapshot_id'] + snapshot = api.cinder.volume_snapshot_get(self.request, + snapshot_id) + except Exception: + redirect = self.get_redirect_url() + exceptions.handle(self.request, + _('Unable to retrieve snapshot details.'), + redirect=redirect) + return snapshot + + @staticmethod + def get_redirect_url(): + return reverse('horizon:project:volumes:index') + + def get_tabs(self, request, *args, **kwargs): + snapshot = self.get_data() + return self.tab_group_class(request, snapshot=snapshot, **kwargs) diff --git a/pool/shard007/Python/0070155_linechart_module.py b/pool/shard007/Python/0070155_linechart_module.py new file mode 100644 index 0000000000000000000000000000000000000000..2be75524d8d312c8f76a900843859b7fa04beab6 --- /dev/null +++ b/pool/shard007/Python/0070155_linechart_module.py @@ -0,0 +1,25 @@ +from modules.chart_module import ChartModule +import tornado.web +import logging + + +class LineChartModule(ChartModule): + + def render(self, header, color, chart_data, chart_id="linechart"): + self.chart_id = chart_id + self.chart_data = chart_data + return self.render_string('modules/linechart.html', + header=header, color=color, chart_id=self.chart_id) + def chart_options(self): + return super(LineChartModule, self).chart_options() + + def embedded_javascript(self): + options = self.chart_options() + return ''' + var ctx = document.getElementById("{2}").getContext("2d"); + var myLineChart = new Chart(ctx,{{ + type:'line', + data:{1}, + options:{0} + }}); + '''.format(options, self.chart_data, self.chart_id) diff --git a/pool/shard007/Python/0070156_tests.py b/pool/shard007/Python/0070156_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..fd92a0b634cc11457319c0b044b55f59775fb313 --- /dev/null +++ b/pool/shard007/Python/0070156_tests.py @@ -0,0 +1,99 @@ +from __future__ import unicode_literals + +from django.core.exceptions import FieldError +from django.test import TestCase +from django.utils import six + +from .models import (SelfRefer, Tag, TagCollection, Entry, SelfReferChild, + SelfReferChildSibling, Worksheet, RegressionModelSplit) + + +class M2MRegressionTests(TestCase): + def test_multiple_m2m(self): + # Multiple m2m references to model must be distinguished when + # accessing the relations through an instance attribute. + + s1 = SelfRefer.objects.create(name='s1') + s2 = SelfRefer.objects.create(name='s2') + s3 = SelfRefer.objects.create(name='s3') + s1.references.add(s2) + s1.related.add(s3) + + e1 = Entry.objects.create(name='e1') + t1 = Tag.objects.create(name='t1') + t2 = Tag.objects.create(name='t2') + + e1.topics.add(t1) + e1.related.add(t2) + + self.assertQuerysetEqual(s1.references.all(), [""]) + self.assertQuerysetEqual(s1.related.all(), [""]) + + self.assertQuerysetEqual(e1.topics.all(), [""]) + self.assertQuerysetEqual(e1.related.all(), [""]) + + def test_internal_related_name_not_in_error_msg(self): + # The secret internal related names for self-referential many-to-many + # fields shouldn't appear in the list when an error is made. + + six.assertRaisesRegex( + self, FieldError, + "Choices are: id, name, references, related, selfreferchild, selfreferchildsibling$", + lambda: SelfRefer.objects.filter(porcupine='fred') + ) + + def test_m2m_inheritance_symmetry(self): + # Test to ensure that the relationship between two inherited models + # with a self-referential m2m field maintains symmetry + + sr_child = SelfReferChild(name="Hanna") + sr_child.save() + + sr_sibling = SelfReferChildSibling(name="Beth") + sr_sibling.save() + sr_child.related.add(sr_sibling) + + self.assertQuerysetEqual(sr_child.related.all(), [""]) + self.assertQuerysetEqual(sr_sibling.related.all(), [""]) + + def test_m2m_pk_field_type(self): + # Regression for #11311 - The primary key for models in a m2m relation + # doesn't have to be an AutoField + + w = Worksheet(id='abc') + w.save() + w.delete() + + def test_add_m2m_with_base_class(self): + # Regression for #11956 -- You can add an object to a m2m with the + # base class without causing integrity errors + + t1 = Tag.objects.create(name='t1') + t2 = Tag.objects.create(name='t2') + + c1 = TagCollection.objects.create(name='c1') + c1.tags = [t1, t2] + c1 = TagCollection.objects.get(name='c1') + + self.assertQuerysetEqual(c1.tags.all(), ["", ""], ordered=False) + self.assertQuerysetEqual(t1.tag_collections.all(), [""]) + + def test_manager_class_caching(self): + e1 = Entry.objects.create() + e2 = Entry.objects.create() + t1 = Tag.objects.create() + t2 = Tag.objects.create() + + # Get same manager twice in a row: + self.assertTrue(t1.entry_set.__class__ is t1.entry_set.__class__) + self.assertTrue(e1.topics.__class__ is e1.topics.__class__) + + # Get same manager for different instances + self.assertTrue(e1.topics.__class__ is e2.topics.__class__) + self.assertTrue(t1.entry_set.__class__ is t2.entry_set.__class__) + + def test_m2m_abstract_split(self): + # Regression for #19236 - an abstract class with a 'split' method + # causes a TypeError in add_lazy_relation + m1 = RegressionModelSplit(name='1') + m1.save() diff --git a/pool/shard007/Python/0070158_adapters.py b/pool/shard007/Python/0070158_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..3a8c028279610d5653a709c3dad066034d609e70 --- /dev/null +++ b/pool/shard007/Python/0070158_adapters.py @@ -0,0 +1,46 @@ +from __future__ import absolute_import +from __future__ import unicode_literals + +import subprocess +import sys + +from xiami_downloader._compat import request + + +def get_downloader(name=None): + if not name: + name = { + 'win32': 'urllib2' + }.get(sys.platform, 'wget') + + return { + 'urllib2': urllib2_downloader, + 'wget': wget_downloader + }.get(name, None) + + +def urllib2_downloader(url, dest, headers): + req = request.Request(url) + for h in headers: + req.add_header(h, headers[h]) + response = request.urlopen(req) + length = int(response.headers['Content-Length']) + downloaded = 0.0 + with open(dest, 'wb') as output: + while True: + chunk = response.read(8192) + if not chunk: + break + downloaded += len(chunk) + output.write(chunk) + percent = float(downloaded) / length * 100 + sys.stdout.write('\r{:5.1f}%'.format(percent)) + sys.stdout.flush() + sys.stdout.write('\n') + + +def wget_downloader(url, dest, headers): + wget_opts = ['wget', url, '-O', dest] + for h in headers: + wget_opts.append('--header=%s:%s' % (h, headers[h])) + subprocess.check_call(wget_opts) diff --git a/pool/shard007/Python/0070165_test_sap.py b/pool/shard007/Python/0070165_test_sap.py new file mode 100644 index 0000000000000000000000000000000000000000..c01391758f46fc3ccb39ddcb15a37d59289e34b2 --- /dev/null +++ b/pool/shard007/Python/0070165_test_sap.py @@ -0,0 +1,225 @@ +import pytest +from insights.core.dr import SkipComponent +from insights.core.context import HostContext +from insights.core.spec_factory import DatasourceProvider +from insights.tests import context_wrap +from insights.parsers.hostname import Hostname as HostnameParser +from insights.parsers.saphostctrl import SAPHostCtrlInstances +from insights.combiners.sap import Sap +from insights.combiners.hostname import Hostname +from insights.combiners.tests.test_sap import ( + SAPHOSTCTRL_HOSTINSTANCES_R_CASE, + SAPHOSTCTRL_HOSTINSTANCES_GOOD, HOSTNAME1) +from insights.specs.datasources.sap import ( + LocalSpecs, sap_sid, sap_hana_sid, sap_hana_sid_SID_nr, + ld_library_path_of_user) + +SAPHOSTCTRL_HOSTINSTANCES = ''' +********************************************************* + CreationClassName , String , SAPInstance + SID , String , RH1 + SystemNumber , String , 01 + InstanceName , String , ASCS01 + Hostname , String , vm37-39 + FullQualifiedHostname , String , vm37-39.pek2.com + IPAddress , String , 10.72.37.39 + SapVersionInfo , String , 745, patch 100, changelist 1652052 +********************************************************* + CreationClassName , String , SAPInstance + SID , String , RH1 + SystemNumber , String , 00 + InstanceName , String , D00 + Hostname , String , vm37-39 + FullQualifiedHostname , String , vm37-39.pek2.com + IPAddress , String , 10.72.37.39 + SapVersionInfo , String , 745, patch 100, changelist 1652052 +********************************************************* + CreationClassName , String , SAPInstance + SID , String , SR1 + SystemNumber , String , 02 + InstanceName , String , HDB02 + Hostname , String , vm37-39 + FullQualifiedHostname , String , vm37-39.pek2.com + IPAddress , String , 10.72.37.39 + SapVersionInfo , String , 749, patch 418, changelist 1816226 +********************************************************* + CreationClassName , String , SAPInstance + SID , String , RH2 + SystemNumber , String , 04 + InstanceName , String , ASCS04 + Hostname , String , vm37-39 + FullQualifiedHostname , String , vm37-39.pek2.com + IPAddress , String , 10.72.37.39 + SapVersionInfo , String , 745, patch 100, changelist 1652052 +********************************************************* + CreationClassName , String , SAPInstance + SID , String , RH2 + SystemNumber , String , 03 + InstanceName , String , D03 + Hostname , String , vm37-39 + FullQualifiedHostname , String , vm37-39.pek2.com + IPAddress , String , 10.72.37.39 + SapVersionInfo , String , 745, patch 100, changelist 1652052 +'''.strip() + +RH1ADM_ENV = ''' +TERM=screen-256color +HOME=/home/rh1adm +SHELL=/bin/csh +USER=rh1adm +LOGNAME=rh1adm +PATH=/sapdb/clients/RH1/bin:/sapdb/programs/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/usr/sap/RH1/SYS/exe/uc/linuxx86_64:/usr/sap/RH1/SYS/exe/run:/home/rh1adm:. +XDG_SESSION_ID=6682 +HOSTTYPE=x86_64-linux +VENDOR=unknown +OSTYPE=linux +MACHTYPE=x86_64 +SHLVL=1 +PWD=/home/rh1adm +GROUP=sapsys +HOST=vm37-39 +REMOTEHOST=10.66.136.143 +MAIL=/var/spool/mail/rh1adm +HOSTNAME=vm37-39 +LANG=en_US.UTF-8 +LESSOPEN=||/usr/bin/lesspipe.sh %s +SAPSYSTEMNAME=RH1 +DIR_LIBRARY=/usr/sap/RH1/SYS/exe/run +RSEC_SSFS_DATAPATH=/usr/sap/RH1/SYS/global/security/rsecssfs/data +RSEC_SSFS_KEYPATH=/usr/sap/RH1/SYS/global/security/rsecssfs/key +rsdb_ssfs_connect=0 +LD_LIBRARY_PATH=/usr/sap/RH1/SYS/exe/run:/usr/sap/RH1/SYS/exe/uc/linuxx86_64:/sapdb/clients/RH1/lib +dbms_type=ADA +'''.strip() + +RH2ADM_ENV = ''' +TERM=screen-256color +HOME=/home/rh2adm +SHELL=/bin/csh +USER=rh2adm +LOGNAME=rh2adm +PATH=/sapdb/clients/RH2/bin:/sapdb/programs/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/usr/sap/RH2/SYS/exe/uc/linuxx86_64:/usr/sap/RH2/SYS/exe/run:/home/rh2adm:. +XDG_SESSION_ID=6682 +HOSTTYPE=x86_64-linux +VENDOR=unknown +OSTYPE=linux +MACHTYPE=x86_64 +SHLVL=1 +PWD=/home/rh2adm +GROUP=sapsys +HOST=vm37-39 +REMOTEHOST=10.66.136.143 +MAIL=/var/spool/mail/rh2adm +HOSTNAME=vm37-39 +LANG=en_US.UTF-8 +LESSOPEN=||/usr/bin/lesspipe.sh %s +SAPSYSTEMNAME=RH2 +DIR_LIBRARY=/usr/sap/RH2/SYS/exe/run +RSEC_SSFS_DATAPATH=/usr/sap/RH2/SYS/global/security/rsecssfs/data +RSEC_SSFS_KEYPATH=/usr/sap/RH2/SYS/global/security/rsecssfs/key +rsdb_ssfs_connect=0 +LD_LIBRARY_PATH=/usr/sap/RH2/SYS/exe/run:/usr/sap/RH2/SYS/exe/uc/linuxx86_64:/sapdb/clients/RH2/lib +dbms_type=ADA +'''.strip() + +HOSTNAME = 'vm37-39.pek2.com' + + +class FakeContext(object): + def shell_out(self, cmd, split=True, timeout=None, keep_rc=False, env=None, signum=None): + tmp_cmd = cmd.strip().split() + if 'rh1adm' in tmp_cmd[2]: + return 0, RH1ADM_ENV.splitlines() + if 'rh2adm' in tmp_cmd[2]: + return 0, RH2ADM_ENV.splitlines() + return -1, [] + + +def test_hana_instance_skip(): + inst = SAPHostCtrlInstances(context_wrap(SAPHOSTCTRL_HOSTINSTANCES_R_CASE)) + hn = Hostname(HostnameParser(context_wrap(HOSTNAME)), None, None, None) + sap = Sap(hn, inst, None) + broker = {Sap: sap} + broker.update({LocalSpecs.sap_instance: LocalSpecs.sap_instance(broker)}) + with pytest.raises(SkipComponent): + LocalSpecs.sap_hana_instance(broker) + + +def test_sid(): + # Good + inst = SAPHostCtrlInstances(context_wrap(SAPHOSTCTRL_HOSTINSTANCES)) + hn = Hostname(HostnameParser(context_wrap(HOSTNAME)), None, None, None) + sap = Sap(hn, inst, None) + broker = {Sap: sap} + broker.update({LocalSpecs.sap_instance: LocalSpecs.sap_instance(broker)}) + result = sap_sid(broker) + assert result is not None + assert isinstance(result, list) + assert result == sorted(set(v.sid.lower() for v in sap.values())) + + +def test_hana_sid(): + # Good + inst = SAPHostCtrlInstances(context_wrap(SAPHOSTCTRL_HOSTINSTANCES)) + hn = Hostname(HostnameParser(context_wrap(HOSTNAME)), None, None, None) + sap = Sap(hn, inst, None) + broker = {Sap: sap} + broker.update({LocalSpecs.sap_instance: LocalSpecs.sap_instance(broker)}) + broker.update({LocalSpecs.sap_hana_instance: LocalSpecs.sap_hana_instance(broker)}) + result = sap_hana_sid(broker) + assert result is not None + assert isinstance(result, list) + assert result == list(set(v.sid.lower() for v in sap.values() if v.type == 'HDB')) + + # Bad + broker.update({LocalSpecs.sap_hana_instance: []}) + with pytest.raises(SkipComponent): + sap_hana_sid(broker) + + +def test_hana_sid_SID_nr(): + # Good + inst = SAPHostCtrlInstances(context_wrap(SAPHOSTCTRL_HOSTINSTANCES)) + hn = Hostname(HostnameParser(context_wrap(HOSTNAME)), None, None, None) + sap = Sap(hn, inst, None) + broker = {Sap: sap} + broker.update({LocalSpecs.sap_instance: LocalSpecs.sap_instance(broker)}) + broker.update({LocalSpecs.sap_hana_instance: LocalSpecs.sap_hana_instance(broker)}) + result = sap_hana_sid_SID_nr(broker) + assert result is not None + assert isinstance(result, list) + assert result == list((v.sid.lower(), v.sid, v.number) for v in sap.values() if v.type == 'HDB') + + # Bad + broker.update({LocalSpecs.sap_hana_instance: []}) + with pytest.raises(SkipComponent): + sap_hana_sid_SID_nr(broker) + + +def test_ld_library_path_of_user(): + # Good + inst = SAPHostCtrlInstances(context_wrap(SAPHOSTCTRL_HOSTINSTANCES)) + hn = Hostname(HostnameParser(context_wrap(HOSTNAME)), None, None, None) + sap = Sap(hn, inst, None) + broker = {Sap: sap, HostContext: FakeContext()} + broker.update({LocalSpecs.sap_instance: LocalSpecs.sap_instance(broker)}) + broker.update({sap_sid: sap_sid(broker)}) + result = ld_library_path_of_user(broker) + assert result is not None + assert isinstance(result, DatasourceProvider) + assert sorted(result.content) == [ + 'rh1adm /usr/sap/RH1/SYS/exe/run:/usr/sap/RH1/SYS/exe/uc/linuxx86_64:/sapdb/clients/RH1/lib', + 'rh2adm /usr/sap/RH2/SYS/exe/run:/usr/sap/RH2/SYS/exe/uc/linuxx86_64:/sapdb/clients/RH2/lib', + ] + assert result.relative_path == 'insights_commands/echo_user_LD_LIBRARY_PATH' + + # Bad + inst = SAPHostCtrlInstances(context_wrap(SAPHOSTCTRL_HOSTINSTANCES_GOOD)) + hn = Hostname(HostnameParser(context_wrap(HOSTNAME1)), None, None, None) + sap = Sap(hn, inst, None) + broker = {Sap: sap, HostContext: FakeContext()} + broker.update({LocalSpecs.sap_instance: LocalSpecs.sap_instance(broker)}) + broker.update({sap_sid: sap_sid(broker)}) + with pytest.raises(SkipComponent): + result = ld_library_path_of_user(broker) + assert result is None diff --git a/pool/shard007/Python/0070186_init__.py b/pool/shard007/Python/0070186_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..64dcbbe6cc7a3a355cf7d1abca383b8b65a2cbcf --- /dev/null +++ b/pool/shard007/Python/0070186_init__.py @@ -0,0 +1,56 @@ + +# This file is part of pyGenClean. +# +# pyGenClean 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. +# +# pyGenClean 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 +# pyGenClean. If not, see . + + +import logging + + +try: + from .version import pygenclean_version as __version__ +except: + __version__ = None + + +__author__ = "Louis-Philippe Lemieux Perreault" +__copyright__ = "Copyright 2014, Beaulieu-Saucier Pharmacogenomics Centre" +__credits__ = ["Louis-Philippe Lemieux Perreault", "Marc-Andre Legault"] +__license__ = "GPL" +__maintainer__ = "Louis-Philippe Lemieux Perreault" +__email__ = "louis-philippe.lemieux.perreault@statgen.org" +__status__ = "Development" + + +# Configuring logging +logging.basicConfig( + level=logging.INFO, + format="[%(asctime)s %(name)s %(levelname)s] %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", +) + + +def add_file_handler_to_root(log_fn): + """Adds a file handler to the root logging. + + :param log_fn: the name of the log file. + + :type log_fn: str + + """ + file_handler = logging.FileHandler(log_fn, mode="w") + file_handler.setFormatter(logging.Formatter( + fmt="[%(asctime)s %(name)s %(levelname)s] %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + )) + logging.root.addHandler(file_handler) diff --git a/pool/shard007/Python/0070187_MyoRaw.py b/pool/shard007/Python/0070187_MyoRaw.py new file mode 100644 index 0000000000000000000000000000000000000000..86a0a0dfdfbbc4d65b09b27d71c636a7e5f61a84 --- /dev/null +++ b/pool/shard007/Python/0070187_MyoRaw.py @@ -0,0 +1,245 @@ +from __future__ import print_function + +import re +import struct +import sys +import threading +import os +import errno +import time + +import serial +from serial.tools.list_ports import comports + +from common import * +from MyoBT import * + +class MyoRaw(object): + '''Implements the Myo-specific communication protocol.''' + + def __init__(self, tty=None): + if tty is None: + tty = self.detect_tty() + if tty is None: + raise ValueError('Myo dongle not found!') + + self.bt = BT(tty) + self.conn = None + self.emg_handlers = [] + self.imu_handlers = [] + self.arm_handlers = [] + self.pose_handlers = [] + + def detect_tty(self): + for p in comports(): + if re.search(r'PID=2458:0*1', p[2]): + print('using device:', p[0]) + return p[0] + + return None + + def run(self, timeout=None): + self.bt.recv_packet(timeout) + + def connect(self): + ## stop everything from before + self.bt.end_scan() + self.bt.disconnect(0) + self.bt.disconnect(1) + self.bt.disconnect(2) + + ## start scanning + print('scanning...') + self.bt.discover() + while True: + p = self.bt.recv_packet() + ## print('scan response:', p) + + if p.payload.endswith(b'\x06\x42\x48\x12\x4A\x7F\x2C\x48\x47\xB9\xDE\x04\xA9\x01\x00\x06\xD5'): + addr = list(multiord(p.payload[2:8])) + break + self.bt.end_scan() + + ## connect and wait for status event + conn_pkt = self.bt.connect(addr) + self.conn = multiord(conn_pkt.payload)[-1] + self.bt.wait_event(3, 0) + + ## get firmware version + fw = self.read_attr(0x17) + _, _, _, _, v0, v1, v2, v3 = unpack('BHBBHHHH', fw.payload) + print('firmware version: %d.%d.%d.%d' % (v0, v1, v2, v3)) + + self.old = (v0 == 0) + + if self.old: + ## don't know what these do; Myo Connect sends them, though we get data + ## fine without them + self.write_attr(0x19, b'\x01\x02\x00\x00') + self.write_attr(0x2f, b'\x01\x00') + self.write_attr(0x2c, b'\x01\x00') + self.write_attr(0x32, b'\x01\x00') + self.write_attr(0x35, b'\x01\x00') + + ## enable EMG data + self.write_attr(0x28, b'\x01\x00') + ## enable IMU data + self.write_attr(0x1d, b'\x01\x00') + + ## Sampling rate of the underlying EMG sensor, capped to 1000. If it's + ## less than 1000, emg_hz is correct. If it is greater, the actual + ## framerate starts dropping inversely. Also, if this is much less than + ## 1000, EMG data becomes slower to respond to changes. In conclusion, + ## 1000 is probably a good value. + C = 1000 + emg_hz = 50 + ## strength of low-pass filtering of EMG data + emg_smooth = 100 + + imu_hz = 50 + + ## send sensor parameters, or we don't get any data + self.write_attr(0x19, pack('BBBBHBBBBB', 2, 9, 2, 1, C, emg_smooth, C // emg_hz, imu_hz, 0, 0)) + + else: + name = self.read_attr(0x03) + print('device name: %s' % name.payload) + + ## enable IMU data + self.write_attr(0x1d, b'\x01\x00') + ## enable on/off arm notifications + self.write_attr(0x24, b'\x02\x00') + + # self.write_attr(0x19, b'\x01\x03\x00\x01\x01') + self.start_raw() + + ## add data handlers + def handle_data(p): + if (p.cls, p.cmd) != (4, 5): return + + c, attr, typ = unpack('BHB', p.payload[:4]) + pay = p.payload[5:] + + if attr == 0x27: + vals = unpack('8HB', pay) + ## not entirely sure what the last byte is, but it's a bitmask that + ## seems to indicate which sensors think they're being moved around or + ## something + emg = vals[:8] + moving = vals[8] + self.on_emg(emg, moving) + elif attr == 0x1c: + vals = unpack('10h', pay) + quat = vals[:4] + acc = vals[4:7] + gyro = vals[7:10] + self.on_imu(quat, acc, gyro) + elif attr == 0x23: + typ, val, xdir = unpack('3B', pay) + + if typ == 1: # on arm + self.on_arm(Arm(val), XDirection(xdir)) + elif typ == 2: # removed from arm + self.on_arm(Arm.UNKNOWN, XDirection.UNKNOWN) + elif typ == 3: # pose + self.on_pose(Pose(val)) + else: + print('data with unknown attr: %02X %s' % (attr, p)) + + self.bt.add_handler(handle_data) + + + def write_attr(self, attr, val): + if self.conn is not None: + self.bt.write_attr(self.conn, attr, val) + + def read_attr(self, attr): + if self.conn is not None: + return self.bt.read_attr(self.conn, attr) + return None + + def disconnect(self): + if self.conn is not None: + self.bt.disconnect(self.conn) + + def start_raw(self): + '''Sending this sequence for v1.0 firmware seems to enable both raw data and + pose notifications. + ''' + + self.write_attr(0x28, b'\x01\x00') + self.write_attr(0x19, b'\x01\x03\x01\x01\x00') + self.write_attr(0x19, b'\x01\x03\x01\x01\x01') + + def mc_start_collection(self): + '''Myo Connect sends this sequence (or a reordering) when starting data + collection for v1.0 firmware; this enables raw data but disables arm and + pose notifications. + ''' + + self.write_attr(0x28, b'\x01\x00') + self.write_attr(0x1d, b'\x01\x00') + self.write_attr(0x24, b'\x02\x00') + self.write_attr(0x19, b'\x01\x03\x01\x01\x01') + self.write_attr(0x28, b'\x01\x00') + self.write_attr(0x1d, b'\x01\x00') + self.write_attr(0x19, b'\x09\x01\x01\x00\x00') + self.write_attr(0x1d, b'\x01\x00') + self.write_attr(0x19, b'\x01\x03\x00\x01\x00') + self.write_attr(0x28, b'\x01\x00') + self.write_attr(0x1d, b'\x01\x00') + self.write_attr(0x19, b'\x01\x03\x01\x01\x00') + + def mc_end_collection(self): + '''Myo Connect sends this sequence (or a reordering) when ending data collection + for v1.0 firmware; this reenables arm and pose notifications, but + doesn't disable raw data. + ''' + + self.write_attr(0x28, b'\x01\x00') + self.write_attr(0x1d, b'\x01\x00') + self.write_attr(0x24, b'\x02\x00') + self.write_attr(0x19, b'\x01\x03\x01\x01\x01') + self.write_attr(0x19, b'\x09\x01\x00\x00\x00') + self.write_attr(0x1d, b'\x01\x00') + self.write_attr(0x24, b'\x02\x00') + self.write_attr(0x19, b'\x01\x03\x00\x01\x01') + self.write_attr(0x28, b'\x01\x00') + self.write_attr(0x1d, b'\x01\x00') + self.write_attr(0x24, b'\x02\x00') + self.write_attr(0x19, b'\x01\x03\x01\x01\x01') + + def vibrate(self, length): + if length in xrange(1, 4): + ## first byte tells it to vibrate; purpose of second byte is unknown + self.write_attr(0x19, pack('3B', 3, 1, length)) + + + def add_emg_handler(self, h): + self.emg_handlers.append(h) + + def add_imu_handler(self, h): + self.imu_handlers.append(h) + + def add_pose_handler(self, h): + self.pose_handlers.append(h) + + def add_arm_handler(self, h): + self.arm_handlers.append(h) + + + def on_emg(self, emg, moving): + for h in self.emg_handlers: + h(emg, moving) + + def on_imu(self, quat, acc, gyro): + for h in self.imu_handlers: + h(quat, acc, gyro) + + def on_pose(self, p): + for h in self.pose_handlers: + h(p) + + def on_arm(self, arm, xdir): + for h in self.arm_handlers: + h(arm, xdir) diff --git a/pool/shard007/Python/0070188_scons_support.py b/pool/shard007/Python/0070188_scons_support.py new file mode 100644 index 0000000000000000000000000000000000000000..f05d2b5ee507dd30fdc7cab9c6b5105bd72de74a --- /dev/null +++ b/pool/shard007/Python/0070188_scons_support.py @@ -0,0 +1,40 @@ +from os.path import join as pjoin, splitext, basename as pbasename + +from interface_gen import generate_interface + +def do_generate_interface(target, source, env): + """Generate a .pyf file from another pyf file (!).""" + # XXX: do this correctly + target_name = str(target[0]) + source_name = str(source[0]) + + # XXX handle skip names + name = splitext(pbasename(target_name))[0] + generate_interface(name, source_name, target_name) + return 0 + +def generate_interface_emitter(target, source, env): + base = str(target[0]) + return (['%s.pyf' % base], source) + +def do_generate_fake_interface(target, source, env): + """Generate a (fake) .pyf file from another pyf file (!).""" + # XXX: do this correctly + target_name = str(target[0]) + source_name = str(source[0]) + + # XXX handle skip names + name = splitext(pbasename(target_name))[0] + generate_interface(name, source_name, target_name) + + f = open(target_name, 'w') + f.write('python module '+name+'\n') + f.write('usercode void empty_module(void) {}\n') + f.write('interface\n') + f.write('subroutine empty_module()\n') + f.write('intent(c) empty_module\n') + f.write('end subroutine empty_module\n') + f.write('end interface\nend python module'+name+'\n') + f.close() + + return 0 diff --git a/pool/shard007/Python/0070193_cmath_fun.py b/pool/shard007/Python/0070193_cmath_fun.py new file mode 100644 index 0000000000000000000000000000000000000000..15b72e7a6203b22db6997fefc0d9c39153996162 --- /dev/null +++ b/pool/shard007/Python/0070193_cmath_fun.py @@ -0,0 +1,65 @@ +# test the functions imported from cmath + +try: + from cmath import * +except ImportError: + print("SKIP") + raise SystemExit + +# make sure these constants exist in cmath +print("%.5g" % e) +print("%.5g" % pi) + +test_values_non_zero = [] +base_values = (0.0, 0.5, 1.2345, 10.0) +for r in base_values: + for i in base_values: + if r != 0.0 or i != 0.0: + test_values_non_zero.append(complex(r, i)) + if r != 0.0: + test_values_non_zero.append(complex(-r, i)) + if i != 0.0: + test_values_non_zero.append(complex(r, -i)) + if r != 0.0 and i != 0.0: + test_values_non_zero.append(complex(-r, -i)) +test_values = [complex(0.0, 0.0),] + test_values_non_zero +print(test_values) + +functions = [ + ("phase", phase, test_values), + ("polar", polar, test_values), + ( + "rect", + rect, + ((0, 0), (0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (-1, 1), (1, -1), (123.0, -456.0)), + ), + ("exp", exp, test_values), + ("log", log, test_values_non_zero), + ("sqrt", sqrt, test_values), + ("cos", cos, test_values), + ("sin", sin, test_values), +] + +for f_name, f, test_vals in functions: + print(f_name) + for val in test_vals: + if type(val) == tuple: + ret = f(*val) + else: + ret = f(val) + if type(ret) == float: + print("%.5g" % ret) + elif type(ret) == tuple: + print("%.5g %.5g" % ret) + else: + # some test (eg cmath.sqrt(-0.5)) disagree with CPython with tiny real part + real = ret.real + if abs(real) < 1e-6: + real = 0.0 + print("complex(%.5g, %.5g)" % (real, ret.imag)) + +# test invalid type passed to cmath function +try: + log([]) +except TypeError: + print("TypeError") diff --git a/pool/shard007/Python/0070199_controller.py b/pool/shard007/Python/0070199_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..de60fdacc09353691b144a381e8cd3c362507c2d --- /dev/null +++ b/pool/shard007/Python/0070199_controller.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python +# Arup IoT Desk Controller +# Ben Hussey - March 2017 + +import sched +import time +from tinkerforge.ip_connection import IPConnection +from config import * +# import gettext +# gettext.install('deskcontrol', 'locale', unicode=1) + + +class Controller: + identity = SHORT_IDENT + + ipcon = None + current_module = None + previous_module = None + screen = None + + modules = {} + ticklist = [] + + # Event handlers handle internal events + event_handlers = {} + # The local database stores key value pairs + localdb = None + + scheduler = sched.scheduler(time.time, time.sleep) + + def __init__(self): + self.ipcon = IPConnection() + self.ipcon.connect(HOST, PORT) + + for module in MODULES: + self.add_module(module) + + if "MenuModule" in self.modules: + for module in MENU_MODULES: + self.add_module(module) + self.modules["MenuModule"].add_menu_item( + self.modules[module[0]]) + + self.ipcon.register_callback( + IPConnection.CALLBACK_ENUMERATE, self.assign_bricklets) + self.scheduler.enter(2, 1, self.ipcon.enumerate, (),) + + def add_module(self, module): + self.modules[module[0]] = getattr( + __import__("modules." + module[1], + fromlist=[module[0]]), module[0])(self) + if self.modules[module[0]].always_tick: + self.ticklist.append(module[0]) + print("Loaded " + module[0]) + + def tick(self): + if self.current_module: + self.current_module.tick() + for module in self.ticklist: + self.modules[module].tick() + self.scheduler.enter(1, 1, desk.tick, (),) + + def change_module(self, module): + if not module: + self.current_module = None + if self.screen: + self.screen.draw_splash() + else: + if self.current_module: + self.previous_module = self.current_module + if module in self.modules: + # print("changing to " + module) + self.current_module = self.modules[module] + self.current_module.draw() + + def prev_module(self): + if self.previous_module: + self.change_module(self.previous_module.id) + + def navigate(self, direction): + if "SleepModule" in self.modules: + self.modules["SleepModule"].motion_changed(1) + if direction not in ["forward", "back", "up", "down", "enter"]: + return + if self.current_module: + self.current_module.navigate(direction) + else: + self.change_module("MenuModule") + + def assign_bricklets( + self, uid, connected_uid, position, hardware_version, + firmware_version, device_identifier, enumeration_type): + if enumeration_type == IPConnection.ENUMERATION_TYPE_DISCONNECTED: + return + for state in self.modules: + self.modules[state].try_bricklet(uid, device_identifier, position) + + def event(self, event, data): + print("event triggered", str(event), str(data)) + if event in self.event_handlers: + for handler in self.event_handlers[event]: + handler(data) + + def add_event_handler(self, event, handler): + if event in self.event_handlers: + self.event_handlers[event].append(handler) + else: + self.event_handlers[event] = [handler, ] + + +if __name__ == "__main__": + try: + desk = Controller() + desk.tick() + desk.scheduler.run() + except KeyboardInterrupt: + desk.ipcon.disconnect() + print("Exiting") diff --git a/pool/shard007/Python/0070202_storage.py b/pool/shard007/Python/0070202_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..123c65b8595c8815bdd150b6d60750e69289dc8b --- /dev/null +++ b/pool/shard007/Python/0070202_storage.py @@ -0,0 +1,55 @@ +from __future__ import absolute_import + +from django.conf import settings +from django.contrib.staticfiles.storage import CachedFilesMixin, StaticFilesStorage +from pipeline.storage import PipelineMixin + +class AddHeaderMixin(object): + def post_process(self, paths, dry_run=False, **kwargs): + if dry_run: + return + + with open(settings.STATIC_HEADER_FILE) as header_file: + header = header_file.read().decode(settings.FILE_CHARSET) + + # A dictionary of path to tuples of (old_path, new_path, + # processed). The return value of this method is the values + # of this dictionary + ret_dict = {} + + for name in paths: + storage, path = paths[name] + + if not path.startswith('min/') or not path.endswith('.css'): + ret_dict[path] = (path, path, False) + continue + + # Prepend the header + with storage.open(path) as orig_file: + orig_contents = orig_file.read().decode(settings.FILE_CHARSET) + + storage.delete(path) + + with storage.open(path, 'w') as new_file: + new_file.write(header + orig_contents) + + ret_dict[path] = (path, path, True) + + super_class = super(AddHeaderMixin, self) + if hasattr(super_class, 'post_process'): + super_ret = super_class.post_process(paths, dry_run, **kwargs) + else: + super_ret = [] + + # Merge super class's return value with ours + for val in super_ret: + old_path, new_path, processed = val + if processed: + ret_dict[old_path] = val + + return ret_dict.itervalues() + + +class ZulipStorage(PipelineMixin, AddHeaderMixin, CachedFilesMixin, + StaticFilesStorage): + pass diff --git a/pool/shard007/Python/0070206_settings.py b/pool/shard007/Python/0070206_settings.py new file mode 100644 index 0000000000000000000000000000000000000000..0f2850842b36e4d46bb66dc30da9b23ed24f4c23 --- /dev/null +++ b/pool/shard007/Python/0070206_settings.py @@ -0,0 +1,174 @@ +import os + +import requests +from django.core.exceptions import ImproperlyConfigured + + +def get_env(key, required=True): + try: + return os.environ[key] + except KeyError: + if required: + err = "Environment variable not set: {}".format(key) + raise ImproperlyConfigured(err) + +def get_local_ipv4(): + # > The Elastic Load Balancer HTTP health check will use the instance's internal IP. + # https://forums.aws.amazon.com/thread.jspa?messageID=423533 + return requests.get('http://169.254.169.254/latest/meta-data/local-ipv4', timeout=0.01).text + + +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY') or 'SECRET_SECRET_SECRET_SECRET_SECRET' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = False + +ALLOWED_HOSTS = ['localhost'] +ALLOWED_HOSTS.append('snps.io') +ALLOWED_HOSTS.append(get_local_ipv4()) + +allowed_hosts_env = get_env('DJANGO_ALLOWED_HOST', required=False) +if allowed_hosts_env: + ALLOWED_HOSTS.append(allowed_hosts_env) + +# Application definition + +INSTALLED_APPS = ( + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + + 'rest_framework', + 'django_extensions', + + 'dbsnp', +) + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'config.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [ + 'templates', + ], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'config.wsgi.application' + +# dbsnp +DBSNP_BUILD = os.environ.get('DBSNP_BUILD') or '' +DBSNP_REF_GENOME_BUILD = os.environ.get('DBSNP_REF_GENOME_BUILD') or '' +DBSNP_QUERY_COUNTS_LIMIT = int(os.environ.get('DBSNP_QUERY_COUNTS_LIMIT', 30)) + + +# Database +# https://docs.djangoproject.com/en/1.10/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), + }, + 'dbsnp': { + 'ENGINE': 'django.db.backends.postgresql_psycopg2', + 'NAME': get_env('DBSNP_DB_NAME'), + 'USER': get_env('DBSNP_DB_USER'), + 'PASSWORD': os.environ.get('DBSNP_DB_PASS') or '', + 'HOST': os.environ.get('DBSNP_DB_HOST') or '127.0.0.1', + 'PORT': os.environ.get('DBSNP_DB_PORT') or '5432', + } +} + +if get_env('DJANGO_DB_NAME', required=False): + DATABASES['default'] = { + 'ENGINE': 'django.db.backends.postgresql_psycopg2', + 'NAME': get_env('DJANGO_DB_NAME'), + 'USER': get_env('DJANGO_DB_USER'), + 'PASSWORD': os.environ.get('DJANGO_DB_PASS') or '', + 'HOST': os.environ.get('DJANGO_DB_HOST') or '127.0.0.1', + 'PORT': os.environ.get('DJANGO_DB_PORT') or '5432', + } + + +# Password validation +# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/1.10/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/1.10/howto/static-files/ + +STATIC_URL = '/static/' + +# +REST_FRAMEWORK = { + 'PAGE_SIZE': 10, + 'DEFAULT_THROTTLE_CLASSES': ( + 'rest_framework.throttling.AnonRateThrottle', + 'rest_framework.throttling.UserRateThrottle' + ), + 'DEFAULT_THROTTLE_RATES': { + 'anon': '10/second', + 'user': '10/second', + }, +} diff --git a/pool/shard007/Python/0070211_cookie.py b/pool/shard007/Python/0070211_cookie.py new file mode 100644 index 0000000000000000000000000000000000000000..8996ea2b25fbf25e2558f429d0c0da4e43c221ca --- /dev/null +++ b/pool/shard007/Python/0070211_cookie.py @@ -0,0 +1,63 @@ +# 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. + +import hmac + +from zope.interface import implementer + +from pyramid_csrf.interfaces import ICSRF, ICSRFFactory +from pyramid_csrf.utils import random_token + + +@implementer(ICSRF) +class CookieCSRF(object): + + def __init__(self, request, cookie_name, options): + self.request = request + self.request.add_response_callback(self._store_cookie) + self.cookie_name = cookie_name + self.options = options + self.token = None + + def _store_cookie(self, request, response): + response.set_cookie(self.cookie_name, self.token, **self.options) + + def has_token(self): + return self.cookie_name in self.request.cookies + + def new_token(self): + self.token = random_token() + return self.token + + def get_token(self): + if self.token is None: + self.token = self.new_token() + return self.token + + def get_scoped_token(self, scope): + # Here we want to do HMAC_sha512(unscoped_token, scope). This will make + # it possible to have scope specific CSRF tokens which means that a + # single scope token being leaked cannot be used for other scopes. + unscoped = self.get_token().encode("utf8") + scope = scope.encode("utf8") + return hmac.new(unscoped, scope, "sha512").hexdigest() + + +@implementer(ICSRFFactory) +class CookieCSRFFactory(object): + + def __init__(self, cookie_name="csrf.token", **options): + self.cookie_name = cookie_name + self.options = options + + def __call__(self, request): + return CookieCSRF(request, self.cookie_name, self.options) diff --git a/pool/shard007/Python/0070213_CuisineProcess.py b/pool/shard007/Python/0070213_CuisineProcess.py new file mode 100644 index 0000000000000000000000000000000000000000..6451b33022080e0c2a8f3779c24e856878b1809f --- /dev/null +++ b/pool/shard007/Python/0070213_CuisineProcess.py @@ -0,0 +1,142 @@ + +from JumpScale import j +import re + +base = j.tools.cuisine._getBaseClass() + + +class CuisineProcess(base): + + def __init__(self, executor, cuisine): + self._executor = executor + self._cuisine = cuisine + + def tcpport_check(self, port, prefix=""): + res = [] + for item in self.info_get(prefix): + if item["localport"] == port: + return True + return False + + def _info_get(self): + """ + return + [$item,] + + $item is dict + + {'local': '0.0.0.0', + 'localport': 6379, + 'pid': 13824, + 'process': 'redis', + 'receive': 0, + 'receivebytes': 0, + 'remote': '0.0.0.0', + 'remoteport': '*', + 'send': 0, + 'sendbytes': 0, + 'parentpid':0} + + + """ + result = [] + if "linux" in self._cuisine.platformtype.platformtypes: + cmdlinux = 'netstat -lntp' + _, out, _ = self._cuisine.core.run(cmdlinux, showout=False) + # to troubleshoot https://regex101.com/#python + p = re.compile( + u"tcp *(?P[0-9]*) *(?P[0-9]*) *(?P[0-9*.]*):(?P[0-9*]*) *(?P[0-9.*]*):(?P[0-9*]*) *(?P[A-Z]*) *(?P[0-9]*)/(?P\w*)") + for line in out.split("\n"): + res = re.search(p, line) + if res is not None: + # print (line) + d = res.groupdict() + d["process"] = d["process"].lower() + if d["state"] == "LISTEN": + d.pop("state") + result.append(d) + + elif "darwin" in self._cuisine.platformtype.platformtypes: + # cmd='sudo netstat -anp tcp' + # # out=self._cuisine.core.run(cmd) + # p = re.compile(u"tcp4 *(?P[0-9]*) *(?P[0-9]*) *(?P[0-9.*]*) *(?P[0-9.*]*) *LISTEN") + cmd = "lsof -i 4tcp -sTCP:LISTEN -FpcRn" + _, out, _ = self._cuisine.core.run(cmd, showout=False) + d = {} + for line in out.split("\n"): + if line.startswith("p"): + d = {'local': '', 'localport': 0, 'pid': 0, 'process': '', 'receive': 0, 'receivebytes': 0, + 'remote': '', 'remoteport': 0, 'send': 0, 'sendbytes': 0, 'parentpid': 0} + d["pid"] = int(line[1:]) + if line.startswith("R"): + d["parentpid"] = int(line[1:]) + if line.startswith("c"): + d["process"] = line[1:].strip() + if line.startswith("n"): + a, b = line.split(":") + d["local"] = a[1:].strip() + try: + d["localport"] = int(b) + except: + d["localport"] = 0 + result.append(d) + + else: + raise j.exceptions.RuntimeError("platform not supported") + + for d in result: + for item in ["receive", "send", "pid", "localport", "remoteport"]: + if d[item] == "*": + continue + else: + d[item] = int(d[item]) + + return result + + def info_get(self, prefix=""): + if prefix == "": + return self._info_get() + res = [] + for item in self._info_get(): + if item["process"].lower().startswith(prefix): + res.append(item) + return res + + def find(self, name, exact=False): + """Returns the pids of processes with the given name. If exact is `False` + it will return the list of all processes that start with the given + `name`.""" + is_string = isinstance(name, str) or isinstance(name, unicode) + # NOTE: ps -A seems to be the only way to not have the grep appearing + # as well + RE_SPACES = re.compile("[\s\t]+") + + cmd = "ps -A | grep {0} ; true".format(name) if is_string else "ps -A" + processes = self._cuisine.core.run(cmd, replaceArgs=False)[1] + + res = [] + for line in processes.split("\n"): + if not line.strip(): + continue + line = RE_SPACES.split(line, 3) + # 3010 pts/1 00:00:07 gunicorn + # PID TTY TIME CMD + # 0 1 2 3 + # We skip lines that are not like we expect them (sometimes error + # message creep up the output) + if len(line) < 4: + continue + pid, tty, time, command = line + if is_string: + if pid and ((exact and command == name) or (not exact and command.find(name) >= 0)): + res.append(pid) + elif name(line) and pid: + res.append(pid) + return res + + def kill(self, name, signal=9, exact=False): + """Kills the given processes with the given name. If exact is `False` + it will return the list of all processes that start with the given + `name`.""" + for pid in self.find(name, exact): + self._cuisine.core.run("kill -s {0} {1} ; true".format(signal, pid), showout=False, replaceArgs=False) diff --git a/pool/shard007/Python/0070215_neopixels.py b/pool/shard007/Python/0070215_neopixels.py new file mode 100644 index 0000000000000000000000000000000000000000..46e4b8e2622691b90f0dc774ee32b565540b14af --- /dev/null +++ b/pool/shard007/Python/0070215_neopixels.py @@ -0,0 +1,41 @@ +from __future__ import print_function + +try: + from neopixel import * + mock = False +except ImportError: + print("No neopixel library found - will generate mock NeoPixels objects") + mock = True + + +def new_instance(num_leds): + if mock: + return NeoPixelsMock(num_leds) + else: + return NeoPixels(num_leds) + + +class NeoPixels: + + def __init__(self, num_leds, output_pin=18, led_freq_hz=800000, dma=5, + invert=False, brightness=255, channel=0, strip=ws.SK6812W_STRIP): + self.pixels = Adafruit_NeoPixel(num_leds, output_pin, led_freq_hz, dma, + invert, brightness, channel, strip) + self.pixels.begin() + + def set_all(self, r, g, b): + """ Set all pixels to the given color """ + col = Color(r, g, b) + for i in range(self.pixels.numPixels()): + self.pixels.setPixelColor(i, col) + self.pixels.show() + + +class NeoPixelsMock: + + def __init__(self, num_leds, output_pin=18, led_freq_hz=800000, dma=5, + invert=False, brightness=255, channel=0, strip=ws.SK6812W_STRIP): + pass + + def set_all(self, r, g, b): + print("Set all to ", r, g, b) diff --git a/pool/shard007/Python/0070217_test_user_controller.py b/pool/shard007/Python/0070217_test_user_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..74bcbd4a33d0f12a2295e6ced7c094db1a23f0c5 --- /dev/null +++ b/pool/shard007/Python/0070217_test_user_controller.py @@ -0,0 +1,19 @@ + +import sys +sys.path.insert(0, r'../..') +from porper.models.connection import mysql_connection +from porper.controllers.user_controller import UserController + +connection = mysql_connection() +user_controller = UserController(connection) + +#access_token = '091e304b-1a3f-4406-ac3a-cf8afd8cd647'; # alex.ough +#access_token = '3ab4ae48-97fe-4420-8cb1-b1e3c62737f5'; # cloud_test_user +#params = {}; +#role_id = '435a6417-6c1f-4d7c-87dd-e8f6c0effc7a'; # public +role_id = '3867c370-552f-43b8-bed9-6aa00ffc41b4'; # Awesome Role +access_token = '3ab4ae48-97fe-4420-8cb1-b1e3c62737f5'; # cloud_test_user +params = {'role_id': role_id}; +print user_controller.find_all(access_token, params) + +connection.commit() diff --git a/pool/shard007/Python/0070220_NetloadIn.py b/pool/shard007/Python/0070220_NetloadIn.py new file mode 100644 index 0000000000000000000000000000000000000000..025095fbbc43085f7c0e922d8fbad6e1477e52f3 --- /dev/null +++ b/pool/shard007/Python/0070220_NetloadIn.py @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- + +from ..internal.OCR import OCR + + +class NetloadIn(OCR): + __name__ = "NetloadIn" + __type__ = "ocr" + __version__ = "0.17" + __status__ = "testing" + + __description__ = """Netload.in ocr plugin""" + __license__ = "GPLv3" + __authors__ = [("pyLoad Team", "admin@pyload.org")] + + def recognize(self, image): + self.load_image(image) + self.to_greyscale() + self.clean(3) + self.clean(3) + self.run_tesser(True, True, False, False) + + self.result_captcha = self.result_captcha.replace( + " ", "")[:4] # cut to 4 numbers + + return self.result_captcha diff --git a/pool/shard007/Python/0070223_email_template.py b/pool/shard007/Python/0070223_email_template.py new file mode 100644 index 0000000000000000000000000000000000000000..d13400dc1c4d1c14228a732921704b2cd3cc00d3 --- /dev/null +++ b/pool/shard007/Python/0070223_email_template.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +# This file is part of Shuup. +# +# Copyright (c) 2012-2021, Shuup Commerce Inc. All rights reserved. +# +# This source code is licensed under the OSL-3.0 license found in the +# LICENSE file in the root directory of this source tree. +from django.db import models +from django.utils.translation import ugettext_lazy as _ + + +class EmailTemplate(models.Model): + name = models.CharField(verbose_name=_("Name"), max_length=60) + template = models.TextField( + verbose_name=_("Template"), + help_text=_( + "Enter the base HTML template to be used in emails. " + "Mark the place to inject the email content using the variable `%html_body%` inside the body." + ), + ) + + class Meta: + verbose_name = _("Email Template") + verbose_name_plural = _("Email Templates") + + def __str__(self): + return self.name diff --git a/pool/shard007/Python/0070226_test_groups.py b/pool/shard007/Python/0070226_test_groups.py new file mode 100644 index 0000000000000000000000000000000000000000..d6b82625f3007c531ab406cf06b912c59d0489ac --- /dev/null +++ b/pool/shard007/Python/0070226_test_groups.py @@ -0,0 +1,252 @@ +# -*- coding: utf-8 -*- +# +# Copyright © 2013-2014 Red Hat, Inc. +# +# This copyrighted material is made available to anyone wishing to use, +# modify, copy, or redistribute it subject to the terms and conditions +# of the GNU General Public License v.2, or (at your option) any later +# version. This program is distributed in the hope that it will be +# useful, but WITHOUT ANY WARRANTY expressed or implied, including the +# implied warranties 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. +# +# Any Red Hat trademarks that are incorporated in the source +# code or documentation are not subject to the GNU General Public +# License and may only be used or replicated with the express permission +# of Red Hat, Inc. +# + +''' +pkgdb tests for the Collection object. +''' + +__requires__ = ['SQLAlchemy >= 0.7'] +import pkg_resources + +import json +import unittest +import sys +import os + +from mock import patch + +sys.path.insert(0, os.path.join(os.path.dirname( + os.path.abspath(__file__)), '..')) + +import pkgdb2 +import pkgdb2.lib.model as model +from tests import (Modeltests, FakeFasUser, + FakeFasGroupValid, create_package_acl, + create_package_acl2, user_set) + + +class PkgdbGrouptests(Modeltests): + """ PkgdbGroup tests. """ + + def setUp(self): + """ Set up the environnment, ran before every tests. """ + super(PkgdbGrouptests, self).setUp() + + pkgdb2.APP.config['TESTING'] = True + pkgdb2.SESSION = self.session + pkgdb2.api.extras.SESSION = self.session + pkgdb2.ui.SESSION = self.session + pkgdb2.ui.acls.SESSION = self.session + pkgdb2.ui.admin.SESSION = self.session + pkgdb2.ui.collections.SESSION = self.session + pkgdb2.ui.packagers.SESSION = self.session + pkgdb2.ui.packages.SESSION = self.session + self.app = pkgdb2.APP.test_client() + + # Let's make sure the cache is empty for the tests + pkgdb2.CACHE.invalidate() + + def set_group_acls(self): + ''' Create some Group ACLs. ''' + fedocal_pkg = model.Package.by_name(self.session, 'fedocal') + devel_collec = model.Collection.by_name(self.session, 'master') + f18_collec = model.Collection.by_name(self.session, 'f18') + + pklist_fedocal_f18 = model.PackageListing.by_pkgid_collectionid( + self.session, fedocal_pkg.id, f18_collec.id) + pklist_fedocal_devel = model.PackageListing.by_pkgid_collectionid( + self.session, fedocal_pkg.id, devel_collec.id) + + packager = model.PackageListingAcl( + fas_name='group::infra-sig', + packagelisting_id=pklist_fedocal_f18.id, + acl='commit', + status='Approved', + ) + self.session.add(packager) + + packager = model.PackageListingAcl( + fas_name='group::infra-sig', + packagelisting_id=pklist_fedocal_devel.id, + acl='commit', + status='Approved', + ) + self.session.add(packager) + + packager = model.PackageListingAcl( + fas_name='group::infra-sig', + packagelisting_id=pklist_fedocal_f18.id, + acl='watchbugzilla', + status='Approved', + ) + self.session.add(packager) + + packager = model.PackageListingAcl( + fas_name='group::infra-sig', + packagelisting_id=pklist_fedocal_devel.id, + acl='watchbugzilla', + status='Approved', + ) + self.session.add(packager) + + self.session.commit() + + def test_api_bugzilla_group(self): + """ Test the api_bugzilla function. """ + create_package_acl2(self.session) + self.set_group_acls() + + output = self.app.get('/api/bugzilla/') + self.assertEqual(output.status_code, 200) + expected = """# Package Database VCS Acls +# Text Format +# Collection|Package|Description|Owner|Initial QA|Initial CCList +# Backslashes (\) are escaped as \u005c Pipes (|) are escaped as \u007c + +Fedora|fedocal|A web-based calendar for Fedora|pingou||group::infra-sig,pingou +Fedora|geany|A fast and lightweight IDE using GTK2|group::gtk-sig|| +Fedora|guake|Top down terminal for GNOME|pingou||spot""" + self.assertEqual(output.data, expected) + + output = self.app.get('/api/bugzilla/?format=json') + self.assertEqual(output.status_code, 200) + expected = { + u'bugzillaAcls': { + 'Fedora': { + "fedocal": { + "owner": "pingou", + "cclist": { + "groups": ["@infra-sig"], + "people": ["pingou"] + }, + "qacontact": None, + "summary": "A web-based calendar for Fedora" + }, + 'geany': { + 'owner': '@gtk-sig', + 'cclist': { + 'groups': [], + 'people': [] + }, + 'qacontact': None, + 'summary': 'A fast and lightweight IDE using ' + 'GTK2' + }, + 'guake': { + 'owner': 'pingou', + 'cclist': { + 'groups': [], + 'people': ['spot'] + }, + 'qacontact': None, + 'summary': 'Top down terminal for GNOME' + } + } + }, + 'title': 'Fedora Package Database -- Bugzilla ACLs' + } + data = json.loads(output.data) + self.assertEqual(data, expected) + + @patch('pkgdb2.lib.utils') + @patch('pkgdb2.packager_login_required') + def test_package_give_group(self, login_func, mock_func): + """ Test the package_give function to a group. """ + login_func.return_value = None + create_package_acl(self.session) + + mock_func.get_packagers.return_value = ['spot'] + group = FakeFasGroupValid() + group.name = 'gtk-sig' + mock_func.get_fas_group.return_value = group + mock_func.log.return_value = '' + user = FakeFasUser() + + with user_set(pkgdb2.APP, user): + output = self.app.get('/package/guake/give') + self.assertEqual(output.status_code, 200) + self.assertTrue( + '

Give Point of Contact of package: guake

' + in output.data) + self.assertTrue( + '')[0] + + data = { + 'branches': 'master', + 'poc': 'spot', + 'csrf_token': csrf_token, + } + + output = self.app.post('/package/guake/give', data=data, + follow_redirects=True) + self.assertEqual(output.status_code, 200) + self.assertTrue( + '

guake

' + in output.data) + self.assertEqual( + output.data.count(''), 2) + + user.username = 'spot' + user.groups.append('gtk-sig') + with user_set(pkgdb2.APP, user): + output = self.app.get('/package/guake/give') + self.assertEqual(output.status_code, 200) + self.assertTrue( + '

Give Point of Contact of package: guake

' + in output.data) + self.assertTrue( + '')[0] + + data = { + 'branches': 'master', + 'poc': 'group::gtk-sig', + 'csrf_token': csrf_token, + } + + output = self.app.post('/package/guake/give', data=data, + follow_redirects=True) + self.assertEqual(output.status_code, 200) + self.assertEqual( + output.data.count('
'), 2) + self.assertEqual( + output.data.count(''), + 1) + + output = self.app.get('/package/guake/give') + self.assertEqual(output.status_code, 200) + self.assertTrue( + '

Give Point of Contact of package: guake

' + in output.data) + self.assertTrue( + '' + in output.data) + + +if __name__ == '__main__': + SUITE = unittest.TestLoader().loadTestsFromTestCase(PkgdbGrouptests) + unittest.TextTestRunner(verbosity=2).run(SUITE) diff --git a/pool/shard007/Python/0070227_vault_credential.py b/pool/shard007/Python/0070227_vault_credential.py new file mode 100644 index 0000000000000000000000000000000000000000..14e2bce84955c492dfd6bd6d78cdf52b0c631269 --- /dev/null +++ b/pool/shard007/Python/0070227_vault_credential.py @@ -0,0 +1,74 @@ +from lib.common import helpers + +class Module: + + def __init__(self, mainMenu, params=[]): + + self.info = { + 'Name': 'Get-VaultCredential', + + 'Author': ['@mattifestation'], + + 'Description': ("Runs PowerSploit's Get-VaultCredential to display " + "Windows vault credential objects including " + "cleartext web credentials."), + + 'Background' : True, + + 'OutputExtension' : None, + + 'NeedsAdmin' : True, + + 'OpsecSafe' : True, + + 'Language' : 'powershell', + + 'MinLanguageVersion' : '2', + + 'Comments': [ + 'https://github.com/mattifestation/PowerSploit/blob/master/Exfiltration/Get-VaultCredential.ps1' + ] + } + + # any options needed by the module, settable during runtime + self.options = { + # format: + # value_name : {description, required, default_value} + 'Agent' : { + 'Description' : 'Agent to run module on.', + 'Required' : True, + 'Value' : '' + } + } + + # save off a copy of the mainMenu object to access external functionality + # like listeners/agent handlers/etc. + self.mainMenu = mainMenu + + for param in params: + # parameter format is [Name, Value] + option, value = param + if option in self.options: + self.options[option]['Value'] = value + + + def generate(self): + + # read in the common module source code + moduleSource = self.mainMenu.installPath + "/data/module_source/credentials/Get-VaultCredential.ps1" + + try: + f = open(moduleSource, 'r') + except: + print helpers.color("[!] Could not read module source path at: " + str(moduleSource)) + return "" + + moduleCode = f.read() + f.close() + + script = moduleCode + + + script += "Get-VaultCredential" + + return script diff --git a/pool/shard007/Python/0070229_test_pascal_voc_dataset.py b/pool/shard007/Python/0070229_test_pascal_voc_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..d84fe1d897347a017676afff1ab9d4c1ea277080 --- /dev/null +++ b/pool/shard007/Python/0070229_test_pascal_voc_dataset.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +import os +import unittest + +import cv2 as cv +from datasets.pascal_voc_dataset import VOC + + +class TestVOC(unittest.TestCase): + + def setUp(self): + self.dataset = VOC('train', False) + if not os.path.exists('tests/imgs'): + os.makedirs('tests/imgs') + + def test_save_example(self): + ret = self.dataset[:5] + + self.assertEqual(len(ret), 5) + self.assertEqual(len(ret[0]), len(ret[1])) + self.assertEqual(len(ret[0]), 3) + self.assertEqual(ret[0][0].ndim, 3) + self.assertEqual(len(ret[0][1]), 2) + + for i in range(5): + img, im_info, bbox = ret[i] + self.assertEqual(bbox.shape[1], 5) + img = img.transpose(1, 2, 0) + self.dataset.mean + for bb in bbox: + bb = [int(b) for b in bb] + cv.rectangle(img, (bb[0], bb[1]), (bb[2], bb[3]), (0, 0, 255)) + cv.imwrite('tests/imgs/example_{}.png'.format(i), img) diff --git a/pool/shard007/Python/0070230_url_patterns.py b/pool/shard007/Python/0070230_url_patterns.py new file mode 100644 index 0000000000000000000000000000000000000000..93587e814bde1fed2cc07dccd92b4ae74b98d08c --- /dev/null +++ b/pool/shard007/Python/0070230_url_patterns.py @@ -0,0 +1,47 @@ +# Copyright 2011 the Melange authors. +# +# 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. + +"""Module for constructing GCI related URL patterns +""" + + +from django.conf.urls import url as django_url + +from soc.views.helper import url_patterns + + +def url(regex, view, kwargs=None, name=None): + """Constructs an url pattern prefixed with ^gci/. + + Args: see django.conf.urls.url + """ + return django_url('^gci/%s' % regex, view, kwargs=kwargs, name=name) + + +class CIUrlPatternConstructor(url_patterns.UrlPatternConstructor): + """Implementation of UrlPatternConstructor which constructs Code In-specific + URL patterns prefixed with ^gci/. + """ + + def construct(self, regex, view, kwargs=None, name=None): + """See url_patterns.UrlPatternConstructor.construct for specification.""" + return django_url('^gci/%s' % regex, view, kwargs=kwargs, name=name) + +CI_URL_PATTERN_CONSTRUCTOR = CIUrlPatternConstructor() + + +TASK = url_patterns.namedIdBasedPattern(['sponsor', 'program']) +PREFIXES = "(gci_program|gci_org)" +DOCUMENT = url_patterns.DOCUMENT_FMT % PREFIXES +ORG_DOCUMENT = url_patterns.ORG_DOCUMENT_FMT % PREFIXES diff --git a/pool/shard007/Python/0070235_word_db.py b/pool/shard007/Python/0070235_word_db.py new file mode 100644 index 0000000000000000000000000000000000000000..cdf7b217a9c33c1b2e14c10268bbe91f9c47fe1f --- /dev/null +++ b/pool/shard007/Python/0070235_word_db.py @@ -0,0 +1,65 @@ +import sqlite3 +import os + +class InvalidDatabaseException(Exception): pass + + +def create_db(db_path): + """Creates a new word database and returns a WordsDB object for it. If + db_path already exists, it is overwritten with a new database.""" + + if os.path.exists(db_path): + os.remove(db_path) + print 'Removed existing database at %s' % db_path + + + conn = sqlite3.connect(db_path) + c = conn.cursor() + c.execute('PRAGMA foreign_keys = ON') + + table = ''' + CREATE TABLE word( + id INTEGER PRIMARY KEY, + word TEXT, + reading TEXT, + solved BOOLEAN DEFAULT FALSE, + UNIQUE(word, reading) + ) + ''' + c.execute(table) + c.execute('CREATE INDEX word_idx ON word(word)') + c.execute('CREATE INDEX reading_idx ON word(reading)') + + table = ''' + CREATE TABLE segment( + id INTEGER PRIMARY KEY, + word_id INTEGER, + reading_id TEXT, + character TEXT, + 'index' INTEGER, + indexr INTEGER, + FOREIGN KEY (word_id) REFERENCES word(id) ON DELETE CASCADE + ) + ''' + c.execute(table) + + table = ''' + CREATE TABLE tag( + id INTEGER PRIMARY KEY, + segment_id INTEGER, + tag TEXT, + FOREIGN KEY (segment_id) REFERENCES segment(id) ON DELETE CASCADE + ) + ''' + c.execute(table) + + +def get_connection(db_path): + """Returns a connection to the given database.""" + + if not os.path.exists(db_path): + raise InvalidDatabaseException("No such database: %s" % db_path) + conn = sqlite3.connect(db_path) + conn.row_factory = sqlite3.Row + conn.execute('PRAGMA foreign_keys = ON') + return conn \ No newline at end of file diff --git a/pool/shard007/Python/0070237_scrub_rescrape.py b/pool/shard007/Python/0070237_scrub_rescrape.py new file mode 100644 index 0000000000000000000000000000000000000000..fe29732786f13f84a8cd4034f42ad2d7bee213aa --- /dev/null +++ b/pool/shard007/Python/0070237_scrub_rescrape.py @@ -0,0 +1,140 @@ +import os +import numpy as np +import pandas as pd +import cPickle as pickle +from pymongo import MongoClient +from scrape_ratings_threaded import threaded_scrape, mongo_to_pandas + + +def load_filepaths(): + ''' + Function to load in data that has previously been pickled and stored + + INPUT: + None + + OUTPUT: + List of filepaths + ''' + paths = [os.path.join('data', 'ratings_df_{}.pkl'.format(i + 1)) + for i in range(5)] + if os.path.exists(os.path.join('data', 'rescrape_df.pkl')): + paths.append(os.path.join('data', 'rescrape_df.pkl')) + return paths + + +def init_mongo(coll_name): + ''' + Function to initialize pymongo db connection. + + INPUT: + coll_name: string, name of mongo collection to connect + + OUTPUT: + pymongo collection object + ''' + client = MongoClient() + db = client['glassdoor'] + coll = db[coll_name] + return coll + + +def drop_junk(ratings_df): + ''' + Function to get rid of junk reviews + + INPUT: + ratings_df: pandas DataFrame (combined with all rating data) + + OUTPUT: + ratings_df: pandas DataFrame, free of garbage + ''' + ratings_df = ratings_df[ratings_df['review_text'] != 'Pros'] + ratings_df.drop_duplicates(inplace=True) + ratings_df.reset_index(inplace=True, drop=True) + return ratings_df + + +def combine_data(paths): + ''' + Function to combine dataframes from pickled form + + INPUT: + paths: Iterable of filepaths for pickled DataFrames + + OUTPUT: + ratings_df: Single pandas DataFrame with all ratings + ''' + ratings_df = pd.read_pickle(paths[0]) + for path in paths[1:]: + ratings_df = ratings_df.append(pd.read_pickle(path)) + return ratings_df + + +def check_review_counts(ratings_df): + ''' + Function to check that enough data was collected. Compares number of reviews + for each target employer with the number of reviews collected + + INPUT: + ratings_df: Pandas DataFrame containing scraped review text + + OUTPUT: + good_er_ids, bad_er_ids: Lists of tuples to rescrape from glassdoor + ''' + clean_df = pd.read_pickle(os.path.join('data', 'clean_employers.pkl')) + target_ratings = clean_df[['company_name', 'company_id', + 'num_ratings', 'overall_rating']] + company_ratings = ratings_df['company_name'].value_counts() + company_ratings = company_ratings.to_frame(name='ratings_collected') + company_ratings.reset_index(inplace=True) + check_df = target_ratings.merge(company_ratings, + how='left', + left_on='company_name', + right_on='index') + check_df['company_id'] = check_df['company_id'].astype(int) + check_df.drop('index', axis=1, inplace=True) + check_df['delta'] = check_df['num_ratings'] - check_df['ratings_collected'] + check_df['delta_pct'] = check_df['delta'] / check_df['num_ratings'] + rescrape = check_df[check_df['delta_pct'] > 0.5] + good_rescrape = rescrape[rescrape['overall_rating'] > 3.5] + bad_rescrape = rescrape[rescrape['overall_rating'] < 3.5] + good_er_ids = zip(good_rescrape['company_name'], + good_rescrape['company_id']) + bad_er_ids = zip(bad_rescrape['company_name'], bad_rescrape['company_id']) + pickle.dump(good_er_ids, + open(os.path.join('data', 'rescrape_pros.pkl'), 'wb')) + pickle.dump(bad_er_ids, + open(os.path.join('data', 'rescrape_cons.pkl'), 'wb')) + return good_er_ids, bad_er_ids + + +def rescrape(ratings_df, coll, good_er_ids, bad_er_ids): + ''' + Function to go back and scrape stuff that we missed the first time + + INPUT: + ratings_df: original pandas DataFrame containing all review text, + coll: pymongo collection for storing new reviews, + good_er_ids: employer tuples for rescraping "pros" + bad_er_ids: employer tuples for rescraping "cons" + + OUTPUT: + ratings_df: pandas DataFrame with rescraped reviews added and scrubbed + ''' + if (len(good_er_ids) > 0) or (len(bad_er_ids) > 0): + threaded_scrape(good_er_ids, 'pro', coll) + threaded_scrape(bad_er_ids, 'con', coll) + rescrape_df = mongo_to_pandas(coll) + rescrape_df.to_pickle(os.path.join('data', 'rescrape_df.pkl')) + ratings_df = drop_junk(ratings_df.append(rescrape_df)) + return ratings_df + + +if __name__ == '__main__': + paths = load_filepaths() + ratings_df = drop_junk(combine_data(paths)) + coll = init_mongo('ratings_rescrape') + good_er_ids, bad_er_ids = check_review_counts(ratings_df) + ratings_df = rescrape(ratings_df, coll, good_er_ids, bad_er_ids) + ratings_df.to_pickle(os.path.join('data', 'ratings_df_all.pkl')) diff --git a/pool/shard007/Python/0070238_post.py b/pool/shard007/Python/0070238_post.py new file mode 100644 index 0000000000000000000000000000000000000000..6c0b1a657081b6f43a8272afb693044de2e372be --- /dev/null +++ b/pool/shard007/Python/0070238_post.py @@ -0,0 +1,39 @@ +import uuid +from src.common.database import Database +import datetime + +__author__ = 'jslvtr' + + +class Post(object): + + def __init__(self, blog_id, title, content, author, created_date=datetime.datetime.utcnow(), _id=None): + self.blog_id = blog_id + self.title = title + self.content = content + self.author = author + self.created_date = created_date + self._id = uuid.uuid4().hex if _id is None else _id + + def save_to_mongo(self): + Database.insert(collection='posts', + data=self.json()) + + def json(self): + return { + '_id': self._id, + 'blog_id': self.blog_id, + 'author': self.author, + 'content': self.content, + 'title': self.title, + 'created_date': self.created_date + } + + @classmethod + def from_mongo(cls, id): + post_data = Database.find_one(collection='posts', query={'_id': id}) + return cls(**post_data) + + @staticmethod + def from_blog(id): + return [post for post in Database.find(collection='posts', query={'blog_id': id})] \ No newline at end of file diff --git a/pool/shard007/Python/0070243_cache.py b/pool/shard007/Python/0070243_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..fee2f49d23f81e630aef4a7285321c02677db58c --- /dev/null +++ b/pool/shard007/Python/0070243_cache.py @@ -0,0 +1,94 @@ +import json +import os +import shutil +import tempfile + +from time import time +from .compat import is_win32 + +if is_win32: + xdg_cache = os.environ.get("APPDATA", + os.path.expanduser("~")) +else: + xdg_cache = os.environ.get("XDG_CACHE_HOME", + os.path.expanduser("~/.cache")) + +cache_dir = os.path.join(xdg_cache, "streamlink") + + +class Cache(object): + """Caches Python values as JSON and prunes expired entries.""" + + def __init__(self, filename, key_prefix=""): + self.key_prefix = key_prefix + self.filename = os.path.join(cache_dir, filename) + + self._cache = {} + + def _load(self): + if os.path.exists(self.filename): + try: + with open(self.filename, "r") as fd: + self._cache = json.load(fd) + except Exception: + self._cache = {} + else: + self._cache = {} + + def _prune(self): + now = time() + pruned = [] + + for key, value in self._cache.items(): + expires = value.get("expires", time()) + if expires <= now: + pruned.append(key) + + for key in pruned: + self._cache.pop(key, None) + + return len(pruned) > 0 + + def _save(self): + fd, tempname = tempfile.mkstemp() + fd = os.fdopen(fd, "w") + json.dump(self._cache, fd, indent=2, separators=(",", ": ")) + fd.close() + + # Silently ignore errors + try: + if not os.path.exists(os.path.dirname(self.filename)): + os.makedirs(os.path.dirname(self.filename)) + + shutil.move(tempname, self.filename) + except (IOError, OSError): + os.remove(tempname) + + def set(self, key, value, expires=60 * 60 * 24 * 7): + self._load() + self._prune() + + if self.key_prefix: + key = "{0}:{1}".format(self.key_prefix, key) + + expires += time() + + self._cache[key] = dict(value=value, expires=expires) + self._save() + + def get(self, key, default=None): + self._load() + + if self._prune(): + self._save() + + if self.key_prefix: + key = "{0}:{1}".format(self.key_prefix, key) + + if key in self._cache and "value" in self._cache[key]: + return self._cache[key]["value"] + else: + return default + + +__all__ = ["Cache"] diff --git a/pool/shard007/Python/0070244_generator.py b/pool/shard007/Python/0070244_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..7ce2d6a4bf3d92aff83e3f0e5b6979d01c5a204f --- /dev/null +++ b/pool/shard007/Python/0070244_generator.py @@ -0,0 +1,46 @@ +# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. +# +# 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. +"""This is definition of generator class, which is for managing the state of the algorithm that produces pseudo random numbers.""" + +from . import core +from .framework import _get_paddle_place + +__all__ = ['Generator'] + + +class Generator(core.Generator): + """Generator class""" + + def __init__(self, place=None): + """ + Create a generator object which manages the random number generation. ( Experimental Feature ) + + Parameters: + place(CPUPlace|CUDAPinnedPlace|CUDAPlace|str,optional): The place to allocate Tensor. Can be + CPUPlace, CUDAPinnedPlace, CUDAPlace. Default: None, means global place. If ``place`` is + string, it can be ``cpu`` and ``gpu:x``, where ``x`` is the index of the GPUs. + + Returns: + Generator: A generator object. + + """ + self.place = _get_paddle_place(place) + if not place: + place = core.CPUPlace() + if isinstance(place, core.CPUPlace): + super(Generator, self).__init__() + else: + raise ValueError( + "Generator class with %s does is not supported yet, currently only support generator with CPUPlace " + % place) diff --git a/pool/shard007/Python/0070259_usage_reporting.py b/pool/shard007/Python/0070259_usage_reporting.py new file mode 100644 index 0000000000000000000000000000000000000000..0eb23953e0f6a370decdb0a6673db7561ec4f855 --- /dev/null +++ b/pool/shard007/Python/0070259_usage_reporting.py @@ -0,0 +1,75 @@ +# Copyright 2015 Google Inc. All Rights Reserved. +# +# 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. + +"""Enable reporting of anonymized usage statistics to CourseBuilder team.""" + +__author__ = [ + 'Michael Gainer (mgainer@google.com)', +] + +from controllers import utils +from models import custom_modules +from modules.usage_reporting import config +from modules.usage_reporting import consent_banner +from modules.usage_reporting import course_creation +from modules.usage_reporting import enrollment +from modules.usage_reporting import students + +custom_module = None + + +class StartReportingJobs(utils.AbstractAllCoursesCronHandler): + """Handle callback from cron; launch map/reduce jobs which report stats.""" + + URL = '/cron/usage_reporting/report_usage' + + @classmethod + def is_globally_enabled(cls): + return config.REPORT_ALLOWED.value + + @classmethod + def is_enabled_for_course(cls, app_context): + return True + + def cron_action(self, app_context, global_state): + per_course_jobs = [ + students.StudentCounter(app_context), + enrollment.StudentEnrollmentEventCounter(app_context), + ] + for job in per_course_jobs: + if job.is_active(): + job.cancel() + job.submit() + + +def _notify_module_enabled(): + config.notify_module_enabled() + consent_banner.notify_module_enabled() + course_creation.notify_module_enabled() + enrollment.notify_module_enabled() + + +def register_module(): + global custom_module # pylint: disable=global-statement + global_handlers = [ + (StartReportingJobs.URL, StartReportingJobs), + ( + consent_banner.ConsentBannerRestHandler.URL, + consent_banner.ConsentBannerRestHandler)] + custom_module = custom_modules.Module( + 'Usage Reporting', + 'Sends anonymized usage statistics to CourseBuilder team.', + global_handlers, [], + notify_module_enabled=_notify_module_enabled) + return custom_module diff --git a/pool/shard007/Python/0070263_cinder.py b/pool/shard007/Python/0070263_cinder.py new file mode 100644 index 0000000000000000000000000000000000000000..37f687e9857ec115262eb6664a030ac3c0ef03a5 --- /dev/null +++ b/pool/shard007/Python/0070263_cinder.py @@ -0,0 +1,92 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy +# of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from oslo_config import cfg + +from magnum.i18n import _ + +cinder_group = cfg.OptGroup( + name='cinder', + title='Options for the Cinder configuration') + +cinder_client_group = cfg.OptGroup( + name='cinder_client', + title='Options for the Cinder client') + +cinder_opts = [ + cfg.StrOpt('default_docker_volume_type', + default='', + help=_('The default docker volume_type to use for volumes ' + 'used for docker storage. To use the cinder volumes ' + 'for docker storage, you need to select a default ' + 'value. Otherwise, Magnum will select random one from ' + 'Cinder volume type list.')), + cfg.StrOpt('default_etcd_volume_type', + default='', + help=_('The default etcd volume_type to use for volumes ' + 'used for etcd storage. To use the cinder volumes ' + 'for etcd storage, you need to select a default ' + 'value. Otherwise, Magnum will select random one from ' + 'Cinder volume type list.')), + cfg.StrOpt('default_boot_volume_type', + default='', + help=_('The default boot volume_type to use for volumes ' + 'used for VM of COE. To use the cinder volumes ' + 'for VM of COE, you need to select a default ' + 'value. Otherwise, Magnum will select random one from ' + 'Cinder volume type list.')), + cfg.IntOpt('default_boot_volume_size', + default=0, + help=_('The default volume size to use for volumes ' + 'used for VM of COE.')) +] + +cinder_client_opts = [ + cfg.StrOpt('region_name', + help=_('Region in Identity service catalog to use for ' + 'communication with the OpenStack service.')), + cfg.StrOpt('endpoint_type', + default='publicURL', + help=_('Type of endpoint in Identity service catalog to use ' + 'for communication with the OpenStack service.')), + cfg.StrOpt('api_version', + default='3', + help=_('Version of Cinder API to use in cinderclient.')) +] + +common_security_opts = [ + cfg.StrOpt('ca_file', + help=_('Optional CA cert file to use in SSL connections.')), + cfg.StrOpt('cert_file', + help=_('Optional PEM-formatted certificate chain file.')), + cfg.StrOpt('key_file', + help=_('Optional PEM-formatted file that contains the ' + 'private key.')), + cfg.BoolOpt('insecure', + default=False, + help=_("If set, then the server's certificate will not " + "be verified."))] + + +def register_opts(conf): + conf.register_group(cinder_group) + conf.register_group(cinder_client_group) + conf.register_opts(cinder_opts, group=cinder_group) + conf.register_opts(cinder_client_opts, group=cinder_client_group) + conf.register_opts(common_security_opts, group=cinder_client_group) + + +def list_opts(): + return { + cinder_group: cinder_opts, + cinder_client_group: cinder_client_opts + } diff --git a/pool/shard007/Python/0070274_task_run.py b/pool/shard007/Python/0070274_task_run.py new file mode 100644 index 0000000000000000000000000000000000000000..7fdad4e2ec894699c4b7edb674d414212665a0c7 --- /dev/null +++ b/pool/shard007/Python/0070274_task_run.py @@ -0,0 +1,104 @@ +# -*- coding: utf8 -*- +# This file is part of PyBossa. +# +# Copyright (C) 2013 SF Isle of Man Limited +# +# PyBossa is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# PyBossa 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with PyBossa. If not, see . + +from sqlalchemy import Integer, Text +from sqlalchemy.schema import Column, ForeignKey +from sqlalchemy import event + +from pybossa.core import db +from pybossa.model import DomainObject, JSONType, make_timestamp, update_redis + + + + +class TaskRun(db.Model, DomainObject): + '''A run of a given task by a specific user. + ''' + __tablename__ = 'task_run' + + #: ID of the TaskRun + id = Column(Integer, primary_key=True) + #: UTC timestamp for when TaskRun is created. + created = Column(Text, default=make_timestamp) + #: Project.id of the project associated with this TaskRun. + app_id = Column(Integer, ForeignKey('app.id'), nullable=False) + #: Task.id of the task associated with this TaskRun. + task_id = Column(Integer, ForeignKey('task.id', ondelete='CASCADE'), + nullable=False) + #: User.id of the user contributing the TaskRun (only if authenticated) + user_id = Column(Integer, ForeignKey('user.id')) + #: User.ip of the user contributing the TaskRun (only if anonymous) + user_ip = Column(Text) + finish_time = Column(Text, default=make_timestamp) + timeout = Column(Integer) + calibration = Column(Integer) + #: Value of the answer. + info = Column(JSONType, default=dict) + '''General writable field that should be used by clients to record results\ + of a TaskRun. Usually a template for this will be provided by Task + For example:: + result: { + whatever information should be recorded -- up to task presenter + } + ''' + + +@event.listens_for(TaskRun, 'after_insert') +def update_task_state(mapper, conn, target): + """Update the task.state when n_answers condition is met.""" + # Get app details + sql_query = ('select name, short_name, info from app \ + where id=%s') % target.app_id + results = conn.execute(sql_query) + app_obj = dict(id=target.app_id, + name=None, + short_name=None, + info=None, + action_updated='TaskCompleted') + for r in results: + app_obj['name'] = r.name + app_obj['short_name'] = r.short_name + app_obj['info'] = r.info + + # Check if user is Authenticated + if target.user_id is not None: + sql_query = ('select fullname, name, info from "user" \ + where id=%s') % target.user_id + results = conn.execute(sql_query) + for r in results: + obj = dict(id=target.user_id, + name=r.name, + fullname=r.fullname, + info=r.info, + app_name=app_obj['name'], + app_short_name=app_obj['short_name'], + action_updated='UserContribution') + # Add the event + update_redis(obj) + # Check if Task.state should be updated + sql_query = ('select count(id) from task_run \ + where task_run.task_id=%s') % target.task_id + n_answers = conn.scalar(sql_query) + sql_query = ('select n_answers from task \ + where task.id=%s') % target.task_id + task_n_answers = conn.scalar(sql_query) + if (n_answers) >= task_n_answers: + sql_query = ("UPDATE task SET state=\'completed\' \ + where id=%s") % target.task_id + conn.execute(sql_query) + update_redis(app_obj) diff --git a/pool/shard007/Python/0070287_test_retrieve_and_compute.py b/pool/shard007/Python/0070287_test_retrieve_and_compute.py new file mode 100644 index 0000000000000000000000000000000000000000..fbc22bd5c2f73f37ff3708699b6eedbb2199de7b --- /dev/null +++ b/pool/shard007/Python/0070287_test_retrieve_and_compute.py @@ -0,0 +1,96 @@ +import newspaper + +import zeeguu_core +from zeeguu_core_test.model_test_mixin import ModelTestMixIn +from zeeguu_core_test.rules.language_rule import LanguageRule +from zeeguu_core_test.rules.rss_feed_rule import RSSFeedRule +from zeeguu_core_test.rules.user_rule import UserRule +from zeeguu_core.content_retriever.content_cleaner import cleanup_non_content_bits +from zeeguu_core.content_retriever.article_downloader import download_from_feed, strip_article_title_word +from zeeguu_core.content_retriever.quality_filter import sufficient_quality +from zeeguu_core.model import Topic, LocalizedTopic, ArticleWord + +from zeeguu_core_test.test_data.mocking_the_web import * + + +class TestRetrieveAndCompute(ModelTestMixIn): + def setUp(self): + super().setUp() + + self.user = UserRule().user + self.lan = LanguageRule().de + + def testDifficultyOfFeedItems(self): + feed = RSSFeedRule().feed1 + download_from_feed(feed, zeeguu_core.db.session, 3, False) + + articles = feed.get_articles(limit=2) + + assert len(articles) == 2 + assert articles[0].fk_difficulty + + def testDownloadWithTopic(self): + feed = RSSFeedRule().feed1 + topic = Topic("Spiegel") + zeeguu_core.db.session.add(topic) + zeeguu_core.db.session.commit() + loc_topic = LocalizedTopic(topic, self.lan, "spiegelDE", "spiegel") + zeeguu_core.db.session.add(loc_topic) + zeeguu_core.db.session.commit() + + download_from_feed(feed, zeeguu_core.db.session, 3, False ) + + article = feed.get_articles(limit=2)[0] + + assert (topic in article.topics) + + def testDownloadWithWords(self): + feed = RSSFeedRule().feed1 + + download_from_feed(feed, zeeguu_core.db.session, 3, False) + + article = feed.get_articles(limit=2)[0] + + # Try two words, as one might be filtered out + word = strip_article_title_word(article.title.split()[0]) + article_word = ArticleWord.find_by_word(word) + + if word in ['www', ''] or word.isdigit() or len(word) < 3 or len(word) > 25: + assert (article_word is None) + else: + assert (article in article_word.articles) + + def test_sufficient_quality(self): + + art = newspaper.Article(url_investing_in_index_funds) + art.download() + art.parse() + + assert (sufficient_quality(art)) + + def test_new_scientist_overlay(self): + + art = newspaper.Article(url_fish_will_be_gone) + art.download() + art.parse() + + is_quality, _ = sufficient_quality(art) + assert (not is_quality) + + def test_le_monde_subscription(self): + + art = newspaper.Article(url_vols_americans) + art.download() + art.parse() + + is_quality, _ = sufficient_quality(art) + assert (not is_quality) + + def test_fragment_removal(self): + + art = newspaper.Article(url_onion_us_military) + art.download() + art.parse() + + cleaned_up_text = cleanup_non_content_bits(art.text) + assert ("Advertisement" not in cleaned_up_text) diff --git a/pool/shard007/Python/0070289_models.py b/pool/shard007/Python/0070289_models.py new file mode 100644 index 0000000000000000000000000000000000000000..847a9dd013d04d9d308a557ce3d765bbb38f8f37 --- /dev/null +++ b/pool/shard007/Python/0070289_models.py @@ -0,0 +1,131 @@ +# Copyright 2010-2011 OpenStack Foundation +# All Rights Reserved. +# +# 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. + +"""Model classes that form the core of instances functionality.""" + +from oslo_utils.importutils import import_class + +from trove.common import cfg +from trove.common.i18n import _ +from trove.common import remote + +CONF = cfg.CONF + + +class ModelBase(object): + """ + An object which can be stored in the database. + """ + + _data_fields = [] + _auto_generated_attrs = [] + + def _validate(self, errors): + """Subclasses override this to offer additional validation. + + For each validation error a key with the field name and an error + message is added to the dict. + + """ + pass + + def data(self, **options): + """Called to serialize object to a dictionary.""" + data_fields = self._data_fields + self._auto_generated_attrs + return {field: self[field] for field in data_fields} + + def is_valid(self): + """Called when persisting data to ensure the format is correct.""" + self.errors = {} + self._validate(self.errors) +# self._validate_columns_type() +# self._before_validate() +# self._validate() + return self.errors == {} + + def __setitem__(self, key, value): + """Overloaded to cause this object to look like a data entity.""" + setattr(self, key, value) + + def __getitem__(self, key): + """Overloaded to cause this object to look like a data entity.""" + return getattr(self, key) + + def __eq__(self, other): + """Overloaded to cause this object to look like a data entity.""" + if not hasattr(other, 'id'): + return False + return type(other) == type(self) and other.id == self.id + + def __ne__(self, other): + """Overloaded to cause this object to look like a data entity.""" + return not self == other + + def __hash__(self): + """Overloaded to cause this object to look like a data entity.""" + return self.id.__hash__() + + +class RemoteModelBase(ModelBase): + + # This should be set by the remote model during init time + # The data() method will be using this + _data_object = None + + def _data_item(self, data_object): + data_fields = self._data_fields + self._auto_generated_attrs + return {field: getattr(data_object, field) for field in data_fields} + + # data magic that will allow for a list of _data_object or a single item + # if the object is a list, it will turn it into a list of hash's again + def data(self, **options): + if self._data_object is None: + raise LookupError(_("data object is None")) + if isinstance(self._data_object, list): + return [self._data_item(item) for item in self._data_object] + else: + return self._data_item(self._data_object) + + +class NetworkRemoteModelBase(RemoteModelBase): + + network_driver = None + + @classmethod + def get_driver(cls, context, region_name): + if not cls.network_driver: + cls.network_driver = import_class(CONF.network_driver) + return cls.network_driver(context, region_name) + + +class NovaRemoteModelBase(RemoteModelBase): + + @classmethod + def get_client(cls, context, region_name): + return remote.create_nova_client(context, region_name) + + +class SwiftRemoteModelBase(RemoteModelBase): + + @classmethod + def get_client(cls, context, region_name): + return remote.create_swift_client(context, region_name) + + +class CinderRemoteModelBase(RemoteModelBase): + + @classmethod + def get_client(cls, context): + return remote.create_cinder_client(context) diff --git a/pool/shard007/Python/0070298_sports_streams.py b/pool/shard007/Python/0070298_sports_streams.py new file mode 100644 index 0000000000000000000000000000000000000000..168f106f491fa9114dd2c046d6e5089db9b6affc --- /dev/null +++ b/pool/shard007/Python/0070298_sports_streams.py @@ -0,0 +1,203 @@ +# -*- coding: utf-8 -*- +""" + + Copyright (C) 2018 TonyH + Version 3.0.0 + + --July 8 2018, Added Local time and changed game times to be local-- + Thanks to Bugatsinho for the Time function-- + + --June 16 2018, Added GMT+3 time to the top of the page to make + it easier to figure out when the games start-- + + 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 . + + ------------------------------------------------------------- + + Usage Examples: + + +Sports Streams +games + + +""" + +import requests, re, json, os +import koding +import __builtin__ +import xbmc, xbmcaddon +from koding import route +from resources.lib.plugin import Plugin +from resources.lib.util.context import get_context_items +from resources.lib.util.xml import JenItem, JenList, display_list +from unidecode import unidecode +import datetime, time + +try: import json +except ImportError: import simplejson as json +from dateutil.parser import parse +from dateutil.tz import gettz +from dateutil.tz import tzlocal + +####################################### +# Time and Date Helpers +####################################### +try: + local_tzinfo = tzlocal() + locale_timezone = json.loads(xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Settings.GetSettingValue", "params": {"setting": "locale.timezone"}, "id": 1}')) + if locale_timezone['result']['value']: + local_tzinfo = gettz(locale_timezone['result']['value']) +except: + pass + +def convDateUtil(timestring, newfrmt='default', in_zone='UTC'): + if newfrmt == 'default': + newfrmt = xbmc.getRegion('time').replace(':%S','') + try: + in_time = parse(timestring) + in_time_with_timezone = in_time.replace(tzinfo=gettz(in_zone)) + local_time = in_time_with_timezone.astimezone(local_tzinfo) + return local_time.strftime(newfrmt) + except: + return timestring + + +CACHE_TIME = 3600 # change to wanted cache time in seconds + +addon_fanart = xbmcaddon.Addon().getAddonInfo('fanart') +addon_icon = xbmcaddon.Addon().getAddonInfo('icon') +User_Agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36' + + +class Sports_streams(Plugin): + name = "sports_streams" + + def process_item(self, item_xml): + if "" in item_xml: + item = JenItem(item_xml) + if "games" in item.get("sport_stream", ""): + result_item = { + 'label': item["title"], + 'icon': "https://i.pinimg.com/736x/a2/b9/7c/a2b97c577ff82928cc53591c33ba8f75--stream-online-daytona--live.jpg", + 'fanart': item.get("fanart", addon_fanart), + 'mode': "Sport_Stream", + 'url': item.get("sport_stream", ""), + 'folder': True, + 'imdb': "0", + 'content': "files", + 'season': "0", + 'episode': "0", + 'info': {}, + 'year': "0", + 'context': get_context_items(item), + "summary": item.get("summary", None) + } + result_item["properties"] = { + 'fanart_image': result_item["fanart"] + } + result_item['fanart_small'] = result_item["fanart"] + return result_item + + +@route(mode='Sport_Stream', args=["url"]) +def get_stream(url): + xml = "" + try: + url = "http://www.sports-stream.net/schedule.html" + headers = {'User_Agent': User_Agent} + html = requests.get(url, headers=headers).content + local_time = datetime.datetime.now().strftime('%H:%M') + + xml += ""\ + "[COLOR blue]Local Time %s[/COLOR]"\ + "http://www.logotypes101.com/logos/997/AD71A2CC84DD8DDE7932F9BC585926E1/Sports.png"\ + "http://sportz4you.com/blog/wp-content/uploads/2016/01/0b46b20.jpg"\ + ""\ + "" % local_time + try: + match = re.compile('

(.+?)

(.+?)

',re.DOTALL).findall(html) + match5 = re.compile('(.+?)\s*(.+?)\s*\-\s*%s - %s"\ + "http://www.logotypes101.com/logos/997/AD71A2CC84DD8DDE7932F9BC585926E1/Sports.png"\ + "http://sportz4you.com/blog/wp-content/uploads/2016/01/0b46b20.jpg"\ + "%s"\ + "" % (display_time, name, link) + if xml == "": + block3 = re.compile('

(.+?)',re.DOTALL).findall(html) + match5 = re.compile('(.+?)\s*(.+?)\s*\-\s*%s - %s"\ + "http://www.logotypes101.com/logos/997/AD71A2CC84DD8DDE7932F9BC585926E1/Sports.png"\ + "http://sportz4you.com/blog/wp-content/uploads/2016/01/0b46b20.jpg"\ + "%s"\ + "" % (display_time, name, link) + except: + pass + + try: + match3 = re.compile('

.+?

(.+?)

.+?

(.+?)") + + response = accept_alert(session) + value = assert_success(response) + assert value is None + + +def test_no_top_level_browsing_context(session, closed_window): + response = accept_alert(session) + assert_error(response, "no such window") + + +def test_no_browsing_context(session, closed_frame): + response = accept_alert(session) + assert_error(response, "no such alert") + + +def test_no_user_prompt(session): + response = accept_alert(session) + assert_error(response, "no such alert") + + +def test_accept_alert(session, inline): + session.url = inline("") + + response = accept_alert(session) + assert_success(response) + + with pytest.raises(NoSuchAlertException): + session.alert.text + + +def test_accept_confirm(session, inline): + session.url = inline("") + + response = accept_alert(session) + assert_success(response) + + with pytest.raises(NoSuchAlertException): + session.alert.text + + assert session.execute_script("return window.result") is True + + +def test_accept_prompt(session, inline): + session.url = inline(""" + + """) + + response = accept_alert(session) + assert_success(response) + + with pytest.raises(NoSuchAlertException): + session.alert.text + + assert session.execute_script("return window.result") == "Federer" + + +def test_unexpected_alert(session): + session.execute_script("window.setTimeout(function() { window.alert('Hello'); }, 100);") + wait = Poll( + session, + timeout=5, + ignored_exceptions=NoSuchAlertException, + message="No user prompt with text 'Hello' detected") + wait.until(lambda s: s.alert.text == "Hello") + + response = accept_alert(session) + assert_success(response) + + with pytest.raises(NoSuchAlertException): + session.alert.text + + +def test_accept_in_popup_window(session, inline): + orig_handles = session.handles + + session.url = inline(""" + + """) + button = session.find.css("button", all=False) + button.click() + + session.window_handle = wait_for_new_handle(session, orig_handles) + session.url = inline(""" + + """) + + response = accept_alert(session) + assert_success(response) + + with pytest.raises(NoSuchAlertException): + session.alert.text diff --git a/pool/shard007/Python/0070467_circle.py b/pool/shard007/Python/0070467_circle.py new file mode 100644 index 0000000000000000000000000000000000000000..6f6c27a77affb09b1a6ba8b1060decd0d0f2047b --- /dev/null +++ b/pool/shard007/Python/0070467_circle.py @@ -0,0 +1,78 @@ +""" +Copyright [2016] [Satbir Singh] + +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. +""" + + +import math +from OpenGL.GL import * +import control +import dot +import sys +from PySide import QtGui + + +class Circle(control.Control): + def __init__(self,center=0, radius=0): + super(control.Control, self).__init__() + self._controls = {} + self._dot = dot.Dot() + self._num_triangles = 100 + self.center = center + self.radius = radius + + def render(self): + if self.center is 0: + self.bounds.left_top.x += 0.1 + self.bounds.right_bottom.x += 0.1 + self.center = self.bounds.center() + self.radius = self.bounds.width()/2 + + self.draw_circle(self.center.x, self.center.y, self.radius) + self._dot.set_bounds(control.Bounds(self.center, self.center)) + self._dot.render() + + for key, value in self._controls.items(): + value.render() + return True + + def add(self, pos, c): + self._controls[pos] = c + + def draw_circle(self, x, y, w): + + twice_the_pi = 3.14159 * 2 + glBegin(GL_LINES) + glColor3f(0, 1, 0) + for i in range(self._num_triangles + 1): + glVertex2f(x + (w * math.cos(i * twice_the_pi / self._num_triangles)), + y + (w * math.sin(i * twice_the_pi / self._num_triangles))) + glEnd() + +if __name__ == '__main__': + list = [] + + app = QtGui.QApplication(sys.argv) + bound = control.Bounds(control.Point(-7.0, 1.0), control.Point(-5.0, 3.0)) + circle = Circle() + circle.set_bounds(bound) + + list.append(circle) + + import testbed + + mainWin = testbed.MainWindow(list) + mainWin.show() + sys.exit(app.exec_()) + diff --git a/pool/shard007/Python/0070470_ChangeUnitCell.py b/pool/shard007/Python/0070470_ChangeUnitCell.py new file mode 100644 index 0000000000000000000000000000000000000000..09c135826b0f9938170db1c7a0e082e3e8a1c649 --- /dev/null +++ b/pool/shard007/Python/0070470_ChangeUnitCell.py @@ -0,0 +1,36 @@ +# Checks for Ticket #11 + +from asap3 import * +from ase.lattice.cubic import FaceCenteredCubic +from asap3.testtools import ReportTest + +print "Test for Ticket #11: https://trac.fysik.dtu.dk/projects/Asap/ticket/11" + +atoms = FaceCenteredCubic(directions=[[1,0,0],[0,1,0],[0,0,1]], size=(6,6,6), + symbol="Cu") +atoms.set_calculator(EMT()) +r = atoms.get_positions() +print "Orig position", r[-1] + +uc = atoms.get_cell() +print uc +r[-1] = 1.51*uc[2] +atoms.set_positions(r) +print atoms.get_potential_energy() + +p1 = atoms.get_positions()[-1] +print "p1:", p1 + +atoms.set_cell(uc, scale_atoms=True) +print atoms.get_potential_energy() +p2 = atoms.get_positions()[-1] +print "p2:", p2 + +atoms.set_cell(uc, scale_atoms=False) +print atoms.get_potential_energy() +p3 = atoms.get_positions()[-1] +print "p3:", p3 + +ReportTest("p2 equals p1", p2[2], p1[2], 1e-6) +ReportTest("p3 equals p1", p3[2], p1[2], 1e-6) +ReportTest.Summary() diff --git a/pool/shard007/Python/0070472_message.py b/pool/shard007/Python/0070472_message.py new file mode 100644 index 0000000000000000000000000000000000000000..90587e4672b8309793eae218b43c7515e9f2e5ae --- /dev/null +++ b/pool/shard007/Python/0070472_message.py @@ -0,0 +1,253 @@ +# -*- encoding: utf-8 -*- +import logging +try: + from urllib.parse import urlencode +except ImportError: + from urllib import urlencode +import re +import time +from datetime import datetime + +import requests + +log = logging.getLogger('facebook') +log.setLevel(logging.WARN) + +#MESSAGE_URL = 'https://m.facebook.com/messages/send/?icm=1&refid=12' +MESSAGE_URL = 'https://www.facebook.com/ajax/mercury/send_messages.php?dpr=1' +UPLOAD_URL = 'https://upload.facebook.com/ajax/mercury/upload.php?' +TYP_URL = 'https://www.facebook.com/ajax/messaging/typ.php' +READ_URL = 'https://www.facebook.com/ajax/mercury/change_read_status.php' + +# define like sticker id +LIKE_STICKER = { + 'l': '369239383222810', + 'm': '369239343222814', + 's': '369239263222822' +} + + +def send_group(fb, thread, body, pic=None, sticker=None, like=None): + data = { + "message_batch[0][action_type]": "ma-type:user-generated-message", + "message_batch[0][author]": "fbid:{}".format(fb.user_id), + "message_batch[0][source]": "source:chat:web", + "message_batch[0][body]": body, + "message_batch[0][signatureID]": "3c132b09", + "message_batch[0][ui_push_phase]": "V3", + "message_batch[0][status]": "0", + "message_batch[0][thread_fbid]": thread, + "client": "mercury", + "__user": fb.user_id, + "__a": "1", + "__dyn": "7n8anEBQ9FoBUSt2u6aAix97xN6yUgByV9GiyFqzQC-C26m6oDAyoSnx2ubhHAyXBBzEy5E", + "__req": "c", + "fb_dtsg": fb.dtsg, + "ttstamp": "26581691011017411284781047297", + "__rev": "1436610", + } + + if pic: + # upload the picture and get picture form data + pic_data = upload_picture(fb, pic) + if pic_data: + # merge together to send message with picture + data.update(pic_data) + + # add sticker if sticker is available + if any([sticker, like]): + # if like is not None, find the corresponding sticker id + if like: + try: + sticker = LIKE_STICKER[like.lower()] + except KeyError: + # if user doesn't enter l or m or s, then use the large one + sticker = LIKE_STICKER['l'] + + data["message_batch[0][sticker_id]"] = sticker + + fb.session.post(MESSAGE_URL, data) + + +def send_person(fb, person, body, pic=None, sticker=None, like=None): + '''data = { + "message_batch[0][action_type]": "ma-type:user-generated-message", + "message_batch[0][author]": "fbid:{}".format(fb.user_id), + "message_batch[0][source]": "source:chat:web", + "message_batch[0][body]": body, + "message_batch[0][signatureID]": "3c132b09", + "message_batch[0][ui_push_phase]": "V3", + "message_batch[0][status]": "0", + "message_batch[0][specific_to_list][0]": "fbid:{}".format(person), + "message_batch[0][specific_to_list][1]": "fbid:{}".format(fb.user_id), + "client": "mercury", + "__user": fb.user_id, + "__a": "1", + "__dyn": "7n8anEBQ9FoBUSt2u6aAix97xN6yUgByV9GiyFqzQC-C26m6oDAyoSnx2ubhHAyXBBzEy5E", + "__req": "c", + "fb_dtsg": fb.dtsg, + "ttstamp": "26581691011017411284781047297", + "__rev": "1436610", + }''' + + data = { + "__a": "1", + "__dyn": "", + "__pc": "EXP1:DEFAULT", + "__req": "1d", + "__rev": "2274481", + "__user": fb.user_id, + "client": "mercury", + "fb_dtsg": fb.dtsg, + "message_batch[0][action_type]": "ma - type:user - generated - message", + "message_batch[0][author]": "fbid:{}".format(fb.user_id), + "message_batch[0][author_email]": "", + "message_batch[0][body]": body, + "message_batch[0][ephemeral_ttl_mode]": "0", + "message_batch[0][has_attachment]": "false", + "message_batch[0][html_body]": "false", + "message_batch[0][is_filtered_content]": "false", + "message_batch[0][is_filtered_content_account]": "false", + "message_batch[0][is_filtered_content_bh]": "false", + "message_batch[0][is_filtered_content_invalid_app]": "false", + "message_batch[0][is_filtered_content_quasar]": "false", + "message_batch[0][is_forward]": "false", + "message_batch[0][is_spoof_warning]": "false", + "message_batch[0][is_unread]": "false", + "message_batch[0][manual_retry_cnt]": "0", + "message_batch[0][other_user_fbid]": person, + "message_batch[0][source]": "source:chat:web", + "message_batch[0][source_tags][0]": "source:chat", + "message_batch[0][specific_to_list][0]": "fbid:{}".format(person), + "message_batch[0][specific_to_list][1]": "fbid:{}".format(fb.user_id), + "message_batch[0][status]": "0", + "message_batch[0][thread_id]": "", + "message_batch[0][timestamp]": str(round(time.mktime(datetime.now().timetuple()) * 1000)), + "message_batch[0][timestamp_absolute]": "Today", + "message_batch[0][timestamp_relative]": datetime.now().strftime("%I:%M%P"), + "message_batch[0][timestamp_time_passed]": "0", + "message_batch[0][ui_push_phase]": "V3", + "ttstamp": generate_ttstamp(fb.dtsg) + } + + if pic: + # upload the picture and get picture form data + pic_data = upload_picture(fb, pic) + if pic_data: + # merge together to send message with picture + data.update(pic_data) + + # add sticker if sticker is available + if any([sticker, like]): + # if like is not None, find the corresponding sticker id + if like: + try: + sticker = LIKE_STICKER[like.lower()] + except KeyError: + # if user doesn't enter l or m or s, then use the large one + sticker = LIKE_STICKER['l'] + + data["message_batch[0][sticker_id]"] = sticker + + fb.session.post(MESSAGE_URL, data) + + +def upload_picture(fb, pic): + params = { + "__user": fb.user_id, + "__a": "1", + "__dyn": "7n8anEBQ9FoBUSt2u6aAix97xN6yUgByV9GiyFqzQC-C26m6oDAyoSnx2ubhHAyXBBzEy5E", + "__req": "c", + "fb_dtsg": fb.dtsg, + "ttstamp": "26581691011017411284781047297", + "__rev": "1436610", + 'ft[tn]': '+M', + } + + # upload the image to facebook server, filename should be unique + res = fb.session.post(UPLOAD_URL + urlencode(params), files={ + 'images_only': 'true', + 'upload_1024': (str(time.time()), requests.get(pic).content, 'image/jpeg') + }) + + # check status code + if res.status_code != 200: + return + + # check image_id is valid + m = re.search(r'"image_id":(\d+),', res.text) + if not m: + return + + image_id = m.group(1) + return { + "message_batch[0][has_attachment]": "true", + "message_batch[0][preview_attachments][0][upload_id]": "upload_1024", + "message_batch[0][preview_attachments][0][attach_type]": "photo", + "message_batch[0][preview_attachments][0][preview_uploading]": "true", + "message_batch[0][preview_attachments][0][preview_width]": "540", + "message_batch[0][preview_attachments][0][preview_height]": "720", + "message_batch[0][image_ids][0]": image_id, + } + + +def group_typing(fb, thread): + data = { + "typ": "1", + "to": "", + "source": "web-messenger", + "thread": thread, + "__user": fb.user_id, + "__a": "1", + "__dyn": "7n8anEBQ9FoBUSt2u6aAix97xN6yUgByV9GiyFqzQC-C26m6oDAyoSnx2ubhHAyXBBzEy5E", + "__req": "c", + "fb_dtsg": fb.dtsg, + "ttstamp": "26581691011017411284781047297", + "__rev": "1436610", + } + + fb.session.post(TYP_URL, data) + + +def person_typing(fb, thread): + data = { + "typ": "1", + "to": thread, + "source": "web-messenger", + "thread": thread, + "__user": fb.user_id, + "__a": "1", + "__dyn": "7n8anEBQ9FoBUSt2u6aAix97xN6yUgByV9GiyFqzQC-C26m6oDAyoSnx2ubhHAyXBBzEy5E", + "__req": "c", + "fb_dtsg": fb.dtsg, + "ttstamp": "26581691011017411284781047297", + "__rev": "1436610", + } + + fb.session.post(TYP_URL, data) + + +def read(fb, thread): + data = { + "ids[{}]".format(thread): "true", + "__user": fb.user_id, + "__a": "1", + "__dyn": "7n8anEBQ9FoBUSt2u6aAix97xN6yUgByV9GiyFqzQC-C26m6oDAyoSnx2ubhHAyXBBzEy5E", + "__req": "c", + "fb_dtsg": fb.dtsg, + "ttstamp": "26581691011017411284781047297", + "__rev": "1436610", + } + + fb.session.post(READ_URL, data) + + +def generate_ttstamp(dtsg): + u = '' + v = 0 + while v < len(dtsg): + u += str(ord(dtsg[v])) + v += 1 + ttstamp = '2%s' % u + + return ttstamp diff --git a/pool/shard007/Python/0070473_dns_record_test.py b/pool/shard007/Python/0070473_dns_record_test.py new file mode 100644 index 0000000000000000000000000000000000000000..6eb6c93aa2419d3cffedf578584ad9ed4eab91c9 --- /dev/null +++ b/pool/shard007/Python/0070473_dns_record_test.py @@ -0,0 +1,36 @@ +# Copyright (c) 2020, The MITRE Corporation. All rights reserved. +# See LICENSE.txt for complete terms. + +import unittest + +from mixbox.vendor.six import u + +from cybox.objects.dns_record_object import DNSRecord +from cybox.test.objects import ObjectTestCase +from cybox.test.objects.address_test import TestAddress +from cybox.test.objects.uri_test import TestURI + + +class TestDNSRecord(ObjectTestCase, unittest.TestCase): + object_type = "DNSRecordObjectType" + klass = DNSRecord + + _full_dict = { + 'description': 'A description of this object', + 'domain_name': TestURI._full_dict, + 'queried_date': '2001-01-01T06:56:50+04:00', + 'ip_address': TestAddress._full_dict, + 'address_class': 'IPv4', + 'entry_type': 'SRV', + 'record_name': u('vc.example.com'), + 'record_type': 'DNS', + 'ttl': 14400, + 'flags': u('10'), + 'data_length': 13200, + 'record_data': u('Some Record Data'), + 'xsi:type': object_type, + } + + +if __name__ == "__main__": + unittest.main() diff --git a/pool/shard007/Python/0070475_bifurcationfunc.py b/pool/shard007/Python/0070475_bifurcationfunc.py new file mode 100644 index 0000000000000000000000000000000000000000..9d457a87555b7bbff0de27a478947b1eaf1618ae --- /dev/null +++ b/pool/shard007/Python/0070475_bifurcationfunc.py @@ -0,0 +1,127 @@ +# Copyright (c) 2015, Ecole Polytechnique Federale de Lausanne, Blue Brain Project +# All rights reserved. +# +# This file is part of NeuroM +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the name of the copyright holder nor the names of +# its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +'''Bifurcation point functions''' + +import numpy as np +from neurom import morphmath +from neurom.exceptions import NeuroMError +from neurom.core.dataformat import COLS + + +def _raise_if_not_bifurcation(section): + n_children = len(section.children) + if n_children != 2: + raise NeuroMError('A bifurcation point must have exactly 2 children, found {}'.format( + n_children)) + + +def local_bifurcation_angle(bif_point): + '''Return the opening angle between two out-going sections + in a bifurcation point + + We first ensure that the input point has only two children. + + The bifurcation angle is defined as the angle between the first non-zero + length segments of a bifurcation point. + ''' + def skip_0_length(sec): + '''Return the first point with non-zero distance to first point''' + p0 = sec[0] + cur = sec[1] + for i, p in enumerate(sec[1:]): + if not np.all(p[:COLS.R] == p0[:COLS.R]): + cur = sec[i + 1] + break + + return cur + + _raise_if_not_bifurcation(bif_point) + + ch0, ch1 = (skip_0_length(bif_point.children[0].points), + skip_0_length(bif_point.children[1].points)) + + return morphmath.angle_3points(bif_point.points[-1], ch0, ch1) + + +def remote_bifurcation_angle(bif_point): + '''Return the opening angle between two out-going sections + in a bifurcation point + + We first ensure that the input point has only two children. + + The angle is defined as between the bifurcation point and the + last points in the out-going sections. + ''' + _raise_if_not_bifurcation(bif_point) + + return morphmath.angle_3points(bif_point.points[-1], + bif_point.children[0].points[-1], + bif_point.children[1].points[-1]) + + +def bifurcation_partition(bif_point): + '''Calculate the partition at a bifurcation point + + We first ensure that the input point has only two children. + + The number of nodes in each child tree is counted. The partition is + defined as the ratio of the largest number to the smallest number.''' + _raise_if_not_bifurcation(bif_point) + + n = float(sum(1 for _ in bif_point.children[0].ipreorder())) + m = float(sum(1 for _ in bif_point.children[1].ipreorder())) + return max(n, m) / min(n, m) + + +def partition_asymmetry(bif_point): + '''Calculate the partition asymmetry at a bifurcation point + as defined in https://www.ncbi.nlm.nih.gov/pubmed/18568015 + + The number of nodes in each child tree is counted. The partition + is defined as the ratio of the absolute difference and the sum + of the number of bifurcations in the two daughter subtrees + at each branch point.''' + _raise_if_not_bifurcation(bif_point) + + n = float(sum(1 for _ in bif_point.children[0].ipreorder())) + m = float(sum(1 for _ in bif_point.children[1].ipreorder())) + if n == m: + return 0.0 + return abs(n - m) / abs(n + m) + + +def partition_pair(bif_point): + '''Calculate the partition pairs at a bifurcation point + + The number of nodes in each child tree is counted. The partition + pairs is the number of bifurcations in the two daughter subtrees + at each branch point.''' + n = float(sum(1 for _ in bif_point.children[0].ipreorder())) + m = float(sum(1 for _ in bif_point.children[1].ipreorder())) + return (n, m) diff --git a/pool/shard007/Python/0070476_views.py b/pool/shard007/Python/0070476_views.py new file mode 100644 index 0000000000000000000000000000000000000000..d2e859efd628e9d11250e5002440fc39ff0da969 --- /dev/null +++ b/pool/shard007/Python/0070476_views.py @@ -0,0 +1,133 @@ +import logging + +from django.conf import settings +from django.contrib.admin.views.decorators import staff_member_required +from django.core.cache import cache +from django.http import HttpResponse, HttpResponseRedirect +from django.shortcuts import render_to_response +from django.template.context import RequestContext +from django.template.loader import render_to_string +from django.utils import simplejson +from django.utils.translation import ugettext as _ +from djblets.siteconfig.models import SiteConfiguration +from djblets.siteconfig.views import site_settings as djblets_site_settings + +from reviewboard.admin.cache_stats import get_cache_stats +from reviewboard.admin.checks import check_updates_required +from reviewboard.admin.forms import SSHSettingsForm +from reviewboard.admin.widgets import dynamic_activity_data, \ + primary_widgets, \ + secondary_widgets +from reviewboard.scmtools import sshutils + + +@staff_member_required +def dashboard(request, template_name="admin/dashboard.html"): + """ + Displays the administration dashboard, containing news updates and + useful administration tasks. + """ + return render_to_response(template_name, RequestContext(request, { + 'title': _("Admin Dashboard"), + 'root_path': settings.SITE_ROOT + "admin/db/", + 'primary_widgets': primary_widgets, + 'secondary_widgets': secondary_widgets, + })) + + +@staff_member_required +def cache_stats(request, template_name="admin/cache_stats.html"): + """ + Displays statistics on the cache. This includes such pieces of + information as memory used, cache misses, and uptime. + """ + cache_stats = get_cache_stats() + + return render_to_response(template_name, RequestContext(request, { + 'cache_hosts': cache_stats, + 'cache_backend': cache.__module__, + 'title': _("Server Cache"), + 'root_path': settings.SITE_ROOT + "admin/db/" + })) + + +@staff_member_required +def site_settings(request, form_class, + template_name="siteconfig/settings.html"): + return djblets_site_settings(request, form_class, template_name, { + 'root_path': settings.SITE_ROOT + "admin/db/" + }) + + +@staff_member_required +def ssh_settings(request, template_name='admin/ssh_settings.html'): + key = sshutils.get_user_key() + + if request.method == 'POST': + form = SSHSettingsForm(request.POST, request.FILES) + + if form.is_valid(): + try: + form.create(request.FILES) + return HttpResponseRedirect('.') + except Exception, e: + # Fall through. It will be reported inline and in the log. + logging.error('Uploading SSH key failed: %s' % e) + else: + form = SSHSettingsForm() + + if key: + fingerprint = sshutils.humanize_key(key) + else: + fingerprint = None + + return render_to_response(template_name, RequestContext(request, { + 'title': _('SSH Settings'), + 'key': key, + 'fingerprint': fingerprint, + 'public_key': sshutils.get_public_key(key), + 'form': form, + })) + + +def manual_updates_required(request, updates, + template_name="admin/manual_updates_required.html"): + """ + Checks for required manual updates and displays informational pages on + performing the necessary updates. + """ + return render_to_response(template_name, RequestContext(request, { + 'updates': [render_to_string(template_name, + RequestContext(request, extra_context)) + for (template_name, extra_context) in updates], + })) + + +def widget_toggle(request): + """ + Controls the state of widgets - collapsed or expanded. + Saves the state into site settings. + """ + collapsed = request.GET.get('collapse', None) + widget = request.GET.get('widget', None) + + if widget and collapsed: + siteconfig = SiteConfiguration.objects.get_current() + widget_settings = siteconfig.get("widget_settings", {}) + + widget_settings[widget] = collapsed + siteconfig.set("widget_settings", widget_settings) + siteconfig.save() + + return HttpResponse("") + + +def widget_activity(request): + """ + Receives an AJAX request, sends the data to the widget controller and + returns JSON data + """ + activity_data = dynamic_activity_data(request) + + return HttpResponse(simplejson.dumps(activity_data), + mimetype="application/json") diff --git a/pool/shard007/Python/0070478_io_utils.py b/pool/shard007/Python/0070478_io_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8668736f747326d45b6f4122eda2c404bdad2be0 --- /dev/null +++ b/pool/shard007/Python/0070478_io_utils.py @@ -0,0 +1,70 @@ +# coding=utf-8 +# Copyright 2018 The Google AI Language Team Authors. +# +# 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. +"""Utils for loading data from files and writing data to disk.""" + + + +from language.compir.dataset_parsers.dataset_parser import Example + +from tensorflow.io import gfile + + +def _load_examples(filename): + """Loads raw examples from original data file.""" + examples = [] + with gfile.GFile(filename, "r") as input_file: + for line in input_file: + splits = line.split("OUT:") + input_string = splits[0][3:].strip() + output_string = splits[1].strip() + + examples.append(Example(input_string, output_string)) + return examples + + +def _load_predictions(filename): + """Loads predictions from file.""" + predictions = [] + with gfile.GFile(filename, "r") as input_file: + for line in input_file: + predictions.append(line.strip()) + return predictions + + +def load_data(train_data_path, test_data_path, + prediction_path): + """Loads train and test data, and possibly loads predictions.""" + train_examples = _load_examples(train_data_path) + test_examples = _load_examples(test_data_path) + if prediction_path: + predictions = _load_predictions(prediction_path) + num_predictions = len(predictions) + num_test_examples = len(test_examples) + if num_predictions != num_test_examples: + raise RuntimeError( + "#predictions ({}) must equal #test_examples ({})!".format( + num_predictions, num_test_examples)) + else: + predictions = None + return train_examples, test_examples, predictions + + +def write_to_tsv(examples, output_filename): + """Write examples to tsv file.""" + with gfile.GFile(output_filename, "w") as tsv_file: + for example in examples: + line = "%s\t%s\n" % (example.utterance, example.program) + tsv_file.write(line) + print("Wrote %s examples to %s." % (len(examples), output_filename)) diff --git a/pool/shard007/Python/0070479_422db3d645f_.py b/pool/shard007/Python/0070479_422db3d645f_.py new file mode 100644 index 0000000000000000000000000000000000000000..547cae2c8964d4a56cf7d986890ab3f07284b316 --- /dev/null +++ b/pool/shard007/Python/0070479_422db3d645f_.py @@ -0,0 +1,29 @@ +"""empty message + +Revision ID: 422db3d645f +Revises: None +Create Date: 2015-02-10 12:42:23.891489 + +""" + +# revision identifiers, used by Alembic. +revision = '422db3d645f' +down_revision = None + +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +def upgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.create_table('sor', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('sor', postgresql.JSON(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + + +def downgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.drop_table('sor') + ### end Alembic commands ### diff --git a/pool/shard007/Python/0070483_scripts.py b/pool/shard007/Python/0070483_scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..1a32ed2fb3ada45ba1975d2fd717eee6e8e9e054 --- /dev/null +++ b/pool/shard007/Python/0070483_scripts.py @@ -0,0 +1,44 @@ +# Copyright (c) The PyAMF Project. +# See LICENSE.txt for details. + +""" +Scripts for basic release building in the PyAMF project. +""" + +import logging + +from release import package +from release.package import BuildScript + + +class BuildTarballsScript(BuildScript): + """ + Script for building release tarballs (.zip/.tar.gz/.tar.bz2 files). + """ + + def __init__(self): + self.builder = package.TarballsBuilder + logging.info("Started tarballs builder...") + + +class BuildEggScript(BuildScript): + """ + Script for building Python eggs (.egg files). + """ + + def __init__(self): + self.builder = package.EggBuilder + logging.info("Started egg builder...") + + +class BuildDocumentationScript(BuildScript): + """ + Script for building the Sphinx documentation (.zip/.tar.gz/.tar.bz2/.pdf) files). + """ + + def __init__(self): + self.builder = package.DocumentationBuilder + logging.info("Started documentation builder...") + + +__all__ = ["BuildTarballsScript", "BuildEggScript", "BuildDocumentationScript"] diff --git a/pool/shard007/Python/0070484_pytest.py b/pool/shard007/Python/0070484_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..44916788ee6fb095ca1c5fd8c21e420fd825040f --- /dev/null +++ b/pool/shard007/Python/0070484_pytest.py @@ -0,0 +1,86 @@ +""" py.test plugin for checking files with pylama. """ +from __future__ import absolute_import + +from os import path as op + +import py +import pytest + + +HISTKEY = "pylama/mtimes" + + +def pytest_addoption(parser): + group = parser.getgroup("general") + group.addoption( + '--pylama', action='store_true', + help="perform some pylama code checks on .py files") + + +def pytest_sessionstart(session): + config = session.config + if config.option.pylama and getattr(config, 'cache', None): + config._pylamamtimes = config.cache.get(HISTKEY, {}) + + +def pytest_sessionfinish(session): + config = session.config + if hasattr(config, "_pylamamtimes"): + config.cache.set(HISTKEY, config._pylamamtimes) + + +def pytest_collect_file(path, parent): + config = parent.config + if config.option.pylama and path.ext == '.py': + return PylamaItem(path, parent) + + +class PylamaError(Exception): + """ indicates an error during pylama checks. """ + + +class PylamaItem(pytest.Item, pytest.File): + + def __init__(self, path, parent): + super(PylamaItem, self).__init__(path, parent) + self.add_marker("pep8") + self.cache = None + self._pylamamtimes = None + + def setup(self): + if not getattr(self.config, 'cache', None): + return False + + self.cache = True + self._pylamamtimes = self.fspath.mtime() + pylamamtimes = self.config._pylamamtimes + old = pylamamtimes.get(str(self.fspath), 0) + if old == self._pylamamtimes: + pytest.skip("file(s) previously passed Pylama checks") + + def runtest(self): + call = py.io.StdCapture.call + errors, out, err = call(check_file, self.fspath) + # errors = check_file(self.fspath) + if errors: + raise PylamaError(out, err) + # update mtime only if test passed + # otherwise failures would not be re-run next time + if self.cache: + self.config._pylamamtimes[str(self.fspath)] = self._pylamamtimes + + def repr_failure(self, excinfo): + if excinfo.errisinstance(PylamaError): + return excinfo.value.args[0] + return super(PylamaItem, self).repr_failure(excinfo) + + +def check_file(path): + from pylama.main import parse_options, process_paths + from pylama.config import CURDIR + + options = parse_options() + path = op.relpath(str(path), CURDIR) + return process_paths(options, candidates=[path], error=False) + +# pylama:ignore=D,E1002,W0212 diff --git a/pool/shard007/Python/0070485_conanfile.py b/pool/shard007/Python/0070485_conanfile.py new file mode 100644 index 0000000000000000000000000000000000000000..466fe47403ab9aef61e8c32b937f3c0057e810e0 --- /dev/null +++ b/pool/shard007/Python/0070485_conanfile.py @@ -0,0 +1,15 @@ +from conans import ConanFile, CMake +import os + +class TestNytl(ConanFile): + settings = "os", "compiler", "build_type", "arch" + generators = "cmake" + + def build(self): + cmake = CMake(self) + self.run('cmake "%s" %s' % (self.conanfile_directory, cmake.command_line)) + self.run("cmake --build . %s" % cmake.build_config) + + def test(self): + self.run(os.sep.join([".","bin", "testNytl"])) + diff --git a/pool/shard007/Python/0070492_env.py b/pool/shard007/Python/0070492_env.py new file mode 100644 index 0000000000000000000000000000000000000000..a82255b4f7326b33720c681fb4f5f9f2270423da --- /dev/null +++ b/pool/shard007/Python/0070492_env.py @@ -0,0 +1,86 @@ +from __future__ import with_statement +from alembic import context +from sqlalchemy import create_engine, pool +from logging.config import fileConfig + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +from rfk.database import Base +target_metadata = Base.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def fetch_database_url(): + import rfk + rfk.init(enable_geoip=False) + if rfk.CONFIG.has_option('database', 'url'): + return rfk.CONFIG.get('database', 'url') + else: + return "%s://%s:%s@%s/%s" % (rfk.CONFIG.get('database', 'engine'), + rfk.CONFIG.get('database', 'username'), + rfk.CONFIG.get('database', 'password'), + rfk.CONFIG.get('database', 'host'), + rfk.CONFIG.get('database', 'database')) + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = fetch_database_url() + context.configure(url=url, target_metadata=target_metadata) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + engine = create_engine( + fetch_database_url(), + poolclass=pool.NullPool) + + connection = engine.connect() + context.configure( + connection=connection, + target_metadata=target_metadata + ) + + try: + with context.begin_transaction(): + context.run_migrations() + finally: + connection.close() + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() + diff --git a/pool/shard007/Python/0070493_base.py b/pool/shard007/Python/0070493_base.py new file mode 100644 index 0000000000000000000000000000000000000000..981ae2b70873023ea134e45479903a8601ef0f54 --- /dev/null +++ b/pool/shard007/Python/0070493_base.py @@ -0,0 +1,69 @@ +# 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/. + +exit_unclean = object() +exit_clean = object() + + +class Step(object): + provides = [] + + def __init__(self, logger): + self.logger = logger + + def run(self, step_index, state): + """Base class for state-creating steps. + + When a Step is run() the current state is checked to see + if the state from this step has already been created. If it + has the restore() method is invoked. Otherwise the create() + method is invoked with the state object. This is expected to + add items with all the keys in __class__.provides to the state + object. + """ + + name = self.__class__.__name__ + + try: + stored_step = state.steps[step_index] + except IndexError: + stored_step = None + + if stored_step == name: + self.restore(state) + elif stored_step is None: + self.create(state) + assert set(self.provides).issubset(set(state.keys())) + state.steps = state.steps + [name] + else: + raise ValueError("Expected a %s step, got a %s step" % (name, stored_step)) + + def create(self, data): + raise NotImplementedError + + def restore(self, state): + self.logger.debug("Step %s using stored state" % (self.__class__.__name__,)) + for key in self.provides: + assert key in state + + +class StepRunner(object): + steps = [] + + def __init__(self, logger, state): + """Class that runs a specified series of Steps with a common State""" + self.state = state + self.logger = logger + if "steps" not in state: + state.steps = [] + + def run(self): + rv = None + for step_index, step in enumerate(self.steps): + self.logger.debug("Starting step %s" % step.__name__) + rv = step(self.logger).run(step_index, self.state) + if rv in (exit_clean, exit_unclean): + break + + return rv diff --git a/pool/shard007/Python/0070494_utils.py b/pool/shard007/Python/0070494_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bd57def929ff1bd5a6afc6c37905d348e16f26ba --- /dev/null +++ b/pool/shard007/Python/0070494_utils.py @@ -0,0 +1,195 @@ +import re + +from django.contrib.auth.models import User +from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned +from django.db import connection +from django.db.models import Count, Q + +from devel.models import UserProfile +from main.utils import cache_function +from main.models import Package +from packages.models import PackageRelation + +@cache_function(283) +def get_annotated_maintainers(): + profile_ids = UserProfile.allowed_repos.through.objects.values('userprofile_id') + maintainers = User.objects.filter( + is_active=True, userprofile__id__in=profile_ids).order_by( + 'first_name', 'last_name') + + # annotate the maintainers with # of maintained and flagged packages + pkg_count_sql = """ +SELECT pr.user_id, COUNT(*), COUNT(p.flag_date) + FROM packages_packagerelation pr + JOIN packages p + ON pr.pkgbase = p.pkgbase + WHERE pr.type = %s + GROUP BY pr.user_id +""" + cursor = connection.cursor() + cursor.execute(pkg_count_sql, [PackageRelation.MAINTAINER]) + results = cursor.fetchall() + + pkg_count = {} + flag_count = {} + for k, total, flagged in results: + pkg_count[k] = total + flag_count[k] = flagged + + update_count = Package.objects.values_list('packager').order_by( + 'packager').annotate(Count('packager')) + update_count = dict(update_count) + + for m in maintainers: + m.package_count = pkg_count.get(m.id, 0) + m.flagged_count = flag_count.get(m.id, 0) + m.updated_count = update_count.get(m.id, 0) + + # force non-QS context, otherwise pickling doesn't work + return list(maintainers) + + +def ignore_does_not_exist(func): + def new_func(*args, **kwargs): + try: + return func(*args, **kwargs) + except (ObjectDoesNotExist, MultipleObjectsReturned): + return None + return new_func + + +class UserFinder(object): + def __init__(self): + self.cache = {} + self.username_cache = {} + self.email_cache = {} + self.pgp_cache = {} + + @staticmethod + @ignore_does_not_exist + def user_email(name, email): + if email: + return User.objects.get(email=email) + return None + + @staticmethod + @ignore_does_not_exist + def username_email(name, email): + if email and '@' in email: + # split email addr at '@' symbol, ensure domain matches + # or is a subdomain of archlinux.org + # TODO: configurable domain/regex somewhere? + username, domain = email.split('@', 1) + if re.match(r'^(.+\.)?archlinux.org$', domain): + return User.objects.get(username=username) + return None + + @staticmethod + @ignore_does_not_exist + def profile_email(name, email): + if email: + return User.objects.get(userprofile__public_email=email) + return None + + @staticmethod + @ignore_does_not_exist + def user_name(name, email): + # yes, a bit odd but this is the easiest way since we can't always be + # sure how to split the name. Ensure every 'token' appears in at least + # one of the two name fields. + if not name: + return None + name_q = Q() + for token in name.split(): + # ignore quoted parts; e.g. nicknames in strings + if re.match(r'^[\'"].*[\'"]$', token): + continue + name_q &= (Q(first_name__icontains=token) | + Q(last_name__icontains=token)) + return User.objects.get(name_q) + + def find(self, userstring): + ''' + Attempt to find the corresponding User object for a standard + packager string, e.g. something like + 'A. U. Thor '. + We start by searching for a matching email address; we then move onto + matching by first/last name. If we cannot find a user, then return None. + ''' + if not userstring: + return None + if userstring in self.cache: + return self.cache[userstring] + + name = email = None + + matches = re.match(r'^([^<]+)? ?<([^>]*)>?', userstring) + if not matches: + name = userstring.strip() + else: + name = matches.group(1) + email = matches.group(2) + + user = None + find_methods = (self.user_email, self.profile_email, + self.username_email, self.user_name) + for matcher in find_methods: + user = matcher(name, email) + if user is not None: + break + + self.cache[userstring] = user + self.email_cache[email] = user + return user + + def find_by_username(self, username): + if not username: + return None + if username in self.username_cache: + return self.username_cache[username] + + try: + user = User.objects.get(username=username) + except User.DoesNotExist: + user = None + + self.username_cache[username] = user + return user + + def find_by_email(self, email): + if not email: + return None + if email in self.email_cache: + return self.email_cache[email] + + user = self.user_email(None, email) + if user is None: + user = self.profile_email(None, email) + if user is None: + user = self.username_email(None, email) + + self.email_cache[email] = user + return user + + def find_by_pgp_key(self, pgp_key): + if not pgp_key: + return None + if pgp_key in self.pgp_cache: + return self.pgp_cache[pgp_key] + + try: + user = User.objects.get( + userprofile__pgp_key__endswith=pgp_key) + except User.DoesNotExist: + user = None + + self.pgp_cache[pgp_key] = user + return user + + def clear_cache(self): + self.cache = {} + self.username_cache = {} + self.email_cache = {} + self.pgp_cache = {} + +# vim: set ts=4 sw=4 et: diff --git a/pool/shard007/Python/0070495_app.py b/pool/shard007/Python/0070495_app.py new file mode 100644 index 0000000000000000000000000000000000000000..816465f9c76573fb112cf35b13057415dd115077 --- /dev/null +++ b/pool/shard007/Python/0070495_app.py @@ -0,0 +1,57 @@ +import datetime +import flask +from flask import Flask, jsonify, request +from flask_cors import CORS, cross_origin +import json +import os +import sys + +app = Flask(__name__) +CORS(app) + +now = datetime.datetime.now() + +#server initialisation +raulStatus = { + 'open': False, + 'date-time': now.isoformat(), + 'user': u'Raul Seixas' +} + + +@app.route('/status/', methods=['GET']) +def get_items(): + return jsonify(raulStatus) + + +@app.route('/status/checkin',methods=['POST']) +def check_in(): + raulStatus['open'] = True + now = datetime.datetime.now() + raulStatus['date-time']=now.isoformat() + reqData = request.get_json(silent=True) + if (reqData != None): + raulStatus['user']=reqData['user'] + else: + raulStatus['user']="Raul Seixas" + return jsonify(raulStatus) + +@app.route('/status/checkout',methods=['POST']) +def check_out(): + raulStatus['open'] = False + now = datetime.datetime.now() + raulStatus['date-time']=now.isoformat() + reqData = request.get_json(silent=True) + if (reqData != None): + raulStatus['user']=reqData['user'] + else: + raulStatus['user']="Raul Seixas" + return jsonify(raulStatus) + + +@app.route("/") +def index(): + return "Hello, there's nothing for you here!" + +if __name__ == "__main__": + app.run(debug=True,host='0.0.0.0') diff --git a/pool/shard007/Python/0070496_status.py b/pool/shard007/Python/0070496_status.py new file mode 100644 index 0000000000000000000000000000000000000000..ef7660fa376215e3d14e278e6533302817dc6800 --- /dev/null +++ b/pool/shard007/Python/0070496_status.py @@ -0,0 +1,53 @@ +# Copyright (c) 2018 NEC, Corp. +# +# 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. + +import sys + +from oslo_config import cfg +from oslo_upgradecheck import upgradecheck + +from ceilometer.i18n import _ + +CONF = cfg.CONF + + +class Checks(upgradecheck.UpgradeCommands): + + """Contains upgrade checks + + Various upgrade checks should be added as separate methods in this class + and added to _upgrade_checks tuple. + """ + + def _sample_check(self): + """This is sample check added to test the upgrade check framework + + It needs to be removed after adding any real upgrade check + """ + return upgradecheck.Result(upgradecheck.Code.SUCCESS, 'Sample detail') + + _upgrade_checks = ( + # Sample check added for now. + # Whereas in future real checks must be added here in tuple + (_('Sample Check'), _sample_check), + ) + + +def main(): + return upgradecheck.main( + CONF, project='ceilometer', upgrade_command=Checks()) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/pool/shard007/Python/0070498_urls.py b/pool/shard007/Python/0070498_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..52838adb4aa0aa2abaecf6617860792f45464c5d --- /dev/null +++ b/pool/shard007/Python/0070498_urls.py @@ -0,0 +1,25 @@ +"""PlayPlan URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/1.8/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') +Including another URLconf + 1. Add an import: from blog import urls as blog_urls + 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) +""" +from django.conf.urls import include, url +from django.contrib import admin +from django.views.generic import TemplateView +import User + +urlpatterns = [ + url(r'^admin/', include(admin.site.urls)), + url(r'^$', TemplateView.as_view(template_name='index.html'), name='index'), + url(r'^', include('User.urls')), +] diff --git a/pool/shard007/Python/0070506_database.py b/pool/shard007/Python/0070506_database.py new file mode 100644 index 0000000000000000000000000000000000000000..ab712e6479b8d8f31038f944be83c327fd3edcd8 --- /dev/null +++ b/pool/shard007/Python/0070506_database.py @@ -0,0 +1,57 @@ +# coding= +import sqlite3, json, random, hashlib + +class Database: + + db_path = "songBook.db" + + conn = None + cursor = None + + def __init__(self): + self.conn = sqlite3.connect(self.db_path) + self.cursor = self.conn.cursor() + + def hello(self): + return "Hello!" + + def add_song(self, title, content, userid): + params = [title, content, userid] + self.cursor.execute("INSERT INTO song (title, content, userid) VALUES (?, ?, ?)", params) + self.conn.commit() + print ("added song with title %s" %title) + + def get_song(self, songId): + self.cursor.execute("SELECT * FROM song WHERE id=?", [songId]) + result = self.cursor.fetchone() + if result: + return json.dumps(result) + else: + return False; + + def add_user(self, username, email, password): + + def generate_salt(length = 8): + salt = '' + for i in range(length): + salt += random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/') + return salt + + salt = generate_salt() + + passwordAndSalt = password + salt + + hash_object = hashlib.sha256(passwordAndSalt.encode("utf-8")) + passwordHash = hash_object.hexdigest() + + + params = [username, email, passwordHash, salt] + self.cursor.execute("INSERT INTO user (username, email, passwordHash, passwordSalt) VALUES (?, ?, ?, ?)", params) + self.conn.commit() + return "user added"; + + def get_users(self): + self.cursor.execute("SELECT * FROM user") + return json.dumps(self.cursor.fetchall()) + + diff --git a/pool/shard007/Python/0070513_pablo_network.py b/pool/shard007/Python/0070513_pablo_network.py new file mode 100644 index 0000000000000000000000000000000000000000..0e4deb5dc34d16e897d376dbef24fbeef93edebb --- /dev/null +++ b/pool/shard007/Python/0070513_pablo_network.py @@ -0,0 +1,101 @@ +#!/usr/bin/python + +from nettalk_data import * +import re +import os +import sys +import numpy +import pickle +import pprint +#import pdb +from pybrain.tools.shortcuts import buildNetwork +from pybrain.supervised.trainers import BackpropTrainer +from pybrain.structure.modules import LinearLayer, SigmoidLayer, BiasUnit +from pybrain.structure.networks.feedforward import FeedForwardNetwork +from pybrain.structure import FullConnection +from pybrain.datasets import SupervisedDataSet +from sigmoidsparselayer import SigmoidSparseLayer + +lrate = float(sys.argv[1]); +wdecay = float(sys.argv[2]); +print (lrate, wdecay); + + +def buildNet(): + + inLayer = LinearLayer(NUMINPUTS, name='in') + hiddenLayer = SigmoidSparseLayer(dim=80, beta=0.001, sparsity=0.1, name='hidden') + #hiddenLayer = SigmoidLayer(dim=80, name='hidden') + outLayer = SigmoidLayer(NUMOUTPUTS, name='out') + biasUnit = BiasUnit(name='bias') + + in_to_hidden = FullConnection(inLayer, hiddenLayer) + hidden_to_out = FullConnection(hiddenLayer, outLayer) + bias_to_hidden = FullConnection(biasUnit, hiddenLayer) + bias_to_out = FullConnection(biasUnit, outLayer) + + tosave = [ inLayer, hiddenLayer, outLayer, biasUnit, in_to_hidden, hidden_to_out, bias_to_hidden, bias_to_out ]; + + return tosave + + +if (len(sys.argv) <= 3): + saved = buildNet() +else: + saved = pickle.load(open(sys.argv[3], "rb")); + +pickle.dump( saved, open( "pablosemptynet.p", "wb" ) ) + + +net = FeedForwardNetwork(name='mynet'); + +net.addInputModule(saved[0]) +net.addModule(saved[1]) +net.addOutputModule(saved[2]) +net.addModule(saved[3]) +net.addConnection(saved[4]) +net.addConnection(saved[5]) +net.addConnection(saved[6]) +net.addConnection(saved[7]) + +net.sortModules() + +trainer = BackpropTrainer(net, None, learningrate=lrate, verbose=False, batchlearning=True, weightdecay=wdecay) +stressErrors=list(); +phonemeErrors=list(); + + +for cycle in range(100): + datafile = 'top1000.data'; + for entry in dictionary(datafile): + #print("working on", entry); + outmatrix = outputUnits(entry); + lpos = 0; + ds = SupervisedDataSet(NUMINPUTS, NUMOUTPUTS); + for letterContexts in wordstream(input_entries = (entry,)): + #print("letterContexts", letterContexts); + for inarray in convertToBinary(letterContexts): + outarray = outmatrix[lpos]; + #print("inarray",inarray); + #print("outarray",outarray); + #print("inlen %d outlen %d" % (len(inarray), len(outarray))); + ds.addSample(inarray, outarray); + observed = net.activate(inarray); + phoneme = entry.phonemes[lpos]; + observedPhoneme = closestByDotProduct(observed[:MINSTRESS], articFeatures); + phonemeErrors.append(bool(phoneme != observedPhoneme)); + stress = entry.stress[lpos]; + observedStress = closestByDotProduct(observed[MINSTRESS:], stressFeatures); + stressErrors.append(bool(stress != observedStress)); + lpos += 1 + trainer.setData(ds); + #pdb.set_trace(); + err = trainer.train(); + #print(err, " ", entry); + print("accuracy: phonemes %.3f stresses %.3f" % (1 - np.mean(phonemeErrors), 1 - np.mean(stressErrors)) ); + + +#accuracy is a vector with one element in {0,1} for each letter i +#that we have #trained so far. +#make that two vectors, one for phoneme and one for stress. + diff --git a/pool/shard007/Python/0070514_changemouse.py b/pool/shard007/Python/0070514_changemouse.py new file mode 100644 index 0000000000000000000000000000000000000000..74318149555b357fae2a36cb64987a7d8f4bbb65 --- /dev/null +++ b/pool/shard007/Python/0070514_changemouse.py @@ -0,0 +1,25 @@ +import pygame + +pygame.init() +resolution = (width, height) = (600, 400) +screen = pygame.display.set_mode(resolution) +clock = pygame.time.Clock() +pygame.mouse.set_visible(False) + +miraimg = pygame.image.load("mira.png") +mirarect = miraimg.get_rect() + +while True: + clock.tick(60) + screen.fill(0) + for event in pygame.event.get(): + if event.type == pygame.QUIT: + pygame.quit() + exit(0) + mousepos = pygame.mouse.get_pos() + mirarect.centerx = mousepos[0] + mirarect.centery = mousepos[1] + screen.blit(miraimg, mirarect) + pygame.display.flip() + + diff --git a/pool/shard007/Python/0070518_test_direct_confirmation.py b/pool/shard007/Python/0070518_test_direct_confirmation.py new file mode 100644 index 0000000000000000000000000000000000000000..cb35f0acc4de971db46c2c369cf8174b63385226 --- /dev/null +++ b/pool/shard007/Python/0070518_test_direct_confirmation.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Copyright (C) 2011 Radim Rehurek +# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html + +""" +Automated tests for direct confirmation measures in the direct_confirmation_measure module. +""" + +import logging +import unittest + +from gensim.topic_coherence import direct_confirmation_measure + +class TestDirectConfirmationMeasure(unittest.TestCase): + def setUp(self): + # Set up toy example for better understanding and testing + # of this module. See the modules for the mathematical formulas + self.segmentation = [[(1, 2)]] + self.posting_list = {1: set([2, 3, 4]), 2: set([3, 5])} + self.num_docs = 5 + + def testLogConditionalProbability(self): + """Test log_conditional_probability()""" + obtained = direct_confirmation_measure.log_conditional_probability(self.segmentation, self.posting_list, self.num_docs)[0] + # Answer should be ~ ln(1 / 2) = -0.693147181 + expected = -0.693147181 + self.assertAlmostEqual(obtained, expected) + + def testLogRatioMeasure(self): + """Test log_ratio_measure()""" + obtained = direct_confirmation_measure.log_ratio_measure(self.segmentation, self.posting_list, self.num_docs)[0] + # Answer should be ~ ln{(1 / 5) / [(3 / 5) * (2 / 5)]} = -0.182321557 + expected = -0.182321557 + self.assertAlmostEqual(obtained, expected) + + def testNormalizedLogRatioMeasure(self): + """Test normalized_log_ratio_measure()""" + obtained = direct_confirmation_measure.log_ratio_measure(self.segmentation, self.posting_list, self.num_docs, normalize=True)[0] + # Answer should be ~ -0.182321557 / -ln(1 / 5) = -0.113282753 + expected = -0.113282753 + self.assertAlmostEqual(obtained, expected) + +if __name__ == '__main__': + logging.root.setLevel(logging.WARNING) + unittest.main() diff --git a/pool/shard007/Python/0070520_bpemb_test.py b/pool/shard007/Python/0070520_bpemb_test.py new file mode 100644 index 0000000000000000000000000000000000000000..59c08259e6cf7704a4a9584aec3e212cd4af8248 --- /dev/null +++ b/pool/shard007/Python/0070520_bpemb_test.py @@ -0,0 +1,144 @@ +import unittest +from ..bpemb import BPEmb + + +class BPEmbTest(unittest.TestCase): + + def test_sentencepiece_import(self): + try: + from sentencepiece import SentencePieceProcessor # NOQA + except ImportError: + self.fail( + "Could not import SentencePieceProcessor from sentencepiece.") + + def test_gensim_import(self): + try: + from gensim.models import KeyedVectors # NOQA + except ImportError: + self.fail("Could not import KeyedVectors from gensim.models") + + def test_emb_model_download(self): + bpemb = BPEmb(lang="en", vs=1000, dim=25) + self.assertTrue(bpemb.emb_file.exists()) + self.assertTrue(bpemb.model_file.exists()) + + def test_emb_dim_25(self): + bpemb = BPEmb(lang="en", vs=1000, dim=25) + self.assertEqual(25, bpemb.emb.vectors.shape[1]) + + def test_emb_dim_50(self): + bpemb = BPEmb(lang="fr", vs=1000, dim=50) + self.assertEqual(50, bpemb.emb.vectors.shape[1]) + + def test_emb_dim_100(self): + bpemb = BPEmb(lang="de", vs=1000, dim=100) + self.assertEqual(100, bpemb.emb.vectors.shape[1]) + + def test_emb_vs_1000(self): + bpemb = BPEmb(lang="en", vs=1000, dim=25) + self.assertEqual(1000, bpemb.emb.vectors.shape[0]) + + def test_emb_vs_5000(self): + bpemb = BPEmb(lang="fr", vs=5000, dim=25) + self.assertEqual(5000, bpemb.emb.vectors.shape[0]) + + def test_emb_vs_10000(self): + bpemb = BPEmb(lang="de", vs=10000, dim=25) + self.assertEqual(10000, bpemb.emb.vectors.shape[0]) + + def test_encode_decode_roundtrip(self): + bpemb = BPEmb(lang="en", vs=1000, dim=25) + text = "this is a test" + self.assertEqual(text, bpemb.decode(bpemb.encode(text))) + + def test_encode_ids_decode_ids_roundtrip(self): + bpemb = BPEmb(lang="en", vs=1000, dim=25) + text = "this is a test" + self.assertEqual(text, bpemb.decode_ids(bpemb.encode_ids(text))) + + def test_encode_decode_many_roundtrip(self): + bpemb = BPEmb(lang="en", vs=1000, dim=25) + texts = ["this is a test", "another test", "and one more"] + self.assertEqual(texts, bpemb.decode(bpemb.encode(texts))) + + def test_encode_ids_decode_ids_many_roundtrip(self): + bpemb = BPEmb(lang="en", vs=1000, dim=25) + texts = ["this is a test", "another test", "and one more"] + self.assertEqual(texts, bpemb.decode_ids(bpemb.encode_ids(texts))) + + def test_pickle(self): + import pickle + from tempfile import mkdtemp + from pathlib import Path + bpemb = BPEmb(lang="en", vs=1000, dim=25) + pklfile = Path(mkdtemp()) / "bpemb.pkl" + with pklfile.open("wb") as out: + pickle.dump(bpemb, out) + with pklfile.open("rb") as pkl: + bpemb_unpickled = pickle.load(pkl) + text = "this is a test" + self.assertEqual( + text, bpemb.decode_ids(bpemb_unpickled.encode_ids(text))) + self.assertEqual( + text, bpemb_unpickled.decode_ids(bpemb.encode_ids(text))) + + def test_pickle_custom_cache_dir(self): + import pickle + from tempfile import mkdtemp + from pathlib import Path + bpemb = BPEmb(lang="en", vs=1000, dim=25, cache_dir=mkdtemp()) + pklfile = Path(mkdtemp()) / "bpemb.pkl" + with pklfile.open("wb") as out: + pickle.dump(bpemb, out) + with pklfile.open("rb") as pkl: + bpemb_unpickled = pickle.load(pkl) + text = "this is a test" + self.assertEqual( + text, bpemb.decode_ids(bpemb_unpickled.encode_ids(text))) + self.assertEqual( + text, bpemb_unpickled.decode_ids(bpemb.encode_ids(text))) + + def test_pickle_custom_no_cache(self): + import pickle + from tempfile import mkdtemp + from pathlib import Path + import shutil + cache_dir = mkdtemp() + bpemb = BPEmb(lang="en", vs=1000, dim=25, cache_dir=cache_dir) + shutil.rmtree(cache_dir) + pklfile = Path(mkdtemp()) / "bpemb.pkl" + with pklfile.open("wb") as out: + pickle.dump(bpemb, out) + with pklfile.open("rb") as pkl: + bpemb_unpickled = pickle.load(pkl) + text = "this is a test" + self.assertEqual( + text, bpemb.decode_ids(bpemb_unpickled.encode_ids(text))) + self.assertEqual( + text, bpemb_unpickled.decode_ids(bpemb.encode_ids(text))) + + def test_pad_lookup(self): + dim = 25 + bpemb = BPEmb(lang="en", vs=1000, dim=dim, add_pad_emb=True) + self.assertEqual(set(bpemb[""].tolist()), {0}) + + def test_pad_index(self): + dim = 25 + bpemb = BPEmb(lang="en", vs=1000, dim=dim, add_pad_emb=True) + self.assertEqual(set(bpemb.vectors[-1]), {0}) + + def test_segmentation_only(self): + bpemb = BPEmb(lang="en", vs=1000, dim=25, segmentation_only=True) + self.assertFalse(hasattr(bpemb, 'emb')) + + def test_assert_lang_or_custom_emb(self): + with self.assertRaises(AssertionError): + BPEmb() + with self.assertRaises(AssertionError): + BPEmb(model_file='something') + with self.assertRaises(AssertionError): + BPEmb(emb_file='something') + + +if __name__ == "__main__": + unittest.main() diff --git a/pool/shard007/Python/0070521_exampleModel.py b/pool/shard007/Python/0070521_exampleModel.py new file mode 100644 index 0000000000000000000000000000000000000000..8d6f48f9003b18b6496b7acfd956a9b47f4a5ff0 --- /dev/null +++ b/pool/shard007/Python/0070521_exampleModel.py @@ -0,0 +1,82 @@ +#!/bin/python +# -*- coding: utf-8 -*- + +import numpy as np + +class exampleModel(): + + def __init__(self): + # 紀錄序列 + self.price_series = [] + + # 紀錄狀態 + self.haveStock = 0.0 + self.buyPrice = 0.0 + + # Simple Moving Average + self.price_ma = [0.0 for x in xrange(121)] # the price ma(x) series + + # 參數們 + self.infos = { + "Model Description": "exampleModel", + "Update Time": '2015/03/26', + "Model Version": "2.0.0" + } + + def updateTrade(self, trade): + if trade and trade["Volume"] != 0:# 有交易 + if trade["Type"][-3:] == 'Buy': + self.haveStock += trade["Volume"] + self.buyPrice = float(trade["Price"]) + elif trade["Type"][-4:] == "Sell": + self.haveStock -= trade["Volume"] + + + def updateData(self, row): + self.price_series.append(float(row[6])) + # Simple Moving Average + for i in [20, 60]: + self.price_ma[i] = np.mean(self.price_series[-min(i, len(self.price_series)):]) + + def predict(self, when, price): + ''' + 讓 model 預測下一步應該要怎麼做,模擬下單的過程,會要回傳一個 dictionary,包含: + Type: Buy, Sell or Nothing + Price: 要下單的價格,0 代表用開盤價買 + Volume: 要下單的量,0 代表能買多少盡量買 + ''' + if when == 'start': + ''' + when = start 是開盤時,可以決定要不要下單,可以用當下的開盤價買賣, + 或下單在整天中如果有價格符合下單的條件,就會交易 + ''' + if len(self.price_series) == 0: + return {"Type": "Nothing", "Price": 0, "Volume": 0} + elif self.haveStock == 0 and(# 沒有持有的情況 + + # 高於月線 ma20 + self.price_series[-1] > self.price_ma[20] + # 低於季線 ma60 + and self.price_series[-1] < self.price_ma[60] + + ): + return {"Type": "Finance Buy", "Price": 0, "Volume": 0} + + elif self.haveStock > 0 and (# 有持有的情框 + + # 低於月線 ma20 + self.price_series[-1] < self.price_ma[20] + # 停損 + or self.price_series[-1] < self.buyPrice * 0.9 + + ): + return {"Type": "Finance Sell", "Price": 0, "Volume": 0} + else: + return {"Type": "Nothing", "Price": 0, "Volume": 0} + elif when == 'end': + ''' + when = end 是收盤時,可以決定要不要下單,只能用當下的開盤價買賣 + ''' + return {"Type": "Nothing", "Price": 0, "Volume": 0} + else: + return {"Type": "Nothing", "Price": 0, "Volume": 0} \ No newline at end of file diff --git a/pool/shard007/Python/0070525_test_wsgi.py b/pool/shard007/Python/0070525_test_wsgi.py new file mode 100644 index 0000000000000000000000000000000000000000..ea65fedd3a884b39b217d0219d987ac47182849d --- /dev/null +++ b/pool/shard007/Python/0070525_test_wsgi.py @@ -0,0 +1,171 @@ +# Copyright (c) 2015 Hewlett-Packard Development Company, L.P. (HP) +# +# 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. + +import os +import re +import subprocess +import sys +import tempfile +import time +try: + # python 2 + from urllib2 import urlopen +except ImportError: + # python 3 + from urllib.request import urlopen + +import fixtures + +from pbr.tests import base + + +class TestWsgiScripts(base.BaseTestCase): + + cmd_names = ('pbr_test_wsgi', 'pbr_test_wsgi_with_class') + + def test_wsgi_script_install(self): + """Test that we install a non-pkg-resources wsgi script.""" + if os.name == 'nt': + self.skipTest('Windows support is passthrough') + + stdout, _, return_code = self.run_setup( + 'install', '--prefix=%s' % self.temp_dir) + + self.useFixture( + fixtures.EnvironmentVariable( + 'PYTHONPATH', ".:%s/lib/python%s.%s/site-packages" % ( + self.temp_dir, + sys.version_info[0], + sys.version_info[1]))) + + self._check_wsgi_install_content(stdout) + + def test_wsgi_script_run(self): + """Test that we install a runnable wsgi script. + + This test actually attempts to start and interact with the + wsgi script in question to demonstrate that it's a working + wsgi script using simple server. It's a bit hokey because of + process management that has to be done. + + """ + self.skipTest("Test skipped until we can determine a reliable " + "way to capture subprocess stdout without blocking") + + if os.name == 'nt': + self.skipTest('Windows support is passthrough') + + stdout, _, return_code = self.run_setup( + 'install', '--prefix=%s' % self.temp_dir) + + self.useFixture( + fixtures.EnvironmentVariable( + 'PYTHONPATH', ".:%s/lib/python%s.%s/site-packages" % ( + self.temp_dir, + sys.version_info[0], + sys.version_info[1]))) + # NOTE(sdague): making python unbuffered is critical to + # getting output out of the subprocess. + self.useFixture( + fixtures.EnvironmentVariable( + 'PYTHONUNBUFFERED', '1')) + + self._check_wsgi_install_content(stdout) + + # Live test run the scripts and see that they respond to wsgi + # requests. + self._test_wsgi() + + def _test_wsgi(self): + for cmd_name in self.cmd_names: + cmd = os.path.join(self.temp_dir, 'bin', cmd_name) + stdout = tempfile.NamedTemporaryFile() + print("Running %s > %s" % (cmd, stdout.name)) + # NOTE(sdague): ok, this looks a little janky, and it + # is. However getting python to not hang with + # popen.communicate is beyond me. + # + # We're opening with a random port (so no conflicts), and + # redirecting all stdout and stderr to files. We can then + # safely read these files and not deadlock later in the + # test. This requires shell expansion. + p = subprocess.Popen( + "%s -p 0 > %s 2>&1" % (cmd, stdout.name), + shell=True, + close_fds=True, + cwd=self.temp_dir) + + self.addCleanup(p.kill) + + # the sleep is important to force a context switch to the + # subprocess + time.sleep(0.1) + + stdoutdata = stdout.read() + self.assertIn( + "STARTING test server pbr_testpackage.wsgi", + stdoutdata) + self.assertIn( + "DANGER! For testing only, do not use in production", + stdoutdata) + + m = re.search('(http://[^:]+:\d+)/', stdoutdata) + self.assertIsNotNone(m, "Regex failed to match on %s" % stdoutdata) + + f = urlopen(m.group(1)) + self.assertEqual("Hello World", f.read()) + + # the sleep is important to force a context switch to the + # subprocess + time.sleep(0.1) + + # Kill off the child, it should force a flush of the stdout. + p.kill() + time.sleep(0.1) + + stdoutdata = stdout.read() + # we should have logged an HTTP request, return code 200, that + # returned 11 bytes + self.assertIn('"GET / HTTP/1.1" 200 11', stdoutdata) + + def _check_wsgi_install_content(self, install_stdout): + for cmd_name in self.cmd_names: + install_txt = 'Installing %s script to %s' % (cmd_name, + self.temp_dir) + self.assertIn(install_txt, install_stdout) + + cmd_filename = os.path.join(self.temp_dir, 'bin', cmd_name) + + script_txt = open(cmd_filename, 'r').read() + self.assertNotIn('pkg_resources', script_txt) + + main_block = """if __name__ == "__main__": + import argparse + import socket + import wsgiref.simple_server as wss""" + + if cmd_name == 'pbr_test_wsgi': + app_name = "main" + else: + app_name = "WSGI.app" + + starting_block = ("STARTING test server pbr_testpackage.wsgi." + "%s" % app_name) + + else_block = """else: + application = None""" + + self.assertIn(main_block, script_txt) + self.assertIn(starting_block, script_txt) + self.assertIn(else_block, script_txt) diff --git a/pool/shard007/Python/0070529_coroutinetest.py b/pool/shard007/Python/0070529_coroutinetest.py new file mode 100644 index 0000000000000000000000000000000000000000..f93e330696e24cb241608d7580c60b65520eaf75 --- /dev/null +++ b/pool/shard007/Python/0070529_coroutinetest.py @@ -0,0 +1,143 @@ +import inspect +import functools +from queue import Queue + +def coroutine(simple=None): + if isinstance(simple, type(True)): + simple_ = simple + elif simple is None: + simple_ = False + else: + simple_ = False + + + def _coroutine(func): + if inspect.isgeneratorfunction(func) and not simple_: + @functools.wraps(func) + def generator(*args, **kwargs): + x = func(*args, **kwargs) + next(x) + return x + return generator + else: + @functools.wraps(func) + def generator(target=None): + def inner(target): + try: + while True: + line = yield + x = func(line) + if x is not None: + if inspect.isgenerator(x): + for y in x: + if target is not None: + target.send(y) + else: + if target is not None: + target.send(x) + except GeneratorExit: + if target is not None: + target.close() + ret = inner(target) + next(ret) + return ret + return generator + + if inspect.isfunction(simple): + return _coroutine(simple) + else: + return _coroutine + + +@coroutine +def example(target): #advanced gen + + # setup + + + try: + while 1: + x = yield + + def body(): + + # body + + yield x[::-1] + y = body() + if y is not None: + if inspect.isgenerator(y): + for z in y: + target.send(z) + else: + target.send(y) + except GeneratorExit: + + # teardown + + + target.close() + +@coroutine +def everyother(target): #advanced gen + i = 0 + try: + while 1: + x = yield + def body(): + if i % 2 == 0: + return x, i + 1 + return None, i + 1 + y, i = body() + if y is not None: + if inspect.isgenerator(y): + for z in y: + target.send(z) + else: + target.send(y) + except GeneratorExit: + target.close() + + + +@coroutine # simple is assumed if it is not a generator +def caps(line): + return line.upper() + +@coroutine(simple=True) # simple set manually +def repeattwice(line): + yield line + yield line + +@coroutine # print the end result +def printer(line): + print("result: ",line) + +@coroutine # print the end result +def resulter(results): + try: + while 1: + x = yield + results.put(x) + except GeneratorExit: + results.put(None) + +def inp(x, pipe): # input the first data + pipe.send(x) + pipe.close() + +output = Queue() + +pipe = example(repeattwice(everyother(resulter(output)))) # pipe it all together + +import _thread + +_thread.start_new(inp, ("asd", pipe)) +#inp("asd", pipe) # do the stuff + +result = output.get() +while result is not None: + print(result) + result = output.get() + + diff --git a/pool/shard007/Python/0070532_mcr.py b/pool/shard007/Python/0070532_mcr.py new file mode 100644 index 0000000000000000000000000000000000000000..824181c4144aa2b25f0b51e8c962e32659198d9f --- /dev/null +++ b/pool/shard007/Python/0070532_mcr.py @@ -0,0 +1,149 @@ +## +# Copyright 2009-2017 Ghent University +# +# This file is part of EasyBuild, +# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), +# with support of Ghent University (http://ugent.be/hpc), +# the Flemish Supercomputer Centre (VSC) (https://www.vscentrum.be), +# Flemish Research Foundation (FWO) (http://www.fwo.be/en) +# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en). +# +# http://github.com/hpcugent/easybuild +# +# EasyBuild 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 v2. +# +# EasyBuild 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 EasyBuild. If not, see . +## +""" +EasyBuild support for installing MCR, implemented as an easyblock + +@author: Stijn De Weirdt (Ghent University) +@author: Dries Verdegem (Ghent University) +@author: Kenneth Hoste (Ghent University) +@author: Pieter De Baets (Ghent University) +@author: Jens Timmerman (Ghent University) +@author: Fotis Georgatos (Uni.Lu, NTUA) +@author: Balazs Hajgato (Vrije Universiteit Brussel) +""" +import re +import os +import shutil +import stat +from distutils.version import LooseVersion + +from easybuild.easyblocks.generic.packedbinary import PackedBinary +from easybuild.framework.easyconfig import CUSTOM +from easybuild.tools.build_log import EasyBuildError +from easybuild.tools.filetools import adjust_permissions, read_file, write_file +from easybuild.tools.run import run_cmd + + +class EB_MCR(PackedBinary): + """Support for installing MCR.""" + + def __init__(self, *args, **kwargs): + """Add extra config options specific to MCR.""" + super(EB_MCR, self).__init__(*args, **kwargs) + self.comp_fam = None + self.configfilename = "my_installer_input.txt" + self.subdir = '' + + @staticmethod + def extra_options(): + """Custom easyconfig parameters for MCR.""" + extra_vars = { + 'java_options': ['-Xmx256m', "$_JAVA_OPTIONS value set for install and in module file.", CUSTOM], + } + return PackedBinary.extra_options(extra_vars) + + def configure_step(self): + """Configure MCR installation: create license file.""" + + configfile = os.path.join(self.builddir, self.configfilename) + if LooseVersion(self.version) < LooseVersion('R2015a'): + shutil.copyfile(os.path.join(self.cfg['start_dir'], 'installer_input.txt'), configfile) + config = read_file(configfile) + # compile regex first since re.sub doesn't accept re.M flag for multiline regex in Python 2.6 + regdest = re.compile(r"^# destinationFolder=.*", re.M) + regagree = re.compile(r"^# agreeToLicense=.*", re.M) + regmode = re.compile(r"^# mode=.*", re.M) + + config = regdest.sub("destinationFolder=%s" % self.installdir, config) + config = regagree.sub("agreeToLicense=Yes", config) + config = regmode.sub("mode=silent", config) + else: + config = '\n'.join([ + "destinationFolder=%s" % self.installdir, + "agreeToLicense=Yes", + "mode=silent", + ]) + + write_file(configfile, config) + + self.log.debug("configuration file written to %s:\n %s", configfile, config) + + def install_step(self): + """MCR install procedure using 'install' command.""" + + src = os.path.join(self.cfg['start_dir'], 'install') + + # make sure install script is executable + adjust_permissions(src, stat.S_IXUSR) + + # make sure $DISPLAY is not defined, which may lead to (hard to trace) problems + # this is a workaround for not being able to specify --nodisplay to the install scripts + if 'DISPLAY' in os.environ: + os.environ.pop('DISPLAY') + + if not '_JAVA_OPTIONS' in self.cfg['preinstallopts']: + java_options = 'export _JAVA_OPTIONS="%s" && ' % self.cfg['java_options'] + self.cfg['preinstallopts'] = java_options + self.cfg['preinstallopts'] + + configfile = "%s/%s" % (self.builddir, self.configfilename) + cmd = "%s ./install -v -inputFile %s %s" % (self.cfg['preinstallopts'], configfile, self.cfg['installopts']) + run_cmd(cmd, log_all=True, simple=True) + + # determine subdirectory (e.g. v84 (2014a, 2014b), v85 (2015a), ...) + subdirs = os.listdir(self.installdir) + if len(subdirs) == 1: + self.subdir = subdirs[0] + else: + raise EasyBuildError("Found multiple subdirectories, don't know which one to pick: %s", subdirs) + + def sanity_check_step(self): + """Custom sanity check for MCR.""" + custom_paths = { + 'files': [], + 'dirs': [os.path.join(self.subdir, 'bin', 'glnxa64')], + } + if LooseVersion(self.version) >= LooseVersion('R2016b'): + custom_paths['dirs'].append(os.path.join(self.subdir, 'cefclient', 'sys', 'os', 'glnxa64')) + else: + custom_paths['dirs'].extend([ + os.path.join(self.subdir, 'runtime', 'glnxa64'), + os.path.join(self.subdir, 'sys', 'os', 'glnxa64'), + ]) + super(EB_MCR, self).sanity_check_step(custom_paths=custom_paths) + + def make_module_extra(self): + """Extend PATH and set proper _JAVA_OPTIONS (e.g., -Xmx).""" + txt = super(EB_MCR, self).make_module_extra() + + xapplresdir = os.path.join(self.installdir, self.subdir, 'X11', 'app-defaults') + txt += self.module_generator.set_environment('XAPPLRESDIR', xapplresdir) + for ldlibdir in ['runtime', 'bin', os.path.join('sys', 'os')]: + libdir = os.path.join(self.subdir, ldlibdir, 'glnxa64') + txt += self.module_generator.prepend_paths('LD_LIBRARY_PATH', libdir) + + txt += self.module_generator.set_environment('_JAVA_OPTIONS', self.cfg['java_options']) + txt += self.module_generator.set_environment('MCRROOT', os.path.join(self.installdir, self.subdir)) + + return txt diff --git a/pool/shard007/Python/0070534_permitted_documents_for_user.py b/pool/shard007/Python/0070534_permitted_documents_for_user.py new file mode 100644 index 0000000000000000000000000000000000000000..22777957b81220a296fec8159c5b3566dc89afa9 --- /dev/null +++ b/pool/shard007/Python/0070534_permitted_documents_for_user.py @@ -0,0 +1,54 @@ +# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors +# MIT License. See license.txt + +from __future__ import unicode_literals +import frappe +from frappe import _, throw +import frappe.utils.user +from frappe.permissions import check_admin_or_system_manager +from frappe.model.db_schema import type_map + +def execute(filters=None): + user, doctype = filters.get("user"), filters.get("doctype") + validate(user, doctype) + + columns, fields = get_columns_and_fields(doctype) + data = frappe.get_list(doctype, fields=fields, as_list=True, user=user) + + return columns, data + +def validate(user, doctype): + # check if current user is System Manager + check_admin_or_system_manager() + + if not user: + throw(_("Please specify user")) + + if not doctype: + throw(_("Please specify doctype")) + +def get_columns_and_fields(doctype): + columns = ["Name:Link/{}:200".format(doctype)] + fields = ["name"] + for df in frappe.get_meta(doctype).fields: + if df.in_list_view and df.fieldtype in type_map: + fields.append(df.fieldname) + fieldtype = "Link/{}".format(df.options) if df.fieldtype=="Link" else df.fieldtype + columns.append("{label}:{fieldtype}:{width}".format(label=df.label, fieldtype=fieldtype, width=df.width or 100)) + + return columns, fields + +def query_doctypes(doctype, txt, searchfield, start, page_len, filters): + user = filters.get("user") + user_obj = frappe.utils.user.User(user) + user_obj.build_permissions() + can_read = user_obj.can_read + + single_doctypes = [d[0] for d in frappe.db.get_values("DocType", {"issingle": 1})] + + out = [] + for dt in can_read: + if txt.lower().replace("%", "") in dt.lower() and dt not in single_doctypes: + out.append([dt]) + + return out diff --git a/pool/shard007/Python/0070543_recv_async.py b/pool/shard007/Python/0070543_recv_async.py new file mode 100644 index 0000000000000000000000000000000000000000..b4acb05d1f8223956d7e75ab46398e5417d4fb14 --- /dev/null +++ b/pool/shard007/Python/0070543_recv_async.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python + +# -------------------------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------------------------- + +""" +An example to show receiving events from an Event Hub asynchronously. +""" + +import asyncio +import os +from azure.eventhub.aio import EventHubConsumerClient + +CONNECTION_STR = os.environ["EVENT_HUB_CONN_STR"] +EVENTHUB_NAME = os.environ['EVENT_HUB_NAME'] + + +async def on_event(partition_context, event): + # Put your code here. + # If the operation is i/o intensive, async will have better performance. + print("Received event from partition: {}.".format(partition_context.partition_id)) + await partition_context.update_checkpoint(event) + + +async def on_partition_initialize(partition_context): + # Put your code here. + print("Partition: {} has been initialized.".format(partition_context.partition_id)) + + +async def on_partition_close(partition_context, reason): + # Put your code here. + print("Partition: {} has been closed, reason for closing: {}.".format( + partition_context.partition_id, + reason + )) + + +async def on_error(partition_context, error): + # Put your code here. partition_context can be None in the on_error callback. + if partition_context: + print("An exception: {} occurred during receiving from Partition: {}.".format( + partition_context.partition_id, + error + )) + else: + print("An exception: {} occurred during the load balance process.".format(error)) + + +async def main(): + client = EventHubConsumerClient.from_connection_string( + conn_str=CONNECTION_STR, + consumer_group="$default", + eventhub_name=EVENTHUB_NAME + ) + async with client: + await client.receive( + on_event=on_event, + on_error=on_error, + on_partition_close=on_partition_close, + on_partition_initialize=on_partition_initialize, + starting_position="-1", # "-1" is from the beginning of the partition. + ) + + +if __name__ == '__main__': + asyncio.run(main()) diff --git a/pool/shard007/Python/0070545_test_hasher_crc32.py b/pool/shard007/Python/0070545_test_hasher_crc32.py new file mode 100644 index 0000000000000000000000000000000000000000..6d2193f16a1484b5b3392dc7449a7577bfe82206 --- /dev/null +++ b/pool/shard007/Python/0070545_test_hasher_crc32.py @@ -0,0 +1,23 @@ +from random import randint +from struct import unpack +from unittest import TestCase +from zlib import crc32 + +from redislite.hasher.crc32 import Hasher + +from . import randomword + + +class TestHasherCRC32(TestCase): + def setUp(self): + self.hasher = Hasher('c') + + def test_length(self): + self.assertEqual(self.hasher.hashed_length, 4) + + def test_fuzz(self): + for i in range(0, 20): + word = randomword(randint(1, 200)) + hashed = self.hasher.hash(word) + self.assertEqual(len(hashed), 4) + self.assertEqual(crc32(word), unpack('!i', hashed)[0]) diff --git a/pool/shard007/Python/0070547_crawlconfig.py b/pool/shard007/Python/0070547_crawlconfig.py new file mode 100644 index 0000000000000000000000000000000000000000..5c7bb4409a51f7e2e104249828288c5a07746389 --- /dev/null +++ b/pool/shard007/Python/0070547_crawlconfig.py @@ -0,0 +1,55 @@ +from sky.configs import DEFAULT_CRAWL_CONFIG +from sky.scraper import Scraper +from sky.crawler import crawl + +# Crawling +CRAWL_CONFIG = DEFAULT_CRAWL_CONFIG +CRAWL_CONFIG.update({ + 'seed_urls': [ + 'http://www.techcrunch.com/' + ], + + 'collections_path': '/Users/pascal/GDrive/sky_collections', + + 'collection_name': 'techie', + + # Optional + + 'crawl_filter_regexps': [ + + ], + + 'crawl_required_regexps': [ + '2015', '2014' + ], + + 'index_filter_regexps': [ + + ], + + 'index_required_regexps': [ + '2015', '2014' + ], + + 'max_saved_responses': 100, + + 'max_workers': 10, +}) + +crawl.start(CRAWL_CONFIG) + +# Indexing + +SCRAPE_CONFIG = CRAWL_CONFIG.copy() + +SCRAPE_CONFIG.update({ + 'template_proportion': 0.09, + 'max_templates': 1000 +}) + +skindex = Scraper(SCRAPE_CONFIG) + +skindex.load_local_pages() +skindex.add_template_elements() + +res = skindex.process_all(remove_visuals=True) diff --git a/pool/shard007/Python/0070548_api.py b/pool/shard007/Python/0070548_api.py new file mode 100644 index 0000000000000000000000000000000000000000..8d4fa7895e10191eec796edba2985a668ac7b637 --- /dev/null +++ b/pool/shard007/Python/0070548_api.py @@ -0,0 +1,87 @@ +# gigasight/api.py +import os +from tastypie.authorization import Authorization +from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS +from django.contrib.auth.models import User +from tastypie.resources import ModelResource +from tastypie import fields +from gigasight.models import Segment +from gigasight.models import Stream +from gigasight.models import Tag +from tempfile import NamedTemporaryFile + +from django.core.serializers import json +from django.utils import simplejson +from tastypie.serializers import Serializer + + +NFS_ROOT = "/cloudletstore/segments/" + +class PrettyJSONSerializer(Serializer): + json_indent = 2 + def to_json(self, data, options=None): + options = options or {} + data = self.to_simple(data, options) + return simplejson.dumps(data, cls=json.DjangoJSONEncoder, + sort_keys=True, ensure_ascii=False, indent=self.json_indent) + + +class SegmentResource(ModelResource): + class Meta: + serializer = PrettyJSONSerializer() + authorization = Authorization() + queryset = Segment.objects.all() + always_return_data = True + resource_name = 'segment' + list_allowed_methods = ['get', 'post'] + #excludes = ['seg_id'] + filtering = {"mod_time":ALL} + + +class StreamResource(ModelResource): + segment = fields.ForeignKey(SegmentResource, 'segment') + + class Meta: + serializer = PrettyJSONSerializer() + authorization = Authorization() + queryset = Stream.objects.all() + always_return_data = True + resource_name = 'stream' + list_allowed_methods = ['get', 'post', 'put'] + #excludes = ['container', 'id', 'pub_date', 'pk'] + filtering = {"mod_time":ALL, "segment_id":('exact'), "status":ALL} + + def obj_create(self, bundle, request=None, **kwargs): + segment = bundle.data.get("segment", None) + if segment: + segment_id = [a.strip() for a in segment.split("/") if a != ''][-1] + stream_root = os.path.join(NFS_ROOT, segment_id) + if not os.path.exists(stream_root): + os.makedirs(stream_root) + else: + stream_root = os.path.join(NFS_ROOT) + + #import pdb; pdb.set_trace() + tmp_path = NamedTemporaryFile(prefix="stream-", delete=False, dir=stream_root) + return super(StreamResource, self).obj_create(bundle, request, path=tmp_path.name) + + ''' + def dehydrate(self, bundle): + bundle.data['test'] = "test argument. TO BE DELETED" + return bundle + ''' + +class TagResource(ModelResource): + segment = fields.ForeignKey(SegmentResource, 'segment') + + class Meta: + serializer = PrettyJSONSerializer() + authorization = Authorization() + queryset = Tag.objects.all() + always_return_data = True + resource_name = 'tag' + list_allowed_methods = ['get', 'post', 'put'] + excludes = ['id', 'pk'] + filtering = {"mod_time":ALL, "segment_id":('exact'), "tag":ALL, "segment":ALL} + + diff --git a/pool/shard007/Python/0070550_util.py b/pool/shard007/Python/0070550_util.py new file mode 100644 index 0000000000000000000000000000000000000000..540ffe0d6fc576d6322aa70115fea64c016a0228 --- /dev/null +++ b/pool/shard007/Python/0070550_util.py @@ -0,0 +1,143 @@ +import types +from hashlib import sha1 +from slugify import slugify # noqa + + +def flatten(data, sep='.'): + out = {} + for k, v in data.items(): + ksep = k + sep + if isinstance(v, dict): + for ik, iv in flatten(v, sep).items(): + out[ksep + ik] = iv + else: + out[k] = v + return out + + +def nestify(data): + """ Cubes returns entries and aggregation results in a non-nested way + with a dotted notation for key names. This function turns that format + into a set of nested dictionaries. """ + nested = {} + for key, value in data.items(): + path = key.split('.') + out = nested + for i, level in enumerate(path): + if i == len(path) - 1: + out[level] = value + elif level not in out: + out[level] = {} + out = out[level] + return nested + + +def hash_values(iterable): + """Return a cryptographic hash of an iterable.""" + return sha1(''.join(sha1(unicode(val).encode('utf-8')).hexdigest() + for val in iterable)).hexdigest() + + +def cache_hash(*a, **kw): + """ Try to hash an arbitrary object for caching. """ + + def cache_str(o): + if isinstance(o, (types.FunctionType, types.BuiltinFunctionType, + types.MethodType, types.BuiltinMethodType, + types.UnboundMethodType)): + return getattr(o, 'func_name', 'func') + if isinstance(o, dict): + o = [k + ':' + cache_str(v) for k, v in o.items()] + if isinstance(o, (list, tuple, set)): + o = sorted(map(cache_str, o)) + o = '|'.join(o) + if isinstance(o, basestring): + return o + if hasattr(o, 'updated_at'): + return cache_str((repr(o), o.updated_at)) + return repr(o) + + hash = cache_str((a, kw)).encode('utf-8') + return sha1(hash).hexdigest() + + +def sort_by_reference(ref, sort, sort_fn=None): + """ + + Sort the iterable ``sort`` by ``sort_fn`` (if omitted, the whole object + will be used to sort) according the order defined by the list given in + ``ref``. + + Will raise nasty errors if ``ref`` and ``sort`` aren't 1-to-1, and doesn't + currently perform any error-checking to ensure that they are. + + Example: + + ids = [4, 7, 1, 3] + objs = [{'id': 1}, {'id': 7}, {'id': 4}, {'id': 3}] + + sorted = sort_list_pair(ids, objs, lambda x: x['id']) + # => [{'id': 4}, {'id': 7}, {'id': 1}, {'id': 3}] + + """ + if sort_fn is None: + sort_fn = lambda x: x + + ref_map = dict((r, idx) for idx, r in enumerate(ref)) + + ordered = [None] * len(ref) + for x in sort: + key = sort_fn(x) + if key in ref_map: + ordered[ref_map[key]] = x + + return filter(lambda x: x is not None, ordered) + + +def expand_facets(facets, dataset): + """ + For the given dataset we return the facets as a dict with facet + names for keys and the value is the list of its members along with + the total count (facet_values). + """ + + # We'll fill in and return this dict + expanded_facets = {} + + # Find dimension names in the dataset + dimension_names = [d.name for d in dataset.model.dimensions] + + # Loop over all facets (their names) + for (facet_name, facet_members) in facets.iteritems(): + # We only act on facets which are compound dimensions + if facet_name in dimension_names and dataset.model[facet_name].is_compound: + # Get the dimension from the dataset + dimension = dataset.model[facet_name] + # We get the member names and their facet values into + # their own variables because we need to work more with + # the member names + member_names = [] + facet_values = [] + for member in facet_members: + # We've processed the members so that they're tuples + # that look like: (name,count) + member_names.append(member[0]) + facet_values.append(member[1]) + + # Get all the members for this dimension + members = dimension.members(dimension.alias.c.name. + in_(member_names)) + # We need to sort them by the member names so that they retain + # the same order as the facet_alues + members = sort_by_reference(member_names, members, + lambda x: x['name']) + + # Now we zip them all up into tuples and add into the output dict + expanded_facets[facet_name] = zip(members, facet_values) + else: + # If the facet isn't a compound dimension we still want to keep + # it around + expanded_facets[facet_name] = facet_members + + # ... and return it + return expanded_facets diff --git a/pool/shard007/Python/0070551_kmeans_w_plot.py b/pool/shard007/Python/0070551_kmeans_w_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..f43e71721337db20f1633a066be5c932d40529af --- /dev/null +++ b/pool/shard007/Python/0070551_kmeans_w_plot.py @@ -0,0 +1,120 @@ +''' +Kmeans algorithm on dimension reduced data without plots +Author : Diviyan Kalainathan +Date : 6/06/2016 + +''' + +import numpy +from sklearn.cluster import MiniBatchKMeans +from sklearn.manifold import TSNE +from random import sample +from collections import Counter +import colorsys, csv + + +def minibatch_kmeans(num_clusters, num_init, size_batch, folder_name, + data_file, datadim, num_runs=1, type_init='random', num_iter=100): + """ + :param num_clusters: Number of clusters to be found but the algorithm (int) + :param num_init: number of different runs of the algorithm (int) + :param size_batch: Number of data values per batch(int) + :param folder_name: Folder in which the results are stored + :param data_file: Name of the input file for the minibatch k-means(String) + :param datadim: dimensionality of the input data(int) + :param num_runs: Number of runs of the whole program (int) + :param type_init: Type of init for the Kmeans algorithm (String) + :param num_iter: Number of max iterations for the Kmeans algorithm(int) + :return: + """ + + for run in range(0, num_runs): + + N = num_clusters + print N,'--run n : ', run + + # Creating colors to plot according to which cluster the points belong to + + HSV_tuples = [(x * 1.0 / N, 0.5, 0.5) for x in range(N)] + RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples) + + numpy.set_printoptions(threshold='nan') + + # Preparing the data for k-means + inputdata = numpy.loadtxt(data_file, delimiter=';') + + inputdata = numpy.transpose(inputdata) + inputdata = numpy.hstack((inputdata, numpy.arange(numpy.shape(inputdata)[0])[:, numpy.newaxis])) + inputdata = numpy.random.permutation(inputdata) + index_array = inputdata[:, -1:] + inputdata = inputdata[:, :-1] + + # Applying the algorithm + + result = MiniBatchKMeans(n_clusters=num_clusters, n_init=num_init, init=type_init, batch_size=size_batch, + max_iter=num_iter) + R = result.fit_predict(inputdata) + R2 = result.cluster_centers_ + + # For the first run, creating plots + + if False:#run == 0: + + # TSNE + # For t-SNE, choosing 4000 random points to plot + randomdata = numpy.zeros((4000, datadim)) + randlist = sample(range(31112), 4000) + + for i in range(0, 4000): + randomdata[i, :] = inputdata[randlist[i], :] + displaydata = numpy.vstack((randomdata, R2)) + + model = TSNE(n_components=2) + numpy.set_printoptions(suppress=True) + toprint = model.fit_transform(displaydata) + + with open('output/' + folder_name + '/tsne_c' + str(num_clusters) + + '_n' + str(num_init) + '_r' + str(run) + '.csv', 'wb') as outputfile: + datawriter = csv.writer(outputfile, delimiter=';', quotechar='|') + datawriter.writerow( + str(folder_name) + '_t-sne_c' + str(num_clusters) + '_n' + str(num_init) + '_r' + str(run)) + for i in range(0, len(toprint[:, 1])): + point_toprint = [] + if i < 4000: + + color = RGB_tuples[R[randlist[i]]] + point_toprint += [toprint[i, 0]] + point_toprint += [toprint[i, 1]] + point_toprint += [color] + + else: + point_toprint += [toprint[i, 0]] + point_toprint += [toprint[i, 1]] + # + + with open('output/' + folder_name + '/tsne_c' + str(num_clusters) + + '_n' + str(num_init) + '_r' + str(run) + '.csv', 'a') as outputfile: + datawriter = csv.writer(outputfile, delimiter=';', quotechar='|', + lineterminator='\n') + datawriter.writerow(point_toprint) + + # Plotting histogram of repartition of points in clusters + + R_s = R.flatten() + R_s.sort() + labels, values = zip(*Counter(R_s).items()) + s_values = sorted(values) + numpy.savetxt('output/' + folder_name + '/hist_c' + str(num_clusters) + + '_n' + str(num_init) + '_r' + str(run) + '.csv', s_values, delimiter=';') + + # Save data + + + R = R[:, numpy.newaxis] + R = numpy.hstack((R, index_array)) + numpy.savetxt('output/' + folder_name + '/cluster_centers_c' + str(num_clusters) + + '_n' + str(num_init) + '_r' + str(run) + '.csv', R2, delimiter=';') + numpy.savetxt('output/' + folder_name + '/cluster_predictions_c' + str(num_clusters) + + '_n' + str(num_init) + '_r' + str(run) + '.csv', R, delimiter=';') + + return 0 diff --git a/pool/shard007/Python/0070555_analysis.py b/pool/shard007/Python/0070555_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..9321152588cc4361968958488bf81aff56cd4b93 --- /dev/null +++ b/pool/shard007/Python/0070555_analysis.py @@ -0,0 +1,77 @@ +# python3 +# pylint: disable=g-bad-file-header +# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved. +# +# 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. +# ============================================================================ +"""Analysis for bandit_noise.""" + +from typing import Optional, Sequence + +from bsuite.experiments.bandit import analysis as bandit_analysis +from bsuite.experiments.bandit_noise import sweep +from bsuite.utils import plotting +import numpy as np +import pandas as pd +import plotnine as gg + +NUM_EPISODES = sweep.NUM_EPISODES +TAGS = sweep.TAGS + + +def score(df: pd.DataFrame, scaling_var='noise_scale') -> float: + """Output a single score for experiment = mean - std over scaling_var.""" + return plotting.score_by_scaling( + df=df, + score_fn=bandit_analysis.score, + scaling_var=scaling_var, + ) + + +def plot_learning(df: pd.DataFrame, + sweep_vars: Optional[Sequence[str]] = None, + group_col: str = 'noise_scale') -> gg.ggplot: + """Plots the average regret through time.""" + p = plotting.plot_regret_learning( + df_in=df, group_col=group_col, sweep_vars=sweep_vars, + max_episode=sweep.NUM_EPISODES) + return bandit_analysis.bandit_learning_format(p) + + +def plot_average(df: pd.DataFrame, + sweep_vars: Optional[Sequence[str]] = None, + group_col: str = 'noise_scale') -> gg.ggplot: + """Plots the average regret through time by noise_scale.""" + p = plotting.plot_regret_average( + df_in=df, + group_col=group_col, + episode=sweep.NUM_EPISODES, + sweep_vars=sweep_vars + ) + p += gg.scale_y_continuous(breaks=np.arange(0, 1.1, 0.1).tolist()) + p += gg.theme(panel_grid_major_y=gg.element_line(size=2.5), + panel_grid_minor_y=gg.element_line(size=0),) + p += gg.geom_hline(gg.aes(yintercept=bandit_analysis.BASE_REGRET), + linetype='dashed', alpha=0.4, size=1.75) + p += gg.coord_cartesian(ylim=(0, 1)) + return p + + +def plot_seeds(df: pd.DataFrame, + sweep_vars: Optional[Sequence[str]] = None) -> gg.ggplot: + """Plot the performance by individual work unit.""" + return bandit_analysis.plot_seeds( + df_in=df, + sweep_vars=sweep_vars, + colour_var='noise_scale' + ) + gg.ylab('average episodic return (removing noise)') diff --git a/pool/shard007/Python/0070556_test_root.py b/pool/shard007/Python/0070556_test_root.py new file mode 100644 index 0000000000000000000000000000000000000000..e0bfa779bb17abdbc74b01ee46e39f840c4653a8 --- /dev/null +++ b/pool/shard007/Python/0070556_test_root.py @@ -0,0 +1,35 @@ +from twisted.trial import unittest + +from ...storage_client import NativeStorageServer +from ...web.root import Root + +class FakeRoot(Root): + def __init__(self): + pass + def now_fn(self): + return 0 + +class FakeContext: + def __init__(self): + self.slots = {} + self.tag = self + def fillSlots(self, slotname, contents): + self.slots[slotname] = contents + +class RenderServiceRow(unittest.TestCase): + def test_missing(self): + # minimally-defined static servers just need anonymous-storage-FURL + # and permutation-seed-base32. The WUI used to have problems + # rendering servers that lacked nickname and version. This tests that + # we can render such minimal servers. + ann = {"anonymous-storage-FURL": "pb://w2hqnbaa25yw4qgcvghl5psa3srpfgw3@tcp:127.0.0.1:51309/vucto2z4fxment3vfxbqecblbf6zyp6x", + "permutation-seed-base32": "w2hqnbaa25yw4qgcvghl5psa3srpfgw3", + } + s = NativeStorageServer("server_id", ann, None, {}) + + r = FakeRoot() + ctx = FakeContext() + res = r.render_service_row(ctx, s) + self.assertIdentical(res, ctx) + self.assertEqual(ctx.slots["version"], "") + self.assertEqual(ctx.slots["nickname"], "") diff --git a/pool/shard007/Python/0070560_TestEncoder.py b/pool/shard007/Python/0070560_TestEncoder.py new file mode 100644 index 0000000000000000000000000000000000000000..ea3044ae98a6f46696f5dbe7726d93abf1ba670b --- /dev/null +++ b/pool/shard007/Python/0070560_TestEncoder.py @@ -0,0 +1,101 @@ +import unittest +import sys +import os + +sys.path.insert( + 0, + os.path.abspath( + os.path.join( + os.path.dirname(__file__), + ".."))) + +import emotion +from emotion.axis import Axis +#from emotion import log +#log.level(log.DEBUG) + +config_xml = """ + + + + + + + + + + + + + + + + + + + + +""" + + +class TestEncoder(unittest.TestCase): + + def setUp(self): + emotion.load_cfg_fromstring(config_xml) + + def test_get_encoder(self): + enc = emotion.get_encoder("m0enc") + self.assertTrue(enc) + self.assertEquals(enc.steps_per_unit, 50) + m0 = emotion.get_axis("m0") + self.assertEquals(m0.encoder, enc) + m1 = emotion.get_axis("m1") + self.assertEquals(m1.encoder, None) + + def test_encoder_read(self): + m0 = emotion.get_axis("m0") + enc = emotion.get_encoder("m0enc") + self.assertEquals(enc.read(), m0.dial()/enc.steps_per_unit) + + def test_encoder_set(self): + m0 = emotion.get_axis("m0") + enc = emotion.get_encoder("m0enc") + self.assertEquals(enc.set(133), 133) + + def test_axis_get_noisy_measured_position(self): + m0 = emotion.get_axis("m0") + _pos = m0.dial() + # Switch to noisy mode. + m0.custom_set_measured_noise(0.1) + self.failIf( abs(_pos - m0.dial_measured_position()) > 0.1) + # switch back to normal mode. + m0.custom_set_measured_noise(0.0) + + def test_tolerance(self): + enc = emotion.get_encoder("m0enc") + self.assertEquals(enc.tolerance, 0.001) + + def test_maxee(self): + m1 = emotion.get_axis("m1") + m1.move(1) + self.assertEquals(m1.position(), 1) + + m0 = emotion.get_axis("m0") + m0.dial(0); m0.position(0) + + self.assertRaises(RuntimeError, m0.move, 1) + + enc = emotion.get_encoder("m0enc") + enc.set(2) + m0.move(2) + self.assertEquals(m0.position(), 2) + + +if __name__ == '__main__': + suite = unittest.TestLoader().loadTestsFromTestCase(TestEncoder) + unittest.TextTestRunner(verbosity=2).run(suite) diff --git a/pool/shard007/Python/0070562_pRPNCalculator.py b/pool/shard007/Python/0070562_pRPNCalculator.py new file mode 100644 index 0000000000000000000000000000000000000000..bfeffa20a93679f986cbf0cac875042b2231a88a --- /dev/null +++ b/pool/shard007/Python/0070562_pRPNCalculator.py @@ -0,0 +1,37 @@ +# !/usr/bin/env python + +# # +# Created by vivek on 02/07/2014. +## + +import sys +import re + +# dictionary - +OPS = { + '+': (lambda x, y: x + y), + '-': (lambda x, y: y - x), + '*': (lambda x, y: x * y), + '/': (lambda x, y: y / x) +} + + +def evalTokens(tokens): + ''' Evaluate RPN expr (given as string of tokens) ''' + stack = [] + for token in tokens: + if token in OPS: + stack.append(OPS[token](stack.pop(), stack.pop())) + else: + stack.append(float(token)) + return stack.pop() + + +if __name__ == "__main__": + while True: + # Read line by line from stdin + tokenize line + evaluates line + tokens = re.split(" *", sys.stdin.readline().strip()) + print tokens + if not tokens: + break + sys.stdout.write("Expression: %2.2fn" % evalTokens(tokens)) \ No newline at end of file diff --git a/pool/shard007/Python/0070564_setup.py b/pool/shard007/Python/0070564_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..238465272137a8ce2683de018b53da890a5d5cbb --- /dev/null +++ b/pool/shard007/Python/0070564_setup.py @@ -0,0 +1,22 @@ +from distutils.core import setup +from distutils.extension import Extension +import os.path + +import numpy +numpy_path = os.path.join(numpy.__path__[0], 'core', 'include') + +setup( + name = "rsvd", + ext_modules = [Extension("rsvd/rsvd", ["rsvd/rsvd.c"], + include_dirs=[numpy_path], + extra_link_args=["-O3","-ffast-math"] + ), + ], + version = "0.2.6", + description="A regularized SVD solver for partial matrices", + author='Peter Prettenhofer', + author_email='peter.prettenhofer@gmail.com', + url="http://code.google.com/p/pyrsvd/", + scripts = ["rsvd_train","rsvd_predict","rsvd_lc"], + packages=['rsvd'], +) diff --git a/pool/shard007/Python/0070565_test_hive_to_samba.py b/pool/shard007/Python/0070565_test_hive_to_samba.py new file mode 100644 index 0000000000000000000000000000000000000000..26c33292ca828aabb65182e60ba82390f5d297c5 --- /dev/null +++ b/pool/shard007/Python/0070565_test_hive_to_samba.py @@ -0,0 +1,88 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# 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. +import os +import unittest +from unittest.mock import MagicMock, Mock, PropertyMock, patch + +from airflow.providers.apache.hive.transfers.hive_to_samba import HiveToSambaOperator +from airflow.utils.operator_helpers import context_to_airflow_vars +from tests.providers.apache.hive import DEFAULT_DATE, TestHiveEnvironment +from tests.test_utils.mock_hooks import MockHiveServer2Hook, MockSambaHook + + +class TestHive2SambaOperator(TestHiveEnvironment): + def setUp(self): + self.kwargs = dict( + hql='hql', + destination_filepath='destination_filepath', + samba_conn_id='samba_default', + hiveserver2_conn_id='hiveserver2_default', + task_id='test_hive_to_samba_operator', + ) + super().setUp() + + @patch('airflow.providers.apache.hive.transfers.hive_to_samba.SambaHook') + @patch('airflow.providers.apache.hive.transfers.hive_to_samba.HiveServer2Hook') + @patch('airflow.providers.apache.hive.transfers.hive_to_samba.NamedTemporaryFile') + def test_execute(self, mock_tmp_file, mock_hive_hook, mock_samba_hook): + type(mock_tmp_file).name = PropertyMock(return_value='tmp_file') + mock_tmp_file.return_value.__enter__ = Mock(return_value=mock_tmp_file) + context = {} + + HiveToSambaOperator(**self.kwargs).execute(context) + + mock_hive_hook.assert_called_once_with(hiveserver2_conn_id=self.kwargs['hiveserver2_conn_id']) + mock_hive_hook.return_value.to_csv.assert_called_once_with( + hql=self.kwargs['hql'], + csv_filepath=mock_tmp_file.name, + hive_conf=context_to_airflow_vars(context), + ) + mock_samba_hook.assert_called_once_with(samba_conn_id=self.kwargs['samba_conn_id']) + mock_samba_hook.return_value.push_from_local.assert_called_once_with( + self.kwargs['destination_filepath'], mock_tmp_file.name + ) + + @unittest.skipIf( + 'AIRFLOW_RUNALL_TESTS' not in os.environ, "Skipped because AIRFLOW_RUNALL_TESTS is not set" + ) + @patch('tempfile.tempdir', '/tmp/') + @patch('tempfile._RandomNameSequence.__next__') + @patch( + 'airflow.providers.apache.hive.transfers.hive_to_samba.HiveServer2Hook', + side_effect=MockHiveServer2Hook, + ) + def test_hive2samba(self, mock_hive_server_hook, mock_temp_dir): + mock_temp_dir.return_value = "tst" + + samba_hook = MockSambaHook(self.kwargs['samba_conn_id']) + samba_hook.upload = MagicMock() + + with patch( + 'airflow.providers.apache.hive.transfers.hive_to_samba.SambaHook', return_value=samba_hook + ): + samba_hook.conn.upload = MagicMock() + op = HiveToSambaOperator( + task_id='hive2samba_check', + samba_conn_id='tableau_samba', + hql="SELECT * FROM airflow.static_babynames LIMIT 10000", + destination_filepath='test_airflow.csv', + dag=self.dag, + ) + op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) + + samba_hook.conn.upload.assert_called_with('/tmp/tmptst', 'test_airflow.csv') diff --git a/pool/shard007/Python/0070576_model.py b/pool/shard007/Python/0070576_model.py new file mode 100644 index 0000000000000000000000000000000000000000..7585682557cae5ab478c36616b029eadd04d4e8f --- /dev/null +++ b/pool/shard007/Python/0070576_model.py @@ -0,0 +1,19 @@ +import os + +path = os.path.dirname(os.path.realpath(__file__)) +sbmlFilePath = os.path.join(path, 'MODEL1012090002.xml') + +with open(sbmlFilePath,'r') as f: + sbmlString = f.read() + +def module_exists(module_name): + try: + __import__(module_name) + except ImportError: + return False + else: + return True + +if module_exists('libsbml'): + import libsbml + sbml = libsbml.readSBMLFromString(sbmlString) \ No newline at end of file diff --git a/pool/shard007/Python/0070578_CamGrabber.py b/pool/shard007/Python/0070578_CamGrabber.py new file mode 100644 index 0000000000000000000000000000000000000000..d5f00446f1b201e714a47cb160a5c52d46190084 --- /dev/null +++ b/pool/shard007/Python/0070578_CamGrabber.py @@ -0,0 +1,85 @@ +''' +Created on 16.10.2013 + +@author: northernstars +''' +from AbstractSourceGrabber import AbstractSourceGrabber +from imageLibs.imageprocessing import openCam, getImgFromCam, setCamImgSize +from cv2 import resize +from cv2.cv import CV_CAP_PROP_FRAME_WIDTH, CV_CAP_PROP_FRAME_HEIGHT + +class CamGrabber(AbstractSourceGrabber): + ''' + Calss for grabbing image from camera (USB/Firewire) + ''' + __cam = None + + + def __init__(self, source=0, w=320, h=240): + ''' + Constructor + @param source: Video source number + ''' + super(CamGrabber, self).__init__(source) + self.__cam = openCam(self._source) + setCamImgSize(self.__cam, w, h) + + def close(self): + ''' + Closes camera device + ''' + if self.__cam != None and self.__cam.isOpened(): + self.__cam.release() + self.__cam = None + + def isOpened(self): + ''' + Returns True if camera is opened + ''' + if self.__cam != None: + return self.__cam.isOpened() + return False + + def getImg(self): + ''' + Returns image from camera + ''' + if self.__cam != None: + img = getImgFromCam(self.__cam, self._gray) + if img != None: + # resize image + if self._resize != None: + img = resize(img, self._resize) + + return img + + return False + + def setImgSize(self, w=320, h=240): + ''' + Sets camera image size + @param w: Image width + @param h: Image height + ''' + self.close() + self.__init__(self._source, w, h) + + def setParameter(self, srcW=None, srcH=None, gray=None, imgW=None, imgH=None): + ''' + Sets parameter of source + @param srcW: Width of source image + @param srcH: Height of source image + @param gray: If True the image will, be converted to gray + @param imgW: Width of image (resize) + @param imgH: Height of image (resize) + ''' + super(CamGrabber, self).setParameter(imgW, imgH, gray) + + # set source image size + if self.__cam != None and self.__cam.isOpened(): + if srcW != None: + self.__cam.set(CV_CAP_PROP_FRAME_WIDTH, srcW) + if srcH != None: + self.__cam.set(CV_CAP_PROP_FRAME_HEIGHT, srcH) + + \ No newline at end of file diff --git a/pool/shard007/Python/0070580_test_0047_insert_into_positions.py b/pool/shard007/Python/0070580_test_0047_insert_into_positions.py new file mode 100644 index 0000000000000000000000000000000000000000..b2c68e25d4efc2d2f973eccc992df31def47cd78 --- /dev/null +++ b/pool/shard007/Python/0070580_test_0047_insert_into_positions.py @@ -0,0 +1,41 @@ +import itertools +import unittest + + +class Solution: + def permuteUnique(self, nums): + """ + :type nums: List[int] + :rtype: List[List[int]] + """ + nums.sort() + result = [[]] + for num in nums: + num_permutations = len(result) + for i in range(num_permutations): + permutation = result[i] + for j in range(len(permutation)): + if permutation[j] == num: + permutation.insert(j, num) + break + clone = list(permutation) + clone.insert(j, num) + result.append(clone) + else: + permutation.append(num) + return result + + +class Test(unittest.TestCase): + def test(self): + self._test([1, 1, 2]) + self._test([1, 2, 3]) + self._test([0, 1, 0, 0, 9]) + + def _test(self, nums): + actual = Solution().permuteUnique(nums) + self.assertCountEqual([list(p) for p in set(p for p in itertools.permutations(nums))], actual) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard007/Python/0070581_ais_nmea_uptime.py b/pool/shard007/Python/0070581_ais_nmea_uptime.py new file mode 100644 index 0000000000000000000000000000000000000000..870b09035f311ab7d83b870f958b181b0f37b3a9 --- /dev/null +++ b/pool/shard007/Python/0070581_ais_nmea_uptime.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python + +__author__ = 'Kurt Schwehr' +__version__ = '$Revision: 4799 $'.split()[1] +__revision__ = __version__ # For pylint +__date__ = '$Date: 2006-09-25 11:09:02 -0400 (Mon, 25 Sep 2006) $'.split()[1] +__copyright__ = '2009' +__license__ = 'GPL v3' +__contact__ = 'kurt at ccom.unh.edu' +__doc__ =''' +Look at a stream of USCG NMEA messages in the old format and give an estimate of uptime. +How many minutes did we receive data from during the time span? + +@requires: U{Python} >= 2.5 +@requires: U{epydoc} >= 3.0.1 + +@undocumented: __doc__ +@since: 2009-Jun-09 +@status: under development +@organization: U{CCOM} +''' + +import sys +import datetime +import traceback + +def uptime(filename): + times = set() + 'minute increments' + tmin = None + tmax = None + for linenum,line in enumerate(file(filename)): + if '!AIVDM' != line[:6]: + continue + try: + t = int(line.split(',')[-1]) + t = datetime.datetime.utcfromtimestamp(t) + except Exception, e: + #sys.stderr.write(' Exception:' + str(type(Exception))+'\n') + #sys.stderr.write(' Exception args:'+ str(e)+'\n') + #sys.stderr.write(' LINE: %s\n' % (line,)) + #traceback.print_exc(file=sys.stderr) + continue + + t = datetime.datetime(t.year, t.month, t.day, t.hour, t.minute) + + if tmin is None: + tmin = t + tmax = t + if t < tmin: tmin = t + if t > tmax: tmax = t + times.add(t) + + if linenum % 10000 == 0: + sys.stderr.write('%d: %s\n' % ( linenum, str(t))) + + dt = tmax - tmin + + #print tmin,tmax,len(times) + #print tmin.strftime('%j') + #print tmax.strftime('%j') + minutes = len(times) + minutes_expected = (dt.days * 3600*24 + dt.seconds) / 60. + + #print minutes / minutes_expected + julian_day = tmax.strftime('%j') + return julian_day, minutes / minutes_expected + +def main(): + ''' + FIX: document main + ''' + from optparse import OptionParser + parser = OptionParser(usage="%prog [options]", + version="%prog "+__version__+' ('+__date__+')') + + parser.add_option('-v', '--verbose', dest='verbose', default=False, action='store_true', + help='run the tests run in verbose mode') + + (options, args) = parser.parse_args() + v = options.verbose + + for filename in args: + day,up = uptime(filename) + print day,up + + +if __name__ == '__main__': + main() diff --git a/pool/shard007/Python/0070586_views.py b/pool/shard007/Python/0070586_views.py new file mode 100644 index 0000000000000000000000000000000000000000..6eedf657ce9da8f40dd53e3bdf2a2e5176b61fa1 --- /dev/null +++ b/pool/shard007/Python/0070586_views.py @@ -0,0 +1,50 @@ +from django.conf import settings +from django.contrib.auth import authenticate +from django.contrib.auth import login + +from registration import signals +from registration.views import RegistrationView as BaseRegistrationView + +try: + from django.contrib.auth import get_user_model +except ImportError: + from django.contrib.auth.models import User +else: + User = get_user_model() + +class RegistrationView(BaseRegistrationView): + """ + A registration backend which implements the simplest possible + workflow: a user supplies an email address and password (the + bare minimum for a useful account), and is immediately signed + up and logged in). + + """ + def register(self, request, **cleaned_data): + email, password = cleaned_data['email'], cleaned_data['password1'] + User.objects.create_user(email, password) + + new_user = authenticate(email=email, password=password) + login(request, new_user) + signals.user_registered.send(sender=self.__class__, + user=new_user, + request=request) + return new_user + + def registration_allowed(self, request): + """ + Indicate whether account registration is currently permitted, + based on the value of the setting ``REGISTRATION_OPEN``. This + is determined as follows: + + * If ``REGISTRATION_OPEN`` is not specified in settings, or is + set to ``True``, registration is permitted. + + * If ``REGISTRATION_OPEN`` is both specified and set to + ``False``, registration is not permitted. + + """ + return getattr(settings, 'REGISTRATION_OPEN', True) + + def get_success_url(self, request, user): + return user.get_absolute_url(), (), {} diff --git a/pool/shard007/Python/0070587_observer.py b/pool/shard007/Python/0070587_observer.py new file mode 100644 index 0000000000000000000000000000000000000000..73103567cc5cc366274bf8430b13074752432216 --- /dev/null +++ b/pool/shard007/Python/0070587_observer.py @@ -0,0 +1,48 @@ +""" +.. module:: RistrettoORM Observer Mixin + :platform: Linux + :synopsis: Simple Observer Mixin + :copyright: (c) 2013 by Ernesto Bossi. + :license: BSD. + +.. moduleauthor:: Ernesto Bossi +""" +from functools import wraps +from abc import ABCMeta, abstractmethod + +class Subject: + def __init__(self): + self._observers = [] + + def attach(self, observer): + if not observer in self._observers: + self._observers.append(observer) + + def detach(self, observer): + try: + self._observers.remove(observer) + except ValueError: + pass + + def notify(self, modifier=None): + for observer in self._observers: + if modifier != observer: + observer.update(self) + + +class Observer: + @abstractmethod + def update(self, subject): + raise NotImplementedError + + +def notify(func): + + def wrapper(self,*args,**kwargs): + ret =func(self,*args,**kwargs) + try: + getattr(self,"notify")() #notify observers + except AttributeError: + self.__class__.__bases__ = (Subject,) + self.__class__.__bases__ + return ret + return wrapper \ No newline at end of file diff --git a/pool/shard007/Python/0070588_test_external_volumes.py b/pool/shard007/Python/0070588_test_external_volumes.py new file mode 100644 index 0000000000000000000000000000000000000000..1e6b55b5a62b4fd2da0d4b38586cf3007ad559d6 --- /dev/null +++ b/pool/shard007/Python/0070588_test_external_volumes.py @@ -0,0 +1,78 @@ +import logging +import pytest +import re + +import sdk_agents +import sdk_install +import sdk_plan +import sdk_tasks +from tests import config + +log = logging.getLogger(__name__) + + +@pytest.fixture(scope="module", autouse=True) +def configure_package(configure_security): + try: + sdk_install.uninstall(config.PACKAGE_NAME, config.SERVICE_NAME) + yield # let the test session execute + finally: + sdk_install.uninstall(config.PACKAGE_NAME, config.SERVICE_NAME) + + +@pytest.mark.external_volumes +@pytest.mark.sanity +@pytest.mark.dcos_min_version("2.1") +def test_default_deployment(): + # Test default installation with external volumes. + # Ensure service comes up successfully. + options = { + "nodes": {"external_volume": {"enabled": True}}, + } + sdk_install.install( + config.PACKAGE_NAME, + config.SERVICE_NAME, + 3, + additional_options=options, + wait_for_deployment=True, + ) + # Wait for scheduler to restart. + sdk_plan.wait_for_completed_deployment(config.SERVICE_NAME) + + +@pytest.mark.skip(reason="Conflicts with Cassandra Custom Recovery Manager") +@pytest.mark.sanity +def test_auto_replace_on_drain(): + candidate_tasks = sdk_tasks.get_tasks_avoiding_scheduler( + config.SERVICE_NAME, re.compile("^node-[0-9]+-server$") + ) + + assert len(candidate_tasks) != 0, "Could not find a node to drain" + + # Pick the host of the first task from the above list + replace_agent_id = candidate_tasks[0].agent_id + replace_tasks = [task for task in candidate_tasks if task.agent_id == replace_agent_id] + log.info( + "Tasks on agent {} to be replaced after drain: {}".format(replace_agent_id, replace_tasks) + ) + sdk_agents.drain_agent(replace_agent_id) + + sdk_plan.wait_for_kicked_off_recovery(config.SERVICE_NAME) + sdk_plan.wait_for_completed_recovery(config.SERVICE_NAME) + + new_tasks = sdk_tasks.get_summary() + + for replaced_task in replace_tasks: + new_task = [ + task + for task in new_tasks + if task.name == replaced_task.name and task.id != replaced_task.id + ][0] + log.info( + "Checking affected task has moved to a new agent:\n" + "old={}\nnew={}".format(replaced_task, new_task) + ) + assert replaced_task.agent_id != new_task.agent_id + + # Reactivate the drained agent, otherwise uninstall plans will be halted for portworx + sdk_agents.reactivate_agent(replace_agent_id) diff --git a/pool/shard007/Python/0070589_from_model.py b/pool/shard007/Python/0070589_from_model.py new file mode 100644 index 0000000000000000000000000000000000000000..31a862b60166cfd25e8ea74490761470d5b74c13 --- /dev/null +++ b/pool/shard007/Python/0070589_from_model.py @@ -0,0 +1,264 @@ +# Authors: Gilles Louppe, Mathieu Blondel, Maheshakya Wijewardena +# License: BSD 3 clause + +import numpy as np + +from .base import SelectorMixin +from ..base import TransformerMixin, BaseEstimator, clone +from ..externals import six + +from ..utils import safe_mask, check_array, deprecated +from ..utils.validation import check_is_fitted +from ..exceptions import NotFittedError +from ..utils.fixes import norm + + +def _get_feature_importances(estimator, norm_order=1): + """Retrieve or aggregate feature importances from estimator""" + importances = getattr(estimator, "feature_importances_", None) + + if importances is None and hasattr(estimator, "coef_"): + if estimator.coef_.ndim == 1: + importances = np.abs(estimator.coef_) + + else: + importances = norm(estimator.coef_, axis=0, ord=norm_order) + + elif importances is None: + raise ValueError( + "The underlying estimator %s has no `coef_` or " + "`feature_importances_` attribute. Either pass a fitted estimator" + " to SelectFromModel or call fit before calling transform." + % estimator.__class__.__name__) + + return importances + + +def _calculate_threshold(estimator, importances, threshold): + """Interpret the threshold value""" + + if threshold is None: + # determine default from estimator + est_name = estimator.__class__.__name__ + if ((hasattr(estimator, "penalty") and estimator.penalty == "l1") or + "Lasso" in est_name): + # the natural default threshold is 0 when l1 penalty was used + threshold = 1e-5 + else: + threshold = "mean" + + if isinstance(threshold, six.string_types): + if "*" in threshold: + scale, reference = threshold.split("*") + scale = float(scale.strip()) + reference = reference.strip() + + if reference == "median": + reference = np.median(importances) + elif reference == "mean": + reference = np.mean(importances) + else: + raise ValueError("Unknown reference: " + reference) + + threshold = scale * reference + + elif threshold == "median": + threshold = np.median(importances) + + elif threshold == "mean": + threshold = np.mean(importances) + + else: + raise ValueError("Expected threshold='mean' or threshold='median' " + "got %s" % threshold) + + else: + threshold = float(threshold) + + return threshold + + +class _LearntSelectorMixin(TransformerMixin): + # Note because of the extra threshold parameter in transform, this does + # not naturally extend from SelectorMixin + """Transformer mixin selecting features based on importance weights. + + This implementation can be mixin on any estimator that exposes a + ``feature_importances_`` or ``coef_`` attribute to evaluate the relative + importance of individual features for feature selection. + """ + @deprecated('Support to use estimators as feature selectors will be ' + 'removed in version 0.19. Use SelectFromModel instead.') + def transform(self, X, threshold=None): + """Reduce X to its most important features. + + Uses ``coef_`` or ``feature_importances_`` to determine the most + important features. For models with a ``coef_`` for each class, the + absolute sum over the classes is used. + + Parameters + ---------- + X : array or scipy sparse matrix of shape [n_samples, n_features] + The input samples. + + threshold : string, float or None, optional (default=None) + The threshold value to use for feature selection. Features whose + importance is greater or equal are kept while the others are + discarded. If "median" (resp. "mean"), then the threshold value is + the median (resp. the mean) of the feature importances. A scaling + factor (e.g., "1.25*mean") may also be used. If None and if + available, the object attribute ``threshold`` is used. Otherwise, + "mean" is used by default. + + Returns + ------- + X_r : array of shape [n_samples, n_selected_features] + The input samples with only the selected features. + """ + check_is_fitted(self, ('coef_', 'feature_importances_'), + all_or_any=any) + + X = check_array(X, 'csc') + importances = _get_feature_importances(self) + if len(importances) != X.shape[1]: + raise ValueError("X has different number of features than" + " during model fitting.") + + if threshold is None: + threshold = getattr(self, 'threshold', None) + threshold = _calculate_threshold(self, importances, threshold) + + # Selection + try: + mask = importances >= threshold + except TypeError: + # Fails in Python 3.x when threshold is str; + # result is array of True + raise ValueError("Invalid threshold: all features are discarded.") + + if np.any(mask): + mask = safe_mask(X, mask) + return X[:, mask] + else: + raise ValueError("Invalid threshold: all features are discarded.") + + +class SelectFromModel(BaseEstimator, SelectorMixin): + """Meta-transformer for selecting features based on importance weights. + + .. versionadded:: 0.17 + + Parameters + ---------- + estimator : object + The base estimator from which the transformer is built. + This can be both a fitted (if ``prefit`` is set to True) + or a non-fitted estimator. + + threshold : string, float, optional default None + The threshold value to use for feature selection. Features whose + importance is greater or equal are kept while the others are + discarded. If "median" (resp. "mean"), then the ``threshold`` value is + the median (resp. the mean) of the feature importances. A scaling + factor (e.g., "1.25*mean") may also be used. If None and if the + estimator has a parameter penalty set to l1, either explicitly + or implicitly (e.g, Lasso), the threshold used is 1e-5. + Otherwise, "mean" is used by default. + + prefit : bool, default False + Whether a prefit model is expected to be passed into the constructor + directly or not. If True, ``transform`` must be called directly + and SelectFromModel cannot be used with ``cross_val_score``, + ``GridSearchCV`` and similar utilities that clone the estimator. + Otherwise train the model using ``fit`` and then ``transform`` to do + feature selection. + + norm_order : non-zero int, inf, -inf, default 1 + Order of the norm used to filter the vectors of coefficients below + ``threshold`` in the case where the ``coef_`` attribute of the + estimator is of dimension 2. + + Attributes + ---------- + `estimator_`: an estimator + The base estimator from which the transformer is built. + This is stored only when a non-fitted estimator is passed to the + ``SelectFromModel``, i.e when prefit is False. + + `threshold_`: float + The threshold value used for feature selection. + """ + + def __init__(self, estimator, threshold=None, prefit=False, norm_order=1): + self.estimator = estimator + self.threshold = threshold + self.prefit = prefit + self.norm_order = norm_order + + def _get_support_mask(self): + # SelectFromModel can directly call on transform. + if self.prefit: + estimator = self.estimator + elif hasattr(self, 'estimator_'): + estimator = self.estimator_ + else: + raise ValueError( + 'Either fit the model before transform or set "prefit=True"' + ' while passing the fitted estimator to the constructor.') + scores = _get_feature_importances(estimator, self.norm_order) + self.threshold_ = _calculate_threshold(estimator, scores, + self.threshold) + return scores >= self.threshold_ + + def fit(self, X, y=None, **fit_params): + """Fit the SelectFromModel meta-transformer. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The training input samples. + + y : array-like, shape (n_samples,) + The target values (integers that correspond to classes in + classification, real numbers in regression). + + **fit_params : Other estimator specific parameters + + Returns + ------- + self : object + Returns self. + """ + if self.prefit: + raise NotFittedError( + "Since 'prefit=True', call transform directly") + self.estimator_ = clone(self.estimator) + self.estimator_.fit(X, y, **fit_params) + return self + + def partial_fit(self, X, y=None, **fit_params): + """Fit the SelectFromModel meta-transformer only once. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The training input samples. + + y : array-like, shape (n_samples,) + The target values (integers that correspond to classes in + classification, real numbers in regression). + + **fit_params : Other estimator specific parameters + + Returns + ------- + self : object + Returns self. + """ + if self.prefit: + raise NotFittedError( + "Since 'prefit=True', call transform directly") + if not hasattr(self, "estimator_"): + self.estimator_ = clone(self.estimator) + self.estimator_.partial_fit(X, y, **fit_params) + return self diff --git a/pool/shard007/Python/0070590_zkmigrator.py b/pool/shard007/Python/0070590_zkmigrator.py new file mode 100644 index 0000000000000000000000000000000000000000..49fb5e80c8b3eab8e2b3f901f0fa6139f3a49da0 --- /dev/null +++ b/pool/shard007/Python/0070590_zkmigrator.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python +""" +Licensed to the Apache Software Foundation (ASF) under one +or more contributor license agreements. See the NOTICE file +distributed with this work for additional information +regarding copyright ownership. The ASF licenses this file +to you under the Apache License, Version 2.0 (the +"License"); you may not use this file except in compliance +with the License. You may obtain a copy of the License at + + 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. + +Ambari Agent + +""" + +from resource_management.core.resources.system import Execute +from resource_management.core.logger import Logger +from resource_management.libraries.functions import format + +class ZkMigrator: + def __init__(self, zk_host, java_exec, java_home, jaas_file, user): + self.zk_host = zk_host + self.java_exec = java_exec + self.java_home = java_home + self.jaas_file = jaas_file + self.user = user + self.zkmigrator_jar = "/var/lib/ambari-agent/tools/zkmigrator.jar" + + def set_acls(self, znode, acl, tries=3): + Logger.info(format("Setting ACL on znode {znode} to {acl}")) + Execute( + self._acl_command(znode, acl), \ + user=self.user, \ + environment={ 'JAVA_HOME': self.java_home }, \ + logoutput=True, \ + tries=tries) + + def delete_node(self, znode, tries=3): + Logger.info(format("Removing znode {znode}")) + Execute( + self._delete_command(znode), \ + user=self.user, \ + environment={ 'JAVA_HOME': self.java_home }, \ + logoutput=True, \ + tries=tries) + + def _acl_command(self, znode, acl): + return "{0} -Djava.security.auth.login.config={1} -jar {2} -connection-string {3} -znode {4} -acl {5}".format( \ + self.java_exec, self.jaas_file, self.zkmigrator_jar, self.zk_host, znode, acl) + + def _delete_command(self, znode): + return "{0} -Djava.security.auth.login.config={1} -jar {2} -connection-string {3} -znode {4} -delete".format( \ + self.java_exec, self.jaas_file, self.zkmigrator_jar, self.zk_host, znode) diff --git a/pool/shard007/Python/0070591_XMILE2Py.py b/pool/shard007/Python/0070591_XMILE2Py.py new file mode 100644 index 0000000000000000000000000000000000000000..3fb32cbbdde29501fa0057257106cd0b2f0de2e5 --- /dev/null +++ b/pool/shard007/Python/0070591_XMILE2Py.py @@ -0,0 +1,67 @@ +''' +August 15 2014 +James Houghton +Major edits June 22 2015 +''' +from pysd.translators.SMILE2Py import SMILEParser +from lxml import etree +from pysd import builder + + +def translate_xmile(xmile_file): + """ Translate an xmile model file into a python class. + Functionality is currently limited. + + """ + py_model_file = build_python(xmile_file) + return py_model_file + + +def build_python(xmile_file): + """ Load the xml file and pass the relevant elements to the builder class """ + + smile_parser = SMILEParser() + + xml_parser = etree.XMLParser(encoding="utf-8", recover=True) + root = etree.parse(xmile_file, parser=xml_parser).getroot() + NS = root.nsmap.values()[0] + + filename = '.'.join(xmile_file.split('.')[:-1])+'.py' + builder.new_model(filename) + + # add aux and flow nodes + flaux_xpath = '//ns:model/ns:variables/ns:aux|//ns:model/ns:variables/ns:flow' + for element in root.xpath(flaux_xpath, namespaces={'ns':NS}): + identifier = smile_parser.parse(element.attrib['name'], context='defn') + pyeqn = smile_parser.parse(element.xpath('ns:eqn', namespaces={'ns':NS})[0].text) + builder.add_flaux(filename, identifier, pyeqn) + + + # add nodes for the derivatives of stocks + stock_xpath = '//ns:model/ns:variables/ns:stock' + for element in root.xpath(stock_xpath,namespaces={'ns':NS}): + identifier = smile_parser.parse(element.attrib['name'], context='defn') + + inflows = [smile_parser.parse(e.text) for e in element.xpath('ns:inflow', namespaces={'ns':NS})] + outflows = [smile_parser.parse(e.text) for e in element.xpath('ns:outflow', namespaces={'ns':NS})] + pyeqn = ' + '.join(inflows) if inflows else '' + pyeqn += ' - '+' - '.join(outflows) if outflows else '' + + initial_value = smile_parser.parse(element.xpath('ns:eqn', namespaces={'ns':NS})[0].text) + + builder.add_stock(filename, identifier, pyeqn, initial_value) + + + #Get timeseries information from the XMILE file + tstart = smile_parser.parse(root.xpath('//ns:sim_specs/ns:start',namespaces={'ns':NS})[0].text) + builder.add_flaux(filename, 'initial_time', tstart) + + tstop = smile_parser.parse(root.xpath('//ns:sim_specs/ns:stop',namespaces={'ns':NS})[0].text) + builder.add_flaux(filename, 'final_time', tstop) + + dt = smile_parser.parse(root.xpath('//ns:sim_specs/ns:dt',namespaces={'ns':NS})[0].text) + builder.add_flaux(filename, 'time_step', dt) + + return filename + + diff --git a/pool/shard007/Python/0070595_leave_group_v0.py b/pool/shard007/Python/0070595_leave_group_v0.py new file mode 100644 index 0000000000000000000000000000000000000000..c8bc6829f47c22bcc7f18bd43a130fa2ec88d071 --- /dev/null +++ b/pool/shard007/Python/0070595_leave_group_v0.py @@ -0,0 +1,42 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from kafka.tools.protocol.requests import BaseRequest, ArgumentError +from kafka.tools.protocol.responses.leave_group_v0 import LeaveGroupV0Response + + +class LeaveGroupV0Request(BaseRequest): + api_key = 10 + api_version = 0 + cmd = "LeaveGroup" + response = LeaveGroupV0Response + + supports_cli = True + help_string = ("Request: {0}V{1}\n".format(cmd, api_version) + + "Format: {0}V{1} group_id member_id\n".format(cmd, api_version) + + "Description: Remove the specified member from the specified group\n") + + schema = [ + {'name': 'group_id', 'type': 'string'}, + {'name': 'member_id', 'type': 'string'}, + ] + + @classmethod + def process_arguments(cls, cmd_args): + if len(cmd_args) != 2: + raise ArgumentError("LeaveGroupV0 requires exactly two arguments") + return {'group_id': cmd_args[0], 'member_id': cmd_args[1]} diff --git a/pool/shard007/Python/0070599_component_setup.py b/pool/shard007/Python/0070599_component_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..766d328acfee4c92bbb912d8d6e8dc616c6ee120 --- /dev/null +++ b/pool/shard007/Python/0070599_component_setup.py @@ -0,0 +1,245 @@ +#!/usr/bin/python +# Copyright (c) 2011 The Native Client Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Main setup for software construction toolkit. + +This module is a SCons tool which should be include in all environments. +It is used as follows: + env = Environment(tools = ['component_setup']) +and should be the first tool from this toolkit referenced by any environment. +""" + +import os +import sys +import SCons +import usage_log + + +#------------------------------------------------------------------------------ + + +def InstallUsingLink(target, source, env): + """Install function for environment which uses link in preference to copy. + + Args: + target: Destintion filename + source: Source filename + env: Environment + + Returns: + Return code from SCons Node link function. + """ + + # Use link function for Install() and InstallAs(), since it's much much + # faster than copying. This is ok for the way we build clients, where we're + # installing to a build output directory and not to a permanent location such + # as /usr/bin. + # Need to force the target and source to be lists of nodes + return SCons.Node.FS.LinkFunc([env.Entry(target)], [env.Entry(source)], env) + + +def PreEvaluateVariables(env): + """Deferred function to pre-evaluate SCons varables for each build mode. + + Args: + env: Environment for the current build mode. + """ + # Convert directory variables to strings. Must use .abspath not str(), since + # otherwise $OBJ_ROOT is converted to a relative path, which evaluates + # improperly in SConscripts not in $MAIN_DIR. + for var in env.SubstList2('$PRE_EVALUATE_DIRS'): + env[var] = env.Dir('$' + var).abspath + + +#------------------------------------------------------------------------------ + + +def generate(env): + # NOTE: SCons requires the use of this name, which fails gpylint. + """SCons entry point for this tool.""" + + # Use MD5 to tell when files differ, if the timestamps differ. This is + # better than pure MD5 (since if the timestamps are the same, we don't need + # to rescan the file), and also better than pure timestamp (since if a file + # is rebuilt to the same contents, we don't need to trigger the build steps + # which depend on it). + env.Decider('MD5-timestamp') + + # For duplication order, use hard links then fall back to copying. Don't use + # soft links, since those won't do the right thing if the output directory + # is tar'd up and moved elsewhere. + SCons.Script.SetOption('duplicate', 'hard-copy') + + # Remove the alias namespace lookup function from the list which SCons uses + # when coercing strings into nodes. This prevents SCons from looking up + # aliases in input/output lists if they're not explicitly coerced via + # Alias(), and removes a conflict where a program has the same shorthand + # alias as the program name itself. This conflict manifests itself as a + # python exception if you try to build a program in multiple modes on linux, + # for example: + # hammer --mode=dbg,opt port_test + new_lookup_list = [] + for func in env.lookup_list: + if func.im_class != SCons.Node.Alias.AliasNameSpace: + new_lookup_list.append(func) + env.lookup_list = new_lookup_list + + # Add command line options + SCons.Script.AddOption( + '--brief', + dest='brief_comstr', + default=True, + action='store_true', + help='brief command line output') + SCons.Script.AddOption( + '--verbose', + dest='brief_comstr', + default=True, + action='store_false', + help='verbose command line output') + + # Add help for command line options + SCons.Script.Help("""\ + --verbose Print verbose output while building, including + the full command lines for all commands. + --brief Print brief output while building (the default). + This and --verbose are opposites. Use --silent + to turn off all output. +""") + + # Cover part of the environment + env.Replace( + # Add a reference to our python executable, so subprocesses can find and + # invoke python. + PYTHON = env.File(sys.executable), + + # Get the absolute path to the directory containing main.scons (or + # SConstruct). This should be used in place of the SCons variable '#', + # since '#' is not always replaced (for example, when being used to set + # an environment variable). + MAIN_DIR = env.Dir('#').abspath, + # Supply deprecated SCONSTRUCT_DIR for legacy suport + # TODO: remove legacy support once everyone has switched over. + SCONSTRUCT_DIR = env.Dir('#').abspath, + + # Use install function above, which uses links in preference to copying. + INSTALL = InstallUsingLink, + ) + + # Specify defaults for variables where we don't need to force replacement + env.SetDefault( + # Directories + DESTINATION_ROOT='$MAIN_DIR/scons-out$HOST_PLATFORM_SUFFIX', + TARGET_ROOT='$DESTINATION_ROOT/$BUILD_TYPE', + OBJ_ROOT='$TARGET_ROOT/obj', + ARTIFACTS_DIR='$TARGET_ROOT/artifacts', + ) + + # Add default list of variables we should pre-evaluate for each build mode + env.Append(PRE_EVALUATE_DIRS = [ + 'ARTIFACTS_DIR', + 'DESTINATION_ROOT', + 'OBJ_ROOT', + 'SOURCE_ROOT', + 'TARGET_ROOT', + 'TOOL_ROOT', + ]) + + # If a host platform was specified on the command line, need to put the SCons + # output in its own destination directory. + force_host_platform = SCons.Script.GetOption('host_platform') + if force_host_platform: + env['HOST_PLATFORM_SUFFIX'] = '-' + force_host_platform + + # Put the .sconsign.dblite file in our destination root directory, so that we + # don't pollute the source tree. Use the '_' + sys.platform suffix to prevent + # the .sconsign.dblite from being shared between host platforms, even in the + # case where the --host_platform option is not used (for instance when the + # project has platform suffixes on all the build types). + # + # This will prevent host platforms from mistakenly using each other's + # .sconsign databases and will allow two host platform builds to occur in the + # same # shared tree simulataneously. + # + # Note that we use sys.platform here rather than HOST_PLATFORM, since we need + # different sconsign databases for cygwin vs. win32. + sconsign_dir = env.Dir('$DESTINATION_ROOT').abspath + sconsign_filename = '$DESTINATION_ROOT/.sconsign_%s' % sys.platform + sconsign_file = env.File(sconsign_filename).abspath + # SConsignFile() doesn't seem to like it if the destination directory + # doesn't already exist, so make sure it exists. + # TODO: Remove once SCons has fixed this bug. + if not os.path.isdir(sconsign_dir): + os.makedirs(sconsign_dir) + SCons.Script.SConsignFile(sconsign_file) + + # Build all by default + # TODO: This would be more nicely done by creating an 'all' alias and mapping + # that to $DESTINATION_ROOT (or the accumulation of all $TARGET_ROOT's for + # the environments which apply to the current host platform). Ideally, that + # would be done in site_init.py and not here. But since we can't do that, + # just set the default to be DESTINATION_ROOT here. Note that this currently + # forces projects which want to override the default to do so after including + # the component_setup tool (reasonable, since component_setup should pretty + # much be the first thing in a SConstruct. + env.Default('$DESTINATION_ROOT') + + # Use brief command line strings if necessary + if env.GetOption('brief_comstr'): + env.SetDefault( + ARCOMSTR='________Creating library $TARGET', + ASCOMSTR='________Assembling $TARGET', + CCCOMSTR='________Compiling $TARGET', + CXXCOMSTR='________Compiling $TARGET', + LDMODULECOMSTR='________Building loadable module $TARGET', + LINKCOMSTR='________Linking $TARGET', + MANIFEST_COMSTR='________Updating manifest for $TARGET', + MIDLCOMSTR='________Compiling IDL $TARGET', + PCHCOMSTR='________Precompiling $TARGET', + RANLIBCOMSTR='________Indexing $TARGET', + RCCOMSTR='________Compiling resource $TARGET', + SHCCCOMSTR='________Compiling $TARGET', + SHCXXCOMSTR='________Compiling $TARGET', + SHLINKCOMSTR='________Linking $TARGET', + SHMANIFEST_COMSTR='________Updating manifest for $TARGET', + # Strip doesn't seem to be a first-class citizen in SCons country, + # so we have to add these *COM, *COMSTR manually. + STRIPCOMSTR='________Stripping to create $TARGET', + TRANSLATECOMSTR='________Translating $TARGET', + ) + + # Add other default tools from our toolkit + # TODO: Currently this needs to be before SOURCE_ROOT in case a tool needs to + # redefine it. Need a better way to handle order-dependency in tool setup. + for t in component_setup_tools: + env.Tool(t) + + # The following environment replacements use env.Dir() to force immediate + # evaluation/substitution of SCons variables. They can't be part of the + # preceding env.Replace() since they they may rely indirectly on variables + # defined there, and the env.Dir() calls would be evaluated before the + # env.Replace(). + + # Set default SOURCE_ROOT if there is none, assuming we're in a local + # site_scons directory for the project. + source_root_relative = os.path.normpath( + os.path.join(os.path.dirname(__file__), '../..')) + source_root = env.get('SOURCE_ROOT', source_root_relative) + env['SOURCE_ROOT'] = env.Dir(source_root).abspath + + usage_log.log.SetParam('component_setup.project_path', + env.RelativePath('$SOURCE_ROOT', '$MAIN_DIR')) + + # Make tool root separate from source root so it can be overridden when we + # have a common location for tools outside of the current clientspec. Need + # to check if it's defined already, so it can be set prior to this tool + # being included. + tool_root = env.get('TOOL_ROOT', '$SOURCE_ROOT') + env['TOOL_ROOT'] = env.Dir(tool_root).abspath + + # Defer pre-evaluating some environment variables, but do before building + # SConscripts. + env.Defer(PreEvaluateVariables) + env.Defer('BuildEnvironmentSConscripts', after=PreEvaluateVariables) diff --git a/pool/shard007/Python/0070604_dqn_complex.py b/pool/shard007/Python/0070604_dqn_complex.py new file mode 100644 index 0000000000000000000000000000000000000000..12eb84ebc67fed90d1f45eb0827b3682bb61afa1 --- /dev/null +++ b/pool/shard007/Python/0070604_dqn_complex.py @@ -0,0 +1,83 @@ +import numpy as np +import gym + +from keras.models import Sequential +from keras.layers import Dense, Activation, Flatten +from keras.optimizers import Adam + +from rl.agents.dqn import DQNAgent +from rl.policy import BoltzmannQPolicy, LinearAnnealedPolicy +from rl.memory import SequentialMemory + +from oscar.env.envs.general_learning_env import GeneralLearningEnv +from ML_homework.policy_iteration.complex_policy_iteration import policy_iteration_iterator, state_from_obs + +CONFIG_FILE = 'config/learning_complex.json' +LOG_FILE = 'learning_tools/learning_nn/keras-rl/duel_dqn_{}.csv'.format(CONFIG_FILE[7:-5]) + + +# Get the environment and extract the number of actions. +env = GeneralLearningEnv(CONFIG_FILE, False, log_file_path=None, publish_stats=False) +np.random.seed(123) +env.seed(123) +nb_actions = env.action_space.n + +# Next, we build a very simple model regardless of the dueling architecture +# if you enable dueling network in DQN , DQN will build a dueling network base on your model automatically +# Also, you can build a dueling network by yourself and turn off the dueling network in DQN. +model = Sequential() +model.add(Flatten(input_shape=(1,) + env.observation_space.shape)) +model.add(Dense(16)) +model.add(Activation('relu')) +model.add(Dense(16)) +model.add(Activation('relu')) +model.add(Dense(16)) +model.add(Activation('relu')) +model.add(Dense(nb_actions, activation='linear')) +print(model.summary()) + +# Finally, we configure and compile our agent. You can use every built-in Keras optimizer and +# even the metrics! +memory = SequentialMemory(limit=50000, window_length=1) +boltzmann_policy = BoltzmannQPolicy(tau=20.0, clip=(0.0, 500.0)) +policy = LinearAnnealedPolicy(boltzmann_policy, 'tau', 1.0, 20.0, 1.0, 10000) +# enable the dueling network +# you can specify the dueling_type to one of {'avg','max','naive'} +dqn = DQNAgent(model=model, nb_actions=nb_actions, memory=memory, nb_steps_warmup=10, + enable_dueling_network=True, dueling_type='avg', target_model_update=1e-2, policy=policy) +dqn.compile(Adam(lr=1e-3), metrics=['mae']) + +# warm up +pi = None +for p in policy_iteration_iterator(10, 0.5, file_path="/tmp/state_table.csv", save_path="/tmp/OSCAR/"): + pi = p + +for i in range(20): + obs = env.reset() + while True: + s = state_from_obs(obs) + a = pi[s.id()] + old_obs = obs + obs, r, done, debug_dict = env.step(a) + memory.append(old_obs, a, r, done, False) + if done: + break + +env.close() +env = GeneralLearningEnv(CONFIG_FILE, False, log_file_path=LOG_FILE, publish_stats=False) + +# Okay, now it's time to learn something! We visualize the training here for show, but this +# slows down training quite a lot. You can always safely abort the training prematurely using +# Ctrl + C. +dqn.fit(env, nb_steps=500000, visualize=False, verbose=2) + +# After training is done, we save the final weights. +dqn.save_weights('learning_tools/learning_nn/keras-rl/duel_dqn_{}_weights.h5f'.format(CONFIG_FILE[7:-5]), + overwrite=True) + +env.close() +del env +# env = GeneralLearningEnv(CONFIG_FILE, True, publish_stats=False) +# +# # Finally, evaluate our algorithm for 5 episodes. +# dqn.test(env, nb_episodes=5, visualize=False) diff --git a/pool/shard007/Python/0070605_init__.py b/pool/shard007/Python/0070605_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6e545d19fe26f03a83415db6376dc1ab7c3b37f3 --- /dev/null +++ b/pool/shard007/Python/0070605_init__.py @@ -0,0 +1,104 @@ +"""Connect two Home Assistant instances via MQTT.""" +import asyncio +import json + +import voluptuous as vol + +from homeassistant.core import callback +from homeassistant.components.mqtt import ( + valid_publish_topic, valid_subscribe_topic) +from homeassistant.const import ( + ATTR_SERVICE_DATA, EVENT_CALL_SERVICE, + EVENT_STATE_CHANGED, EVENT_TIME_CHANGED, MATCH_ALL) +from homeassistant.core import EventOrigin, State +import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.json import JSONEncoder + +DOMAIN = 'mqtt_eventstream' +DEPENDENCIES = ['mqtt'] + +CONF_PUBLISH_TOPIC = 'publish_topic' +CONF_SUBSCRIBE_TOPIC = 'subscribe_topic' +CONF_PUBLISH_EVENTSTREAM_RECEIVED = 'publish_eventstream_received' +CONF_IGNORE_EVENT = 'ignore_event' + +CONFIG_SCHEMA = vol.Schema({ + DOMAIN: vol.Schema({ + vol.Optional(CONF_PUBLISH_TOPIC): valid_publish_topic, + vol.Optional(CONF_SUBSCRIBE_TOPIC): valid_subscribe_topic, + vol.Optional(CONF_PUBLISH_EVENTSTREAM_RECEIVED, default=False): + cv.boolean, + vol.Optional(CONF_IGNORE_EVENT, default=[]): cv.ensure_list, + }), +}, extra=vol.ALLOW_EXTRA) + + +@asyncio.coroutine +def async_setup(hass, config): + """Set up the MQTT eventstream component.""" + mqtt = hass.components.mqtt + conf = config.get(DOMAIN, {}) + pub_topic = conf.get(CONF_PUBLISH_TOPIC) + sub_topic = conf.get(CONF_SUBSCRIBE_TOPIC) + ignore_event = conf.get(CONF_IGNORE_EVENT) + + @callback + def _event_publisher(event): + """Handle events by publishing them on the MQTT queue.""" + if event.origin != EventOrigin.local: + return + if event.event_type == EVENT_TIME_CHANGED: + return + + # User-defined events to ignore + if event.event_type in ignore_event: + return + + # Filter out the events that were triggered by publishing + # to the MQTT topic, or you will end up in an infinite loop. + if event.event_type == EVENT_CALL_SERVICE: + if ( + event.data.get('domain') == mqtt.DOMAIN and + event.data.get('service') == mqtt.SERVICE_PUBLISH and + event.data[ATTR_SERVICE_DATA].get('topic') == pub_topic + ): + return + + event_info = {'event_type': event.event_type, 'event_data': event.data} + msg = json.dumps(event_info, cls=JSONEncoder) + mqtt.async_publish(pub_topic, msg) + + # Only listen for local events if you are going to publish them. + if pub_topic: + hass.bus.async_listen(MATCH_ALL, _event_publisher) + + # Process events from a remote server that are received on a queue. + @callback + def _event_receiver(topic, payload, qos): + """Receive events published by and fire them on this hass instance.""" + event = json.loads(payload) + event_type = event.get('event_type') + event_data = event.get('event_data') + + # Special case handling for event STATE_CHANGED + # We will try to convert state dicts back to State objects + # Copied over from the _handle_api_post_events_event method + # of the api component. + if event_type == EVENT_STATE_CHANGED and event_data: + for key in ('old_state', 'new_state'): + state = State.from_dict(event_data.get(key)) + + if state: + event_data[key] = state + + hass.bus.async_fire( + event_type, + event_data=event_data, + origin=EventOrigin.remote + ) + + # Only subscribe if you specified a topic. + if sub_topic: + yield from mqtt.async_subscribe(sub_topic, _event_receiver) + + return True diff --git a/pool/shard007/Python/0070610_scss.disabled..py b/pool/shard007/Python/0070610_scss.disabled..py new file mode 100644 index 0000000000000000000000000000000000000000..cafcdbd344e7f1220f10aedae38f6e070ba6601f --- /dev/null +++ b/pool/shard007/Python/0070610_scss.disabled..py @@ -0,0 +1,58 @@ +# -*- coding: utf-8; -*- +# +# Licensed to Crate (https://crate.io) under one or more contributor +# license agreements. See the NOTICE file distributed with this work for +# additional information regarding copyright ownership. Crate licenses +# this file to you under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. You may +# obtain a copy of the License at +# +# 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. +# +# However, if you have executed another commercial license agreement +# with Crate these terms will supersede the license and you may use the +# software solely pursuant to the terms of the relevant commercial agreement. + +import os +import sys +import pipes +import shutil +import subprocess + +from cactus.utils.filesystem import fileList + +""" +This plugin uses pyScss to translate sass files to css + +Install: + +sudo easy_install pyScss + +""" + +try: + from scss import Scss +except: + sys.exit("Could not find pyScss, please install: sudo easy_install pyScss") + + +CSS_PATH = 'static/css' + +for path in fileList(CSS_PATH): + + if not path.endswith('.scss'): + continue + + with open(path, 'r') as f: + data = f.read() + + css = Scss().compile(data) + + with open(path.replace('.scss', '.css'), 'w') as f: + f.write(css) diff --git a/pool/shard007/Python/0070611_profile_composite_expression.py b/pool/shard007/Python/0070611_profile_composite_expression.py new file mode 100644 index 0000000000000000000000000000000000000000..697404b11df5d6d4146d2f79d1fc64069579be2f --- /dev/null +++ b/pool/shard007/Python/0070611_profile_composite_expression.py @@ -0,0 +1,34 @@ + +import logging +from pyvisdk.exceptions import InvalidArgumentError + +######################################## +# Automatically generated, do not edit. +######################################## + +log = logging.getLogger(__name__) + +def ProfileCompositeExpression(vim, *args, **kwargs): + '''DataObject to Compose expressions. It is used to group expressions together. + They are similar to a parentheses in an expression.''' + + obj = vim.client.factory.create('ns0:ProfileCompositeExpression') + + # do some validation checking... + if (len(args) + len(kwargs)) < 5: + raise IndexError('Expected at least 6 arguments got: %d' % len(args)) + + required = [ 'expressionName', 'operator', 'displayName', 'id', 'negated' ] + optional = [ 'dynamicProperty', 'dynamicType' ] + + for name, arg in zip(required+optional, args): + setattr(obj, name, arg) + + for name, value in kwargs.items(): + if name in required + optional: + setattr(obj, name, value) + else: + raise InvalidArgumentError("Invalid argument: %s. Expected one of %s" % (name, ", ".join(required + optional))) + + return obj + \ No newline at end of file diff --git a/pool/shard007/Python/0070612_hall.py b/pool/shard007/Python/0070612_hall.py new file mode 100644 index 0000000000000000000000000000000000000000..07027b207aaa8710a67fa7b852881d8fe0a74278 --- /dev/null +++ b/pool/shard007/Python/0070612_hall.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python + +import time + +import pigpio + +# +# OH3144E or equivalent Hall effect sensor +# +# Pin 1 - 5V +# Pin 2 - Ground +# Pin 3 - gpio (here P1-8, gpio 14, TXD is used) +# +# The internal gpio pull-up is enabled so that the sensor +# normally reads high. It reads low when a magnet is close. +# + +HALL=14 + +pi = pigpio.pi() # connect to local Pi + +pi.set_mode(HALL, pigpio.INPUT) +pi.set_pull_up_down(HALL, pigpio.PUD_UP) + +start = time.time() + +while (time.time() - start) < 300: + print("Hall = {}".format(pi.read(HALL))) + time.sleep(0.2) + +pi.stop() + diff --git a/pool/shard007/Python/0070614_getdata.py b/pool/shard007/Python/0070614_getdata.py new file mode 100644 index 0000000000000000000000000000000000000000..4d99a25293d1f8423547c9576899c4b395fa4477 --- /dev/null +++ b/pool/shard007/Python/0070614_getdata.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python +# vim: set fileencoding=utf-8: +import string +import itertools +import json +from webscraping import download, xpath, common + + +def normalise(data): + """Create a lower-case, no-spaces, no-parentheses version of data""" + return data \ + .lower() \ + .translate(None, "(),[]123456789'\".") \ + .translate(string.maketrans(' ', '-')) + + +def extract_offset(data): + """Get the numerical offset of the timezone from UTC""" + parity = 0 + data = data.decode('utf-8') + + if data == 'UTC': + return 0 + + # it's an offset of some type; is it positive? + if data[3] == '+': + parity = 1 + else: + parity = -1 + + # Strip the leading "UTC" and parity indicator + data = data[4:] + + # Convert the offset to a number for parity processing + # If there is a n+half-hour offset, remove it from the string, + # then re-add numerically. + if ':' in data: + data = data[:-3] + data = int(data) + 0.5 + else: + data = int(data) + + return parity * data + + +def main(): + """Convert the table of timezone data to a JavaScript array of records""" + D = download.Download() + html = D.get('http://en.wikipedia.org/wiki/List_of_time_zone_abbreviations') + cells = xpath.search(html, '//table[2]//td') + fields = ['abbreviation', 'name', 'offset'] + + records = {} # store the complete records collection + temp_rec = {} # build up a record as we go + temp_rec_abbr = '' + temp_rec_id = '' + complete = False # when a record is complete, it can be added to the store + + for field, cell in zip(itertools.cycle(fields), cells): + if field == 'abbreviation': + temp_rec_abbr = cell.lower() + #cell = quote(cell) + elif field == 'name': + cell = common.remove_tags(cell) + #cell = quote(cell) + temp_rec_id = temp_rec_abbr + '-' + normalise(cell) + elif field == 'offset': + cell = extract_offset(common.remove_tags(cell)) + complete = True + else: + raise Exception('ERROR: unknown field "' + field + '"') + + temp_rec[field] = cell + + if complete: + records[temp_rec_id] = temp_rec + complete = False + temp_rec = {} + temp_rec_id = '' + temp_rec_abbr = '' + + print json.dumps( + records, + ensure_ascii = False, + sort_keys = True, + indent = 4 + ) + + +if __name__ == '__main__': + main() diff --git a/pool/shard007/Python/0070617_ut_helpers_asm.py b/pool/shard007/Python/0070617_ut_helpers_asm.py new file mode 100644 index 0000000000000000000000000000000000000000..9f6dc5c20c872f1c8d9540e0de94b40fc3971c27 --- /dev/null +++ b/pool/shard007/Python/0070617_ut_helpers_asm.py @@ -0,0 +1,101 @@ +# Toshiba MeP-c4 - unit tests helpers +# Guillaume Valadon + +from __future__ import print_function + +from builtins import range + +from miasm.core.utils import decode_hex, encode_hex +from miasm.arch.mep.arch import mn_mep +from miasm.core.cpu import Disasm_Exception +from miasm.core.locationdb import LocationDB +from miasm.expression.expression import ExprId, ExprInt, ExprLoc + +import re + + +def dis(mn_hex): + """Disassembly helper""" + mn_bin = decode_hex(mn_hex) + try: + return mn_mep.dis(mn_bin, "b") + except Disasm_Exception: + assert(False) # miasm don't know what to do + + +def check_instruction(mn_str, mn_hex, multi=None, offset=0): + """Try to disassemble and assemble this instruction""" + + # Rename objdump registers names + mn_str = re.sub("\$([0-9]+)", lambda m: "R"+m.group(1), mn_str) + mn_str = mn_str.replace("$", "") + + # Disassemble + mn = dis(mn_hex) + mn.offset = offset + if mn.dstflow(): + + # Remember ExprInt arguments sizes + args_size = list() + for i in range(len(mn.args)): + if isinstance(mn.args[i], ExprInt): + args_size.append(mn.args[i].size) + else: + args_size.append(None) + + # Adjust arguments values using the instruction offset + loc_db = LocationDB() + mn.dstflow2label(loc_db) + + # Convert ExprLoc to ExprInt + for i in range(len(mn.args)): + if args_size[i] is None: + continue + if isinstance(mn.args[i], ExprLoc): + addr = loc_db.get_location_offset(mn.args[i].loc_key) + mn.args[i] = ExprInt(addr, args_size[i]) + + print("dis: %s -> %s" % (mn_hex.rjust(20), str(mn).rjust(20))) + assert(str(mn) == mn_str) # disassemble assertion + + # Assemble and return all possible candidates + instr = mn_mep.fromstring(mn_str, "b") + instr.offset = offset + instr.mode = "b" + if instr.offset: + instr.fixDstOffset() + asm_list = [encode_hex(i).decode() for i in mn_mep.asm(instr)] + + # Check instructions variants + if multi: + print("Instructions count:", len(asm_list)) + assert(len(asm_list) == multi) + + # Ensure that variants correspond to the same disassembled instruction + for mn_hex_tmp in asm_list: + mn = dis(mn_hex_tmp) + print("dis: %s -> %s" % (mn_hex_tmp.rjust(20), str(mn).rjust(20))) + + # Check the assembly result + print( + "asm: %s -> %s" % ( + mn_str.rjust(20), + ", ".join(asm_list).rjust(20) + ) + ) + assert(mn_hex in asm_list) # assemble assertion + + +def launch_tests(obj): + """Call test methods by name""" + + test_methods = [name for name in dir(obj) if name.startswith("test")] + + for method in test_methods: + print(method) + try: + getattr(obj, method)() + except AttributeError as e: + print("Method not found: %s" % method) + assert(False) + print('-' * 42) diff --git a/pool/shard007/Python/0070619_StorageDataAdapters.py b/pool/shard007/Python/0070619_StorageDataAdapters.py new file mode 100644 index 0000000000000000000000000000000000000000..ed99474bc0a25224c75d0945be93c454616333f3 --- /dev/null +++ b/pool/shard007/Python/0070619_StorageDataAdapters.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# ------------------------------------------------------------------- +# Copyright (c) 2010-2019 Denis Machard +# This file is part of the extensive automation project +# +# 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. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, +# MA 02110-1301 USA +# ------------------------------------------------------------------- + +import os +import shutil +import time + +from ea.libs import Settings, Logger +from ea.serverinterfaces import EventServerInterface as ESI +from ea.serverrepositories import (RepoManager) + + +class StorageDataAdapters(RepoManager.RepoManager, Logger.ClassLogger): + def __init__(self, context): + """ + Storage data adapters + """ + RepoManager.RepoManager.__init__(self, pathRepo='%s%s' % (Settings.getDirExec(), + Settings.get('Paths', 'tmp')), + context=context) + self.context = context + self.prefixAdapters = "adapter" + self.prefixAdaptersAll = "private_storage" + self.adpDataPath = os.path.normpath("%s/AdaptersData" % self.testsPath) + + self.initStorage() + + def getStoragePath(self): + """ + Returns the storage main path + """ + return self.adpDataPath + + def initSubStorage(self, dirProject, dirToday, dirTest): + """ + Initialize the sub storage folders YYYY-MM-DD/testid + """ + # create temp main dir + mainDir = "%s/%s" % (self.adpDataPath, dirProject) + mainDir = os.path.normpath(mainDir) + try: + if not os.path.exists(mainDir): + os.mkdir(mainDir, 0o755) + self.trace("sub adapters storage created: %s" % dirProject) + except Exception as e: + self.error("sub adapters folder creation error: %s" % str(e)) + + mainDir = "%s/%s/%s" % (self.adpDataPath, dirProject, dirToday) + mainDir = os.path.normpath(mainDir) + try: + if not os.path.exists(mainDir): + os.mkdir(mainDir, 0o755) + self.trace("sub adapters storage created: %s" % dirToday) + except Exception as e: + self.error("sub adapters folder creation error: %s" % str(e)) + + testDir = "%s/%s" % (mainDir, dirTest) + testDir = os.path.normpath(testDir) + try: + # remove first + if os.path.exists(testDir): + shutil.rmtree(testDir) + else: + os.mkdir(testDir, 0o755) + self.trace("sub test adapters storage created: %s" % dirTest) + except Exception as e: + self.error("sub test adapters folder creation error: %s" % str(e)) + + def removeSubStorage(self, dirToday, dirTest, projectId=0): + """ + Remove the sub storage folder, just the testid + """ + mainDir = "%s/%s/%s" % (self.adpDataPath, projectId, dirToday) + testDir = "%s/%s" % (mainDir, dirTest) + testDir = os.path.normpath(testDir) + try: + if os.path.exists(testDir): + shutil.rmtree(testDir) + self.trace("adapters storage deleted: %s" % dirTest) + except Exception as e: + self.error( + "unable to delete the temp adapters folder: %s" % + str(e)) + + def initStorage(self): + """ + Initialize the storage + """ + try: + if not os.path.exists(self.adpDataPath): + os.mkdir(self.adpDataPath, 0o755) + self.trace("adapters storage created") + except Exception as e: + self.trace("folder creation error: %s" % str(e)) + + def zipDataV2(self, dirToday, dirTest, destPathZip, + replayId, projectId=0, virtualName=""): + """ + Zip data by adapters and notify users in just one zip + """ + self.trace("Starting to zip all adapters logs") + ret = False + try: + mainDir = "%s/%s/%s" % (self.adpDataPath, projectId, dirToday) + testDir = "%s/%s" % (mainDir, dirTest) + testDir = os.path.normpath(testDir) + + # prepare the file name + tp = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime(time.time())) \ + + ".%3.3d" % int((time.time() * 1000) % 1000) + fileName = "%s_%s_%s" % (self.prefixAdaptersAll, tp, replayId) + + # zip the folder + zipped = self.zipFolder(folderPath=testDir, + zipName="%s.zip" % fileName, + zipPath=destPathZip) + + if zipped == self.context.CODE_OK: + # notify users + if Settings.getInt('Notifications', 'archives'): + size_ = os.path.getsize( + "%s/%s.zip" % + (destPathZip, fileName)) + notif = {} + m = [{"type": "folder", + "name": dirToday, + "project": "%s" % projectId, + "content": [{"type": "folder", + "name": dirTest, + "project": "%s" % projectId, + "virtual-name": virtualName, + "content": [{"type": "file", + "name": "%s.zip" % fileName, + 'size': str(size_), + "project": "%s" % projectId}]}]}] + notif['archive'] = m + data = ('archive', (None, notif)) + ESI.instance().notifyByUserTypes(body=data, + admin=True, + monitor=False, + tester=True) + ret = True + else: + self.error('error to zip data adapters') + ret = False + except Exception as e: + self.error('unable to zip data adapters v2: %s' % str(e)) + return ret + + +SDAMng = None + + +def instance(): + """ + Returns the singleton + """ + return SDAMng + + +def initialize(context): + """ + Instance creation + """ + global SDAMng + SDAMng = StorageDataAdapters(context=context) + + +def finalize(): + """ + Destruction of the singleton + """ + global SDAMng + if SDAMng: + SDAMng = None diff --git a/pool/shard007/Python/0070624_log_update.py b/pool/shard007/Python/0070624_log_update.py new file mode 100644 index 0000000000000000000000000000000000000000..a68e6a5980a61f69c8a36d3857db1228d3782a63 --- /dev/null +++ b/pool/shard007/Python/0070624_log_update.py @@ -0,0 +1,69 @@ +from __future__ import absolute_import, print_function + +import argparse +import configparser +import json +import translogrify.create +import os +import pandas as pd +import sqlalchemy + +def insert_log_entry(message, level, recipients): + + config = translogrify.create.read_config() + + conn_str = "mysql+pymysql://{S}:{P}@{H}/{D}".format(S=config['mysqluser'], + P=config['mysqlpass'], + H=config['mysqlhost'], + D=config['db']) + + engine = sqlalchemy.create_engine(conn_str) + + meta = sqlalchemy.MetaData() + meta.reflect(bind=engine,only=[config['table']]) + + log_table = sqlalchemy.Table(config['table'],meta) + + ins = log_table.insert().values(level=level, + message=message, + recipient = recipients) + + with engine.connect() as con: + try: + con.execute(ins) + except Exception as e: + print(e) + +def add_log_line_cli(): + + config = translogrify.create.read_config() + + parser = argparse.ArgumentParser(description = "Take in a line to add to the translogrify log") + + parser.add_argument('message',type=str,nargs=1, + help="Log file message") + parser.add_argument('level',type=int,nargs=1, + help="Level of alert") + parser.add_argument('recipients',type=str,nargs='+', + help="email addresses of relevant message recipients") + + args = parser.parse_args() + + recipients_json = json.dumps({"email":args.recipients}) + + insert_log_entry(args.message[0], + args.level[0], + recipients_json) + +def add_log_line(message, level, recipients): + + recipients_json = json.dumps({"email":recipients}) + + insert_log_entry(message, + level, + recipients_json) + + +if __name__ == '__main__': + + add_log_line() diff --git a/pool/shard007/Python/0070625_index.py b/pool/shard007/Python/0070625_index.py new file mode 100644 index 0000000000000000000000000000000000000000..5720f4c7996bf45461565229c8b98b1e0cf6de58 --- /dev/null +++ b/pool/shard007/Python/0070625_index.py @@ -0,0 +1,255 @@ +"""UserAvatarRequestHandlerFunction + +Fetches the Gravatar of a user. + +Using this Lambda-backed API Gateway endpoint as a proxy, we avoid having to +expose the plain MD5 hash of each user's e-mail address. This allows for more +realistic e-mail address privacy. + +""" + +from __future__ import print_function + +import os +import json +import time +import base64 +import hashlib +from datetime import datetime +import requests +import boto3 +import botocore +from apigateway_helpers.exception import APIGatewayException +from apigateway_helpers.headers import get_response_headers as get_base_response_headers + +cognito_identity_client = boto3.client("cognito-identity") +cognito_idp_client = boto3.client("cognito-idp") +cognito_sync_client = boto3.client("cognito-sync") +s3_client = boto3.client("s3") + +shared_bucket_name = os.environ["SHARED_BUCKET"] +identity_pool_id = os.environ["COGNITO_IDENTITY_POOL_ID"] +user_pool_id = os.environ["COGNITO_USER_POOL_ID"] +user_profile_dataset_name = os.environ["COGNITO_USER_PROFILE_DATASET_NAME"] + +cached_gravatars_prefix = "cached-gravatars/" +http_strftime_format = "%a, %d %b %Y %H:%M:%S %Z" + +def lambda_handler(event, context): + + print("Event: {}".format(json.dumps(event))) + + if "warming" in event and "{}".format(event["warming"]).lower() == "true": + return { + "message": "Warmed!" + } + + identity_id = event["pathParameters"].get("user-id", "") + + if identity_id == "": + raise APIGatewayException("Parameter \"user-id\" specified in path must be longer than zero characters.", 400) + + user_specified_author_avatar_hash = event["queryStringParameters"].get("hash") + + # Pixels + image_size = 80 + + if "s" in event["queryStringParameters"]: + try: + image_size = int(event["queryStringParameters"]["s"]) + if image_size < 1: + raise Exception + if image_size > 2048: + raise Exception + except: + raise APIGatewayException("Parameter \"s\" must be a positive integer up to 2048.", 400) + + cached_avatar_available = False + cached_avatar_last_modified_string = None + force_fresh_gravatar_pull = False + + try: + response = s3_client.head_object( + Bucket = shared_bucket_name, + Key = get_cached_gravatar_s3_key(identity_id, image_size) + ) + + expires_datetime = datetime.strptime(response["Metadata"]["expires"], http_strftime_format) + + current_datetime = datetime.utcnow().replace(tzinfo=expires_datetime.tzinfo) + + seconds_until_expiration = int((expires_datetime - current_datetime).total_seconds()) + + if seconds_until_expiration > 0: + cached_avatar_available = True + print("Expires in {} second(s).".format(seconds_until_expiration)) + else: + print("Cached avatar expired {} second(s) ago.".format(-1 * seconds_until_expiration)) + + cached_avatar_last_modified_string = response["Metadata"].get("source-last-modified") + + if "author-avatar-hash" in response["Metadata"] and user_specified_author_avatar_hash is not None: + if user_specified_author_avatar_hash != response["Metadata"]["author-avatar-hash"]: + cached_avatar_available = False + force_fresh_gravatar_pull = True + print("Cached avatar is for a different e-mail address than user requested.") + + except botocore.exceptions.ClientError as e: + if e.response['Error']['Code'] == '404': + pass + else: + raise + + if cached_avatar_available: + print("Cached avatar not yet expired. Returning it.") + + return return_cached_object(identity_id, image_size) + + + try: + response = cognito_sync_client.list_records( + IdentityPoolId = identity_pool_id, + IdentityId = identity_id, + DatasetName = user_profile_dataset_name + ) + except botocore.exceptions.ClientError as e: + if e.response['Error']['Code'] == 'ValidationException': + raise APIGatewayException("Parameter \"user-id\" specified in path does not correspond to a valid user.", 400) + else: + raise + + user_pool_user_id = None + + for each_record in response.get("Records", []): + if each_record["Key"] == "user-id": + user_pool_user_id = each_record["Value"] + break + + if user_pool_user_id is None: + raise APIGatewayException("Parameter \"user-id\" specified in path does not correspond to a valid user.", 400) + + response = cognito_idp_client.admin_get_user( + UserPoolId = user_pool_id, + Username = user_pool_user_id + ) + + user_email_address = None + user_email_address_verified = False + user_sub = None + + for each_attribute_set in response.get("UserAttributes", []): + if each_attribute_set["Name"] == "email": + user_email_address = each_attribute_set["Value"] + elif each_attribute_set["Name"] == "email_verified": + user_email_address_verified = each_attribute_set["Value"] + elif each_attribute_set["Name"] == "sub": + user_sub = each_attribute_set["Value"] + + author_avatar_hash = hashlib.md5("{}{}".format(user_sub, user_email_address)).hexdigest() + + if user_email_address is None: + raise Exception("Unable to find e-mail address in Cogito User Pool record.") + elif not user_email_address_verified: + raise Exception("User's e-mail address is not yet verified.") + + print("Request is for avatar of user with e-mail address: {}".format(user_email_address)) + + # http://en.gravatar.com/site/implement/hash/ + email_address_gravatar_hash = hashlib.md5(user_email_address.strip().lower()).hexdigest() + + request_kwargs = { + "params": { + "s": str(image_size), + "r": "pg", + "d": "identicon" + }, + "headers": {} + } + + if cached_avatar_last_modified_string is not None and not force_fresh_gravatar_pull: + print("Last modified: {}".format(cached_avatar_last_modified_string)) + request_kwargs["headers"]["If-Modified-Since"] = cached_avatar_last_modified_string + + r = requests.get( + "https://www.gravatar.com/avatar/{}".format(email_address_gravatar_hash), + **request_kwargs + ) + + r.raise_for_status() + + if r.status_code == 304: + + print("Gravatar not modified since cached version. Returning cached version.") + + response = s3_client.copy_object( + Bucket = shared_bucket_name, + Key = get_cached_gravatar_s3_key(identity_id, image_size), + CopySource = { + "Bucket": shared_bucket_name, + "Key": get_cached_gravatar_s3_key(identity_id, image_size) + }, + MetadataDirective = "REPLACE", + Metadata = { + "Author-Avatar-Hash": author_avatar_hash, + "Expires": r.headers["Expires"], + "Source-Last-Modified": r.headers["Last-Modified"] + } + ) + + # We can keep serving our cached version. + return return_cached_object(identity_id, image_size) + + else: + # Save this new version. + + print("Caching Gravatar response image and returning live result.") + + s3_client.put_object( + Bucket = shared_bucket_name, + Key = get_cached_gravatar_s3_key(identity_id, image_size), + Body = r.content, + Metadata = { + "Author-Avatar-Hash": author_avatar_hash, + "Expires": r.headers["Expires"], + "Source-Last-Modified": r.headers["Last-Modified"] + } + ) + + return base64.b64encode(r.content) + +def get_cached_gravatar_s3_key(identity_id, image_size): + return "{}{}/{}.png".format( + cached_gravatars_prefix, + identity_id, + image_size + ) + +def return_cached_object(identity_id, image_size): + + response = s3_client.get_object( + Bucket = shared_bucket_name, + Key = get_cached_gravatar_s3_key(identity_id, image_size) + ) + + return base64.b64encode(response["Body"].read()) + +def proxy_lambda_handler(event, context): + + response_headers = get_response_headers(event, context) + + try: + return_var = lambda_handler(event, context) + except APIGatewayException as e: + return { + "statusCode": e.http_status_code, + "headers": response_headers, + "body": json.dumps({ + "message": e.http_status_message + }) + } + + return { + "statusCode": 200, + "headers": response_headers, + "body": return_var + } \ No newline at end of file diff --git a/pool/shard007/Python/0070626_zone.py b/pool/shard007/Python/0070626_zone.py new file mode 100644 index 0000000000000000000000000000000000000000..6353ac086b47f6c8f7ff55863c7777f74511642b --- /dev/null +++ b/pool/shard007/Python/0070626_zone.py @@ -0,0 +1,136 @@ +# -*- coding: utf-8 -*- + +# Copyright (2018) Hewlett Packard Enterprise Development LP +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +from oneview_redfish_toolkit.api.capabilities_object import \ + CapabilitiesObject +from oneview_redfish_toolkit.api.computer_system import ComputerSystem +from oneview_redfish_toolkit.api.redfish_json_validator \ + import RedfishJsonValidator +from oneview_redfish_toolkit.api.resource_block_collection import \ + ResourceBlockCollection +from oneview_redfish_toolkit.api import status_mapping +from oneview_redfish_toolkit.api.zone_collection import ZoneCollection +from oneview_redfish_toolkit.services.computer_system_service import \ + ComputerSystemService + + +class Zone(RedfishJsonValidator): + """Creates a Zone Redfish dict + + Populates self.redfish with Zone data retrieved from + OneView + """ + + SCHEMA_NAME = 'Zone' + + def __init__(self, + resource_id, + profile_template, + server_hardware_list, + enclosure_name, + drives=[], + volume_list=[]): + """Zone constructor + + Populates self.redfish with the contents of + server profile template and server hardware list from Oneview + + Args: + resource_id: The resource id + profile_template: Oneview's server profile template dict + server_hardware_list: Oneview's server hardware list + (servers and empty bays) for assignment to a server profile + enclosure_name: Enclosure name associated with a Zone. + If Zone has not enclosure it will be None. + drives: Oneview's dict drives list + volume_list: Oneview's storage volume list + """ + super().__init__(self.SCHEMA_NAME) + + has_valid_controller = \ + ComputerSystemService.get_storage_controller(profile_template) + + if not has_valid_controller: + drives = [] + + self.redfish["@odata.type"] = self.get_odata_type() + self.redfish["Id"] = resource_id + self.redfish["Name"] = self.get_zone_name( + profile_template["name"], enclosure_name) + status_from_ov = profile_template["status"] + self.redfish["Status"] = status_mapping.STATUS_MAP[status_from_ov] + + self.redfish["Links"] = dict() + self.redfish["Links"]["ResourceBlocks"] = list() + + self.fill_resource_blocks(profile_template, server_hardware_list, + drives, volume_list) + + self.capabilities_key = "@Redfish.CollectionCapabilities" + self.redfish[self.capabilities_key] = dict() + self.redfish[self.capabilities_key]["@odata.type"] = \ + self.get_odata_type_by_schema('CollectionCapabilities') + self.redfish[self.capabilities_key]["Capabilities"] = list() + + self.fill_capabilities_collection(profile_template) + + self.redfish["@odata.context"] = "/redfish/v1/$metadata#Zone.Zone" + self.redfish["@odata.id"] = ZoneCollection.BASE_URI + "/" +\ + self.redfish["Id"] + + self._validate() + + @staticmethod + def get_zone_name(spt_name, enclosure_name): + zone_name = spt_name + if enclosure_name: + zone_name = spt_name + " - " + enclosure_name + return zone_name + + def fill_resource_blocks(self, profile_template, server_hardware_list, + drives, volume_list): + for item in server_hardware_list: + self.add_resource_block_item_to_links(item, "uri") + + for item in drives: + self.add_resource_block_item_to_links(item, "uri") + + for item in volume_list: + self.add_resource_block_item_to_links(item, "uri") + + self.add_resource_block_item_to_links(profile_template, "uri") + + def add_resource_block_item_to_links(self, original_dict, uri_key): + uuid = original_dict[uri_key].split("/")[-1] + dict_item = dict() + dict_item["@odata.id"] = ResourceBlockCollection.BASE_URI + "/" + uuid + self.redfish["Links"]["ResourceBlocks"].append(dict_item) + + def fill_capabilities_collection(self, profile_template): + spt_id = profile_template["uri"].split("/")[-1] + capability = { + "CapabilitiesObject": { + "@odata.id": + CapabilitiesObject.BASE_URI + "/" + spt_id + }, + "UseCase": "ComputerSystemComposition", + "Links": { + "TargetCollection": { + "@odata.id": ComputerSystem.BASE_URI + } + } + } + self.redfish[self.capabilities_key]["Capabilities"].append(capability) diff --git a/pool/shard007/Python/0070627_configdb_display.py b/pool/shard007/Python/0070627_configdb_display.py new file mode 100644 index 0000000000000000000000000000000000000000..ed0f0054edfec5ee7b615c2e15fdfeab1dc365e5 --- /dev/null +++ b/pool/shard007/Python/0070627_configdb_display.py @@ -0,0 +1,16 @@ +import os +from django import template +from django.conf import settings + +register = template.Library() + + +@register.inclusion_tag('h1ds_configdb/configdb_display.html') +def show_configfile(configfile): + tag_data = {'name': os.path.basename(configfile.dbfile.name)} + ## TODO: this is a hack. fix the filename, URL path properly + tag_data['file_url'] = settings.MEDIA_URL + configfile.dbfile.name + tag_data['properties'] = [] + for p in configfile.configdbproperty_set.all(): + tag_data['properties'].append([p.configdb_propertytype.name, p.get_value()]) + return tag_data diff --git a/pool/shard007/Python/0070631_variables.py b/pool/shard007/Python/0070631_variables.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9d620c5d83cccf447b838e448a907b71f1f623 --- /dev/null +++ b/pool/shard007/Python/0070631_variables.py @@ -0,0 +1,36 @@ +import os +from optparse import make_option + + +class Variable(object): + + def __init__(self, name, default=None, environ=None, help=None, + metavar=None, prompt=None): + self.name = name + if environ: + self.default = os.environ.get(environ, default) + else: + self.default = default + self.help = help + self.metavar = metavar + self.prompt_text = prompt + + def is_valid(self, value): + return value or self.default is not None + + def prompt(self): + text = self.prompt_text or self.name.replace('_', ' ').capitalize() + if self.default: + text = '{0} [{1}]'.format(text, self.default) + while True: + value = raw_input('{0}: '.format(text)).strip() + if self.is_valid(value): + return value or self.default + + +class String(Variable): + + def add_to_parser(self, parser): + parser.add_argument('--{0}'.format(self.name.replace('_', '-')), + action='store', dest=self.name, + help=self.help, metavar=self.metavar) diff --git a/pool/shard007/Python/0070632_evaluate-senna-hash-pos-gazetteer-128-64-rmsprop5.py b/pool/shard007/Python/0070632_evaluate-senna-hash-pos-gazetteer-128-64-rmsprop5.py new file mode 100644 index 0000000000000000000000000000000000000000..16b162714d4eeedbba06c71e0574246f6ab824fc --- /dev/null +++ b/pool/shard007/Python/0070632_evaluate-senna-hash-pos-gazetteer-128-64-rmsprop5.py @@ -0,0 +1,105 @@ +''' +evaluate result +''' + +from keras.models import load_model +from keras.utils import np_utils + +import numpy as np + +import os +import sys + +# add path +sys.path.append('../') +sys.path.append('../tools') + + +from tools import conf +from tools import load_data +from tools import prepare + +# input sentence dimensions +step_length = conf.ner_step_length +pos_length = conf.ner_pos_length +chunk_length = conf.ner_chunk_length +gazetteer_length = conf.gazetteer_length + +IOB = conf.ner_IOB_decode + +data = sys.argv[1] + +best_epoch = sys.argv[2] + +if data=="dev": + test_data = load_data.load_ner(dataset='eng.testa') +elif data == "test": + test_data = load_data.load_ner(dataset='eng.testb') +tokens = [len(x[0]) for x in test_data] +print(sum(tokens)) +print('%s shape:'%data, len(test_data)) + +model_name = os.path.basename(__file__)[9:-3] +folder_path = './model/%s'%model_name + +model_path = '%s/model_epoch_%s.h5'%(folder_path, best_epoch) +result = open('%s/predict.txt'%folder_path, 'w') + +def convert(chunktags): + # convert BIOES to BIO + for p, q in enumerate(chunktags): + if q.startswith("E-"): + chunktags[p] = "I-" + q[2:] + elif q.startswith("S-"): + if p==0: + chunktags[p] = "I-" + q[2:] + elif q[2:]==chunktags[p-1][2:]: + chunktags[p] = "B-" + q[2:] + elif q[2:]!=chunktags[p-1][2:]: + chunktags[p] = "I-" + q[2:] + elif q.startswith("B-"): + if p==0: + chunktags[p] = "I-" + q[2:] + else: + if q[2:]!=chunktags[p-1][2:]: + chunktags[p] = "I-" + q[2:] + return chunktags + +print('loading model...') +model = load_model(model_path) +print('loading model finished.') + +for each in test_data: + embed_index, hash_index, pos, chunk, label, length, sentence = prepare.prepare_ner(batch=[each], gram='tri') + pos = np.array([(np.concatenate([np_utils.to_categorical(p, pos_length), np.zeros((step_length-length[l], pos_length))])) for l,p in enumerate(pos)]) + # chunk = np.array([(np.concatenate([np_utils.to_categorical(c, chunk_length), np.zeros((step_length-length[l], chunk_length))])) for l,c in enumerate(chunk)]) + gazetteer, length_2 = prepare.prepare_gazetteer(batch=[each]) + gazetteer = np.array([(np.concatenate([a, np.zeros((step_length-length_2[l], gazetteer_length))])) for l,a in enumerate(gazetteer)]) + prob = model.predict_on_batch([embed_index, hash_index, pos, gazetteer]) + + for i, l in enumerate(length): + predict_label = np_utils.categorical_probas_to_classes(prob[i]) + chunktags = [IOB[j] for j in predict_label][:l] + + word_pos_chunk = list(zip(*each)) + + # convert + word_pos_chunk = list(zip(*word_pos_chunk)) + word_pos_chunk = [list(x) for x in word_pos_chunk] +# if data == "test": +# word_pos_chunk[3] = convert(word_pos_chunk[3]) + word_pos_chunk = list(zip(*word_pos_chunk)) + + #convert +# if data == "test": +# chunktags = convert(chunktags) + # chunktags = prepare.gazetteer_lookup(each[0], chunktags, data) + for ind, chunktag in enumerate(chunktags): + result.write(' '.join(word_pos_chunk[ind])+' '+chunktag+'\n') + result.write('\n') + +result.close() +print('epoch %s predict over !'%best_epoch) + +os.system('../tools/conlleval < %s/predict.txt'%folder_path) + diff --git a/pool/shard007/Python/0070640_entity.py b/pool/shard007/Python/0070640_entity.py new file mode 100644 index 0000000000000000000000000000000000000000..810ad74b953a12207f1017b094816e859deaba78 --- /dev/null +++ b/pool/shard007/Python/0070640_entity.py @@ -0,0 +1,195 @@ +"""Classes shared among Wemo entities.""" +from __future__ import annotations + +import asyncio +from collections.abc import Generator +import contextlib +import logging + +import async_timeout +from pywemo import WeMoDevice +from pywemo.exceptions import ActionException + +from homeassistant.helpers.entity import DeviceInfo, Entity + +from .const import DOMAIN as WEMO_DOMAIN + +_LOGGER = logging.getLogger(__name__) + + +class ExceptionHandlerStatus: + """Exit status from the _wemo_exception_handler context manager.""" + + # An exception if one was raised in the _wemo_exception_handler. + exception: Exception | None = None + + @property + def success(self) -> bool: + """Return True if the handler completed with no exception.""" + return self.exception is None + + +class WemoEntity(Entity): + """Common methods for Wemo entities. + + Requires that subclasses implement the _update method. + """ + + def __init__(self, device: WeMoDevice) -> None: + """Initialize the WeMo device.""" + self.wemo = device + self._state = None + self._available = True + self._update_lock = None + self._has_polled = False + + @property + def name(self) -> str: + """Return the name of the device if any.""" + return self.wemo.name + + @property + def available(self) -> bool: + """Return true if switch is available.""" + return self._available + + @contextlib.contextmanager + def _wemo_exception_handler( + self, message: str + ) -> Generator[ExceptionHandlerStatus, None, None]: + """Wrap device calls to set `_available` when wemo exceptions happen.""" + status = ExceptionHandlerStatus() + try: + yield status + except ActionException as err: + status.exception = err + _LOGGER.warning("Could not %s for %s (%s)", message, self.name, err) + self._available = False + else: + if not self._available: + _LOGGER.info("Reconnected to %s", self.name) + self._available = True + + def _update(self, force_update: bool | None = True): + """Update the device state.""" + raise NotImplementedError() + + async def async_added_to_hass(self) -> None: + """Wemo device added to Home Assistant.""" + # Define inside async context so we know our event loop + self._update_lock = asyncio.Lock() + + async def async_update(self) -> None: + """Update WeMo state. + + Wemo has an aggressive retry logic that sometimes can take over a + minute to return. If we don't get a state within the scan interval, + assume the Wemo switch is unreachable. If update goes through, it will + be made available again. + """ + # If an update is in progress, we don't do anything + if self._update_lock.locked(): + return + + try: + async with async_timeout.timeout( + self.platform.scan_interval.total_seconds() - 0.1 + ) as timeout: + await asyncio.shield(self._async_locked_update(True, timeout)) + except asyncio.TimeoutError: + _LOGGER.warning("Lost connection to %s", self.name) + self._available = False + + async def _async_locked_update( + self, force_update: bool, timeout: async_timeout.timeout | None = None + ) -> None: + """Try updating within an async lock.""" + async with self._update_lock: + await self.hass.async_add_executor_job(self._update, force_update) + self._has_polled = True + # When the timeout expires HomeAssistant is no longer waiting for an + # update from the device. Instead, the state needs to be updated + # asynchronously. This also handles the case where an update came + # directly from the device (device push). In that case no polling + # update was involved and the state also needs to be updated + # asynchronously. + if not timeout or timeout.expired: + self.async_write_ha_state() + + +class WemoSubscriptionEntity(WemoEntity): + """Common methods for Wemo devices that register for update callbacks.""" + + @property + def unique_id(self) -> str: + """Return the id of this WeMo device.""" + return self.wemo.serialnumber + + @property + def device_info(self) -> DeviceInfo: + """Return the device info.""" + return { + "name": self.name, + "identifiers": {(WEMO_DOMAIN, self.unique_id)}, + "model": self.wemo.model_name, + "manufacturer": "Belkin", + } + + @property + def is_on(self) -> bool: + """Return true if the state is on. Standby is on.""" + return self._state + + @property + def should_poll(self) -> bool: + """Return True if the the device requires local polling, False otherwise. + + It is desirable to allow devices to enter periods of polling when the + callback subscription (device push) is not working. To work with the + entity platform polling logic, this entity needs to report True for + should_poll initially. That is required to cause the entity platform + logic to start the polling task (see the discussion in #47182). + + Polling can be disabled if three conditions are met: + 1. The device has polled to get the initial state (self._has_polled) and + to satisfy the entity platform constraint mentioned above. + 2. The polling was successful and the device is in a healthy state + (self.available). + 3. The pywemo subscription registry reports that there is an active + subscription and the subscription has been confirmed by receiving an + initial event. This confirms that device push notifications are + working correctly (registry.is_subscribed - this method is async safe). + """ + registry = self.hass.data[WEMO_DOMAIN]["registry"] + return not ( + self.available and self._has_polled and registry.is_subscribed(self.wemo) + ) + + async def async_added_to_hass(self) -> None: + """Wemo device added to Home Assistant.""" + await super().async_added_to_hass() + + registry = self.hass.data[WEMO_DOMAIN]["registry"] + await self.hass.async_add_executor_job(registry.register, self.wemo) + registry.on(self.wemo, None, self._subscription_callback) + + async def async_will_remove_from_hass(self) -> None: + """Wemo device removed from hass.""" + registry = self.hass.data[WEMO_DOMAIN]["registry"] + await self.hass.async_add_executor_job(registry.unregister, self.wemo) + + def _subscription_callback( + self, _device: WeMoDevice, _type: str, _params: str + ) -> None: + """Update the state by the Wemo device.""" + _LOGGER.info("Subscription update for %s", self.name) + updated = self.wemo.subscription_update(_type, _params) + self.hass.add_job(self._async_locked_subscription_callback(not updated)) + + async def _async_locked_subscription_callback(self, force_update: bool) -> None: + """Handle an update from a subscription.""" + # If an update is in progress, we don't do anything + if self._update_lock.locked(): + return + + await self._async_locked_update(force_update) diff --git a/pool/shard007/Python/0070646_common.py b/pool/shard007/Python/0070646_common.py new file mode 100644 index 0000000000000000000000000000000000000000..7770af74a91c1bc3e1c48cc3ae43bdc7348c95eb --- /dev/null +++ b/pool/shard007/Python/0070646_common.py @@ -0,0 +1,163 @@ +# vim:set et sts=4 sw=4: +# +# ibus - The Input Bus +# +# Copyright (c) 2007-2008 Huang Peng +# +# 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 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. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this program; if not, write to the +# Free Software Foundation, Inc., 59 Temple Place, Suite 330, +# Boston, MA 02111-1307 USA + +__all__ = ( + "IBUS_IFACE_IBUS", + "IBUS_SERVICE_IBUS", + "IBUS_PATH_IBUS", + "IBUS_IFACE_CONFIG", + "IBUS_IFACE_PANEL", + "IBUS_IFACE_ENGINE", + "IBUS_IFACE_ENGINE_FACTORY", + "IBUS_IFACE_INPUT_CONTEXT", + "IBUS_IFACE_NOTIFICATIONS", + "default_reply_handler", + "default_error_handler", + "DEFAULT_ASYNC_HANDLERS", + "CONFIG_GENERAL_SHORTCUT_TRIGGER", + "CONFIG_GENERAL_SHORTCUT_NEXT_ENGINE", + "CONFIG_GENERAL_SHORTCUT_PREV_ENGINE", + "CONFIG_GENERAL_SHORTCUT_TRIGGER_DEFAULT", + "CONFIG_GENERAL_SHORTCUT_NEXT_ENGINE_DEFAULT", + "CONFIG_GENERAL_SHORTCUT_PREV_ENGINE_DEFAULT", + "main", + "main_quit", + "main_iteration", + "get_address", + "get_socket_path" + ) + +import os +import sys +from xdg import BaseDirectory +import ctypes + +# __display = os.environ["DISPLAY"] +# __hostname, __display_screen = __display.split(":", 1) +# if not __hostname.strip(): +# __hostname = "unix" +# __display_number = __display_screen.split(".")[0] +# +# __username = None +# try: +# __username = os.getlogin() +# except: +# pass +# if not __username: +# __username = os.getenv ("LOGNAME") +# if not __username: +# __username = os.getenv ("USER") +# if not __username: +# __username = os.getenv ("LNAME") +# if not __username: +# __username = os.getenv ("USERNAME") +# libibus = ctypes.CDLL("libibus.so") +# id = ctypes.c_char_p(libibus.ibus_get_local_machine_id()).value +# +# IBUS_SOCKET_FILE = os.path.join(BaseDirectory.xdg_config_home, +# "ibus", "bus", +# "%s-%s-%s"% (id, __hostname, __display_number)) +# def get_address(): +# libibus = ctypes.CDLL("libibus.so") +# address = ctypes.c_char_p(libibus.ibus_get_address()).value +# return address +# +# address = os.getenv("IBUS_ADDRESS") +# if address: +# return address +# try: +# for l in file(IBUS_SOCKET_FILE): +# if not l.startswith("IBUS_ADDRESS="): +# continue +# address = l[13:] +# address = address.strip() +# break +# except: +# return None +# return address + +libibus = ctypes.CDLL("libibus.so.1") +get_address = libibus.ibus_get_address +get_address.restype=ctypes.c_char_p + +get_socket_path = libibus.ibus_get_socket_path +get_socket_path.restype=ctypes.c_char_p + +# __session_id = os.getenv ("IBUS_SESSION_ID") +# +# IBUS_ADDR = "unix:path=/tmp/ibus-%s%s/ibus-%s-%s" % (__username, +# "-" + __session_id if __session_id else "", +# __hostname, +# __display_number) +# IBUS_ADDR = "tcp:host=localhost,port=7799" + +IBUS_IFACE_IBUS = "org.freedesktop.IBus" +IBUS_PATH_IBUS = "/org/freedesktop/IBus" +IBUS_SERVICE_IBUS = "org.freedesktop.IBus" + +IBUS_IFACE_PANEL = "org.freedesktop.IBus.Panel" +IBUS_IFACE_CONFIG = "org.freedesktop.IBus.Config" +IBUS_IFACE_ENGINE = "org.freedesktop.IBus.Engine" +IBUS_IFACE_ENGINE_FACTORY = "org.freedesktop.IBus.EngineFactory" +IBUS_IFACE_INPUT_CONTEXT = "org.freedesktop.IBus.InputContext" +IBUS_IFACE_NOTIFICATIONS = "org.freedesktop.IBus.Notifications" + +def default_reply_handler( *args): + pass + +def default_error_handler(e): + print >> sys.stderr, e + +DEFAULT_ASYNC_HANDLERS = { + "reply_handler" : default_reply_handler, + "error_handler" : default_error_handler +} + +CONFIG_GENERAL_SHORTCUT_TRIGGER = "/general/keyboard_shortcut_trigger" +CONFIG_GENERAL_SHORTCUT_TRIGGER_DEFAULT = [ + "Ctrl+space", + "Zenkaku_Hankaku", + "Hangul"] +CONFIG_GENERAL_SHORTCUT_NEXT_ENGINE = "/general/keyboard_shortcut_next_engine" +CONFIG_GENERAL_SHORTCUT_NEXT_ENGINE_DEFAULT = [] +CONFIG_GENERAL_SHORTCUT_PREV_ENGINE = "/general/keyboard_shortcut_prev_engine" +CONFIG_GENERAL_SHORTCUT_PREV_ENGINE_DEFAULT = [] + +__mainloop = None + +def __init_main_loop(): + global __mainloop + if __mainloop == None: + import gobject + __mainloop = gobject.MainLoop() + +def main(): + __init_main_loop() + __mainloop.run() + +def main_quit(): + global __mainloop + if __mainloop: + __mainloop.quit() + +def main_iteration(may_block=False): + __init_main_loop() + return __mainloop.get_context().iteration(may_block) diff --git a/pool/shard007/Python/0070647_test_collection.py b/pool/shard007/Python/0070647_test_collection.py new file mode 100644 index 0000000000000000000000000000000000000000..b1db640efbf581b8a66fcf25a439325f4a331ed6 --- /dev/null +++ b/pool/shard007/Python/0070647_test_collection.py @@ -0,0 +1,140 @@ +# coding: utf-8 + +import os, tempfile +from tests.shared import assertException, getEmptyCol +from anki.stdmodels import addBasicModel + +from anki import Collection as aopen + +newPath = None +newMod = None + +def test_create(): + global newPath, newMod + (fd, path) = tempfile.mkstemp(suffix=".anki2", prefix="test_attachNew") + try: + os.close(fd) + os.unlink(path) + except OSError: + pass + deck = aopen(path) + # for open() + newPath = deck.path + deck.close() + newMod = deck.mod + del deck + +def test_open(): + deck = aopen(newPath) + assert deck.mod == newMod + deck.close() + +def test_openReadOnly(): + # non-writeable dir + assertException(Exception, + lambda: aopen("/attachroot.anki2")) + # reuse tmp file from before, test non-writeable file + os.chmod(newPath, 0) + assertException(Exception, + lambda: aopen(newPath)) + os.chmod(newPath, 0666) + os.unlink(newPath) + +def test_noteAddDelete(): + deck = getEmptyCol() + # add a note + f = deck.newNote() + f['Front'] = u"one"; f['Back'] = u"two" + n = deck.addNote(f) + assert n == 1 + # test multiple cards - add another template + m = deck.models.current(); mm = deck.models + t = mm.newTemplate("Reverse") + t['qfmt'] = "{{Back}}" + t['afmt'] = "{{Front}}" + mm.addTemplate(m, t) + mm.save(m) + # the default save doesn't generate cards + assert deck.cardCount() == 1 + # but when templates are edited such as in the card layout screen, it + # should generate cards on close + mm.save(m, templates=True) + assert deck.cardCount() == 2 + # creating new notes should use both cards + f = deck.newNote() + f['Front'] = u"three"; f['Back'] = u"four" + n = deck.addNote(f) + assert n == 2 + assert deck.cardCount() == 4 + # check q/a generation + c0 = f.cards()[0] + assert "three" in c0.q() + # it should not be a duplicate + assert not f.dupeOrEmpty() + # now let's make a duplicate + f2 = deck.newNote() + f2['Front'] = u"one"; f2['Back'] = u"" + assert f2.dupeOrEmpty() + # empty first field should not be permitted either + f2['Front'] = " " + assert f2.dupeOrEmpty() + +def test_fieldChecksum(): + deck = getEmptyCol() + f = deck.newNote() + f['Front'] = u"new"; f['Back'] = u"new2" + deck.addNote(f) + assert deck.db.scalar( + "select csum from notes") == int("c2a6b03f", 16) + # changing the val should change the checksum + f['Front'] = u"newx" + f.flush() + assert deck.db.scalar( + "select csum from notes") == int("302811ae", 16) + +def test_addDelTags(): + deck = getEmptyCol() + f = deck.newNote() + f['Front'] = u"1" + deck.addNote(f) + f2 = deck.newNote() + f2['Front'] = u"2" + deck.addNote(f2) + # adding for a given id + deck.tags.bulkAdd([f.id], "foo") + f.load(); f2.load() + assert "foo" in f.tags + assert "foo" not in f2.tags + # should be canonified + deck.tags.bulkAdd([f.id], "foo aaa") + f.load() + assert f.tags[0] == "aaa" + assert len(f.tags) == 2 + +def test_timestamps(): + deck = getEmptyCol() + assert len(deck.models.models) == 4 + for i in range(100): + addBasicModel(deck) + assert len(deck.models.models) == 104 + +def test_furigana(): + deck = getEmptyCol() + mm = deck.models + m = mm.current() + # filter should work + m['tmpls'][0]['qfmt'] = '{{kana:Front}}' + mm.save(m) + n = deck.newNote() + n['Front'] = 'foo[abc]' + deck.addNote(n) + c = n.cards()[0] + assert c.q().endswith("abc") + # and should avoid sound + n['Front'] = 'foo[sound:abc.mp3]' + n.flush() + assert "sound:" in c.q(reload=True) + # it shouldn't throw an error while people are editing + m['tmpls'][0]['qfmt'] = '{{kana:}}' + mm.save(m) + c.q(reload=True) diff --git a/pool/shard007/Python/0070654_trapSerial.py b/pool/shard007/Python/0070654_trapSerial.py new file mode 100644 index 0000000000000000000000000000000000000000..697e7acbcf6f1db28cd112ee1cd73b24388900c2 --- /dev/null +++ b/pool/shard007/Python/0070654_trapSerial.py @@ -0,0 +1,29 @@ +#trapSerial.py +#example to run: python trapSerial.py 0.0 1.0 10000 + +import numpy +import sys + +#takes in command-line arguments [a,b,n] +a = float(sys.argv[1]) +b = float(sys.argv[2]) +n = int(sys.argv[3]) + +def f(x): + return x*x + +def integrateRange(a, b, n): + '''Numerically integrate with the trapezoid rule on the interval from + a to b with n trapezoids. + ''' + integral = -(f(a) + f(b))/2.0 + # n+1 endpoints, but n trapazoids + for x in numpy.linspace(a,b,n+1): + integral = integral + f(x) + integral = integral* (b-a)/n + return integral + +integral = integrateRange(a, b, n) +print "With n =", n, "trapezoids, our estimate of the integral\ +from", a, "to", b, "is", integral + diff --git a/pool/shard007/Python/0070663_test_ssl.py b/pool/shard007/Python/0070663_test_ssl.py new file mode 100644 index 0000000000000000000000000000000000000000..25d2170e2a4805b588c90de66fdd6f29d51c789b --- /dev/null +++ b/pool/shard007/Python/0070663_test_ssl.py @@ -0,0 +1,199 @@ +import os +import tempfile + +from OpenSSL.crypto import dump_certificate, load_certificate, FILETYPE_PEM +from OpenSSL.SSL import Error as SSLError +from OpenSSL.version import __version__ as pyopenssl_version + +from twisted.internet import reactor +from twisted.internet.ssl import DefaultOpenSSLContextFactory +from twisted.protocols.policies import WrappingFactory +from twisted.python import log +from twisted.python.filepath import FilePath +from twisted.test.test_sslverify import makeCertificate +from twisted.web import server, static + +from txaws import exception +from txaws.client import ssl +from txaws.client.base import BaseQuery +from txaws.service import AWSServiceEndpoint +from txaws.testing.base import TXAWSTestCase + + +def sibpath(path): + return os.path.join(os.path.dirname(__file__), path) + + +PRIVKEY = sibpath("private.ssl") +PUBKEY = sibpath("public.ssl") +BADPRIVKEY = sibpath("badprivate.ssl") +BADPUBKEY = sibpath("badpublic.ssl") +PRIVSANKEY = sibpath("private_san.ssl") +PUBSANKEY = sibpath("public_san.ssl") + + +class BaseQuerySSLTestCase(TXAWSTestCase): + + def setUp(self): + self.cleanupServerConnections = 0 + name = self.mktemp() + os.mkdir(name) + FilePath(name).child("file").setContent("0123456789") + r = static.File(name) + self.site = server.Site(r, timeout=None) + self.wrapper = WrappingFactory(self.site) + pub_key = file(PUBKEY) + pub_key_data = pub_key.read() + pub_key.close() + pub_key_san = file(PUBSANKEY) + pub_key_san_data = pub_key_san.read() + pub_key_san.close() + ssl._ca_certs = [load_certificate(FILETYPE_PEM, pub_key_data), + load_certificate(FILETYPE_PEM, pub_key_san_data)] + + def tearDown(self): + ssl._ca_certs = None + # If the test indicated it might leave some server-side connections + # around, clean them up. + connections = self.wrapper.protocols.keys() + # If there are fewer server-side connections than requested, + # that's okay. Some might have noticed that the client closed + # the connection and cleaned up after themselves. + for n in range(min(len(connections), self.cleanupServerConnections)): + proto = connections.pop() + log.msg("Closing %r" % (proto,)) + proto.transport.loseConnection() + if connections: + log.msg("Some left-over connections; this test is probably buggy.") + return self.port.stopListening() + + def _get_url(self, path): + return "https://localhost:%d/%s" % (self.portno, path) + + def test_ssl_verification_positive(self): + """ + The L{VerifyingContextFactory} properly allows to connect to the + endpoint if the certificates match. + """ + context_factory = DefaultOpenSSLContextFactory(PRIVKEY, PUBKEY) + self.port = reactor.listenSSL( + 0, self.site, context_factory, interface="127.0.0.1") + self.portno = self.port.getHost().port + + endpoint = AWSServiceEndpoint(ssl_hostname_verification=True) + query = BaseQuery("an action", "creds", endpoint) + d = query.get_page(self._get_url("file")) + return d.addCallback(self.assertEquals, "0123456789") + + def test_ssl_verification_negative(self): + """ + The L{VerifyingContextFactory} fails with a SSL error the certificates + can't be checked. + """ + context_factory = DefaultOpenSSLContextFactory(BADPRIVKEY, BADPUBKEY) + self.port = reactor.listenSSL( + 0, self.site, context_factory, interface="127.0.0.1") + self.portno = self.port.getHost().port + + endpoint = AWSServiceEndpoint(ssl_hostname_verification=True) + query = BaseQuery("an action", "creds", endpoint) + d = query.get_page(self._get_url("file")) + return self.assertFailure(d, SSLError) + + def test_ssl_verification_bypassed(self): + """ + L{BaseQuery} doesn't use L{VerifyingContextFactory} + if C{ssl_hostname_verification} is C{False}, thus allowing to connect + to non-secure endpoints. + """ + context_factory = DefaultOpenSSLContextFactory(BADPRIVKEY, BADPUBKEY) + self.port = reactor.listenSSL( + 0, self.site, context_factory, interface="127.0.0.1") + self.portno = self.port.getHost().port + + endpoint = AWSServiceEndpoint(ssl_hostname_verification=False) + query = BaseQuery("an action", "creds", endpoint) + d = query.get_page(self._get_url("file")) + return d.addCallback(self.assertEquals, "0123456789") + + def test_ssl_subject_alt_name(self): + """ + L{VerifyingContextFactory} supports checking C{subjectAltName} in the + certificate if it's available. + """ + context_factory = DefaultOpenSSLContextFactory(PRIVSANKEY, PUBSANKEY) + self.port = reactor.listenSSL( + 0, self.site, context_factory, interface="127.0.0.1") + self.portno = self.port.getHost().port + + endpoint = AWSServiceEndpoint(ssl_hostname_verification=True) + query = BaseQuery("an action", "creds", endpoint) + d = query.get_page("https://127.0.0.1:%d/file" % (self.portno,)) + return d.addCallback(self.assertEquals, "0123456789") + + if pyopenssl_version < "0.12": + test_ssl_subject_alt_name.skip = ( + "subjectAltName not supported by older PyOpenSSL") + + +class CertsFilesTestCase(TXAWSTestCase): + + def setUp(self): + super(CertsFilesTestCase, self).setUp() + # set up temp dir with no certs + self.no_certs_dir = tempfile.mkdtemp() + # create certs + cert1 = makeCertificate(O="Server Certificate 1", CN="cn1") + cert2 = makeCertificate(O="Server Certificate 2", CN="cn2") + cert3 = makeCertificate(O="Server Certificate 3", CN="cn3") + # set up temp dir with one cert + self.one_cert_dir = tempfile.mkdtemp() + self.cert1 = self._write_pem(cert1, self.one_cert_dir, "cert1.pem") + # set up temp dir with two certs + self.two_certs_dir = tempfile.mkdtemp() + self.cert2 = self._write_pem(cert2, self.two_certs_dir, "cert2.pem") + self.cert3 = self._write_pem(cert3, self.two_certs_dir, "cert3.pem") + + def tearDown(self): + super(CertsFilesTestCase, self).tearDown() + os.unlink(self.cert1) + os.unlink(self.cert2) + os.unlink(self.cert3) + os.removedirs(self.no_certs_dir) + os.removedirs(self.one_cert_dir) + os.removedirs(self.two_certs_dir) + + def _write_pem(self, cert, dir, filename): + data = dump_certificate(FILETYPE_PEM, cert[1]) + full_path = os.path.join(dir, filename) + fh = open(full_path, "w") + fh.write(data) + fh.close() + return full_path + + def test_get_ca_certs_no_certs(self): + os.environ["TXAWS_CERTS_PATH"] = self.no_certs_dir + self.patch(ssl, "DEFAULT_CERTS_PATH", self.no_certs_dir) + self.assertRaises(exception.CertsNotFoundError, ssl.get_ca_certs) + + def test_get_ca_certs_with_default_path(self): + self.patch(ssl, "DEFAULT_CERTS_PATH", self.two_certs_dir) + certs = ssl.get_ca_certs() + self.assertEqual(len(certs), 2) + + def test_get_ca_certs_with_env_path(self): + os.environ["TXAWS_CERTS_PATH"] = self.one_cert_dir + certs = ssl.get_ca_certs() + self.assertEqual(len(certs), 1) + + def test_get_ca_certs_multiple_paths(self): + os.environ["TXAWS_CERTS_PATH"] = "%s:%s" % ( + self.one_cert_dir, self.two_certs_dir) + certs = ssl.get_ca_certs() + self.assertEqual(len(certs), 3) + + def test_get_ca_certs_one_empty_path(self): + os.environ["TXAWS_CERTS_PATH"] = "%s:%s" % ( + self.no_certs_dir, self.one_cert_dir) + certs = ssl.get_ca_certs() + self.assertEqual(len(certs), 1) diff --git a/pool/shard007/Python/0070673_subsystem_util.py b/pool/shard007/Python/0070673_subsystem_util.py new file mode 100644 index 0000000000000000000000000000000000000000..3c34766830a019ca2be18d9f18ecc66258d72320 --- /dev/null +++ b/pool/shard007/Python/0070673_subsystem_util.py @@ -0,0 +1,79 @@ +# coding=utf-8 +# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). +# Licensed under the Apache License, Version 2.0 (see LICENSE). + +from __future__ import (absolute_import, division, generators, nested_scopes, print_function, + unicode_literals, with_statement) + +from pants.subsystem.subsystem import Subsystem +from pants_test.option.util.fakes import create_options_for_optionables + + +def global_subsystem_instance(subsystem_type, options=None): + """Returns the global instance of a subsystem, for use in tests. + + :API: public + + :param type subsystem_type: The subclass of :class:`pants.subsystem.subsystem.Subsystem` + to create. + :param options: dict of scope -> (dict of option name -> value). + The scopes may be that of the global instance of the subsystem (i.e., + subsystem_type.options_scope) and/or the scopes of instances of the + subsystems it transitively depends on. + """ + init_subsystem(subsystem_type, options) + return subsystem_type.global_instance() + + +def init_subsystems(subsystem_types, options=None): + """Initialize subsystems for use in tests. + + Does not create an instance. This function is for setting up subsystems that the code + under test creates. + + Note that there is some redundancy between this function and BaseTest.context(for_subsystems=...). + TODO: Fix that. + + :API: public + + :param list subsystem_types: The subclasses of :class:`pants.subsystem.subsystem.Subsystem` + to create. + :param options: dict of scope -> (dict of option name -> value). + The scopes may be those of the global instances of the subsystems (i.e., + subsystem_type.options_scope) and/or the scopes of instances of the + subsystems they transitively depend on. + """ + optionables = set() + for s in subsystem_types: + if not Subsystem.is_subsystem_type(s): + raise TypeError('{} is not a subclass of `Subsystem`'.format(s)) + for si in s.known_scope_infos(): + optionables.add(si.optionable_cls) + if options: + allowed_scopes = {o.options_scope for o in optionables} + for scope in options.keys(): + if scope != '' and scope not in allowed_scopes: + raise ValueError('`{}` is not the scope of any of these subsystems: {}'.format( + scope, optionables)) + # Don't trample existing subsystem options, in case a test has set up some + # other subsystems in some other way. + updated_options = dict(Subsystem._options.items()) if Subsystem._options else {} + if options: + updated_options.update(options) + Subsystem.set_options(create_options_for_optionables(optionables, options=updated_options)) + + +def init_subsystem(subsystem_type, options=None): + """ + Singular form of :func:`pants_test.subsystem.subsystem_util.init_subsystems` + + :API: public + + :param subsystem_type: The subclass of :class:`pants.subsystem.subsystem.Subsystem` + to create. + :param options: dict of scope -> (dict of option name -> value). + The scopes may be those of the global instance of the subsystem (i.e., + subsystem_type.options_scope) and/or the scopes of instance of the + subsystem it transitively depends on. + """ + init_subsystems([subsystem_type], options) diff --git a/pool/shard007/Python/0070678_test_forgot_password.py b/pool/shard007/Python/0070678_test_forgot_password.py new file mode 100644 index 0000000000000000000000000000000000000000..c222fac868fd12bc9ed9444640087a39d9d9d044 --- /dev/null +++ b/pool/shard007/Python/0070678_test_forgot_password.py @@ -0,0 +1,30 @@ +from . import TheInternetTestCase +from helium.api import start_chrome, S, get_driver, set_driver, write, click, \ + Text, Link, kill_browser, wait_until + +class ForgotPasswordTest(TheInternetTestCase): + def get_page(self): + return "http://the-internet.herokuapp.com/forgot_password" + def test_retrieve_password(self): + email_address = self._get_temporary_email_address() + write(email_address, into="E-mail") + click("Retrieve Password") + self.assertTrue(Text("Your e-mail's been sent!").exists()) + set_driver(self.emailbox_driver) + wait_until( + self._refresh_and_check_if_exists, + timeout_secs=60, interval_secs=1 + ) + self.assertTrue(Text("no-reply@the-internet.herokuapp.com").exists()) + kill_browser() + set_driver(self.test_case_driver) + def _get_temporary_email_address(self): + self.test_case_driver = get_driver() + start_chrome("http://temp-mail.org/") + self.emailbox_driver = get_driver() + email_address = S("#email").web_element.text + set_driver(self.test_case_driver) + return email_address + def _refresh_and_check_if_exists(self): + click("Refresh") + return Link("Forgot Password from the").exists() \ No newline at end of file diff --git a/pool/shard007/Python/0070682_metacriticspider.py b/pool/shard007/Python/0070682_metacriticspider.py new file mode 100644 index 0000000000000000000000000000000000000000..5d87b7b11c9c385baa12c1d6d70e2c31159a3aa7 --- /dev/null +++ b/pool/shard007/Python/0070682_metacriticspider.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# Copyright (C) Hugo Lindström +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero 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 Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . + +from scrapy.selector import Selector +from tomahawkspider import TomahawkCrawlSpider +from tomahawk.helpers.tomahawkspiderhelper import extract, TomahawkSpiderHelper +from tomahawk.itemloaders import TomahawkItemLoader + + +class MetacriticSpider(TomahawkCrawlSpider): + + name = 'Metacritic' + + start_urls = [ + "http://www.metacritic.com/music" + ] + + genre_nav_xpath = './/ul[@class="genre_nav"]/li' + next_page_xpath = './/div[@class="page_flipper"]/span[@class="flipper next"]/a' + + current_page_name_xpath = './/ul[contains(@class, "tabs")]/li/span[@class="active"]/span/text()' + list_xpath = './/ol[contains(@class,"list_product_condensed")]/li' + + rules = ( + TomahawkCrawlSpider.follow_link_as_chart( + xpath=genre_nav_xpath, + deny=["music", "name"], + ), + TomahawkCrawlSpider.follow_link_as_next( + xpath=next_page_xpath, + allow=[r'\?page=[1-9]'] + ), + ) + + def get_current_genre(self, selector): + navList = selector.xpath(self.genre_nav_xpath) + for index, item in enumerate(navList): + if item.xpath('.//span'): + return item.xpath('.//span/text()').extract()[0].strip() + return None + + def do_create_chart(self, chart, response): + name = self.get_current_genre(chart.selector) + chart.add_value("name", name) + chart.add_value("type", TomahawkSpiderHelper.AlbumType) + chart.add_xpath("description", self.current_page_name_xpath) + return chart + + def do_parse(self, chart, response): + selector = Selector(response) + + for rank, item in enumerate(selector.xpath(self.list_xpath)): + entry = TomahawkItemLoader(selector=item) + entry.add_value("rank", rank) + entry.add_xpath("artist", './/span[@class="data"]/text()') + entry.add_xpath("album", './/a/text()') + chart.add_value("list", entry.load_item()) + + # process the item if there is no more next_pages, otherwise, return none and keep parsing + next_selector = selector.xpath(self.next_page_xpath) + if not next_selector: + self.log("No more next page! Processing") + return self.do_process_item(chart) + + next_page = extract(self.next_page_xpath+"/@href", selector)[-1:] + if next_page and int(next_page) > 9: + self.log("Maximum depth! Processing") + return self.do_process_item(chart) + + return None \ No newline at end of file diff --git a/pool/shard007/Python/0070685_url_manager_tests.py b/pool/shard007/Python/0070685_url_manager_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..0cc13bcface22d5cdc45f6e9faa417a237b31364 --- /dev/null +++ b/pool/shard007/Python/0070685_url_manager_tests.py @@ -0,0 +1,60 @@ +from tests.testing_framework.base_test_cases import BaseTestCase +from hamcrest import * +from flexmock import flexmock +from tests.testing_framework.db.environments import DBEnvironmentBuilder +from framework.db.url_manager import URLManager + + +class URLManagerTests(BaseTestCase): + + def before(self): + environment_builder = DBEnvironmentBuilder() + environment_builder._create_core_mock() + self.core_mock = environment_builder.core_mock + self.url_manager = URLManager(self.core_mock) + + def test_IsFileURL(self): + file_url = "http://test.com/file.exe" + non_file_url = "http://test.com/" + + assert_that(self.url_manager.IsFileURL(file_url)) + assert_that(self.url_manager.IsFileURL(non_file_url), is_(False)) + + def test_IsImageURL(self): + image_url = "http://test.com/file.png" + non_image_url = "http://test.com/" + + assert_that(self.url_manager.IsImageURL(image_url)) + assert_that(self.url_manager.IsImageURL(non_image_url), is_(False)) + + def test_GetURLsToVisit_filters_image_urls(self): + url_list = ["http://test.com/", + "http://test.com/one", + "http://test.com/two.png", + "http://test.com/three", + "http://test.com/four.jpg"] + + assert_that(self.url_manager.GetURLsToVisit(url_list), has_length(equal_to(3))) + + def test_IsURL(self): + http = "http://test.com/" + ftp = "ftp://test.com/" + non_url = "test.com" + + assert_that(self.url_manager.IsURL(http)) + assert_that(self.url_manager.IsURL(ftp)) + assert_that(self.url_manager.IsURL(non_url), is_(False)) + + def test_AddURLToDB_should_call_the_DB_instance_to_perform_the_work(self): + urls = ["http://test.com/file.exe", + "http://test.com/two.png", + "http://notinscope.com"] + self.core_mock.IsInScopeURL = lambda url: url != "http://notinscope.com" + self.core_mock.DB = flexmock() + self.core_mock.DB.DBHandler = flexmock() + self.core_mock.DB.should_receive("Add").times(5) # The two first URLs will be stored twice + flexmock(self.url_manager) + self.url_manager.should_receive("IsURLAlreadyAdded").and_return(False) + + for url in urls: + self.url_manager.AddURL(url) diff --git a/pool/shard007/Python/0070688_test_image_members.py b/pool/shard007/Python/0070688_test_image_members.py new file mode 100644 index 0000000000000000000000000000000000000000..5e2c8afcf3e81bf2339105054209bd5256db9062 --- /dev/null +++ b/pool/shard007/Python/0070688_test_image_members.py @@ -0,0 +1,63 @@ +# Copyright 2013 IBM Corp. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + + +from tempest.api.image import base +from tempest.lib import decorators +from tempest.lib import exceptions as lib_exc + + +class ImageMembersTest(base.BaseV1ImageMembersTest): + """Test image members""" + + @decorators.idempotent_id('1d6ef640-3a20-4c84-8710-d95828fdb6ad') + def test_add_image_member(self): + """Test adding member for image""" + image = self._create_image() + self.image_member_client.create_image_member(image, self.alt_tenant_id) + body = self.image_member_client.list_image_members(image) + members = body['members'] + members = [member['member_id'] for member in members] + self.assertIn(self.alt_tenant_id, members) + # get image as alt user + self.alt_img_cli.show_image(image) + + @decorators.idempotent_id('6a5328a5-80e8-4b82-bd32-6c061f128da9') + def test_get_shared_images(self): + """Test getting shared images""" + image = self._create_image() + self.image_member_client.create_image_member(image, self.alt_tenant_id) + share_image = self._create_image() + self.image_member_client.create_image_member(share_image, + self.alt_tenant_id) + body = self.image_member_client.list_shared_images( + self.alt_tenant_id) + images = body['shared_images'] + images = [img['image_id'] for img in images] + self.assertIn(share_image, images) + self.assertIn(image, images) + + @decorators.idempotent_id('a76a3191-8948-4b44-a9d6-4053e5f2b138') + def test_remove_member(self): + """Test removing member from image""" + image_id = self._create_image() + self.image_member_client.create_image_member(image_id, + self.alt_tenant_id) + self.image_member_client.delete_image_member(image_id, + self.alt_tenant_id) + body = self.image_member_client.list_image_members(image_id) + members = body['members'] + self.assertEmpty(members) + self.assertRaises( + lib_exc.NotFound, self.alt_img_cli.show_image, image_id) diff --git a/pool/shard007/Python/0070695_main_window.py b/pool/shard007/Python/0070695_main_window.py new file mode 100644 index 0000000000000000000000000000000000000000..f3212b1ec01a1c856c07595c64ff99facff92366 --- /dev/null +++ b/pool/shard007/Python/0070695_main_window.py @@ -0,0 +1,76 @@ +# Copyright (C) 2012 Ondrej Martinak +# +# 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 . + +from src.graphics import * +from PySide.QtGui import QMainWindow, QPainter +from PySide.QtCore import QTimer + +class MainWindow(QMainWindow): + def __init__(self, parent=None): + super(MainWindow, self).__init__(parent) + + self.setWindowTitle("arrows") + self.resize(800, 600) + + self.objects = [] + + self.circR = 20 + self.arrSize = 10 + + self.direction = "down" + + self.add(Circle(150, 150, self.circR)) + self.flyer = Circle(300, 50, self.circR) + self.add(self.flyer) + self.add(Circle(600, 300, self.circR)) + self.arrA = Arrow(150, 150, 300, 50, self.circR, self.arrSize) + self.add(self.arrA) + self.arrB = Arrow(300, 50, 600, 300, self.circR, self.arrSize) + self.add(self.arrB) + + timer = QTimer(self) + timer.timeout.connect(self.frameUpdate) + timer.start(20) + + def add(self, obj): + self.objects.append(obj) + + def frameUpdate(self): + fx, fy = self.flyer.getPos() + + if self.direction == "down": + if fy < 550: + self.flyer.move(0, 3) + else: + self.direction = "up" + else: + if fy > 50: + self.flyer.move(0, -3) + else: + self.direction = "down" + + fx, fy = self.flyer.getPos() + self.arrA.setPos(150, 150, fx, fy, self.circR, self.arrSize) + self.arrB.setPos(fx, fy, 600, 300, self.circR, self.arrSize) + + self.update() + + def paintEvent(self, painteevent): + painter = QPainter(self) + + painter.setRenderHint(QPainter.Antialiasing) + + for obj in self.objects: + obj.paint(painter) diff --git a/pool/shard007/Python/0070697_view_results.py b/pool/shard007/Python/0070697_view_results.py new file mode 100644 index 0000000000000000000000000000000000000000..791e2ea9d04722581f7fe8df12c640a33dea9656 --- /dev/null +++ b/pool/shard007/Python/0070697_view_results.py @@ -0,0 +1,95 @@ +""" +Back-end for serving the results of an election. +""" + +__authors__ = ['Waseem Ahmad ', + 'Andrew Capshaw '] + +import models +import logging +import webapp2 + +from authentication import auth +from datetime import datetime, timedelta +from models import models, webapputils + + +PAGE_NAME = '/vote/view-results' + +class ResultsHandler(webapp2.RequestHandler): + """ + Handles GET requests for the Results page. + """ + + def get(self): + """ + Serves the election data to the front-end for display. + """ + page_data = {} + + # Authenticate user + voter = auth.get_voter(self) + net_id = voter.net_id + + # Serve the election the user has requested + election_id = self.request.get('id') + if not election_id: + page_data['error_msg'] = 'No election was specified.' + webapputils.render_page(self, PAGE_NAME, page_data) + return + logging.info('%s requested election: %s', net_id, election_id) + + # Get the election from the database + election = models.Election.get(election_id) + if not election: + page_data['error_msg'] = 'Election not found.' + webapputils.render_page(self, PAGE_NAME, page_data) + return + + # Make sure user is eligible to vote + status = models.voter_status(voter, election) + if status != 'invalid_time' and not models.get_admin_status(voter, election.organization): + page_data['error_msg'] = 'You are not eligible to view results.' + webapputils.render_page(self, PAGE_NAME, page_data) + return + + if not election.result_computed: + page_data['error_msg'] = 'Election results are not available yet.' + webapputils.render_page(self, PAGE_NAME, page_data) + return + + public_result_time = election.end + if election.result_delay: + public_result_time += timedelta(seconds=election.result_delay) + + if datetime.now() < public_result_time: + # Check to see if the user is an election admin + status = models.get_admin_status(voter, election.organization) + if not status: + page_data['error_msg'] = ('Election results are not available to the public yet. ' + 'Please wait for %s longer.' % + str(public_result_time - datetime.now())[:6]) + webapputils.render_page(self, PAGE_NAME, page_data) + return + + # Write election information + for key, value in election.to_json().items(): + page_data[key] = value + page_data['voter_net_id'] = voter.net_id + page_data['positions'] = [] + + # Write position information + election_positions = election.election_positions + for election_position in election_positions: + position = {} + for key, value in election_position.to_json().items(): + position[key] = value + page_data['positions'].append(position) + + logging.info(page_data) + + webapputils.render_page(self, PAGE_NAME, page_data) + +app = webapp2.WSGIApplication([ + ('/view-results', ResultsHandler) +], debug=True) \ No newline at end of file diff --git a/pool/shard007/Python/0070708_ShaderUI.py b/pool/shard007/Python/0070708_ShaderUI.py new file mode 100644 index 0000000000000000000000000000000000000000..202c2768f3e61fe63249265c7b9e87b34394b92c --- /dev/null +++ b/pool/shard007/Python/0070708_ShaderUI.py @@ -0,0 +1,236 @@ +########################################################################## +# +# Copyright (c) 2013, Image Engine Design Inc. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above +# copyright notice, this list of conditions and the following +# disclaimer. +# +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided with +# the distribution. +# +# * Neither the name of John Haddon nor the names of +# any other contributors to this software may be used to endorse or +# promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +########################################################################## + +import os +import re +import string +import fnmatch + +import IECore + +import Gaffer +import GafferUI +import GafferScene + +########################################################################## +# Metadata +########################################################################## + +GafferUI.Metadata.registerNodeDescription( + +GafferScene.Shader, + +"""The base type for all nodes which create shaders. Use the ShaderAssignment node to assign them to objects in the scene.""", + +"name", +{ + "description" : + """The name of the shader being represented. This should be considered read-only. Use the Shader.loadShader() method to load a shader.""", + "nodeUI:section" : "header", +}, + +"parameters", +"""Where the parameters for the shader are represented.""", + +) + +########################################################################## +# PlugValueWidgets +########################################################################## + +class __ShaderNamePlugValueWidget( GafferUI.PlugValueWidget ) : + + def __init__( self, plug, **kw ) : + + row = GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, spacing = 4 ) + + GafferUI.PlugValueWidget.__init__( self, row, plug, **kw ) + + with row : + + self.__label = GafferUI.Label( "" ) + + GafferUI.Spacer( IECore.V2i( 1 ), expand=True ) + + self.__button = GafferUI.Button( "Reload" ) + self.__buttonClickedConnection = self.__button.clickedSignal().connect( Gaffer.WeakMethod( self.__buttonClicked ) ) + + self._updateFromPlug() + + def hasLabel( self ) : + + return True + + def _updateFromPlug( self ) : + + with self.getContext() : + shaderName = self.getPlug().getValue() + self.__label.setText( "

Shader : " + shaderName + "

" ) + ## \todo Disable the type check once we've got all the shader types implementing reloading properly. + nodeType = self.getPlug().node().typeName() + self.__button.setEnabled( bool( shaderName ) and ( "RenderMan" in nodeType or "OSL" in nodeType ) ) + + def __buttonClicked( self, button ) : + + node = self.getPlug().node() + node.shaderLoader().clear() + + with Gaffer.UndoContext( node.ancestor( Gaffer.ScriptNode.staticTypeId() ) ) : + node.loadShader( node["name"].getValue(), keepExistingValues = True ) + +GafferUI.PlugValueWidget.registerCreator( GafferScene.Shader.staticTypeId(), "name", __ShaderNamePlugValueWidget ) + +GafferUI.PlugValueWidget.registerCreator( GafferScene.Shader.staticTypeId(), "parameters", GafferUI.CompoundPlugValueWidget, collapsed=None ) +GafferUI.PlugValueWidget.registerCreator( GafferScene.Shader.staticTypeId(), "out", None ) +GafferUI.PlugValueWidget.registerCreator( GafferScene.Shader.staticTypeId(), "type", None ) +GafferUI.PlugValueWidget.registerCreator( GafferScene.Shader.staticTypeId(), "enabled", None ) + +########################################################################## +# NodeGadgets and Nodules +########################################################################## + +def __nodeGadgetCreator( node ) : + + return GafferUI.StandardNodeGadget( node, GafferUI.LinearContainer.Orientation.Y ) + +GafferUI.NodeGadget.registerNodeGadget( GafferScene.Shader.staticTypeId(), __nodeGadgetCreator ) + +def __parametersNoduleCreator( plug ) : + + return GafferUI.CompoundNodule( plug, GafferUI.LinearContainer.Orientation.Y, spacing = 0.2 ) + +GafferUI.Nodule.registerNodule( GafferScene.Shader.staticTypeId(), "parameters", __parametersNoduleCreator ) +GafferUI.Nodule.registerNodule( GafferScene.Shader.staticTypeId(), "name", lambda plug : None ) +GafferUI.Nodule.registerNodule( GafferScene.Shader.staticTypeId(), "type", lambda plug : None ) +GafferUI.Nodule.registerNodule( GafferScene.Shader.staticTypeId(), "enabled", lambda plug : None ) + +# we leave it to the derived class uis to register creators for the parameters.* plugs, because only the derived classes know whether +# or not networkability makes sense in each case. + +########################################################################## +# NodeFinderDialogue mode +########################################################################## + +def __shaderNameExtractor( node ) : + + if isinstance( node, GafferScene.Shader ) : + return node["name"].getValue() + else : + return "" + +GafferUI.NodeFinderDialogue.registerMode( "Shader Names", __shaderNameExtractor ) + +########################################################################## +# Shader menu +########################################################################## + +## Appends menu items for the creation of all shaders found on some searchpaths. +def appendShaders( menuDefinition, prefix, searchPaths, extensions, nodeCreator, matchExpression = "*" ) : + + menuDefinition.append( prefix, { "subMenu" : IECore.curry( __shaderSubMenu, searchPaths, extensions, nodeCreator, matchExpression ) } ) + +def __nodeName( shaderName ) : + + nodeName = os.path.split( shaderName )[-1] + nodeName = nodeName.translate( string.maketrans( ".-", "__" ) ) + return nodeName + +def __loadFromFile( menu, extensions, nodeCreator ) : + + path = Gaffer.FileSystemPath( os.getcwd() ) + path.setFilter( Gaffer.FileSystemPath.createStandardFilter( extensions ) ) + + dialogue = GafferUI.PathChooserDialogue( path, title="Load Shader", confirmLabel = "Load" ) + path = dialogue.waitForPath( parentWindow = menu.ancestor( GafferUI.ScriptWindow ) ) + + if not path : + return None + + shaderName = os.path.splitext( str( path ) )[0] + + return nodeCreator( __nodeName( shaderName ), shaderName ) + +def __shaderSubMenu( searchPaths, extensions, nodeCreator, matchExpression ) : + + if isinstance( matchExpression, str ) : + matchExpression = re.compile( fnmatch.translate( matchExpression ) ) + + shaders = set() + pathsVisited = set() + for path in searchPaths : + + if path in pathsVisited : + continue + + for root, dirs, files in os.walk( path ) : + for file in files : + if os.path.splitext( file )[1][1:] in extensions : + shaderPath = os.path.join( root, file ).partition( path )[-1].lstrip( "/" ) + if shaderPath not in shaders and matchExpression.match( shaderPath ) : + shaders.add( os.path.splitext( shaderPath )[0] ) + + pathsVisited.add( path ) + + shaders = sorted( list( shaders ) ) + categorisedShaders = [ x for x in shaders if "/" in x ] + uncategorisedShaders = [ x for x in shaders if "/" not in x ] + + shadersAndMenuPaths = [] + for shader in categorisedShaders : + shadersAndMenuPaths.append( ( shader, "/" + shader ) ) + + for shader in uncategorisedShaders : + if not categorisedShaders : + shadersAndMenuPaths.append( ( shader, "/" + shader ) ) + else : + shadersAndMenuPaths.append( ( shader, "/Other/" + shader ) ) + + result = IECore.MenuDefinition() + for shader, menuPath in shadersAndMenuPaths : + menuPath = "/".join( [ IECore.CamelCase.toSpaced( x ) for x in menuPath.split( "/" ) ] ) + result.append( + menuPath, + { + "command" : GafferUI.NodeMenu.nodeCreatorWrapper( IECore.curry( nodeCreator, __nodeName( shader ), shader ) ), + "searchText" : menuPath.rpartition( "/" )[-1].replace( " ", "" ), + }, + ) + + result.append( "/LoadDivider", { "divider" : True } ) + result.append( "/Load...", { "command" : GafferUI.NodeMenu.nodeCreatorWrapper( lambda menu : __loadFromFile( menu, extensions, nodeCreator ) ) } ) + + return result + diff --git a/pool/shard007/Python/0070712_express_route_service_providers_operations.py b/pool/shard007/Python/0070712_express_route_service_providers_operations.py new file mode 100644 index 0000000000000000000000000000000000000000..2f91abf10aaebc9800254e3925e5483b459bce3a --- /dev/null +++ b/pool/shard007/Python/0070712_express_route_service_providers_operations.py @@ -0,0 +1,103 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +import uuid +from msrest.pipeline import ClientRawResponse +from msrestazure.azure_exceptions import CloudError + +from .. import models + + +class ExpressRouteServiceProvidersOperations(object): + """ExpressRouteServiceProvidersOperations operations. + + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An object model deserializer. + :ivar api_version: Client API version. Constant value: "2017-09-01". + """ + + models = models + + def __init__(self, client, config, serializer, deserializer): + + self._client = client + self._serialize = serializer + self._deserialize = deserializer + self.api_version = "2017-09-01" + + self.config = config + + def list( + self, custom_headers=None, raw=False, **operation_config): + """Gets all the available express route service providers. + + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :return: An iterator like instance of ExpressRouteServiceProvider + :rtype: + ~azure.mgmt.network.v2017_09_01.models.ExpressRouteServiceProviderPaged[~azure.mgmt.network.v2017_09_01.models.ExpressRouteServiceProvider] + :raises: :class:`CloudError` + """ + def internal_paging(next_link=None, raw=False): + + if not next_link: + # Construct URL + url = self.list.metadata['url'] + path_format_arguments = { + 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} + query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') + + else: + url = next_link + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if self.config.generate_client_request_id: + header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) + if custom_headers: + header_parameters.update(custom_headers) + if self.config.accept_language is not None: + header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') + + # Construct and send request + request = self._client.get(url, query_parameters) + response = self._client.send( + request, header_parameters, stream=False, **operation_config) + + if response.status_code not in [200]: + exp = CloudError(response) + exp.request_id = response.headers.get('x-ms-request-id') + raise exp + + return response + + # Deserialize response + deserialized = models.ExpressRouteServiceProviderPaged(internal_paging, self._deserialize.dependencies) + + if raw: + header_dict = {} + client_raw_response = models.ExpressRouteServiceProviderPaged(internal_paging, self._deserialize.dependencies, header_dict) + return client_raw_response + + return deserialized + list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Network/expressRouteServiceProviders'} diff --git a/pool/shard007/Python/0070718_http.py b/pool/shard007/Python/0070718_http.py new file mode 100644 index 0000000000000000000000000000000000000000..d94280e8cd7d4867823c8a48f7d170b91e39ad9b --- /dev/null +++ b/pool/shard007/Python/0070718_http.py @@ -0,0 +1,102 @@ +# -*- coding: utf-8 -*- +# +# Stac - Smarter Travel Artifactory Client +# +# Copyright 2015-2016 Smarter Travel +# +# Available under the MIT license. See LICENSE for details. +# + +""" +stac.http +~~~~~~~~~ + +Clients and functionality for interacting with portions of the Artifactory JSON +API. It is typically not required for users of the Stac library to interact +with this module directly. +""" + +from __future__ import absolute_import +# pylint: disable=import-error,no-name-in-module +import distutils.version +import stac.exceptions +import stac.util + + +class VersionApiDao(object): + """HTTP DAO to get one or multiple versions of a particular artifact. + + This DAO interacts with the Artifactory API over HTTP or HTTPS. + + This class is thread safe. + """ + _logger = stac.util.get_log() + + def __init__(self, session, base_url, repo): + """Set the factory for requests session and factory for API urls. + + :param requests.Session session: Session for making HTTP requests to + the Artifactory API. This session should be configured with any required + credentials for accessing the API. + :param str|unicode base_url: Base URL to the Artifactory installation + :param str|unicode repo: Name of repository to search against. + """ + self._session = session + self._base_url = base_url + self._repo = repo + + def get_most_recent_release(self, group, artifact, remote=False): + """Get the version number of the most recent release (non-integration version) + of a particular group and artifact combination. + + :param str group: Group of the artifact to get the version of + :param str artifact: Name of the artifact to get the version of + :param bool remote: Should remote repositories be searched to find the latest + version? Note this can make the request much slower. Default is false. + :return: Version number of the most recent release + :rtype: str + :raises requests.exceptions.HTTPError: For any non-success HTTP responses + from the Artifactory API. + """ + url = self._base_url + '/api/search/latestVersion' + params = {'g': group, 'a': artifact, 'repos': self._repo, 'remote': int(remote)} + self._logger.debug("Using latest version API at %s - params %s", url, params) + + response = self._session.get(url, params=params) + response.raise_for_status() + return response.text.strip() + + def get_most_recent_versions(self, group, artifact, limit, remote=False, integration=False): + """Get a list of the version numbers of the most recent artifacts (integration + or non-integration), ordered by the version number, for a particular group and + artifact combination. + + :param str group: Group of the artifact to get versions of + :param str artifact: Name of the artifact to get versions of + :param int limit: Fetch only this many of the most recent releases + :param bool remote: Should remote repositories be searched to find the latest + versions? Note this can make the request much slower. Default is false. + :param bool integration: If true, fetch only "integration versions", otherwise + fetch only non-integration versions. + :return: Version numbers of the most recent artifacts + :rtype: list + :raises requests.exceptions.HTTPError: For any non-success HTTP responses + from the Artifactory API. + :raises ValueError: If limit is 0 or negative. + """ + if limit < 1: + raise ValueError("Releases limit must be positive") + + url = self._base_url + '/api/search/versions' + params = {'g': group, 'a': artifact, 'repos': self._repo, 'remote': int(remote)} + self._logger.debug("Using all version API at %s - params %s", url, params) + + response = self._session.get(url, params=params) + response.raise_for_status() + + json = response.json() + versions = [ + item['version'] for item in json['results'] if item['integration'] is integration] + # pylint: disable=no-member + versions.sort(key=distutils.version.LooseVersion, reverse=True) + return versions[:limit] diff --git a/pool/shard007/Python/0070721_test_cycle.py b/pool/shard007/Python/0070721_test_cycle.py new file mode 100644 index 0000000000000000000000000000000000000000..9e55129985e6b74aee3b3d574f13e7c15170ba8f --- /dev/null +++ b/pool/shard007/Python/0070721_test_cycle.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python2 +# -*- coding: utf-8 -*- +""" +Created on Thu Aug 17 23:22:43 2017 + +@author: LiuQianKevin +""" +class ListNode: + def __init__(self,data = 0, next_node = None): + self.data = data; + self.next = next_node; + +def has_cycle(L): + #base case + if(not L): return None; + + #find the start of the cycle using the length + slow = fast = L; + while(slow.next and fast.next and fast.next.next): + slow = slow.next; + fast = fast.next.next; + if(slow == fast): + #find the length of the cycle + len = 1; + while(slow.next != fast): + slow = slow.next; + len += 1; + + #use slow node and fast node to find a node in cycle, + slow = fast = L; + for _ in range(0, len): + slow = slow.next; + while(fast != slow): + fast = fast.next; + slow = slow.next; + return slow; + return None; + +def main(): + L3 = ListNode(3, None) + L2 = ListNode(2, L3) + L1 = ListNode(1, L2) + + # Should output 'L1 does not have cycle.' + assert has_cycle(L1) is None + print('L1', 'has' if has_cycle(L1) else 'does not have', 'cycle.') + + # Make it a cycle + L3.next = L2 + # Should output 'L1 has cycle, at node has value 2' + assert has_cycle(L1) is not None + assert has_cycle(L1).data == 2 + temp = has_cycle(L1) + if temp: + print('L1 has cycle, at node has value', temp.data) + else: + print('L1 does not have cycle') + + +if __name__ == '__main__': + main() diff --git a/pool/shard007/Python/0070726_test_object_formpost.py b/pool/shard007/Python/0070726_test_object_formpost.py new file mode 100644 index 0000000000000000000000000000000000000000..3a2233a6effdd1f15ba095b657af287495a36b11 --- /dev/null +++ b/pool/shard007/Python/0070726_test_object_formpost.py @@ -0,0 +1,127 @@ +# Copyright (C) 2013 eNovance SAS +# +# 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. + +import hashlib +import hmac +import time + +from six.moves.urllib import parse as urlparse + +from tempest.api.object_storage import base +from tempest.lib.common.utils import data_utils +from tempest.lib import decorators +from tempest import test + + +class ObjectFormPostTest(base.BaseObjectTest): + + metadata = {} + containers = [] + + @classmethod + def resource_setup(cls): + super(ObjectFormPostTest, cls).resource_setup() + cls.container_name = cls.create_container() + cls.object_name = data_utils.rand_name(name='ObjectTemp') + + cls.key = 'Meta' + cls.metadata = {'Temp-URL-Key': cls.key} + cls.account_client.create_update_or_delete_account_metadata( + create_update_metadata=cls.metadata) + + def setUp(self): + super(ObjectFormPostTest, self).setUp() + + # make sure the metadata has been set + account_client_metadata, _ = \ + self.account_client.list_account_metadata() + self.assertIn('x-account-meta-temp-url-key', + account_client_metadata) + self.assertEqual( + account_client_metadata['x-account-meta-temp-url-key'], + self.key) + + @classmethod + def resource_cleanup(cls): + cls.account_client.create_update_or_delete_account_metadata( + delete_metadata=cls.metadata) + cls.delete_containers() + super(ObjectFormPostTest, cls).resource_cleanup() + + def get_multipart_form(self, expires=600): + path = "%s/%s/%s" % ( + urlparse.urlparse(self.container_client.base_url).path, + self.container_name, + self.object_name) + + redirect = '' + max_file_size = 104857600 + max_file_count = 10 + expires += int(time.time()) + hmac_body = '%s\n%s\n%s\n%s\n%s' % (path, + redirect, + max_file_size, + max_file_count, + expires) + + signature = hmac.new( + self.key.encode(), hmac_body.encode(), hashlib.sha1 + ).hexdigest() + + fields = {'redirect': redirect, + 'max_file_size': str(max_file_size), + 'max_file_count': str(max_file_count), + 'expires': str(expires), + 'signature': signature} + + boundary = '--boundary--' + data = [] + for (key, value) in fields.items(): + data.append('--' + boundary) + data.append('Content-Disposition: form-data; name="%s"' % key) + data.append('') + data.append(value) + + data.append('--' + boundary) + data.append('Content-Disposition: form-data; ' + 'name="file1"; filename="testfile"') + data.append('Content-Type: application/octet-stream') + data.append('') + data.append('hello world') + + data.append('--' + boundary + '--') + data.append('') + + body = '\r\n'.join(data) + content_type = 'multipart/form-data; boundary=%s' % boundary + return body, content_type + + @decorators.idempotent_id('80fac02b-6e54-4f7b-be0d-a965b5cbef76') + @test.requires_ext(extension='formpost', service='object') + def test_post_object_using_form(self): + body, content_type = self.get_multipart_form() + + headers = {'Content-Type': content_type, + 'Content-Length': str(len(body))} + + url = "%s/%s" % (self.container_name, self.object_name) + + resp, body = self.object_client.post(url, body, headers=headers) + self.assertHeaders(resp, "Object", "POST") + + # Ensure object is available + resp, body = self.object_client.get("%s/%s%s" % ( + self.container_name, self.object_name, "testfile")) + self.assertHeaders(resp, "Object", "GET") + self.assertEqual(body.decode(), "hello world") diff --git a/pool/shard007/Python/0070730_XML2Py.py b/pool/shard007/Python/0070730_XML2Py.py new file mode 100644 index 0000000000000000000000000000000000000000..4295b3e0815847d9816c6aab2922efd16c8286c8 --- /dev/null +++ b/pool/shard007/Python/0070730_XML2Py.py @@ -0,0 +1,113 @@ +#!/usr/bin/python +## {{{ http://code.activestate.com/recipes/577267/ (r3) +''' +XML2Py - XML to Python de-serialization + +This code transforms an XML document into a Python data structure + +Usage: + deserializer = XML2Py() + python_object = deserializer.parse( xml_string ) + print xml_string + print python_object +''' + +from lxml import etree + +class XML2Py(): + + def __init__( self ): + + self._parser = parser = etree.XMLParser( remove_blank_text=True ) + self._root = None # root of etree structure + self.data = None # where we store the processed Python structure + + def parse( self, xmlString ): + ''' + processes XML string into Python data structure + ''' + self._root = etree.fromstring( xmlString, self._parser ) + self.data = self._parseXMLRoot() + return self.data + + def tostring( self ): + ''' + creates a string representation using our etree object + ''' + if self._root != None: + return etree.tostring( self._root ) + + def _parseXMLRoot( self ): + ''' + starts processing, takes care of first level idisyncrasies + ''' + childDict = self._parseXMLNode( self._root ) + return { self._root.tag : childDict["children"] } + + def _parseXMLNode( self, element ): + ''' + rest of the processing + ''' + childContainer = None # either Dict or List + + # process any tag attributes + # if we have attributes then the child container is a Dict + # otherwise a List + if element.items(): + childContainer = {} + childContainer.update( dict( element.items() ) ) + else: + childContainer = [] + + + if isinstance( childContainer, list ) and element.text: + # tag with no attributes and one that contains text + childContainer.append( element.text ) + + else: + # tag might have children, let's process them + for child_elem in element.getchildren(): + + childDict = self._parseXMLNode( child_elem ) + + # let's store our child based on container type + # + if isinstance( childContainer, dict ): + # these children are lone tag entities ( eg, 'copyright' ) + childContainer.update( { childDict["tag"] : childDict["children"] } ) + + else: + # these children are repeated tag entities ( eg, 'format' ) + childContainer.append( childDict["children"] ) + + return { "tag":element.tag, "children": childContainer } + + +def main(): + + xml_string = ''' + + + + Python is very nice. Very, very nice. + + + + + + + + + + + ''' + deserializer = XML2Py() + python_object = deserializer.parse( xml_string ) + print xml_string + print python_object + + +if __name__ == '__main__': + main() +## end of http://code.activestate.com/recipes/577267/ }}} + diff --git a/pool/shard007/Python/0070732_getAverageBigWig.py b/pool/shard007/Python/0070732_getAverageBigWig.py new file mode 100644 index 0000000000000000000000000000000000000000..75833054583d22046c852fa15b19e909da80b436 --- /dev/null +++ b/pool/shard007/Python/0070732_getAverageBigWig.py @@ -0,0 +1,42 @@ +import sys +import argparse +import math +import numpy as np +import pybedtools as bt +from deeplearning.mergedPeaksSummitAndMakeContinuousMat import show_value +from genomedatalayer import extractors + +def parseArgument(): + # Parse the input + parser=argparse.ArgumentParser(description=\ + "Get the total depth for each QTL from a list of files") + parser.add_argument("--bigwigListFileName", required=True, \ + help='Name of file with a list of bigwig names') + parser.add_argument("--bedFileName", required=True, \ + help='Name of bed file for which average signals will be computer') + parser.add_argument("--outputFileName", required=True, \ + help='Name of the file where the QTLs and their depths will be recorded') + options = parser.parse_args() + return options + +def getAverageBigWig(options): + # Get the average across each bed region for each region in a bigwig file + bed = bt.BedTool(options.bedFileName) + bedList = [interval for interval in bed] + bigwigListFile = open(options.bigwigListFileName) + bigwigList = [line.strip() for line in bigwigListFile] + bigwigListFile.close() + signalMat = np.zeros((len(bedList), len(bigwigList))) + for i in range(len(bedList)): + # Iterate through the peaks and get the average signal for each + interval = bedList[i] + for j in range(len(bigwigList)): + # Iterate through the bigwigs in groups of 10 and get the signal for each + bwe = extractors.BigwigExtractor(bigwigList[j]) + perPositionSignal = bwe([interval]) + signalMat[i,j] = np.mean(perPositionSignal[0][0][0]) + np.savetxt(options.outputFileName, signalMat, fmt='%.8f', delimiter='\t') + +if __name__=="__main__": + options = parseArgument() + getAverageBigWig(options) diff --git a/pool/shard007/Python/0070735_01-run.py b/pool/shard007/Python/0070735_01-run.py new file mode 100644 index 0000000000000000000000000000000000000000..ca278074a8d97cc9fa9ca204b94ad2373c5e5c69 --- /dev/null +++ b/pool/shard007/Python/0070735_01-run.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Test behaviour of the test running and the term program interaction.""" + +import sys +import pexpect +from testrunner import run + + +def _shellping(child, timeout=1): + """Issue a 'shellping' command. + + Raises a pexpect exception on failure. + :param timeout: timeout for the answer + """ + child.sendline('shellping') + child.expect_exact('shellpong\r\n', timeout=timeout) + + +def _wait_shell_ready(child, numtries=5): + """Wait until the shell is ready by using 'shellping'.""" + for _ in range(numtries - 1): + try: + _shellping(child) + except pexpect.TIMEOUT: + pass + else: + break + else: + # This one should fail + _shellping(child) + + +def _test_no_local_echo(child): + """Verify that there is not local echo while testing.""" + msg = 'true this should not be echoed' + child.sendline(msg) + res = child.expect_exact([pexpect.TIMEOUT, msg], timeout=1) + assert res == 0, "There should have been a timeout and not match stdin" + + +def _test_sending_newline(child): + """Verify that a empty line can be send to the node. + + The local terminal must NOT repeat the previous command. + """ + child.sendline('getchar') + child.sendline('') # send only one newline character + child.expect_exact('getchar 0x0a\r\n') + + +def _test_clean_output(child): + """Verify that only what the node sends is received.""" + child.sendline('toupper lowercase') + retline = child.readline() + assert retline.strip() == 'LOWERCASE' + + +def testfunc(child): + """Run some tests to verify the board under test behaves correctly. + + It currently tests: + + * local echo + * getting some test output without other messages + * sending empty lines + """ + child.expect_exact("Running 'tests_tools' application") + + _wait_shell_ready(child) + + # Verify there is no local and remote echo as it is disabled + _test_no_local_echo(child) + + # The node should still answer after the previous one + _shellping(child) + + # Check that the output is clean without extra terminal output + _test_clean_output(child) + + # It is possible to send an empty newline + _test_sending_newline(child) + + +if __name__ == "__main__": + sys.exit(run(testfunc)) diff --git a/pool/shard007/Python/0070738_errors.py b/pool/shard007/Python/0070738_errors.py new file mode 100644 index 0000000000000000000000000000000000000000..d7870f3a641cb297684739d60d05cf064af0644d --- /dev/null +++ b/pool/shard007/Python/0070738_errors.py @@ -0,0 +1,205 @@ +# -*- coding: utf-8 -*- +# +# This file is part of Invenio. +# Copyright (C) 2016-2018 CERN. +# +# Invenio is free software; you can redistribute it and/or modify it +# under the terms of the MIT License; see LICENSE file for more details. + +"""Records REST errors. + +All error classes in this module are inheriting from +:class:`invenio_rest.errors.RESTException` or +:class:`invenio_rest.errors.RESTValidationError`. +""" + +from __future__ import absolute_import, print_function + +from flask import request +from invenio_rest.errors import FieldError, RESTException, RESTValidationError + + +# +# Search +# +class SearchPaginationRESTError(RESTException): + """Search pagination error.""" + + code = 400 + + def __init__(self, errors=None, **kwargs): + """Initialize exception.""" + _errors = [] + if errors: + for field, messages in errors.items(): + _errors.extend([FieldError(field, msg) for msg in messages]) + super(SearchPaginationRESTError, self).__init__( + errors=_errors, **kwargs) + + +# +# Query +# +class InvalidQueryRESTError(RESTException): + """Invalid query syntax.""" + + code = 400 + description = 'Invalid query syntax.' + + +# +# CiteProc +# +class StyleNotFoundRESTError(RESTException): + """No such style.""" + + code = 400 + + def __init__(self, style=None, **kwargs): + """Initialize exception.""" + super(RESTException, self).__init__(**kwargs) + self.description = 'Style{0}could not be found.'.format( + ' "{0}" '.format(style) if style else ' ') + + +# +# PID +# +class PIDRESTException(RESTException): + """Base REST API PID exception class.""" + + def __init__(self, pid_error=None, **kwargs): + """Initialize exception.""" + super(RESTException, self).__init__(**kwargs) + self.pid_error = pid_error + + +class PIDDoesNotExistRESTError(PIDRESTException): + """Non-existent PID.""" + + code = 404 + description = 'PID does not exist.' + + +class PIDUnregisteredRESTError(PIDRESTException): + """Unregistered PID.""" + + code = 404 + description = 'PID is not registered.' + + +class PIDDeletedRESTError(PIDRESTException): + """Deleted PID.""" + + code = 410 + description = 'PID has been deleted.' + + +class PIDMissingObjectRESTError(PIDRESTException): + """PID missing object.""" + + code = 500 + + def __init__(self, pid, **kwargs): + """Initialize exception.""" + super(PIDMissingObjectRESTError, self).__init__(**kwargs) + self.description = 'No object assigned to {0}.'.format(pid) + + +class PIDRedirectedRESTError(PIDRESTException): + """Invalid redirect for destination.""" + + code = 500 + + def __init__(self, pid_type=None, **kwargs): + """Initialize exception.""" + super(PIDRedirectedRESTError, self).__init__(**kwargs) + self.description = ( + 'Invalid redirect - pid_type{0}endpoint missing.'.format( + ' "{0}" '.format(pid_type) if pid_type else ' ') + ) + + +# +# Views +# +class PIDResolveRESTError(RESTException): + """Invalid PID.""" + + code = 500 + + def __init__(self, pid=None, **kwargs): + """Initialize exception.""" + super(RESTException, self).__init__(**kwargs) + self.description = 'PID{0}could not be resolved.'.format( + ' #{0} '.format(pid) if pid else ' ') + + +class UnsupportedMediaRESTError(RESTException): + """Creating record with unsupported media type.""" + + code = 415 + + def __init__(self, content_type=None, **kwargs): + """Initialize exception.""" + super(RESTException, self).__init__(**kwargs) + content_type = content_type or request.mimetype + self.description = 'Unsupported media type "{0}".'.format(content_type) + + +class InvalidDataRESTError(RESTException): + """Invalid request body.""" + + code = 400 + description = 'Could not load data.' + + +class PatchJSONFailureRESTError(RESTException): + """Failed to patch JSON.""" + + code = 400 + description = 'Could not patch JSON.' + + +class SuggestMissingContextRESTError(RESTException): + """Missing a context value when getting record suggestions.""" + + code = 400 + + def __init__(self, ctx_field=None, **kwargs): + """Initialize exception.""" + super(RESTException, self).__init__(**kwargs) + self.description = 'Missing{0}context'.format( + ' "{0}" '.format(ctx_field) if ctx_field else ' ') + + +class SuggestNoCompletionsRESTError(RESTException): + """No completion requested when getting record suggestions.""" + + code = 400 + + def __init__(self, options=None, **kwargs): + """Initialize exception.""" + super(RESTException, self).__init__(**kwargs) + self.description = 'No completions requested.{0}'.format( + ' (options: {0})'.format(options) if options else '') + + +class JSONSchemaValidationError(RESTValidationError): + """JSONSchema validation error exception.""" + + code = 400 + + def __init__(self, error=None, **kwargs): + """Initialize exception.""" + super(RESTValidationError, self).__init__(**kwargs) + self.description = 'Validation error: {0}.'.format( + error.message if error else '') + + +class UnhandledElasticsearchError(RESTException): + """Failed to handle exception.""" + + code = 500 + description = 'An internal server error occurred when handling the ' \ + 'request.' diff --git a/pool/shard007/Python/0070745_setup.py b/pool/shard007/Python/0070745_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8b48c0a8bf08172249bbf6ae15ca5f730f240e16 --- /dev/null +++ b/pool/shard007/Python/0070745_setup.py @@ -0,0 +1,73 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# 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. +# + +import io +import os +import setuptools # type: ignore + +name = "google-cloud-api-gateway" +version = "1.2.1" +description = "API Gateway client library" +release_status = "Development Status :: 5 - Production/Stable" +url = "https://github.com/googleapis/python-api-gateway" +dependencies = [ + # NOTE: Maintainers, please do not require google-api-core>=2.x.x + # Until this issue is closed + # https://github.com/googleapis/google-cloud-python/issues/10566 + "google-api-core[grpc] >= 1.31.5, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.0", + "proto-plus >= 1.15.0", +] + +package_root = os.path.abspath(os.path.dirname(__file__)) + +readme_filename = os.path.join(package_root, "README.rst") +with io.open(readme_filename, encoding="utf-8") as readme_file: + readme = readme_file.read() + +setuptools.setup( + name=name, + version=version, + description=description, + long_description=readme, + author="Google LLC", + author_email="googleapis-packages@google.com", + license="Apache 2.0", + url=url, + packages=[ + package + for package in setuptools.PEP420PackageFinder.find() + if package.startswith("google") + ], + namespace_packages=("google", "google.cloud"), + platforms="Posix; MacOS X; Windows", + include_package_data=True, + install_requires=dependencies, + python_requires=">=3.6", + classifiers=[ + release_status, + "Intended Audience :: Developers", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Topic :: Internet", + "Topic :: Software Development :: Libraries :: Python Modules", + ], + zip_safe=False, +) diff --git a/pool/shard007/Python/0070748_editor.py b/pool/shard007/Python/0070748_editor.py new file mode 100644 index 0000000000000000000000000000000000000000..fb285858954e72ea5ea8d0f4aa592ed3e9a4d3a0 --- /dev/null +++ b/pool/shard007/Python/0070748_editor.py @@ -0,0 +1,151 @@ +import os, yaml, util +from kivy.uix.floatlayout import FloatLayout +from kivy.graphics import Color, Rectangle + + +class Cell(): + def __init__(self): + self.pattern = None + self.type = None + self.addon = None + +class EditGrid(FloatLayout): + def __init__(self, **kwargs): + super(EditGrid, self).__init__(**kwargs) + self.rows = None + self.cols = None + self.cell_width = None + self.cell_height = None + self.cells = self.load_data() + self.bind(pos=self.update_gfx) + self.bind(size=self.update_gfx) + + def on_touch_down(self, touch): + if not self.collide_point(touch.x, touch.y): + return + i_row = int( (touch.x - self.pos[0]) / self.cell_width ) + i_col = int( (touch.y - self.pos[1]) / self.cell_height ) + cell = self.cells[i_row][i_col] + if Editor.mode == 'pipe-i': + cell.type = 'pipe' + cell.pattern = '1010' + elif Editor.mode == 'pipe-x': + cell.type = 'pipe' + cell.pattern = '1111' + elif Editor.mode == 'pipe-l': + cell.type = 'pipe' + cell.pattern = '1100' + elif Editor.mode == 'pipe-t': + cell.type = 'pipe' + cell.pattern = '1110' + elif Editor.mode == 'pump': + cell.type = 'pump' + cell.pattern = '1000' + elif Editor.mode == 'valve': + if not cell.type is None: + if cell.addon == 'valve': + cell.addon = None + else: cell.addon = 'valve' + elif Editor.mode == 'gauge': + if cell.type == 'pipe' and cell.pattern.count('1') == 2: + if cell.addon == 'gauge': + cell.addon = None + else: cell.addon = 'gauge' + elif Editor.mode == 'turn-left': + if not cell.pattern is None: + cell.pattern = cell.pattern[-3:] + cell.pattern[0] + elif Editor.mode == 'turn-right': + if not cell.pattern is None: + cell.pattern = cell.pattern[-1] + cell.pattern[:-1] + elif Editor.mode == 'clear': + cell.type = None + cell.pattern = None + cell.addon = None + if Editor.mode != None: + self.save_data() + self.draw_tiles() + + def set_dimenstion(self, rows, cols): + self.rows = rows + self.cols = cols + if self.cells is None: + self.cells = [[Cell() for x in range(rows)] for y in xrange(cols)] + self.update_gfx() + + def update_gfx(self, *args): + self.cell_width = self.size[0] / self.cols + self.cell_height = self.size[1] / self.rows + self.draw_tiles() + + def save_data(self): + stream = file('data/pipeline-grid.yaml', 'w') + yaml.dump(self.cells, stream) + + def load_data(self): + if os.path.isfile('data/pipeline-grid.yaml'): + stream = file('data/pipeline-grid.yaml', 'r') + cells = yaml.load(stream) + return list(cells) + else: return None + + def draw_tiles(self, *args): + self.canvas.clear() + with self.canvas: + Color(1,1,1,1) + for i_row in range(self.rows): + for i_col in range(self.cols): + cell_x = self.pos[0] + i_row * self.cell_width + cell_y = self.pos[1] + i_col * self.cell_height + Rectangle(source=os.path.join(util.dir_img, 'ground.png'), + pos=[cell_x, cell_y], size=[self.cell_width, self.cell_height]) + cell = self.cells[i_row][i_col] + if not cell.pattern is None: + Rectangle(source=os.path.join(util.dir_img, cell.type + '-' + cell.pattern + '.png'), + pos=[cell_x, cell_y], size=[self.cell_width, self.cell_height]) + if not cell.addon is None: + Rectangle(source=os.path.join(util.dir_img, cell.addon + '.png'), + pos=[cell_x, cell_y], size=[self.cell_width, self.cell_height]) + + +class Editor: + mode = None + + @classmethod + def pipe_i(cls, touch): + cls.mode = 'pipe-i' + + @classmethod + def pipe_l(cls, touch): + cls.mode = 'pipe-l' + + @classmethod + def pipe_t(cls, touch): + cls.mode = 'pipe-t' + + @classmethod + def pipe_x(cls, touch): + cls.mode = 'pipe-x' + + @classmethod + def valve(cls, touch): + cls.mode = 'valve' + + @classmethod + def pump(cls, touch): + cls.mode = 'pump' + + @classmethod + def gauge(cls, touch): + cls.mode = 'gauge' + + @classmethod + def turn_left(cls, touch): + cls.mode = 'turn-left' + + @classmethod + def turn_right(cls, touch): + cls.mode = 'turn-right' + + @classmethod + def clear(cls, touch): + cls.mode = 'clear' \ No newline at end of file diff --git a/pool/shard007/Python/0070754_rwbench.py b/pool/shard007/Python/0070754_rwbench.py new file mode 100644 index 0000000000000000000000000000000000000000..35c7a1dbb18126faa78807d96cb8f0c541d8a1a1 --- /dev/null +++ b/pool/shard007/Python/0070754_rwbench.py @@ -0,0 +1,112 @@ +# -*- coding: utf-8 -*- +""" + RealWorldish Benchmark + ~~~~~~~~~~~~~~~~~~~~~~ + + A more real-world benchmark of Jinja2. Like the other benchmark in the + Jinja2 repository this has no real-world usefulnes (despite the name). + Just go away and ignore it. NOW! + + :copyright: (c) 2009 by the Jinja Team. + :license: BSD. +""" +import sys +from os.path import join, dirname, abspath +try: + from cProfile import Profile +except ImportError: + from profile import Profile +from pstats import Stats +ROOT = abspath(dirname(__file__)) + +from random import choice, randrange +from datetime import datetime +from timeit import Timer +from ambari_jinja2 import Environment, FileSystemLoader +from ambari_jinja2.utils import generate_lorem_ipsum +from mako.lookup import TemplateLookup +from genshi.template import TemplateLoader as GenshiTemplateLoader + + +def dateformat(x): + return x.strftime('%Y-%m-%d') + + +jinja_env = Environment(loader=FileSystemLoader(join(ROOT, 'jinja'))) +jinja_env.filters['dateformat'] = dateformat +mako_lookup = TemplateLookup(directories=[join(ROOT, 'mako')]) +genshi_loader = GenshiTemplateLoader([join(ROOT, 'genshi')]) + +class Article(object): + + def __init__(self, id): + self.id = id + self.href = '/article/%d' % self.id + self.title = generate_lorem_ipsum(1, False, 5, 10) + self.user = choice(users) + self.body = generate_lorem_ipsum() + self.pub_date = datetime.utcfromtimestamp(randrange(10 ** 9, 2 * 10 ** 9)) + self.published = True + + +class User(object): + + def __init__(self, username): + self.href = '/user/%s' % username + self.username = username + + +users = map(User, [u'John Doe', u'Jane Doe', u'Peter Somewhat']) +articles = map(Article, range(20)) +navigation = [ + ('index', 'Index'), + ('about', 'About'), + ('foo?bar=1', 'Foo with Bar'), + ('foo?bar=2&s=x', 'Foo with X'), + ('blah', 'Blub Blah'), + ('hehe', 'Haha'), +] * 5 + +context = dict(users=users, articles=articles, page_navigation=navigation) + + +jinja_template = jinja_env.get_template('index.html') +mako_template = mako_lookup.get_template('index.html') +genshi_template = genshi_loader.load('index.html') + + +def test_jinja(): + jinja_template.render(context) + +def test_mako(): + mako_template.render_unicode(**context) + + +from djangoext import django_loader, DjangoContext +def test_django(): + # not cached because django is not thread safe and does + # not cache by itself so it would be unfair to cache it here. + django_template = django_loader.get_template('index.html') + django_template.render(DjangoContext(context)) + + +def test_genshi(): + genshi_template.generate(**context).render('html', doctype='html') + + +if __name__ == '__main__': + sys.stdout.write('Realworldish Benchmark:\n') + for test in 'jinja', 'mako', 'django', 'genshi': + t = Timer(setup='from __main__ import test_%s as bench' % test, + stmt='bench()') + sys.stdout.write(' >> %-20s' % test) + sys.stdout.flush() + sys.stdout.write('\r %-20s%.4f seconds\n' % (test, t.timeit(number=200) / 200)) + + if '-p' in sys.argv: + print 'Jinja profile' + p = Profile() + p.runcall(test_jinja) + stats = Stats(p) + stats.sort_stats('time', 'calls') + stats.print_stats() diff --git a/pool/shard007/Python/0070762_omshell.py b/pool/shard007/Python/0070762_omshell.py new file mode 100644 index 0000000000000000000000000000000000000000..cc4fa456a4d35426d9776b43e1396806e07cb4a3 --- /dev/null +++ b/pool/shard007/Python/0070762_omshell.py @@ -0,0 +1,192 @@ +# Copyright 2012 Canonical Ltd. This software is licensed under the +# GNU Affero General Public License version 3 (see the file LICENSE). + +"""Python wrapper around the `omshell` utility which amends objects +inside the DHCP server. +""" + +from __future__ import ( + absolute_import, + print_function, + unicode_literals, + ) + +str = None + +__metaclass__ = type +__all__ = [ + "generate_omapi_key", + "Omshell", + ] + +import os +import re +from subprocess import ( + PIPE, + Popen, + ) +from textwrap import dedent + +from provisioningserver.utils import ( + call_capture_and_check, + ExternalProcessError, + parse_key_value_file, + tempdir, + ) + + +bad_key_pattern = re.compile("[+/]no|no[+/]", flags=re.IGNORECASE) + + +def call_dnssec_keygen(tmpdir): + path = os.environ.get("PATH", "").split(os.pathsep) + path.append("/usr/sbin") + env = dict(os.environ, PATH=os.pathsep.join(path)) + return call_capture_and_check( + ['dnssec-keygen', '-r', '/dev/urandom', '-a', 'HMAC-MD5', + '-b', '512', '-n', 'HOST', '-K', tmpdir, '-q', 'omapi_key'], + env=env) + + +def run_repeated_keygen(tmpdir): + # omshell has a bug where if the chars '/' or '+' appear either + # side of the word 'no' (in any case), it throws an error like + # "partial base64 value left over". We check for that here and + # repeatedly generate a new key until a good one is generated. + + key = None + while key is None: + key_id = call_dnssec_keygen(tmpdir) + + # Locate the file that was written and strip out the Key: field in + # it. + if not key_id: + raise AssertionError("dnssec-keygen didn't generate anything") + key_id = key_id.strip() # Remove trailing newline. + key_file_name = os.path.join(tmpdir, key_id + '.private') + parsing_error = False + try: + config = parse_key_value_file(key_file_name) + except ValueError: + parsing_error = True + if parsing_error or 'Key' not in config: + raise AssertionError( + "Key field not found in output from dnssec-keygen") + + key = config['Key'] + if bad_key_pattern.search(key) is not None: + # Force a retry. + os.remove(key_file_name) # Stop dnssec_keygen complaints. + key = None + + return key + + +def generate_omapi_key(): + """Generate a HMAC-MD5 key by calling out to the dnssec-keygen tool. + + :return: The shared key suitable for OMAPI access. + :type: string + """ + # dnssec-keygen writes out files to a specified directory, so we + # need to make a temp directory for that. + # This relies on the temporary directory being accessible only to its + # owner. + temp_prefix = "%s." % os.path.basename(__file__) + with tempdir(prefix=temp_prefix) as tmpdir: + key = run_repeated_keygen(tmpdir) + return key + + +class Omshell: + """Wrap up the omshell utility in Python. + + 'omshell' is an external executable that communicates with a DHCP daemon + and manipulates its objects. This class wraps up the commands necessary + to add and remove host maps (MAC to IP). + + :param server_address: The address for the DHCP server (ip or hostname) + :param shared_key: An HMAC-MD5 key generated by dnssec-keygen like: + $ dnssec-keygen -r /dev/urandom -a HMAC-MD5 -b 512 -n HOST omapi_key + $ cat Komapi_key.+*.private |grep ^Key|cut -d ' ' -f2- + It must match the key set in the DHCP server's config which looks + like this: + + omapi-port 7911; + key omapi_key { + algorithm HMAC-MD5; + secret "XXXXXXXXX"; #<-The output from the generated key above. + }; + omapi-key omapi_key; + """ + + def __init__(self, server_address, shared_key): + self.server_address = server_address + self.shared_key = shared_key + + def _run(self, stdin): + command = ["omshell"] + proc = Popen(command, stdin=PIPE, stdout=PIPE) + stdout, stderr = proc.communicate(stdin) + if proc.poll() != 0: + raise ExternalProcessError(proc.returncode, command, stdout) + return proc.returncode, stdout + + def create(self, ip_address, mac_address): + # The "name" is not a host name; it's an identifier used within + # the DHCP server. We just happen to use the IP address. + stdin = dedent("""\ + server {self.server_address} + key omapi_key {self.shared_key} + connect + new host + set ip-address = {ip_address} + set hardware-address = {mac_address} + set hardware-type = 1 + set name = "{ip_address}" + create + """) + stdin = stdin.format( + self=self, ip_address=ip_address, mac_address=mac_address) + + returncode, output = self._run(stdin) + # If the call to omshell doesn't result in output containing the + # magic string 'hardware-type' then we can be reasonably sure + # that the 'create' command failed. Unfortunately there's no + # other output like "successful" to check so this is the best we + # can do. + if "hardware-type" in output: + # Success. + pass + elif "can't open object: I/O error" in output: + # Host map already existed. Treat as success. + pass + else: + raise ExternalProcessError(returncode, "omshell", output) + + def remove(self, ip_address): + # The "name" is not a host name; it's an identifier used within + # the DHCP server. We just happen to use the IP address. + stdin = dedent("""\ + server {self.server_address} + key omapi_key {self.shared_key} + connect + new host + set name = "{ip_address}" + open + remove + """) + stdin = stdin.format( + self=self, ip_address=ip_address) + + returncode, output = self._run(stdin) + + # If the omshell worked, the last line should reference a null + # object. + lines = output.splitlines() + try: + last_line = lines[-1] + except IndexError: + last_line = "" + if last_line != "obj: ": + raise ExternalProcessError(returncode, "omshell", output) diff --git a/pool/shard007/Python/0070767_pmtoggle.py b/pool/shard007/Python/0070767_pmtoggle.py new file mode 100644 index 0000000000000000000000000000000000000000..19caf9e7098fd0b376aaa03fd7a8baddca82583f --- /dev/null +++ b/pool/shard007/Python/0070767_pmtoggle.py @@ -0,0 +1,57 @@ +from helpers import * +import org.bukkit.Bukkit as Bukkit +from java.util.UUID import fromString as juuid + +toggle_dict = {} +permission = "utils.pmtoggle" + +@hook.command("pmtoggle", + aliases = ["tm", "mt", "tmsg", "msgt", "pmt", "tpm"], + usage = "/ [player]", + description = "Toggle automatic sending of messages" + ) +def on_toggle_message_command(sender, command, label, args): + if not sender.hasPermission(permission) or not is_player(sender): + noperm(sender) + return True + plugin_header(sender, "Private Message Toggle") + uuid = uid(sender) + if len(args) > 0: + if len(args) > 1: + msg(sender, "&cToo many arguments!") + return True + target = Bukkit.getPlayer(args[0]) + if target: + toggle_dict[uuid] = uid(target) + msg(sender, "&2Enabled toggle so that you're now sending only to %s &2by default" % target.getDisplayName()) + else: + msg(sender, "&cThat player could not be found") + elif uuid in toggle_dict: + del toggle_dict[uuid] + msg(sender, "&2Disabled toggle successfully") + else: + msg(sender, "&cExpected a player as argument") + return True + + +@hook.event("player.AsyncPlayerChatEvent", "normal") +def on_chat(event): + if event.isCancelled(): + return + player = event.getPlayer() + uuid = uid(player) + if uuid in toggle_dict: + event.setCancelled(True) + target = Bukkit.getPlayer(juuid(toggle_dict[uuid])).getName() + runas(player, "msg %s %s" % (target, event.getMessage())) + + +@hook.event("player.PlayerQuitEvent", "normal") +def on_quit(event): + uuid = uid(event.getPlayer()) + if uuid in toggle_dict: + del toggle_dict[uuid] + for pid in list(toggle_dict): + if toggle_dict[pid] == uuid: + del toggle_dict[pid] + msg(Bukkit.getPlayer(juuid(pid)), "%s &cwent off so your Private Message Toggle has been disabled!" % Bukkit.getPlayer(juuid(uuid)).getDisplayName()) \ No newline at end of file diff --git a/pool/shard007/Python/0070769_PlyParser.py b/pool/shard007/Python/0070769_PlyParser.py new file mode 100644 index 0000000000000000000000000000000000000000..d1f2d410c7ed020d796a8fb8af5a8ab2b506c12c --- /dev/null +++ b/pool/shard007/Python/0070769_PlyParser.py @@ -0,0 +1,60 @@ +# ICE Revision: $Id$ +"""Base class for all parser classes based on PLY + +Most of this class was shamelessly stolen from the examples""" + +import sys +from PyFoam.Error import PyFoamException + +if sys.version_info < (2,3): + raise PyFoamException("Version "+str(sys.version_info)+" is not sufficient for ply (2.3 needed)") + +import PyFoam.ThirdParty.ply.lex as lex +import PyFoam.ThirdParty.ply.yacc as yacc + +import os + +from PyFoam.FoamInformation import getUserTempDir + +class PlyParser(object): + """ + Base class for a lexer/parser that has the rules defined as methods + """ + tokens = () + precedence = () + + + def __init__(self, **kw): + """Constructs the parser and the lexer""" + self.debug = kw.get('debug', 2) + self.names = { } + try: + modname = os.path.split(os.path.splitext(__file__)[0])[1] + "_" + self.__class__.__name__ + except: + modname = "parser"+"_"+self.__class__.__name__ + self.debugfile = modname + ".dbg" + self.tabmodule = modname + "_" + "parsetab" + #print self.debugfile, self.tabmodule + + # Build the lexer and parser + lex.lex(module=self, debug=self.debug) + yacc.yacc(module=self, + debug=self.debug, + debugfile=self.debugfile, + tabmodule=self.tabmodule, + outputdir=getUserTempDir(), + check_recursion=self.debug) + self.lex=lex + self.yacc=yacc + + def parse(self,content): + """Do the actual parsing + :param content: String that is to be parsed + :return: Result of the parsing""" + + if self.debug: + debug=10 + else: + debug=0 + + return yacc.parse(content,debug=debug) diff --git a/pool/shard007/Python/0070771_app.py b/pool/shard007/Python/0070771_app.py new file mode 100644 index 0000000000000000000000000000000000000000..469131944844fa2c285b3341d5b073ab295ea1a4 --- /dev/null +++ b/pool/shard007/Python/0070771_app.py @@ -0,0 +1,173 @@ +import wx + + + +class NotEmptyValidator(wx.PyValidator): + def __init__(self, person, key): + wx.PyValidator.__init__(self) + self._person = person + self._key = key + + def Clone(self): + return NotEmptyValidator(self._person, self._key) + + def TransferToWindow(self): + win = self.GetWindow() + win.SetValue(self._person.get(self._key, '')) + return True + + def TransferFromWindow(self): + win = self.GetWindow() + self._person[self._key] = win.GetValue() + return True + + def Validate(self, ctl): + win = self.GetWindow() + val = win.GetValue().strip() + if val == '': + msg = '%s: non deve essere vuoto.' % win.GetName() + wx.MessageBox(msg) + return False + else: + return True + + +class AgeValidator(wx.PyValidator): + def __init__(self, person): + wx.PyValidator.__init__(self) + self._person = person + + def Clone(self): return AgeValidator(self._person) + + def Validate(self, win): return True # non facciamo validazione + + def TransferToWindow(self): + win = self.GetWindow() + win.SetRange(0, 100) # minimo e massimo + win.SetValue(self._person.get('eta', 20)) # valore di default + return True + + def TransferFromWindow(self): + win = self.GetWindow() + self._person['eta'] = win.GetValue() + return True + + +class PersonDialog(wx.Dialog): + def __init__(self, *a, **k): + print 'LATO APP - PersonDialog.OnInit' + + wx.Dialog.__init__(self, *a, **k) + person = self.GetParent().current_person + self.first_name = wx.TextCtrl( + self, name='Nome', + validator=NotEmptyValidator(person, 'nome') + ) + self.family_name = wx.TextCtrl( + self, name='Cognome', + validator=NotEmptyValidator(person, 'cognome') + ) + self.year = wx.SpinCtrl(self, name="Eta'") + self.year.SetValidator(AgeValidator(person)) + ok = wx.Button(self, wx.ID_OK, 'conferma') + cancel = wx.Button(self, wx.ID_CANCEL, 'annulla') + + s = wx.FlexGridSizer(3, 2, 5, 5) + s.AddGrowableCol(1) + for ctl, lab in ( + (self.first_name, 'nome:'), + (self.family_name, 'cognome:'), + (self.year, "eta':") + ): + s.Add(wx.StaticText(self, -1, lab), 0, wx.ALIGN_CENTER_VERTICAL) + s.Add(ctl, 1, wx.EXPAND) + + s1 = wx.BoxSizer() + s1.Add(ok, 1, wx.EXPAND | wx.ALL, 5) + s1.Add(cancel, 1, wx.EXPAND | wx.ALL, 5) + + s2 = wx.BoxSizer(wx.VERTICAL) + s2.Add(s, 1, wx.EXPAND | wx.ALL, 5) + s2.Add(s1, 0, wx.EXPAND) + self.SetSizer(s2) + s2.Fit(self) + + +class TopFrame(wx.Frame): + def __init__(self, *a, **k): + print 'LATO APP - TopFrame.OnInit' + + wx.Frame.__init__(self, *a, **k) + p = wx.Panel(self) + self.people = wx.ListBox(p) + self.people.Bind(wx.EVT_LISTBOX_DCLICK, self.on_view_person) + new = wx.Button(p, -1, 'Add a person') + new.Bind(wx.EVT_BUTTON, self.on_new) + # Per unittest + self.bottone = new + + s = wx.BoxSizer(wx.VERTICAL) + s.Add(self.people, 1, wx.EXPAND | wx.ALL, 5) + s.Add(new, 0, wx.EXPAND | wx.ALL, 5) + p.SetSizer(s) + + self.current_person = {} + self.reload_people_list() + + + def reload_people_list(self): + self.people.Clear() + people = wx.GetApp().PEOPLE + for p in people: + s = '%i: %s %s %i' % ( + p, people[p]['nome'], + people[p]['cognome'], + people[p]['eta'] + ) + self.people.Append(s) + self.current_person = {} + + def on_view_person(self, evt): + app = wx.GetApp() + selected = self.people.GetString(evt.GetSelection()) + # questo e' molto brutto, ma e' per fare in fretta.... + id = int(selected.split(':')[0]) + self.current_person = app.PEOPLE[id] + self.prova = PersonDialog(self, title='Vedi persona') + ret = self.prova.ShowModal() + if ret == wx.ID_OK: + app.PEOPLE[id] = self.current_person + self.reload_people_list() + self.prova.Destroy() + + + + def on_new(self, evt): + print 'LATO APP - on=new' + self.current_person = {} + self.dialog = PersonDialog(self, title='Nuova persona') + ret = self.dialog.ShowModal() + if ret == wx.ID_OK: + app = wx.GetApp() + id = max(app.PEOPLE.keys()) + 1 + app.PEOPLE[id] = self.current_person + self.reload_people_list() + self.dialog.Destroy() + + +class WxApp(wx.App): + def OnInit(self): + print 'LATO APP - WxApp.OnInit' + + self.PEOPLE = {1: {'nome': 'Mario', 'cognome': 'Rossi', 'eta': 37}, + 2: {'nome': 'Giuseppe', 'cognome': 'Bianchi', 'eta': 25}, + 3: {'nome': 'Andrea', 'cognome': 'Verdi', 'eta': 42}} + self.top_frame = TopFrame(None, title='Persone', size=(300, 300)) + self.top_frame.Show() + return True + +if __name__ == "__main__": + print 'prima' + app = WxApp(False) + app.MainLoop() + print 'dopo\n' diff --git a/pool/shard007/Python/0070775_hipchat.py b/pool/shard007/Python/0070775_hipchat.py new file mode 100644 index 0000000000000000000000000000000000000000..9b6bf3f8fd0ffe5a7d2ca78369d5cddec222d6cd --- /dev/null +++ b/pool/shard007/Python/0070775_hipchat.py @@ -0,0 +1,57 @@ +import logging +import requests + +from redash.destinations import * +from redash.models import Alert +from redash.utils import json_dumps + + +colors = { + Alert.OK_STATE: 'green', + Alert.TRIGGERED_STATE: 'red', + Alert.UNKNOWN_STATE: 'yellow' +} + + +class HipChat(BaseDestination): + @classmethod + def configuration_schema(cls): + return { + "type": "object", + "properties": { + "url": { + "type": "string", + "title": "HipChat Notification URL (get it from the Integrations page)" + }, + }, + "required": ["url"] + } + + @classmethod + def icon(cls): + return 'fa-comment-o' + + def notify(self, alert, query, user, new_state, app, host, options): + try: + alert_url = '{host}/alerts/{alert_id}'.format(host=host, alert_id=alert.id) + query_url = '{host}/queries/{query_id}'.format(host=host, query_id=query.id) + + message = u'{alert_name} changed state to {new_state} (based on
this query).'.format( + alert_name=alert.name, new_state=new_state.upper(), + alert_url=alert_url, + query_url=query_url) + + data = { + 'message': message, + 'color': colors.get(new_state, 'green') + } + headers = {'Content-Type': 'application/json'} + response = requests.post(options['url'], data=json_dumps(data), headers=headers, timeout=5.0) + + if response.status_code != 204: + logging.error('Bad status code received from HipChat: %d', response.status_code) + except Exception: + logging.exception("HipChat Send ERROR.") + + +register(HipChat) diff --git a/pool/shard007/Python/0070780_urls.py b/pool/shard007/Python/0070780_urls.py new file mode 100644 index 0000000000000000000000000000000000000000..9559554e9ae05e2612beb35bc3e6e4e222aaf914 --- /dev/null +++ b/pool/shard007/Python/0070780_urls.py @@ -0,0 +1,16 @@ +from django.conf.urls import include, url +from . import views + +""" +urlpatterns = [ + url(r'^$', views.browse, name='home'), + url(r'^(?P[a-zA-Z0-9]+)(?:/)$', views.browse, name='browse'), + url(r'^(?P[a-zA-Z0-9]+):(?P[a-zA-Z0-9]+)(?:/)$', views.browse, name='browse') +] +""" + +urlpatterns = [ + url(r'^$', views.index, name='homepage'), + url(r'^(?P[a-zA-Z0-9\-]+)/$', views.standalonePage, name='page'), + url(r'^(?P[a-zA-Z0-9\-]+)/(?P[a-zA-Z0-9\-]+)/$', views.categorizedPage, name='catPage') +] diff --git a/pool/shard007/Python/0070784_test_markup.py b/pool/shard007/Python/0070784_test_markup.py new file mode 100644 index 0000000000000000000000000000000000000000..87ae4608810b794b5f3ec3f8191351cbe548904d --- /dev/null +++ b/pool/shard007/Python/0070784_test_markup.py @@ -0,0 +1,172 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2015 nexB Inc. and others. All rights reserved. +# http://nexb.com and https://github.com/nexB/scancode-toolkit/ +# The ScanCode software is licensed under the Apache License version 2.0. +# Data generated with ScanCode require an acknowledgment. +# ScanCode is a trademark of nexB Inc. +# +# You may not use this software except in compliance with the License. +# You may obtain a copy of the License at: http://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. +# +# When you publish or redistribute any data created with ScanCode or any ScanCode +# derivative work, you must accompany this data with the following acknowledgment: +# +# Generated with ScanCode and provided on an "AS IS" BASIS, WITHOUT WARRANTIES +# OR CONDITIONS OF ANY KIND, either express or implied. No content created from +# ScanCode should be considered or used as legal advice. Consult an Attorney +# for any legal advice. +# ScanCode is a free software code scanning tool from nexB Inc. and others. +# Visit https://github.com/nexB/scancode-toolkit/ for support and download. + +from __future__ import absolute_import +from __future__ import print_function +from __future__ import unicode_literals + +import os + +from commoncode.testcase import FileBasedTesting +from commoncode.testcase import file_cmp +from commoncode import fileutils +from commoncode import text + +from textcode import markup + + +class TestMarkup(FileBasedTesting): + test_data_dir = os.path.join(os.path.dirname(__file__), 'data') + + def atest_gen(self): + """ + Rename to test xxx to regen tests. + """ + test_dir = self.get_test_loc(u'markup', True) + expected_dir = self.get_test_loc(u'markup_expected') + template = u""" + def test_%(tn)s(self): + test_file = self.get_test_loc(u'markup/%(test_file)s') + expected = self.get_test_loc(u'markup_expected/%(test_file)s') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True)""" + + for test_file in os.listdir(test_dir): + tn = text.python_safe_name(test_file) + location = os.path.join(test_dir, test_file) + result = markup.convert_to_text(location) + expected_file = os.path.join(expected_dir, test_file) + fileutils.copyfile(result, expected_file) + print(template % locals()) + + def test_404_htm(self): + test_file = self.get_test_loc(u'markup/404.htm') + expected = self.get_test_loc(u'markup_expected/404.htm') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True) + + def test_a_htm(self): + test_file = self.get_test_loc(u'markup/a.htm') + expected = self.get_test_loc(u'markup_expected/a.htm') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True) + + def test_allclasses_frame_html(self): + test_file = self.get_test_loc(u'markup/allclasses-frame.html') + expected = self.get_test_loc(u'markup_expected/allclasses-frame.html') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True) + + def test_chinese_htm(self): + test_file = self.get_test_loc(u'markup/chinese.htm') + expected = self.get_test_loc(u'markup_expected/chinese.htm') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True) + + def test_contenttype_html(self): + test_file = self.get_test_loc(u'markup/contenttype.html') + expected = self.get_test_loc(u'markup_expected/contenttype.html') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True) + + def test_double_pygment_in_html_html(self): + # FIXME: the output is still markup. we need a second pass + test_file = self.get_test_loc(u'markup/double_pygment_in_html.html') + expected = self.get_test_loc(u'markup_expected/double_pygment_in_html.html') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True) + + def test_json_phps(self): + test_file = self.get_test_loc(u'markup/JSON.phps') + expected = self.get_test_loc(u'markup_expected/JSON.phps') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True) + + def test_json_phps_html(self): + test_file = self.get_test_loc(u'markup/JSON.phps.html') + expected = self.get_test_loc(u'markup_expected/JSON.phps.html') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True) + + def test_label_html(self): + test_file = self.get_test_loc(u'markup/Label.html') + expected = self.get_test_loc(u'markup_expected/Label.html') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True) + + def test_lgpl_license_html(self): + test_file = self.get_test_loc(u'markup/lgpl_license.html') + expected = self.get_test_loc(u'markup_expected/lgpl_license.html') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True) + + def test_pdl_html(self): + test_file = self.get_test_loc(u'markup/PDL.html') + expected = self.get_test_loc(u'markup_expected/PDL.html') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True) + + def test_php_php(self): + test_file = self.get_test_loc(u'markup/php.php') + expected = self.get_test_loc(u'markup_expected/php.php') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True) + + def test_php_highlighted_in_html_html(self): + # FIXME: the output is still markup. we need a second pass + test_file = self.get_test_loc(u'markup/php_highlighted_in_html.html') + expected = self.get_test_loc(u'markup_expected/php_highlighted_in_html.html') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True) + + def test_rst_highlighted_html(self): + test_file = self.get_test_loc(u'markup/rst_highlighted.html') + expected = self.get_test_loc(u'markup_expected/rst_highlighted.html') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True) + + def test_services_htm(self): + test_file = self.get_test_loc(u'markup/services.htm') + expected = self.get_test_loc(u'markup_expected/services.htm') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True) + + def test_sissl_license_html(self): + test_file = self.get_test_loc(u'markup/sissl_license.html') + expected = self.get_test_loc(u'markup_expected/sissl_license.html') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True) + + def test_text_phps(self): + test_file = self.get_test_loc(u'markup/text.phps') + expected = self.get_test_loc(u'markup_expected/text.phps') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True) + + def test_us_htm(self): + test_file = self.get_test_loc(u'markup/us.htm') + expected = self.get_test_loc(u'markup_expected/us.htm') + result = markup.convert_to_text(test_file) + file_cmp(expected, result, ignore_line_endings=True) diff --git a/pool/shard007/Python/0070791_test_runner.py b/pool/shard007/Python/0070791_test_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..1363f91cd2c8f0731246cfb39962c5870fd97980 --- /dev/null +++ b/pool/shard007/Python/0070791_test_runner.py @@ -0,0 +1,61 @@ +from __future__ import unicode_literals +from __future__ import absolute_import + +try: + from unittest import mock +except ImportError: + import mock +import logging +import tempfile + +from unittest import TestCase + +from pytui.runner import PytestRunner, Runner + + +logging.basicConfig() +logger = logging.getLogger(__name__) +logger.setLevel('DEBUG') + + +class PytestRunnerTests(TestCase): + def setUp(self): + self.pipe_mock = tempfile.TemporaryFile() + self.pipe_size_mock = mock.Mock() + self.pipe_semaphore_mock = mock.Mock() + + def test_skipping(self): + runner = PytestRunner( + self.pipe_mock.fileno(), + self.pipe_size_mock, + self.pipe_semaphore_mock + ) + with mock.patch.object(PytestRunner, 'pipe_send') as pipe_send_mock: + logger.debug('------ runner init ------') + exitcode, _description = runner.init_tests(['test_projects/test_module_a/']) + assert exitcode == 0 + # logger.debug(pipe_send_mock.call_args_list) + + logger.debug('------ runner run_tests ------') + exitcode, _description = runner.run_tests(False, 'xfail', ['test_projects/test_module_a/']) + assert exitcode == 1 + logger.debug(pipe_send_mock.call_args_list) + + @mock.patch.object(PytestRunner, 'init_tests', return_value=(1, None)) + @mock.patch.object(Runner, 'pipe_send') + def test_pytest_exitcode(self, pipe_send_mock, init_tests_mock): + """ + Test whether set_pytest_error(exitcode=1) is sent to ui from runner throught the pipe. + """ + PytestRunner.process_init_tests( + self.pipe_mock.fileno(), + self.pipe_size_mock, + self.pipe_semaphore_mock, + True, + ['test_projects/test_module_a/'], + ) + + assert pipe_send_mock.call_args_list == [ + mock.call('set_pytest_error', exitcode=1, description=None), + mock.call('init_finished') + ] diff --git a/pool/shard007/Python/0070796_generate_registry.py b/pool/shard007/Python/0070796_generate_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..4aa1216b79fe6a3c7edf27daea5ef760bfb8ff18 --- /dev/null +++ b/pool/shard007/Python/0070796_generate_registry.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python +'''This script grabs the currently registered IANA link relations and +TLDs from iana.org + +''' + +from __future__ import print_function +from __future__ import unicode_literals + +import re +import sys +import codecs + +# we want to write in utf-8 in this script +sys.stdout = codecs.getwriter('utf8')(sys.stdout) + +import requests +try: + from lxml import objectify +except ImportError: + print("This script shouldn't need to be run by end users. But if you " + "need to run it, you should install lxml first.") +import datetime + + +def linewrap(chunks, width=None, sep=' ', preamble='', line_prefix=''): + r'''Takes an iterator of strings, and attempts to wrap them in whole chunks + to fit within width. Takes an optional preamble which is prepended before + the first line, and an optional per-line prefix (which is appended to every + line but the first). If return_gen is true, this function returns a + generator that will produce the lines of output as needed, otherwise it + returns a single joined string''' + sep_len = len(sep) + + if isinstance(chunks, basestring): + chunks = chunks.split() + if preamble: + chunks[0] = preamble + chunks[0] + + def line_len(line): + r'Gets the full length of a line passed a list of strings' + word_len = sum(len(l) for l in line) + seps_len = sep_len * (len(line) - 1) + return word_len + seps_len if seps_len >= 0 else 0 + + def gen(): + r'The generator to incrementally create lines from the input' + sep_len = len(sep) + line = [] + for chunk in chunks: + if line_len(line) + len(chunk) + sep_len > width: + yield sep.join(line) + line = [line_prefix + chunk] + else: + line.append(chunk) + if line: + yield sep.join(line) + + return gen() + +def emit_iana_rels(rels_url): + '''Fetches the IANA link relation registry''' + text = requests.get(rels_url).text.encode('ascii', 'ignore') + xml = objectify.fromstring(text) + iana_rels = {str(rec.value): str(rec.description) + for rec in xml.registry.record} + keys = sorted(iana_rels) + print('# IANA link relation registry last updated on:', xml.updated) + print('# Obtained from', rels_url) + print() + print('iana_rels = {') + for key in keys: + print(' {0!r}: ('.format(key)) + desc_list = list(linewrap(iana_rels[key], width=68)) + for i, line in enumerate(desc_list): + line_ = line.replace('"', '\\"') # escape double quotes + if i < len(desc_list) - 1: + print(' "{0} "'.format(line_)) + else: + print(' "{0}"'.format(line_)) + print(' ),') + print('}') + +def emit_iana_tlds(tlds_url): + lines = requests.get(tlds_url).text.splitlines() + regex = re.compile('Version (?P\d{4})(?P\d{2})(?P\d{2})') + pieces = re.search(regex, lines.pop(0)).groupdict() + + print('# Obtained from', tlds_url) + print('# TLDs last updated: {year}-{month}-{day}\n'.format(**pieces)) + + def fixup(tld): + if tld.startswith('XN--'): + ret = tld.encode('ascii')[4:].decode('punycode') + else: + ret = tld.lower() + return "'{}'".format(ret) + print('\n'.join(linewrap(map(fixup, lines), + width=75, + line_prefix=' ', + preamble='tlds = set([', + sep=', ')), end='])\n') + +def emit_preamble(): + print('# -*- coding: utf-8 -*-') + print('from __future__ import unicode_literals') + print('# This file was autogenerated by', __file__) + print() + print('# This file generated on:', datetime.date.today()) + print() + +def main(): + # location where registry is stored in xml format + rels_url = ('http://www.iana.org/assignments/link-relations/' + 'link-relations.xml') + tlds_url = 'http://data.iana.org/TLD/tlds-alpha-by-domain.txt' + + emit_preamble() + emit_iana_rels(rels_url) + print() + print() + emit_iana_tlds(tlds_url) + + +if __name__ == '__main__': + main() diff --git a/pool/shard007/Python/0070801_parsers.py b/pool/shard007/Python/0070801_parsers.py new file mode 100644 index 0000000000000000000000000000000000000000..fd816d870a47d57d1ce2039f7673c83ef418bd1d --- /dev/null +++ b/pool/shard007/Python/0070801_parsers.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +"""Parser for the API.""" +from collections import OrderedDict +from json import loads + +from django.conf import settings +from django.utils.six import text_type +from rest_framework.exceptions import ParseError +from rest_framework.parsers import JSONParser as BaseJSONParser + + +class JSONParser(BaseJSONParser): + dict_class = OrderedDict + + def parse(self, stream, media_type=None, parser_context=None): + """Parse JSON-serialized data. + + Same as base JSONParser, but uses dict_class to preserve order. + """ + parser_context = parser_context or {} + encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) + + try: + data = stream.read().decode(encoding) + return loads(data, object_pairs_hook=self.dict_class) + except ValueError as exc: + raise ParseError('JSON parse error - %s' % text_type(exc)) diff --git a/pool/shard007/Python/0070809_move_message.py b/pool/shard007/Python/0070809_move_message.py new file mode 100644 index 0000000000000000000000000000000000000000..13dc0cf40145eed7c1538d7b0e1956919fd2f562 --- /dev/null +++ b/pool/shard007/Python/0070809_move_message.py @@ -0,0 +1,18 @@ +import sys + +from examples import acquire_token_by_username_password +from office365.graph_client import GraphClient +from office365.outlook.mail.messages.message import Message + +client = GraphClient(acquire_token_by_username_password) + +my_mail_folders = client.me.mail_folders.filter("displayName eq 'Archive'").get().execute_query() +if len(my_mail_folders) == 0: + sys.exit("Mail folder not found") + +message = client.me.messages.add() # type: Message +message.subject = "Meet for lunch?" +message.body = "The new cafeteria is open." +message.to_recipients = ["fannyd@contoso.onmicrosoft.com"] +message.move(my_mail_folders[0].id).execute_query() +print("Draft message is created && moved into {0} folder".format(my_mail_folders[0].display_name)) diff --git a/pool/shard007/Python/0070814_haze_detection.py b/pool/shard007/Python/0070814_haze_detection.py new file mode 100644 index 0000000000000000000000000000000000000000..80691e47c65915f71df2d5336d29bc417c368d79 --- /dev/null +++ b/pool/shard007/Python/0070814_haze_detection.py @@ -0,0 +1,85 @@ +import cv2 +import os,sys +from multiprocessing.pool import ThreadPool +import numpy as np +from collections import deque + +max_value=255 + +def sinv(x): + global max_value + return max(x,max_value-x) + +def semi_inverse_image(image): + func = np.vectorize(sinv) + image[:,:,0]=func(image[:,:,0]) + image[:,:,1]=func(image[:,:,1]) + image[:,:,2]=func(image[:,:,2]) + return image + +def difference(image,sinv): + hsv1 = cv2.cvtColor(image,cv2.COLOR_BGR2HSV) + hsv2 = cv2.cvtColor(sinv,cv2.COLOR_BGR2HSV) + return cv2.absdiff(hsv1[:,:,0],hsv2[:,:,0]) + +def percentage(difference,rho): + count = 0 + count = (differencethreshold: + return True + else: + return False + +def processImage(image,rho,threshold): + #get semi-inverse + func = np.vectorize(sinv) + semi_inverse = image.copy() + semi_inverse[:,:,0]=func(semi_inverse[:,:,0]) + semi_inverse[:,:,1]=func(semi_inverse[:,:,1]) + semi_inverse[:,:,2]=func(semi_inverse[:,:,2]) + #get absolute difference + hsv1 = cv2.cvtColor(image,cv2.COLOR_BGR2HSV) + hsv2 = cv2.cvtColor(semi_inverse,cv2.COLOR_BGR2HSV) + diff = cv2.absdiff(hsv1[:,:,0],hsv2[:,:,0]) + #count number of values below rho + count = (diffthreshold: + return True + else: + return False + +def processVideoThreaded(video,rho,threshold): + cap = cv2.VideoCapture(video) + image_queue = deque() + pool = ThreadPool(processes=cv2.getNumberOfCPUs()*2) + results = [] + total = 0 + while True: + got_image,image = cap.read() + if not(got_image): + break + total += 1 + results.append(pool.apply(processImage,args=(image,rho,threshold))) + print results + hazed = results.count(True) + cap.release() + hazed_total = float(hazed)/total*100 + print total,hazedhazed_total + if hazed_total > 0: + return True + return False + +if __name__=='__main__': + global data_type + video = sys.argv[1] + #image = cv2.imread(sys.argv[1]) + rho = int(sys.argv[2]) + threshold = int(sys.argv[2]) + #semi_inverse = semi_inverse_image(image.copy()) + #cv2.imwrite("inv.jpg",semi_inverse) + + print processVideoThreaded(video,rho,threshold) diff --git a/pool/shard007/Python/0070815_runtests.py b/pool/shard007/Python/0070815_runtests.py new file mode 100644 index 0000000000000000000000000000000000000000..035a37514b2b4c234d7e611f1728c7563ed58754 --- /dev/null +++ b/pool/shard007/Python/0070815_runtests.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python +# -*- coding: utf-8 +from __future__ import unicode_literals, absolute_import + +import os +import sys + +import django +from django.conf import settings +from django.test.utils import get_runner + + +def run_tests(*test_args): + if not test_args: + test_args = ["tests"] + + os.environ["DJANGO_SETTINGS_MODULE"] = "tests.settings" + django.setup() + TestRunner = get_runner(settings) + test_runner = TestRunner() + failures = test_runner.run_tests(test_args) + sys.exit(bool(failures)) + + +if __name__ == "__main__": + run_tests(*sys.argv[1:]) diff --git a/pool/shard007/Python/0070819_test_machine.py b/pool/shard007/Python/0070819_test_machine.py new file mode 100644 index 0000000000000000000000000000000000000000..a9bb214c815248fdf5a99d34ce4321614cd0da63 --- /dev/null +++ b/pool/shard007/Python/0070819_test_machine.py @@ -0,0 +1,25 @@ +from juju.lib.testing import TestCase +from juju.providers.orchestra.machine import machine_from_dict + + +class MachineTest(TestCase): + + def test_create(self): + info = { + "name": "billy-bob", + "uid": "furblewurbleburble", + "netboot_enabled": True} + machine = machine_from_dict(info) + + self.assertEquals(machine.instance_id, "furblewurbleburble") + self.assertEquals(machine.dns_name, "billy-bob") + self.assertEquals(machine.private_dns_name, "billy-bob") + self.assertEquals(machine.state, "pending") + + def test_provisioned_state(self): + info = { + "name": "billy-bob", + "uid": "furblewurbleburble", + "netboot_enabled": False} + machine = machine_from_dict(info) + self.assertEquals(machine.state, "provisioned") diff --git a/pool/shard007/Python/0070825_corellia_cor_butterfly.py b/pool/shard007/Python/0070825_corellia_cor_butterfly.py new file mode 100644 index 0000000000000000000000000000000000000000..0ac0f820e687946bc483e91934ebc15167e70c89 --- /dev/null +++ b/pool/shard007/Python/0070825_corellia_cor_butterfly.py @@ -0,0 +1,22 @@ +# Spawn Group file created with PSWG Planetary Spawn Tool +import sys +from java.util import Vector +from services.spawn import DynamicSpawnGroup +from services.spawn import MobileTemplate + +def addDynamicGroup(core): + dynamicGroup = DynamicSpawnGroup() + mobileTemplates = Vector() + mobileTemplates.add('corellian_butterfly') + mobileTemplates.add('corellian_butterfly_defender') + mobileTemplates.add('corellian_butterfly_drone') + mobileTemplates.add('corellian_butterfly_monarch') + mobileTemplates.add('corellian_butterfly_warrior') + mobileTemplates.add('corellian_butterfly_worker') + dynamicGroup.setMobiles(mobileTemplates) + dynamicGroup.setGroupMembersNumber(3) + dynamicGroup.setName('corellia_cor_butterfly') + dynamicGroup.setMaxSpawns(-1) + dynamicGroup.setMinSpawnDistance(150) + core.spawnService.addDynamicGroup('corellia_cor_butterfly', dynamicGroup) + return diff --git a/pool/shard007/Python/0070850_gpu_process.py b/pool/shard007/Python/0070850_gpu_process.py new file mode 100644 index 0000000000000000000000000000000000000000..4d0bee69eb1f9d430a31d07d2ba6b9e700360d81 --- /dev/null +++ b/pool/shard007/Python/0070850_gpu_process.py @@ -0,0 +1,54 @@ +# Copyright 2013 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. +import gpu_process_expectations as expectations +import page_sets + +from telemetry import benchmark +from telemetry.page import page_set +from telemetry.page import page_test + +test_harness_script = r""" + var domAutomationController = {}; + domAutomationController._finished = false; + domAutomationController.setAutomationId = function(id) {} + domAutomationController.send = function(msg) { + domAutomationController._finished = true; + } + + window.domAutomationController = domAutomationController; +""" + +class _GpuProcessValidator(page_test.PageTest): + def __init__(self): + super(_GpuProcessValidator, self).__init__( + needs_browser_restart_after_each_page=True) + + def CustomizeBrowserOptions(self, options): + options.AppendExtraBrowserArgs('--enable-gpu-benchmarking') + + def ValidateAndMeasurePage(self, page, tab, results): + if hasattr(page, 'Validate'): + page.Validate(tab, results) + else: + has_gpu_process_js = 'chrome.gpuBenchmarking.hasGpuProcess()' + has_gpu_process = tab.EvaluateJavaScript(has_gpu_process_js) + if not has_gpu_process: + raise page_test.Failure('No GPU process detected') + +class GpuProcess(benchmark.Benchmark): + """Tests that accelerated content triggers the creation of a GPU process""" + test = _GpuProcessValidator + + @classmethod + def Name(cls): + return 'gpu_process' + + def CreateExpectations(self): + return expectations.GpuProcessExpectations() + + def CreatePageSet(self, options): + page_set = page_sets.GpuProcessTestsPageSet() + for page in page_set.pages: + page.script_to_evaluate_on_commit = test_harness_script + return page_set diff --git a/pool/shard007/Python/0070855_topic_hot_answer_crawler.py b/pool/shard007/Python/0070855_topic_hot_answer_crawler.py new file mode 100644 index 0000000000000000000000000000000000000000..7ba5dea44fb1611021a5386916364e60ae799c6e --- /dev/null +++ b/pool/shard007/Python/0070855_topic_hot_answer_crawler.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python +# encoding=utf-8 + +""" +抓取知乎所有话题列表 +""" +import HTMLParser +import datetime + +from pymongo import MongoClient +from xtls.basecrawler import BaseCrawler +from xtls.codehelper import trytry +from xtls.logger import get_logger +from xtls.timeparser import now, parse_time +from xtls.util import BeautifulSoup + +from config import * + +logger = get_logger(__file__) +ZHIHU_URL = 'http://www.zhihu.com' +TOPIC_URL = 'http://www.zhihu.com/topic/{tid}/top-answers?page=' +MONGO = MongoClient(MONGO_HOST, MONGO_PORT) + + +class TopicHotCrawler(BaseCrawler): + def __init__(self, topic_id): + super(TopicHotCrawler, self).__init__(topic_id=topic_id) + + @classmethod + def save(cls, data): + MONGO[DB][TOPIC_COLL].update_one({'_id': data['_id']}, {'$set': data}, upsert=True) + + @classmethod + def unescape(cls, string): + html_parser = HTMLParser.HTMLParser() + html = html_parser.unescape(string) + html = html[1 + html.find('>'):html.rfind('<')].strip() + e_time = '' + try: + text = BeautifulSoup(html).find('a', class_='answer-date-link last_updated meta-item').getText().strip() + if text.startswith(u'编辑于'): + e_time = parse_time(text) + except: + pass + return html, e_time + + @classmethod + def parse_answer(cls, soup): + title_a = soup.find('a', class_='question_link') + body = soup.find('div', class_="entry-body") + + author = soup.find('div', class_='zm-item-answer-author-info') + comment_cnt, a_name, a_desc, a_link, r_time = 0, u'匿名用户', '', '', '' + + with trytry(): + r_time = datetime.datetime.fromtimestamp(int(body['data-created'])).strftime('%Y-%m-%d %H:%M:%S') + + with trytry(): + a = author.find('a', class_='author-link') + if a: + a_name = a.getText().strip() + a_link = ZHIHU_URL + a['href'] + else: + a_name = author.find('span', class_='name').getText().strip() + a_desc = author.find('span', class_='bio')['title'] + with trytry(): + comment_cnt = int(soup.find('a', class_=' meta-item toggle-comment').getText().replace(u'条评论', '').strip()) + + content, e_time = cls.unescape(unicode(soup.find('textarea', class_='content hidden'))) + if not e_time: + e_time = r_time + result = { + 'a_name': a_name, + 'a_link': a_link, + 'a_desc': a_desc, + 'r_time': r_time, + 'e_time': e_time, + 'comment_cnt': comment_cnt, + 'question': title_a.getText().strip(), + 'agree_cnt': int(soup.find('a', class_='zm-item-vote-count')['data-votecount']), + '_id': ZHIHU_URL + title_a['href'] + '/answer/' + body['data-atoken'], + 'content': content, + 'topics': [] + } + return result + + def _run(self, soup): + for index, item in enumerate(soup.find_all('div', class_='feed-item')): + yield self.parse_answer(item) + + def save(self, data): + logger.info('saving %s' % data['_id']) + coll = MONGO[DB][HOT_ANSWER_COLL] + old = coll.find_one({'_id': data['_id']}) + if not old: + MONGO[DB][TOPIC_COLL].update_one({'_id': self.topic_id}, {'$inc': {'count': 1}}) + coll.insert_one(data) + return 0 + elif self.topic_id not in old['topics']: + MONGO[DB][TOPIC_COLL].update_one({'_id': self.topic_id}, {'$inc': {'count': 1}}) + data['topics'].extend(old['topics']) + coll.update_one({'_id': data['_id']}, {'$set': data}) + return 1 + else: + return -1 + + def run(self): + base_url = TOPIC_URL.format(tid=self.topic_id) + for page in xrange(1, 10): + url = base_url + str(page) + logger.info('crawling topic %s, page %s' % (self.topic_id, page)) + + try: + html = self.get(url) + soup = BeautifulSoup(html) + except: + return + + for answer in self._run(soup): + answer['topics'].append(self.topic_id) + answer['updateTime'] = now() + result = self.save(answer) + if result < 0: + return + + +def main(): + # TopicHotCrawler('19552832').run() + for index, item in enumerate(MONGO[DB][TOPIC_COLL].find().batch_size(1)): + logger.info('now topic %s-%s' % (index, item['_id'])) + with trytry(logger=logger): + TopicHotCrawler(item['_id']).run() + + +if __name__ == '__main__': + while True: + main() diff --git a/pool/shard007/Python/0070857_base_filter.py b/pool/shard007/Python/0070857_base_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..051a477a88b43c526435345510d1d2abd83fc6b9 --- /dev/null +++ b/pool/shard007/Python/0070857_base_filter.py @@ -0,0 +1,95 @@ +# Copyright (c) 2011-2012 OpenStack Foundation. +# All Rights Reserved. +# +# 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. + +""" +Filter support +""" + +from openstack.common.gettextutils import _LI +from openstack.common import log as logging +from openstack.common.scheduler import base_handler + +LOG = logging.getLogger(__name__) + + +class BaseFilter(object): + """Base class for all filter classes.""" + def _filter_one(self, obj, filter_properties): + """Return True if it passes the filter, False otherwise. + Override this in a subclass. + """ + return True + + def filter_all(self, filter_obj_list, filter_properties): + """Yield objects that pass the filter. + + Can be overridden in a subclass, if you need to base filtering + decisions on all objects. Otherwise, one can just override + _filter_one() to filter a single object. + """ + for obj in filter_obj_list: + if self._filter_one(obj, filter_properties): + yield obj + + # Set to true in a subclass if a filter only needs to be run once + # for each request rather than for each instance + run_filter_once_per_request = False + + def run_filter_for_index(self, index): + """Return True if the filter needs to be run for the "index-th" + instance in a request. Only need to override this if a filter + needs anything other than "first only" or "all" behaviour. + """ + return not (self.run_filter_once_per_request and index > 0) + + +class BaseFilterHandler(base_handler.BaseHandler): + """Base class to handle loading filter classes. + + This class should be subclassed where one needs to use filters. + """ + + def get_filtered_objects(self, filter_classes, objs, + filter_properties, index=0): + """Get objects after filter + + :param filter_classes: filters that will be used to filter the + objects + :param objs: objects that will be filtered + :param filter_properties: client filter properties + :param index: This value needs to be increased in the caller + function of get_filtered_objects when handling + each resource. + """ + list_objs = list(objs) + LOG.debug("Starting with %d host(s)", len(list_objs)) + for filter_cls in filter_classes: + cls_name = filter_cls.__name__ + filter_class = filter_cls() + + if filter_class.run_filter_for_index(index): + objs = filter_class.filter_all(list_objs, filter_properties) + if objs is None: + LOG.debug("Filter %(cls_name)s says to stop filtering", + {'cls_name': cls_name}) + return + list_objs = list(objs) + msg = (_LI("Filter %(cls_name)s returned %(obj_len)d host(s)") + % {'cls_name': cls_name, 'obj_len': len(list_objs)}) + if not list_objs: + LOG.info(msg) + break + LOG.debug(msg) + return list_objs diff --git a/pool/shard007/Python/0070862_lether.py b/pool/shard007/Python/0070862_lether.py new file mode 100644 index 0000000000000000000000000000000000000000..3126d0fc81be8af5ba9755cdb127c76adeb5eca6 --- /dev/null +++ b/pool/shard007/Python/0070862_lether.py @@ -0,0 +1,49 @@ +# The results have later been reproduced in: +# +# H.T. Rathod, K.V. Nagaraja, B. Venkatesudu, +# Symmetric Gauss Legendre quadrature formulas for composite numerical integration over +# a triangular surface, +# Applied Mathematics and Computation 188 (2007) 865–876 +# . +# +# Reported to Elsevier on June 24, 2019. +# + +import numpy as np + +from ..c1 import gauss_legendre +from ..helpers import article +from ._helpers import T2Scheme, register + +source = article( + authors=["Frank G. Lether"], + title="Computation of double integrals over a triangle", + journal="Journal of Computational and Applied Mathematics", + volume="2", + number="3", + month="sep", + year="1976", + pages="219–224", + url="https://doi.org/10.1016/0771-050X%2876%2990008-5", +) + + +def lether(n): + gl = gauss_legendre(n) + + w = np.outer((1 + gl.points) * gl.weights, gl.weights) / 4 + x = np.outer(1 - gl.points, np.ones(n)) / 2 + y = np.outer(1 + gl.points, 1 - gl.points) / 4 + + points = np.array([x.flatten(), y.flatten()]) + weights = w.flatten() + + points = np.array([points[0], points[1], 1 - points[0] - points[1]]) + + degree = 2 * (n - 1) + return T2Scheme( + f"Lether({n})", {"plain": np.vstack([weights, points])}, degree, source + ) + + +register([lether]) diff --git a/pool/shard007/Python/0070867_read_stc.py b/pool/shard007/Python/0070867_read_stc.py new file mode 100644 index 0000000000000000000000000000000000000000..ac7b8a504a1c7536152abdad10bf21906db1c21d --- /dev/null +++ b/pool/shard007/Python/0070867_read_stc.py @@ -0,0 +1,35 @@ +""" +=================== +Reading an STC file +=================== + +STC files contain activations on cortex ie. source +reconstructions +""" +# Author: Alexandre Gramfort +# +# License: BSD-3-Clause + +# %% + +import matplotlib.pyplot as plt + +import mne +from mne.datasets import sample + +print(__doc__) + +data_path = sample.data_path() +fname = data_path + '/MEG/sample/sample_audvis-meg' + +stc = mne.read_source_estimate(fname) + +n_vertices, n_samples = stc.data.shape +print("stc data size: %s (nb of vertices) x %s (nb of samples)" + % (n_vertices, n_samples)) + +# View source activations +plt.plot(stc.times, stc.data[::100, :].T) +plt.xlabel('time (ms)') +plt.ylabel('Source amplitude') +plt.show() diff --git a/pool/shard007/Python/0070869_flatStep_hyq_pathKino.py b/pool/shard007/Python/0070869_flatStep_hyq_pathKino.py new file mode 100644 index 0000000000000000000000000000000000000000..54f22125cb18e947994cf6fe6d477c139f2eb6bf --- /dev/null +++ b/pool/shard007/Python/0070869_flatStep_hyq_pathKino.py @@ -0,0 +1,168 @@ +## Importing helper class for setting up a reachability planning problem +from hpp.corbaserver.rbprm.rbprmbuilder import Builder + +# Importing Gepetto viewer helper class +from hpp.gepetto import Viewer +import time + +rootJointType = 'freeflyer' +packageName = 'hpp-rbprm-corba' +meshPackageName = 'hpp-rbprm-corba' +# URDF file describing the trunk of the robot HyQ +#~ urdfName = 'hyq_trunk_large' +urdfName = 'hyq_trunk' +# URDF files describing the reachable workspace of each limb of HyQ +urdfNameRom = ['hyq_lhleg_rom','hyq_lfleg_rom','hyq_rfleg_rom','hyq_rhleg_rom'] +urdfSuffix = "" +srdfSuffix = "" +vMax = 2; +aMax = 10; +extraDof = 6 +# Creating an instance of the helper class, and loading the robot +rbprmBuilder = Builder () +rbprmBuilder.loadModel(urdfName, urdfNameRom, rootJointType, meshPackageName, packageName, urdfSuffix, srdfSuffix) +rbprmBuilder.setJointBounds ("base_joint_xyz", [-2.5,2.5, -0.5, 0.5, 0.4, 1.2]) +# The following lines set constraint on the valid configurations: +# a configuration is valid only if all limbs can create a contact ... +rbprmBuilder.setFilter(['hyq_rhleg_rom', 'hyq_lfleg_rom', 'hyq_rfleg_rom','hyq_lhleg_rom']) +rbprmBuilder.setAffordanceFilter('hyq_rhleg_rom', ['Support']) +rbprmBuilder.setAffordanceFilter('hyq_rfleg_rom', ['Support',]) +rbprmBuilder.setAffordanceFilter('hyq_lhleg_rom', ['Support']) +rbprmBuilder.setAffordanceFilter('hyq_lfleg_rom', ['Support',]) +# We also bound the rotations of the torso. +rbprmBuilder.boundSO3([-0.2,0.2,-0.3,0.3,-0.3,0.3]) +rbprmBuilder.client.basic.robot.setDimensionExtraConfigSpace(extraDof) +rbprmBuilder.client.basic.robot.setExtraConfigSpaceBounds([-vMax,vMax,-vMax,vMax,0,0,0,0,0,0,0,0]) + +# Creating an instance of HPP problem solver and the viewer +from hpp.corbaserver.rbprm.problem_solver import ProblemSolver +ps = ProblemSolver( rbprmBuilder ) +ps.client.problem.setParameter("aMax",aMax) +ps.client.problem.setParameter("vMax",vMax) +r = Viewer (ps) + +from hpp.corbaserver.affordance.affordance import AffordanceTool +afftool = AffordanceTool () +afftool.setAffordanceConfig('Support', [0.6, 0.03, 0.00005]) +afftool.loadObstacleModel (packageName, "flat_step", "planning", r) +#r.loadObstacleModel (packageName, "ground", "planning") +afftool.visualiseAffordances('Support', r, [0.25, 0.5, 0.5]) +r.addLandmark(r.sceneName,1) + +# Setting initial and goal configurations +q_init = rbprmBuilder.getCurrentConfig (); +q_init [0:3] = [-2.5, 0, 0.7]; rbprmBuilder.setCurrentConfig (q_init); r (q_init) +q_goal = q_init [::] +q_goal [0:3] = [2.5, 0, 0.7] +#q_goal[0:3]=[3,-4,0.4]#position easy +#q_goal[7:10]=[0,0,0]#velocity +r (q_goal) +#~ q_goal [0:3] = [-1.5, 0, 0.63]; r (q_goal) + +# Choosing a path optimizer +ps.setInitialConfig (q_init) +ps.addGoalConfig (q_goal) +# Choosing RBPRM shooter and path validation methods. +ps.client.problem.selectConFigurationShooter("RbprmShooter") +ps.client.problem.selectPathValidation("RbprmDynamicPathValidation",0.05) +# Choosing kinodynamic methods : +ps.selectSteeringMethod("RBPRMKinodynamic") +ps.selectDistance("KinodynamicDistance") +ps.selectPathPlanner("DynamicPlanner") + +#solve the problem : +r(q_init) + +ps.client.problem.prepareSolveStepByStep() + + +ps.client.problem.finishSolveStepByStep() + +""" +camera = [0.6293167471885681, + -9.560577392578125, + 10.504343032836914, + 0.9323806762695312, + 0.36073973774909973, + 0.008668755181133747, + 0.02139890193939209] +r.client.gui.setCameraTransform(0,camera) +""" + +from hpp.gepetto import PathPlayer +pp = PathPlayer (rbprmBuilder.client.basic, r) +pp.dt=0.03 + +pp.displayVelocityPath(0) + + +""" +ps.client.problem.extractPath(0,0,3.4) + + +# Playing the computed path +from hpp.gepetto import PathPlayer +pp = PathPlayer (rbprmBuilder.client.basic, r) +pp.dt=0.03 +r.client.gui.removeFromGroup("rm",r.sceneName) +pp.displayVelocityPath(1) +r.client.gui.setVisibility("path_1_root","ALWAYS_ON_TOP") +#display path +pp.speed=0.3 +#pp (0) + + +""" +#display path with post-optimisation +""" +r.client.gui.removeFromGroup("path_0_root",r.sceneName) +pp.displayVelocityPath(1) +pp (1) + +""" + +""" +q_far = q_init[::] +q_far[2] = -3 +r(q_far) +""" + + +""" +for i in range(1,10): + rbprmBuilder.client.basic.problem.optimizePath(i) + r.client.gui.removeFromGroup("path_"+str(i)+"_root",r.sceneName) + pp.displayVelocityPath(i+1) + #time.sleep(2) +""" + +""" +i=0 + +ps.clearRoadmap() +ps.solve() +r.client.gui.removeFromGroup("path_"+str(i)+"_root",r.sceneName) +i = i+1 +pp.displayVelocityPath(i) + +pp(i) + + +""" + +""" +r.client.gui.addCurve("c1",qlist,r.color.red) +r.client.gui.setVisibility("c1","ALWAYS_ON_TOP") +r.client.gui.addToGroup("c1",r.sceneName) + + +r.client.gui.addCurve("c2",qlist2,r.color.blue) +r.client.gui.setVisibility("c2","ALWAYS_ON_TOP") +r.client.gui.addToGroup("c2",r.sceneName) + + + +""" + + + diff --git a/pool/shard007/Python/0070873_resnet.py b/pool/shard007/Python/0070873_resnet.py new file mode 100644 index 0000000000000000000000000000000000000000..9a54b131349628bc70c9b9af8ce7d892e9dc9341 --- /dev/null +++ b/pool/shard007/Python/0070873_resnet.py @@ -0,0 +1,229 @@ +""" Copyright 2020 Google LLC + +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 + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +import sys +import numpy as np +from functools import partial +from model.resnet_util import (ResNet, WideResNet, + basic_stack1, basic_stack2, basic_stack3, + bottleneck_stack1, bottleneck_stack2, bottleneck_stack3) + + +__all__ = ['ResNet10', 'ResNet18', 'ResNet50', 'ResNet101', 'ResNet152', + 'ResNet10V2', 'ResNet18V2', 'ResNet50V2', 'ResNet101V2', 'ResNet152V2', + 'WRN28', 'WRN36'] + +BLOCK = { + 'ResNet10': [1, 1, 1, 1], + 'ResNet18': [2, 2, 2, 2], + 'ResNet50': [3, 4, 6, 3], + 'ResNet101': [3, 4, 23, 3], + 'ResNet152': [3, 8, 36, 3], + 'ResNet10v2': [1, 1, 1, 1], + 'ResNet18v2': [2, 2, 2, 2], + 'ResNet50v2': [3, 4, 6, 3], + 'ResNet101v2': [3, 4, 23, 3], + 'ResNet152v2': [3, 8, 36, 3], + 'WRN28': [4, 4, 4], + 'WRN36': [4, 4, 4, 4], +} + +EXPANSION = { + 'ResNet10': 1, + 'ResNet18': 1, + 'ResNet50': 4, + 'ResNet101':4, + 'ResNet152': 4, + 'ResNet10v2': 1, + 'ResNet18v2': 1, + 'ResNet50v2': 4, + 'ResNet101v2': 4, + 'ResNet152v2': 4, + 'WRN28': 1, + 'WRN36': 1, +} + +STACK = { + 'ResNet10': basic_stack1, + 'ResNet18': basic_stack1, + 'ResNet50': bottleneck_stack1, + 'ResNet101': bottleneck_stack1, + 'ResNet152': bottleneck_stack1, + 'ResNet10v2': basic_stack2, + 'ResNet18v2': basic_stack2, + 'ResNet50v2': bottleneck_stack2, + 'ResNet101v2': bottleneck_stack2, + 'ResNet152v2': bottleneck_stack2, + 'WRN28': basic_stack3, + 'WRN36': basic_stack3, +} + + +def ResNetV1( + arch='ResNet18', + head='linear', + head_mlp=None, + input_shape=None, + num_class=1000, + pooling=None, + activation='relu', + bn_sync=False, + width=1.0): + """Instantiates the ResNet architecture.""" + + def stack_fn(x, arch, width=1.0): + block, stack, expansion = BLOCK[arch], STACK[arch], EXPANSION[arch] + x = stack(x, int(64*width), block[0], expansion=expansion, + stride1=1, + activation=activation, bn_sync=bn_sync, name='conv2') + x = stack(x, int(128*width), block[1], expansion=expansion, + activation=activation, bn_sync=bn_sync, name='conv3') + x = stack(x, int(256*width), block[2], expansion=expansion, + activation=activation, bn_sync=bn_sync, name='conv4') + return stack(x, int(512*width), block[3], expansion=expansion, + activation=activation, bn_sync=bn_sync, name='conv5') + + return ResNet( + stack_fn=partial(stack_fn, arch=arch, width=width), + preact=False, + model_name='{}_width{:g}_{}'.format(arch, width, activation), + head=head, + head_mlp=head_mlp, + input_shape=input_shape, + pooling=pooling, + activation=activation, + bn_sync=bn_sync, + num_class=num_class) + + +def ResNetV2( + arch='ResNet18', + head='linear', + head_mlp='', + input_shape=None, + num_class=1000, + pooling=None, + activation='relu', + bn_sync=False, + width=1.0): + """Instantiates the ResNet architecture.""" + + def stack_fn(x, arch, width=1.0): + block, stack, expansion = BLOCK[arch], STACK[arch], EXPANSION[arch] + x = stack(x, int(64*width), block[0], expansion=expansion, + activation=activation, bn_sync=bn_sync, name='conv2') + x = stack(x, int(128*width), block[1], expansion=expansion, + activation=activation, bn_sync=bn_sync, name='conv3') + x = stack(x, int(256*width), block[2], expansion=expansion, + activation=activation, bn_sync=bn_sync, name='conv4') + return stack(x, int(512*width), block[3], expansion=expansion, + stride1=1, + activation=activation, bn_sync=bn_sync, name='conv5') + + return ResNet( + stack_fn=partial(stack_fn, arch=arch, width=width), + preact=True, + model_name='{}_width{:g}_{}'.format(arch, width, activation), + head=head, + head_mlp=head_mlp, + input_shape=input_shape, + pooling=pooling, + activation=activation, + bn_sync=bn_sync, + num_class=num_class) + + +def WRN( + arch='WRN28', + head='linear', + head_mlp='', + input_shape=None, + num_class=1000, + pooling=None, + activation='leaky_relu', + bn_sync=False, + width=1.0): + """Instantiates the ResNet architecture.""" + + def stack_fn(x, arch, width=1.0): + block, stack, expansion = BLOCK[arch], STACK[arch], EXPANSION[arch] + for i, b in enumerate(block): + x = stack(x, int((16 << i)*width), b, + expansion=expansion, + stride1=2 if i > 0 else 1, + activation=activation, + bn_sync=bn_sync, + name='conv%d' %(i+2)) + return x + + return WideResNet( + stack_fn=partial(stack_fn, arch=arch, width=width), + preact=True, + model_name='{}_width{:g}_{}'.format(arch, width, activation), + head=head, + head_mlp=head_mlp, + input_shape=input_shape, + pooling=pooling, + activation=activation, + bn_sync=bn_sync, + num_class=num_class) + + +def ResNet10(**kwargs): + return ResNetV1(arch='ResNet10', **kwargs) + + +def ResNet18(**kwargs): + return ResNetV1(arch='ResNet18', **kwargs) + + +def ResNet50(**kwargs): + return ResNetV1(arch='ResNet50', **kwargs) + + +def ResNet101(**kwargs): + return ResNetV1(arch='ResNet101', **kwargs) + + +def ResNet152(**kwargs): + return ResNetV2(arch='ResNet152', **kwargs) + + +def ResNet10V2(**kwargs): + return ResNetV2(arch='ResNet10v2', **kwargs) + + +def ResNet18V2(**kwargs): + return ResNetV2(arch='ResNet18v2', **kwargs) + + +def ResNet50V2(**kwargs): + return ResNetV2(arch='ResNet50v2', **kwargs) + + +def ResNet101V2(**kwargs): + return ResNetV2(arch='ResNet101v2', **kwargs) + + +def ResNet152V2(**kwargs): + return ResNetV2(arch='ResNet152v2', **kwargs) + + +def WRN28(**kwargs): + return WRN(arch='WRN28', **kwargs) + + +def WRN36(**kwargs): + return WRN(arch='WRN36', **kwargs) diff --git a/pool/shard007/Python/0070874_test_discovery.py b/pool/shard007/Python/0070874_test_discovery.py new file mode 100644 index 0000000000000000000000000000000000000000..64ac6acfc6b09ab74c363d1c5db330997d71cbdf --- /dev/null +++ b/pool/shard007/Python/0070874_test_discovery.py @@ -0,0 +1,143 @@ +#!/usr/local/bin/python3 + +# +# test_discovery.py +# +# (c) 2017 by Andreas Kraft +# License: BSD 3-Clause License. See the LICENSE file for further details. +# +# Unit test for discovery functionality. +# + +import unittest +import os, sys, time +sys.path.append('..') + +from onem2mlib import * +import onem2mlib.constants as CON +import onem2mlib.utilities as UT +from conf import * + + +class TestDiscovery(unittest.TestCase): + session = None + cse = None + ae = None + cnt = None + cin1 = None + cin2 = None + c1n3 = None + cin4 = None + + + @classmethod + def setUpClass(cls): + TestDiscovery.session = Session(host, originator, encoding) + TestDiscovery.cse = CSEBase(TestDiscovery.session, CSE_ID) + if TestDiscovery.cse.findAE(AE_NAME): + print('*** AE with name "' + AE_NAME + '" already present in CSE. Please remove it first.') + exit() + + + @classmethod + def tearDownClass(cls): + if TestDiscovery.ae: + TestDiscovery.ae.deleteFromCSE() + TestDiscovery.ae = None + + + def test_init(self): + TestDiscovery.ae = AE(TestDiscovery.cse, resourceName=AE_NAME) + TestDiscovery.cnt = Container(TestDiscovery.ae, resourceName=CNT_NAME) + TestDiscovery.cin1 = ContentInstance(TestDiscovery.cnt, resourceName=CIN_NAME+'1', content='value1', labels=[CIN_LABELS[0], CIN_LABELS[1]]) # both labels + TestDiscovery.cin2 = ContentInstance(TestDiscovery.cnt, resourceName=CIN_NAME+'2', content='value2', labels=[CIN_LABELS[0]]) # only label 1 + TestDiscovery.cin3 = ContentInstance(TestDiscovery.cnt, resourceName=CIN_NAME+'3', content='value3', labels=[CIN_LABELS[1]]) # only label 2 + TestDiscovery.cin4 = ContentInstance(TestDiscovery.cnt, resourceName=CIN_NAME+'4', content='value4') # no label + self.assertIsNotNone(TestDiscovery.session) + self.assertIsNotNone(TestDiscovery.cse) + self.assertIsNotNone(TestDiscovery.cse.resourceID) + self.assertIsNotNone(TestDiscovery.ae) + self.assertIsNotNone(TestDiscovery.ae.resourceID) + self.assertIsNotNone(TestDiscovery.cnt) + self.assertIsNotNone(TestDiscovery.cnt.resourceID) + self.assertIsNotNone(TestDiscovery.cin1) + self.assertIsNotNone(TestDiscovery.cin1.resourceID) + self.assertIsNotNone(TestDiscovery.cin2) + self.assertIsNotNone(TestDiscovery.cin2.resourceID) + self.assertIsNotNone(TestDiscovery.cin3) + self.assertIsNotNone(TestDiscovery.cin3.resourceID) + self.assertIsNotNone(TestDiscovery.cin4) + self.assertIsNotNone(TestDiscovery.cin4.resourceID) + + + def test_discoverContainer(self): + self.assertIsNotNone(TestDiscovery.ae) + containers = TestDiscovery.ae.discover( [UT.newTypeFilterCriteria(CON.Type_Container)] ) + self.assertIsNotNone(containers) + self.assertIsInstance(containers, list) + self.assertEqual(len(containers), 1) + self.assertIsInstance(containers[0], Container) + self.assertEqual(containers[0].resourceName, CNT_NAME) + + + def test_discoverLabel1(self): + self.assertIsNotNone(TestDiscovery.ae) + cins = TestDiscovery.ae.discover( [UT.newLabelFilterCriteria(CIN_LABELS[0])] ) + self.assertIsNotNone(cins) + self.assertIsInstance(cins, list) + self.assertEqual(len(cins), 2) + for cin in cins: + self.assertIsInstance(cin, ContentInstance) + self.assertTrue(TestDiscovery._checkResourceInList(cins, CIN_NAME+'1')) + self.assertTrue(TestDiscovery._checkResourceInList(cins, CIN_NAME+'2')) + + + def test_discoverLabel2(self): + self.assertIsNotNone(TestDiscovery.ae) + cins = TestDiscovery.ae.discover( [UT.newLabelFilterCriteria(CIN_LABELS[1])] ) + self.assertIsNotNone(cins) + self.assertIsInstance(cins, list) + self.assertEqual(len(cins), 2) + for cin in cins: + self.assertIsInstance(cin, ContentInstance) + self.assertTrue(TestDiscovery._checkResourceInList(cins, CIN_NAME+'1')) + self.assertTrue(TestDiscovery._checkResourceInList(cins, CIN_NAME+'3')) + + + def test_discoverLabel3(self): + self.assertIsNotNone(TestDiscovery.ae) + cins = TestDiscovery.ae.discover( [UT.newLabelFilterCriteria(CIN_LABELS[0]), UT.newLabelFilterCriteria(CIN_LABELS[1])] ) + self.assertIsNotNone(cins) + self.assertIsInstance(cins, list) + self.assertEqual(len(cins), 3) + for cin in cins: + self.assertIsInstance(cin, ContentInstance) + self.assertTrue(TestDiscovery._checkResourceInList(cins, CIN_NAME+'1')) + self.assertTrue(TestDiscovery._checkResourceInList(cins, CIN_NAME+'2')) + self.assertTrue(TestDiscovery._checkResourceInList(cins, CIN_NAME+'3')) + + + def test_finit(self): + self.assertIsNotNone(TestDiscovery.ae) + self.assertTrue(TestDiscovery.ae.deleteFromCSE()) + TestDiscovery.ae = None + + + def _checkResourceInList(list, resourceName): + for cin in list: + if cin.resourceName == resourceName: + return True + return False + + + +if __name__ == '__main__': + suite = unittest.TestSuite() + suite.addTest(TestDiscovery('test_init')) + suite.addTest(TestDiscovery('test_discoverContainer')) + suite.addTest(TestDiscovery('test_discoverLabel1')) + suite.addTest(TestDiscovery('test_discoverLabel2')) + suite.addTest(TestDiscovery('test_discoverLabel3')) + suite.addTest(TestDiscovery('test_finit')) + + unittest.TextTestRunner(verbosity=2, failfast=True).run(suite) diff --git a/pool/shard007/Python/0070878_creating_front_removing_md.py b/pool/shard007/Python/0070878_creating_front_removing_md.py new file mode 100644 index 0000000000000000000000000000000000000000..bd8a157302fc9b8d763421b36c33cadac3988fbd --- /dev/null +++ b/pool/shard007/Python/0070878_creating_front_removing_md.py @@ -0,0 +1,72 @@ +#! /usr/bin/env python +""" + Routines to create front file removing md.1.last solutions. + So, in this front file contains solution from CASP11 stage2 + These routines were developed by: + Rodrigo Antonio Faccioli - rodrigo.faccioli@usp.br / rodrigo.faccioli@gmail.com + Leandro Oliveira Bortot - leandro.bortot@usp.br / leandro.obt@gmail.com +""" +#Example: creating_front_removing_md.py /home/faccioli/Dropbox/Rodrigo_FCFRP/CASP11/analises/2PG /home/faccioli/workspace/2pg_cartesian/build/protpred-Gromacs-Sort_Method_by_Front_Dominance + +import sys +import os + +""" This function obtains all sub-directories + from root_path +""" +def get_all_directory(root_path): + list_res = [] + aux_direct = os.walk(root_path) + for l in aux_direct: + list_res.append(l[0]) + return list_res + +""" This function obtains all front files + in mypath +""" +def get_files_front(mypath): + only_pdbqt_file = [] + for root, dirs, files in os.walk(mypath): + for file in files: + if file.endswith(".front"): + f_path = os.path.join(root,file) + only_pdbqt_file.append(f_path) + return only_pdbqt_file + +def main(): + #root path + root_path = sys.argv[1] + #path_file 2PG program + program_2PG = sys.argv[2] + + + str_to_remove = ".md.1_last" + input_file_sort = "front_without_md.txt" + header_input_file_sort = ";-1 -1 0 \n" + command_ref = "@PROGRAM@ @INPUT_FILE@ 2>/dev/null" + + all_directories = get_all_directory(root_path) + for directory in all_directories: + front_file = get_files_front(directory) + #checking list is empty + if len(front_file) > 0: #not empty + #preparing filename to be saved + full_input_file_sort = os.path.join(directory, input_file_sort) + input_file = open(full_input_file_sort, "w") + #preparing filename to be read + front_file_str = str(front_file[0]) + front_file = open(front_file_str, "r") + #reading front file + input_file.write(header_input_file_sort) + for line in front_file.readlines(): + if str(line).find("#") < 0 and str(line).find(str_to_remove) < 0: + line_splited = line.split() + line_save = str(float(line_splited[3])) +"\t"+ str(float(line_splited[4])) +"\t"+ str(line_splited[5]) +"\n" + input_file.write(line_save) + input_file.close() + front_file.close() + #Running 2PG program + os.chdir(directory) + command = str(command_ref).replace("@PROGRAM@", program_2PG).replace("@INPUT_FILE@", full_input_file_sort) + os.system(command) +main() \ No newline at end of file diff --git a/pool/shard007/Python/0070880_firstgui.py b/pool/shard007/Python/0070880_firstgui.py new file mode 100644 index 0000000000000000000000000000000000000000..a550a953e679998b7bbca8d771e94c56194061d1 --- /dev/null +++ b/pool/shard007/Python/0070880_firstgui.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- + +# Form implementation generated from reading ui file 'firstgui.ui' +# +# Created: Mon Nov 9 09:46:58 2015 +# by: PyQt5 UI code generator 5.2.1 +# +# WARNING! All changes made in this file will be lost! + +from PyQt5 import QtCore, QtGui, QtWidgets + +class Ui_myfirstgui(object): + def setupUi(self, myfirstgui): + myfirstgui.setObjectName("myfirstgui") + myfirstgui.resize(598, 443) + self.buttonBox = QtWidgets.QDialogButtonBox(myfirstgui) + self.buttonBox.setGeometry(QtCore.QRect(200, 410, 381, 32)) + self.buttonBox.setOrientation(QtCore.Qt.Horizontal) + self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Close) + self.buttonBox.setObjectName("buttonBox") + self.myTextInput = QtWidgets.QLineEdit(myfirstgui) + self.myTextInput.setGeometry(QtCore.QRect(10, 10, 101, 21)) + self.myTextInput.setObjectName("myTextInput") + self.listWidget = QtWidgets.QListWidget(myfirstgui) + self.listWidget.setGeometry(QtCore.QRect(120, 10, 181, 191)) + self.listWidget.setObjectName("listWidget") + self.clearBtn = QtWidgets.QPushButton(myfirstgui) + self.clearBtn.setGeometry(QtCore.QRect(10, 70, 101, 23)) + self.clearBtn.setObjectName("clearBtn") + self.addBtn = QtWidgets.QPushButton(myfirstgui) + self.addBtn.setGeometry(QtCore.QRect(10, 40, 101, 23)) + self.addBtn.setObjectName("addBtn") + self.graphicsView = QtWidgets.QGraphicsView(myfirstgui) + self.graphicsView.setGeometry(QtCore.QRect(320, 10, 256, 192)) + self.graphicsView.setObjectName("graphicsView") + self.graphicsView_2 = QtWidgets.QGraphicsView(myfirstgui) + self.graphicsView_2.setGeometry(QtCore.QRect(320, 210, 256, 192)) + self.graphicsView_2.setObjectName("graphicsView_2") + self.graphicsView_3 = QtWidgets.QGraphicsView(myfirstgui) + self.graphicsView_3.setGeometry(QtCore.QRect(40, 210, 256, 192)) + self.graphicsView_3.setObjectName("graphicsView_3") + + self.retranslateUi(myfirstgui) + self.buttonBox.accepted.connect(myfirstgui.accept) + self.buttonBox.rejected.connect(myfirstgui.reject) + self.clearBtn.clicked.connect(self.listWidget.clear) + QtCore.QMetaObject.connectSlotsByName(myfirstgui) + + def retranslateUi(self, myfirstgui): + _translate = QtCore.QCoreApplication.translate + myfirstgui.setWindowTitle(_translate("myfirstgui", "My First Gui!")) + self.clearBtn.setText(_translate("myfirstgui", "clear")) + self.addBtn.setText(_translate("myfirstgui", "add")) + + +if __name__ == "__main__": + import sys + app = QtWidgets.QApplication(sys.argv) + myfirstgui = QtWidgets.QDialog() + ui = Ui_myfirstgui() + ui.setupUi(myfirstgui) + myfirstgui.show() + sys.exit(app.exec_()) + diff --git a/pool/shard007/Python/0070883_mfsrun.py b/pool/shard007/Python/0070883_mfsrun.py new file mode 100644 index 0000000000000000000000000000000000000000..2ac5124308f9531675404df2b4853da044256820 --- /dev/null +++ b/pool/shard007/Python/0070883_mfsrun.py @@ -0,0 +1,133 @@ + +# Function to compute Calculate alpha +def SimCalcAlphaBeta(imtemplate="",taylorlist=[],namealpha="",namebeta="",threshold=0.001): + nterms = len(taylorlist); + + if(nterms>1): + if(not os.path.exists(namealpha)): + cpcmd = 'cp -r ' + imtemplate + ' ' + namealpha; + os.system(cpcmd); + if(nterms>2): + if(not os.path.exists(namebeta)): + cpcmd = 'cp -r ' + imtemplate + ' ' + namebeta; + os.system(cpcmd); + + if(nterms>0): + ia.open(taylorlist[0]); + ptay0 = ia.getchunk(); + ia.close(); + if(nterms>1): + ia.open(taylorlist[1]); + ptay1 = ia.getchunk(); + ia.close(); + ia.open(namealpha); + alpha = ia.getchunk(); + alpha.fill(0.0); + ia.close(); + if(nterms>2): + ia.open(taylorlist[2]); + ptay2 = ia.getchunk(); + ia.close(); + ia.open(namebeta); + beta = ia.getchunk(); + beta.fill(0.0); + ia.close(); + + # Calc alpha,beta from ptay0,ptay1,ptay2 + N = ptay0.shape[0]; + + if(nterms>1): + for ii in range(0,N): + for jj in range(0,N): + if(ptay0[ii,jj,0,0]>threshold): + mtay0 = ptay0[ii,jj,0,0]; + mtay1 = ptay1[ii,jj,0,0]; + alphaval = mtay1/mtay0; + alpha[ii,jj,0,0] = alphaval; + if(nterms>2): + mtay2 = ptay2[ii,jj,0,0]; + beta[ii,jj,0,0] = (mtay2/mtay0) - 0.5*alphaval*(alphaval-1); + if(ii%100 == 0): + print ii; + + if(nterms>1): + ia.open(namealpha); + ia.putchunk(alpha); + ia.close(); + if(nterms>2): + ia.open(namebeta); + ia.putchunk(beta); + ia.close(); + + + +############################################################################## + + +msname = 'ptest.ms'; +rname = 'try'; +niter=100; +scales=[0]; +ntaylor=3; +threshold='0.05mJy'; +imsize=1024; +cellsize="8.0arcsec"; +stokes="I"; +reffreq="1.4GHz"; +gain=0.5; +mask=""; +algo="msmfs"; +weighting="briggs"; +ftm="ft"; + + +models=[]; +restoreds=[]; +residuals=[]; +masks=[]; + +im.close(); +im.open(msname); +im.selectvis(spw=0); +if(algo=="msmfs"): + for tt in range(0,ntaylor): + models.append(rname+'.'+str(tt)+'.model'); + restoreds.append(rname+'.'+str(tt)+'.restored'); + residuals.append(rname+'.'+str(tt)+'.residual'); + masks.append(mask); + im.defineimage(nx=imsize,ny=imsize,cellx=cellsize,celly=cellsize,nchan=1,stokes=stokes,mode='mfs'); + im.make(models[tt]); +else: + models = [rname+'.model']; + restoreds = [rname+'.restored']; + residuals = [rname+'.residual']; + masks = mask; + im.defineimage(nx=imsize,ny=imsize,cellx=cellsize,celly=cellsize,nchan=1,stokes=stokes,mode='mfs'); + im.make(models[0]); + +im.weight(type=weighting); +im.setscales(scalemethod='uservector',uservector=scales); +im.settaylorterms(ntaylorterms=ntaylor,reffreq=(qa.convert(qa.unit(reffreq),"Hz"))['value']); +im.setoptions(ftmachine=ftm); +if(mask == ""): + print 'clean without mask'; + im.clean(model=models,image=restoreds,residual=residuals,algorithm=algo,threshold=threshold,niter=niter,interactive=False,gain=gain); +else: + print 'clean with mask'; + im.clean(model=models,image=restoreds,residual=residuals,algorithm=algo,threshold=threshold,niter=niter,interactive=False,gain=gain,mask=masks); + +im.done(); +########################################################################### + +## Calculate alpha and beta + +imtemplate=rname+'.0.restored'; +taylist=[]; +for i in range(0,ntaylor): + taylist.append(rname+'.'+str(i)+'.restored'); + +SimCalcAlphaBeta(imtemplate=imtemplate,taylorlist=taylist,namealpha=rname+'.'+ftm+'.restored.alpha',namebeta=rname+'.'+ftm+'.restored.beta',threshold=0.02); + + +########################################################################### + diff --git a/pool/shard007/Python/0070887_packaged.py b/pool/shard007/Python/0070887_packaged.py new file mode 100644 index 0000000000000000000000000000000000000000..a2e5619361eeef8e213b383e15fc0c70507a95d0 --- /dev/null +++ b/pool/shard007/Python/0070887_packaged.py @@ -0,0 +1,58 @@ +""" Module for finding regression algorithms packaged with YATSM + +Attributes: + packaged_regressions (list): regression estimators packaged within + ``YATSM`` + +""" +import json +import logging +import os +import pkg_resources + +logger = logging.getLogger('yatsm') + + +packaged_regressions = [] + +_packaged = pkg_resources.resource_filename( + __package__, os.path.join('pickles', 'pickles.json')) +if pkg_resources.resource_exists(__package__, + os.path.join('pickles', 'pickles.json')): + with open(_packaged, 'r') as f: + packaged_regressions = list(json.load(f).keys()) + + +def find_packaged_regressor(name): + """ Find location of a regression method packaged with YATSM + + See :data:`packaged_regressions` for a list of + available pre-packaged regressors + + Args: + name (str): name of packaged regression object + + Returns: + str: path to packaged regression method + + Raises: + KeyError: raise KeyError if user specifies unknown regressor + IOError: raise IOError if the packaged regressor cannot be found + + """ + if name not in packaged_regressions: + raise KeyError('Cannot load unknown packaged regressor %s' % name) + + path = pkg_resources.resource_filename(__name__, 'pickles') + logger.debug('Checking data files in %s for packaged regressors' % path) + if not pkg_resources.resource_exists(__name__, 'pickles'): + raise IOError('Cannot find packaged regressors in %s. Did you install ' + 'YATSM via setuptools?' % path) + + resource = os.path.join('pickles', name + '.pkl') + if not pkg_resources.resource_exists(__name__, resource): + raise IOError('Cannot find packaged regression method %s, but package ' + 'directory exists. Check the contents of %s if possible' + % (resource, path)) + + return pkg_resources.resource_filename(__name__, resource) diff --git a/pool/shard007/Python/0070894_skyeye_ods_tra_day_k_index.py b/pool/shard007/Python/0070894_skyeye_ods_tra_day_k_index.py new file mode 100644 index 0000000000000000000000000000000000000000..b34520116473dd5d855f11c07675305d6630afa8 --- /dev/null +++ b/pool/shard007/Python/0070894_skyeye_ods_tra_day_k_index.py @@ -0,0 +1,61 @@ +#coding=utf8 + +import tushare as ts; +import pymysql; +import time as dt +from datashape.coretypes import string +from pandas.io.sql import SQLDatabase +import sqlalchemy +import datetime +from sqlalchemy import create_engine +from pandas.io import sql +import threading +import pandas as pd; +import sys +sys.path.append('../') #添加配置文件 +from common_function import * +def create_table(table_name): + cmd=''' + create table if not exists %s + ( + `date` varchar(20) COMMENT '数据日期(索引)' + ,`open` FLOAT COMMENT '开盘价' + ,`close` FLOAT COMMENT '收盘价' + ,`high` FLOAT COMMENT '最高价' + ,`low` FLOAT COMMENT '最低价' + ,`volume` FLOAT COMMENT '成交量' + ,`code` varchar(10) COMMENT '股票代码(索引)和数据日期联合作为主键' + ,`int_code` VARCHAR(10) COMMENT '简短的指数代码' + ,PRIMARY KEY(int_code,`date`) + ,index(int_code) + )DEFAULT CHARSET=utf8 + '''%table_name + print (cmd) + run_mysql_cmd(cmd,conn) +def load_data(): + stock_code = get_index_info().index + total_num = len(stock_code); + tempnum = 1; + for tmp_stock_code in stock_code: + tempnum = tempnum + 1 + start_date=get_date_add_days(get_max_date_index(tmp_stock_code),1) #在最大天数加一天作为日期 + end_date=get_date_now() + print(tempnum,tmp_stock_code,start_date,end_date) + tmp_rs = ts.get_k_data(code=tmp_stock_code, start=start_date, end=end_date,index=True, ktype='D') + tmp_rs['int_code']=tmp_stock_code + pd.DataFrame.to_sql(tmp_rs, table_name, con=conn, flavor='mysql', if_exists='append', index=False) +if __name__ == '__main__': + #--------------------设置基本信息--------------------------------- + print("--------------加载股票日k线-----------------------------") + startTime=dt.time() + iphost,user,passwd=get_mysql_conn() + db='ods_data' + charset='utf8' + table_name='ods_tra_day_k_index' + conn = pymysql.connect(user=user, passwd=passwd,host=iphost, db=db,charset=charset) + #--------------------脚本运行开始-------------------------------- + create_table(table_name=table_name) + load_data() + #print get_max_date_index('sh000001') + endTime=dt.time() + print("---------------脚本运行完毕,共计耗费时间%sS------------------"%(endTime-startTime)) diff --git a/pool/shard007/Python/0070895_tests.py b/pool/shard007/Python/0070895_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..663d6b53b2ac684e849fa084c2b3ead4069436d4 --- /dev/null +++ b/pool/shard007/Python/0070895_tests.py @@ -0,0 +1,110 @@ +from django.core.urlresolvers import reverse +from django.test.utils import override_settings + +import xmodule.modulestore.django + +from courseware.tests.tests import LoginEnrollmentTestCase, TEST_DATA_XML_MODULESTORE +from xmodule.modulestore.django import modulestore + + +@override_settings(MODULESTORE=TEST_DATA_XML_MODULESTORE) +class WikiRedirectTestCase(LoginEnrollmentTestCase): + def setUp(self): + xmodule.modulestore.django._MODULESTORES = {} + courses = modulestore().get_courses() + + def find_course(name): + """Assumes the course is present""" + return [c for c in courses if c.location.course == name][0] + + self.toy = find_course("toy") + + # Create two accounts + self.student = 'view@test.com' + self.instructor = 'view2@test.com' + self.password = 'foo' + self.create_account('u1', self.student, self.password) + self.create_account('u2', self.instructor, self.password) + self.activate_user(self.student) + self.activate_user(self.instructor) + + def test_wiki_redirect(self): + """ + Test that requesting wiki URLs redirect properly to or out of classes. + + An enrolled in student going from /courses/edX/toy/2012_Fall/progress + to /wiki/some/fake/wiki/page/ will redirect to + /courses/edX/toy/2012_Fall/wiki/some/fake/wiki/page/ + + An unenrolled student going to /courses/edX/toy/2012_Fall/wiki/some/fake/wiki/page/ + will be redirected to /wiki/some/fake/wiki/page/ + + """ + self.login(self.student, self.password) + + self.enroll(self.toy) + + referer = reverse("progress", kwargs={'course_id': self.toy.id}) + destination = reverse("wiki:get", kwargs={'path': 'some/fake/wiki/page/'}) + + redirected_to = referer.replace("progress", "wiki/some/fake/wiki/page/") + + resp = self.client.get(destination, HTTP_REFERER=referer) + self.assertEqual(resp.status_code, 302) + + self.assertEqual(resp['Location'], 'http://testserver' + redirected_to) + + + # Now we test that the student will be redirected away from that page if the course doesn't exist + # We do this in the same test because we want to make sure the redirected_to is constructed correctly + + # This is a location like /courses/*/wiki/* , but with an invalid course ID + bad_course_wiki_page = redirected_to.replace(self.toy.location.course, "bad_course") + + resp = self.client.get(bad_course_wiki_page, HTTP_REFERER=referer) + self.assertEqual(resp.status_code, 302) + self.assertEqual(resp['Location'], 'http://testserver' + destination) + + def create_course_page(self, course): + """ + Test that loading the course wiki page creates the wiki page. + The user must be enrolled in the course to see the page. + """ + + course_wiki_home = reverse('course_wiki', kwargs={'course_id': course.id}) + referer = reverse("progress", kwargs={'course_id': self.toy.id}) + + resp = self.client.get(course_wiki_home, follow=True, HTTP_REFERER=referer) + + course_wiki_page = referer.replace('progress', 'wiki/' + self.toy.wiki_slug + "/") + + ending_location = resp.redirect_chain[-1][0] + ending_status = resp.redirect_chain[-1][1] + + self.assertEquals(ending_location, 'http://testserver' + course_wiki_page) + self.assertEquals(resp.status_code, 200) + + self.has_course_navigator(resp) + + def has_course_navigator(self, resp): + """ + Ensure that the response has the course navigator. + """ + self.assertTrue("course info" in resp.content.lower()) + self.assertTrue("courseware" in resp.content.lower()) + + def test_course_navigator(self): + """" + Test that going from a course page to a wiki page contains the course navigator. + """ + + self.login(self.student, self.password) + self.enroll(self.toy) + self.create_course_page(self.toy) + + course_wiki_page = reverse('wiki:get', kwargs={'path': self.toy.wiki_slug + '/'}) + referer = reverse("courseware", kwargs={'course_id': self.toy.id}) + + resp = self.client.get(course_wiki_page, follow=True, HTTP_REFERER=referer) + + self.has_course_navigator(resp) diff --git a/pool/shard007/Python/0070897_knapsack.py b/pool/shard007/Python/0070897_knapsack.py new file mode 100644 index 0000000000000000000000000000000000000000..5a9746b514f4b065e5031bd1c46a872e01f252d5 --- /dev/null +++ b/pool/shard007/Python/0070897_knapsack.py @@ -0,0 +1,46 @@ + +def knapsack(items, knapsack_size): + n = len(items) + + memo = [[0 for x in range(knapsack_size + 1)] for x in range(n + 1)] + + for i in range(1, n + 1): + item_value, item_weight = items[i - 1] + + for c in range(knapsack_size + 1): + if (item_weight > c): + memo[i][c] = memo[i - 1][c] + else: + memo[i][c] = max( + memo[i - 1][c], + memo[i - 1][c - item_weight] + item_value) + + return memo[n][knapsack_size] + + +def knapsack_recursive(items, knapsack_size, n=None, memo=None): + if n is None: + n = len(items) + + if n == 0 or knapsack_size == 0: + return 0 + + if memo is None: + memo = {} + + item_value, item_weight = items[n - 1] + item_key = f'{n - 1}_{knapsack_size}' + + if (item_key in memo): + return memo[item_key] + + if (item_weight > knapsack_size): + intermediate = knapsack_recursive(items, knapsack_size, n - 1, memo) + else: + intermediate = max( + knapsack_recursive(items, knapsack_size, n - 1, memo), + knapsack_recursive(items, knapsack_size - item_weight, n - 1, memo) + item_value) + + memo[item_key] = intermediate + + return intermediate diff --git a/pool/shard007/Python/0070898_jobs.py b/pool/shard007/Python/0070898_jobs.py new file mode 100644 index 0000000000000000000000000000000000000000..1e577100a535508b4e34dc061aa9168be09cc106 --- /dev/null +++ b/pool/shard007/Python/0070898_jobs.py @@ -0,0 +1,33 @@ +import json + +def simplemath(arg1=0, arg2=2): + return arg1 + arg2 + + +# Return the result after it runs +def return_result(job=None, result=None): + pl = job.redis.pipeline() + result = json.dumps({'data': result}) + pl.lpush('retools:result:%s' % job.job_id, result) + pl.expire('retools:result:%s', 3600) + pl.execute() + +# If it fails, return a 'ERROR' +def return_failure(job=None, exc=None): + pl = job.redis.pipeline() + exc = json.dumps({'data': 'ERROR: %s' % exc}) + pl.lpush('retools:result:%s' % job.job_id, exc) + pl.expire('retools:result:%s', 3600) + pl.execute() + + +def add_events(qm): + qm.subscriber('job_postrun', 'retools.jobs:simplemath', + handler='retools.jobs:return_result') + qm.subscriber('job_failure', 'retools.jobs:simplemath', + handler='retools.jobs:return_failure') + +def wait_for_result(qm, job, **kwargs): + job_id = qm.enqueue(job, **kwargs) + result = qm.redis.blpop('retools:result:%s' % job_id)[1] + return json.loads(result)['data'] diff --git a/pool/shard007/Python/0070899_rawtransactions.py b/pool/shard007/Python/0070899_rawtransactions.py new file mode 100644 index 0000000000000000000000000000000000000000..0bb7d8bdaf2a540cb467108b406f14aecc887e9b --- /dev/null +++ b/pool/shard007/Python/0070899_rawtransactions.py @@ -0,0 +1,162 @@ +#!/usr/bin/env python3 +# Copyright (c) 2014-2016 The Bitcoin Core developers +# Distributed under the MIT software license, see the accompanying +# file COPYING or http://www.opensource.org/licenses/mit-license.php. + +# +# Test re-org scenarios with a mempool that contains transactions +# that spend (directly or indirectly) coinbase transactions. +# + +from test_framework.test_framework import DankcoinTestFramework +from test_framework.util import * + +# Create one-input, one-output, no-fee transaction: +class RawTransactionsTest(DankcoinTestFramework): + + def __init__(self): + super().__init__() + self.setup_clean_chain = True + self.num_nodes = 3 + + def setup_network(self, split=False): + self.nodes = start_nodes(self.num_nodes, self.options.tmpdir) + + #connect to a local machine for debugging + #url = "http://dankcoinrpc:DP6DvqZtqXarpeNWyN3LZTFchCCyCUuHwNF7E8pX99x1@%s:%d" % ('127.0.0.1', 18332) + #proxy = AuthServiceProxy(url) + #proxy.url = url # store URL on proxy for info + #self.nodes.append(proxy) + + connect_nodes_bi(self.nodes,0,1) + connect_nodes_bi(self.nodes,1,2) + connect_nodes_bi(self.nodes,0,2) + + self.is_network_split=False + self.sync_all() + + def run_test(self): + + #prepare some coins for multiple *rawtransaction commands + self.nodes[2].generate(1) + self.sync_all() + self.nodes[0].generate(101) + self.sync_all() + self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(),1.5) + self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(),1.0) + self.nodes[0].sendtoaddress(self.nodes[2].getnewaddress(),5.0) + self.sync_all() + self.nodes[0].generate(5) + self.sync_all() + + ######################################### + # sendrawtransaction with missing input # + ######################################### + inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1}] #won't exists + outputs = { self.nodes[0].getnewaddress() : 4.998 } + rawtx = self.nodes[2].createrawtransaction(inputs, outputs) + rawtx = self.nodes[2].signrawtransaction(rawtx) + + try: + rawtx = self.nodes[2].sendrawtransaction(rawtx['hex']) + except JSONRPCException as e: + assert("Missing inputs" in e.error['message']) + else: + assert(False) + + + ######################### + # RAW TX MULTISIG TESTS # + ######################### + # 2of2 test + addr1 = self.nodes[2].getnewaddress() + addr2 = self.nodes[2].getnewaddress() + + addr1Obj = self.nodes[2].validateaddress(addr1) + addr2Obj = self.nodes[2].validateaddress(addr2) + + mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey']]) + mSigObjValid = self.nodes[2].validateaddress(mSigObj) + + #use balance deltas instead of absolute values + bal = self.nodes[2].getbalance() + + # send 1.2 PEPE to msig adr + txId = self.nodes[0].sendtoaddress(mSigObj, 1.2) + self.sync_all() + self.nodes[0].generate(1) + self.sync_all() + assert_equal(self.nodes[2].getbalance(), bal+Decimal('1.20000000')) #node2 has both keys of the 2of2 ms addr., tx should affect the balance + + + # 2of3 test from different nodes + bal = self.nodes[2].getbalance() + addr1 = self.nodes[1].getnewaddress() + addr2 = self.nodes[2].getnewaddress() + addr3 = self.nodes[2].getnewaddress() + + addr1Obj = self.nodes[1].validateaddress(addr1) + addr2Obj = self.nodes[2].validateaddress(addr2) + addr3Obj = self.nodes[2].validateaddress(addr3) + + mSigObj = self.nodes[2].addmultisigaddress(2, [addr1Obj['pubkey'], addr2Obj['pubkey'], addr3Obj['pubkey']]) + mSigObjValid = self.nodes[2].validateaddress(mSigObj) + + txId = self.nodes[0].sendtoaddress(mSigObj, 2.2) + decTx = self.nodes[0].gettransaction(txId) + rawTx = self.nodes[0].decoderawtransaction(decTx['hex']) + sPK = rawTx['vout'][0]['scriptPubKey']['hex'] + self.sync_all() + self.nodes[0].generate(1) + self.sync_all() + + #THIS IS A INCOMPLETE FEATURE + #NODE2 HAS TWO OF THREE KEY AND THE FUNDS SHOULD BE SPENDABLE AND COUNT AT BALANCE CALCULATION + assert_equal(self.nodes[2].getbalance(), bal) #for now, assume the funds of a 2of3 multisig tx are not marked as spendable + + txDetails = self.nodes[0].gettransaction(txId, True) + rawTx = self.nodes[0].decoderawtransaction(txDetails['hex']) + vout = False + for outpoint in rawTx['vout']: + if outpoint['value'] == Decimal('2.20000000'): + vout = outpoint + break + + bal = self.nodes[0].getbalance() + inputs = [{ "txid" : txId, "vout" : vout['n'], "scriptPubKey" : vout['scriptPubKey']['hex']}] + outputs = { self.nodes[0].getnewaddress() : 2.19 } + rawTx = self.nodes[2].createrawtransaction(inputs, outputs) + rawTxPartialSigned = self.nodes[1].signrawtransaction(rawTx, inputs) + assert_equal(rawTxPartialSigned['complete'], False) #node1 only has one key, can't comp. sign the tx + + rawTxSigned = self.nodes[2].signrawtransaction(rawTx, inputs) + assert_equal(rawTxSigned['complete'], True) #node2 can sign the tx compl., own two of three keys + self.nodes[2].sendrawtransaction(rawTxSigned['hex']) + rawTx = self.nodes[0].decoderawtransaction(rawTxSigned['hex']) + self.sync_all() + self.nodes[0].generate(1) + self.sync_all() + assert_equal(self.nodes[0].getbalance(), bal+Decimal('50.00000000')+Decimal('2.19000000')) #block reward + tx + + inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : 1000}] + outputs = { self.nodes[0].getnewaddress() : 1 } + rawtx = self.nodes[0].createrawtransaction(inputs, outputs) + decrawtx= self.nodes[0].decoderawtransaction(rawtx) + assert_equal(decrawtx['vin'][0]['sequence'], 1000) + + inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : -1}] + outputs = { self.nodes[0].getnewaddress() : 1 } + assert_raises(JSONRPCException, self.nodes[0].createrawtransaction, inputs, outputs) + + inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : 4294967296}] + outputs = { self.nodes[0].getnewaddress() : 1 } + assert_raises(JSONRPCException, self.nodes[0].createrawtransaction, inputs, outputs) + + inputs = [ {'txid' : "1d1d4e24ed99057e84c3f80fd8fbec79ed9e1acee37da269356ecea000000000", 'vout' : 1, 'sequence' : 4294967294}] + outputs = { self.nodes[0].getnewaddress() : 1 } + rawtx = self.nodes[0].createrawtransaction(inputs, outputs) + decrawtx= self.nodes[0].decoderawtransaction(rawtx) + assert_equal(decrawtx['vin'][0]['sequence'], 4294967294) + +if __name__ == '__main__': + RawTransactionsTest().main() diff --git a/pool/shard007/Python/0070909_pod.py b/pool/shard007/Python/0070909_pod.py new file mode 100644 index 0000000000000000000000000000000000000000..745e8d19156665e56bb22e2aed279b1d2b4b9594 --- /dev/null +++ b/pool/shard007/Python/0070909_pod.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python + +# Compute the Principal Orthogonal Decomposition +# of a series of snapshots. + +import sys +import vtktools +import scipy +import scipy.linalg +import numpy +import math +import operator + +# sys.argv[1] should be the name of a VTU +# with fields like +# Temperature1, Temperature2, Temperature3, etc +# to be PODded. +# sys.argv[2] should be the field to POD +# (in this case, "Temperature") + +vtu = vtktools.vtu(sys.argv[1]) +field_name = sys.argv[2] + +# figure out the number of snapshots +K = 1 +while True: + try: + vtu.GetScalarField(field_name + "%s" % K) + K = K + 1 + except: + break + +K = K - 1 +N = vtu.ugrid.GetNumberOfPoints() + +# Compute the mean: +mean = numpy.zeros((N)) +for k in range(K): + field = vtu.GetScalarField(field_name + "%s" % (k+1)) + mean = mean + field +mean = [mean[i]/K for i in range(len(mean))] + +# Assemble the matrix +A = numpy.mat(numpy.zeros((N, K))) +for k in range(K): + field = vtu.GetScalarField(field_name + "%s" % (k+1)) + A[:, k] = (field - mean).reshape(N, 1) + +ATA = A.T * A + +(evals, evecs) = scipy.linalg.eig(ATA) +evals = [float(x) for x in evals] +(evals, evecs) = zip(*sorted(zip(evals, evecs), key=operator.itemgetter(0), reverse=True)) +print evals + +sum_evals = sum(evals) +running_sum = 0.0 +for k in range(K): + running_sum = running_sum + evals[k] + print "I(%s): %s" % (k+1, running_sum / sum_evals) + + # Numpy is a bit rubbish. It doesn't even recognise matrix-vector multiplication. + phi = (A * evecs[k].reshape(evecs[k].shape + (1,))) / math.sqrt(evals[k]) + vtu.AddScalarField("POD%s" % (k+1), phi) + +vtu.Write() diff --git a/pool/shard007/Python/0070913_echobad.py b/pool/shard007/Python/0070913_echobad.py new file mode 100644 index 0000000000000000000000000000000000000000..fac30437d723cf0119c5b2fe3feab1ec4b92bb4e --- /dev/null +++ b/pool/shard007/Python/0070913_echobad.py @@ -0,0 +1,40 @@ +# echobad.py +# +# A flawed implementation of an concurrent echo server using our task scheduler. +# If you run this, you will notice that it freezes up right away. This +# is because the accept() operation in the server is blocking. Since we're +# not using threads, this blocks the operation of everything! + +from pyos6 import * +from socket import * + +def handle_client(client,addr): + print "Connection from", addr + while True: + data = client.recv(65536) + if not data: + break + client.send(data) + client.close() + print "Client closed" + yield # Make the function a generator/coroutine + +def server(port): + print "Server starting" + sock = socket(AF_INET,SOCK_STREAM) + sock.bind(("",port)) + sock.listen(5) + while True: + client,addr = sock.accept() + yield NewTask(handle_client(client,addr)) + +def alive(): + while True: + print "I'm alive!" + yield + +sched = Scheduler() +sched.new(alive()) +sched.new(server(45000)) +sched.mainloop() + diff --git a/pool/shard007/Python/0070915_data.py b/pool/shard007/Python/0070915_data.py new file mode 100644 index 0000000000000000000000000000000000000000..86dcdc3b68a218c4cb0c06b0ce6db499def133b7 --- /dev/null +++ b/pool/shard007/Python/0070915_data.py @@ -0,0 +1,86 @@ +# Copyright The PyTorch Lightning team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any, Iterable, Mapping, Union + +import torch +from torch.utils.data import DataLoader, IterableDataset + +from pytorch_lightning.utilities import rank_zero_warn + +BType = Union[torch.Tensor, str, Mapping[Any, "BType"], Iterable["BType"]] + + +def extract_batch_size(batch: BType) -> int: + """ + Recursively unpack a batch to find a torch.Tensor. + + Returns: + ``len(tensor)`` when found, or ``1`` when it hits an empty or non iterable. + """ + if isinstance(batch, torch.Tensor): + return batch.size(0) + if isinstance(batch, str): + return len(batch) + if isinstance(batch, dict): + sample = next(iter(batch.values()), 1) + return extract_batch_size(sample) + if isinstance(batch, Iterable): + sample = next(iter(batch), 1) + return extract_batch_size(sample) + + return 1 + + +def has_iterable_dataset(dataloader: DataLoader) -> bool: + return hasattr(dataloader, "dataset") and isinstance(dataloader.dataset, IterableDataset) + + +def has_len(dataloader: DataLoader) -> bool: + """ + Checks if a given Dataloader has ``__len__`` method implemented i.e. if + it is a finite dataloader or infinite dataloader. + + Raises: + ValueError: + If the length of Dataloader is 0, as it requires at least one batch + """ + + try: + # try getting the length + if len(dataloader) == 0: + raise ValueError("`Dataloader` returned 0 length. Please make sure that it returns at least 1 batch") + has_len = True + except TypeError: + has_len = False + except NotImplementedError: # e.g. raised by torchtext if a batch_size_fn is used + has_len = False + + if has_len and has_iterable_dataset(dataloader): + rank_zero_warn( + "Your `IterableDataset` has `__len__` defined." + " In combination with multi-process data loading (when num_workers > 1)," + " `__len__` could be inaccurate if each worker is not configured independently" + " to avoid having duplicate data." + ) + return has_len + + +def get_len(dataloader: DataLoader) -> Union[int, float]: + """Return the length of the given DataLoader. If ``__len__`` method is not implemented, return float('inf').""" + + if has_len(dataloader): + return len(dataloader) + + return float("inf") diff --git a/pool/shard007/Python/0070921_test_send_raw_transaction.py b/pool/shard007/Python/0070921_test_send_raw_transaction.py new file mode 100644 index 0000000000000000000000000000000000000000..6919971fd6e88a91e51c1e0fd2d704dbafbfa2f5 --- /dev/null +++ b/pool/shard007/Python/0070921_test_send_raw_transaction.py @@ -0,0 +1,25 @@ +import rlp + +from ethereum import tester +from ethereum.transactions import Transaction + +from testrpc.client.utils import ( + encode_data, +) + + +def test_eth_sendRawTransaction(hex_accounts, client): + tx = Transaction(0, tester.gas_price, tester.gas_limit, tester.accounts[1], 1234, '') + tx.sign(tester.keys[0]) + + raw_tx = rlp.encode(tx) + raw_tx_hex = encode_data(raw_tx) + + tx_hash = client.send_raw_transaction(raw_tx_hex) + assert tx_hash + + tx_data = client.get_transaction_by_hash(tx_hash) + + assert tx_data['hash'] == tx_hash + assert tx_data['from'] == hex_accounts[0] + assert tx_data['to'] == hex_accounts[1] diff --git a/pool/shard007/Python/0070925_baidu_search_spider.py b/pool/shard007/Python/0070925_baidu_search_spider.py new file mode 100644 index 0000000000000000000000000000000000000000..f371b4feb638f402cb176534d3b6821238e379f0 --- /dev/null +++ b/pool/shard007/Python/0070925_baidu_search_spider.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python +# coding=utf-8 + +import urllib +import urllib2 +import re +from bs4 import BeautifulSoup as BS +from pdb import * +def web(): + baseUrl = 'http://www.baidu.com/s' + page = 1 #第几页 + word = '水滴筹' #搜索关键词 + + data = {'wd':word,'pn':str(page-1)+'0','tn':'baidurt','ie':'utf-8','bsst':'1'} + data = urllib.urlencode(data) + url = baseUrl+'?'+data + + try: + request = urllib2.Request(url) + response = urllib2.urlopen(request) + except urllib2.HttpError,e: + print e.code + exit(0) + except urllib2.URLError,e: + print e.reason + exit(0) + + html = response.read() + soup = BS(html) + td = soup.find_all(class_='result') + for t in td: + title = t.h3.a.get_text().replace('\n','').replace('','').strip() + url = t.h3.a['href'].replace('\n','').replace(' ','').strip() + if url.find('https://www.baidu.com/link')>=0: + request = urllib2.Request(url) + response = urllib2.urlopen(request) + content = response.read() + #urls=re.findall(r"http://.*?\?fr=aladdin",content,re.I) + urls = re.findall(r"\"http://.*?\"",content,re.I)+re.findall(r"\"https://.*?\"",content,re.I) + if len(urls)>0: + url = urls[0].strip("\"") + else: + set_trace() + print title,url + +def wap(): + baseUrl = 'http://m.baidu.com/s' + page = 1 #第几页 + word = '水滴筹' #搜索关键词 + + data = {'wd':word,'pn':str(page-1)+'0','tn':'baidurt','ie':'utf-8','bsst':'1'} + data = urllib.urlencode(data) + url = baseUrl+'?'+data + + try: + request = urllib2.Request(url) + response = urllib2.urlopen(request) + except urllib2.HttpError,e: + print e.code + exit(0) + except urllib2.URLError,e: + print e.reason + exit(0) + + html = response.read() + soup = BS(html) + #try: + if 1: + td = soup.find_all(class_='result') + for index,t in enumerate(td): + title='' + url='' + if t.h3: + title= t.h3.get_text().replace('\n','').replace('','').strip() + if t.h3.parent and t.h3.parent.has_key('href'): + url = t.h3.parent['href'].replace('\n','').replace(' ','').strip() + if url.find('https://www.baidu.com/link')>=0: + request = urllib2.Request(url) + response = urllib2.urlopen(request) + content = response.read() + #urls=re.findall(r"http://.*?\?fr=aladdin",content,re.I) + urls = re.findall(r"\"http://.*?\"",content,re.I)+re.findall(r"\"https://.*?\"",content,re.I) + if len(urls)>0: + url = urls[0].strip("\"") + else: + set_trace() + print index,title,url + #except Exception,e: + # print e +if __name__=='__main__': + #wap() + web() diff --git a/pool/shard007/Python/0070929_test_constraints.py b/pool/shard007/Python/0070929_test_constraints.py new file mode 100644 index 0000000000000000000000000000000000000000..f620453bbf36ee852cb2309802e3cc50c515e5b9 --- /dev/null +++ b/pool/shard007/Python/0070929_test_constraints.py @@ -0,0 +1,199 @@ +import pytest +import yaml + +from astroplan import Observer +from astropy import units as u +from astropy.coordinates import EarthLocation +from astropy.coordinates import get_moon +from astropy.time import Time + +from pocs.scheduler.field import Field +from pocs.scheduler.observation import Observation + +from pocs.scheduler.constraint import Altitude +from pocs.scheduler.constraint import BaseConstraint +from pocs.scheduler.constraint import Duration +from pocs.scheduler.constraint import MoonAvoidance + + +@pytest.fixture +def observer(config): + loc = config['location'] + location = EarthLocation(lon=loc['longitude'], lat=loc['latitude'], height=loc['elevation']) + return Observer(location=location, name="Test Observer", timezone=loc['timezone']) + + +field_list = yaml.load(""" +- + name: HD 189733 + position: 20h00m43.7135s +22d42m39.0645s + priority: 100 +- + name: HD 209458 + position: 22h03m10.7721s +18d53m03.543s + priority: 100 +- + name: Tres 3 + position: 17h52m07.02s +37d32m46.2012s + priority: 100 + exp_set_size: 15 + min_nexp: 240 +- + name: M5 + position: 15h18m33.2201s +02d04m51.7008s + priority: 50 +- + name: KIC 8462852 + position: 20h06m15.4536s +44d27m24.75s + priority: 50 + exp_time: 60 + exp_set_size: 15 + min_nexp: 45 +- + name: Wasp 33 + position: 02h26m51.0582s +37d33m01.733s + priority: 100 +- + name: M42 + position: 05h35m17.2992s -05d23m27.996s + priority: 25 + exp_time: 240 +- + name: M44 + position: 08h40m24s +19d40m00.12s + priority: 50 +""") + + +@pytest.fixture +def field(): + return Field('Test Observation', '20h00m43.7135s +22d42m39.0645s') + + +@pytest.fixture +def observation(field): + return Observation(field) + + +def test_bad_str_weight(): + with pytest.raises(AssertionError): + BaseConstraint("1.0") + + +def test_negative_weight(): + with pytest.raises(AssertionError): + BaseConstraint(-1.0) + + +def test_default_weight(): + c = BaseConstraint() + assert c.weight == 1.0 + + +def test_altitude_subclass(): + assert issubclass(Altitude, BaseConstraint) + + +def test_altitude_no_minimum(): + with pytest.raises(TypeError): + Altitude() + + +def test_altitude_minimum_no_units(): + with pytest.raises(TypeError): + Altitude(30) + + +def test_altitude_vals(): + ac = Altitude(minimum=30 * u.degree) + assert ac.minimum == 30 * u.degree + + +def test_altitude_defaults(): + ac = Altitude(18 * u.degree) + assert ac.weight == 1.0 + assert ac.minimum == 18 * u.degree + + +def test_altitude_vetor_for_up_target(observation, observer): + ac = Altitude(18 * u.degree) + + time = Time('2016-08-13 07:42:00.034059') + + veto, score = ac.get_score(time, observer, observation) + + assert veto is False + + +def test_altitude_veto_for_down_target(observation, observer): + ac = Altitude(18 * u.degree) + + time = Time('2016-08-13 17:42:00.034059') + + veto, score = ac.get_score(time, observer, observation) + + assert veto is True + + +def test_duration_veto(observer): + dc = Duration(30 * u.degree) + + time = Time('2016-08-13 17:42:00.034059') + sunrise = observer.tonight(time=time, horizon=18 * u.degree)[-1] + + hd189733 = field_list[0] + observation = Observation(Field(**hd189733), **hd189733) + veto, score = dc.get_score(time, observer, observation, sunrise=sunrise) + assert veto is True + + wasp33 = field_list[-3] + observation = Observation(Field(**wasp33), **wasp33) + veto, score = dc.get_score(time, observer, observation, sunrise=sunrise) + assert veto is False + + +def test_duration_score(observer): + dc = Duration(30 * u.degree) + + time = Time('2016-08-13 10:00:00') + sunrise = observer.tonight(time=time, horizon=18 * u.degree)[-1] + + observation1 = Observation(Field('HD189733', '20h00m43.7135s +22d42m39.0645s')) # HD189733 + observation2 = Observation(Field('Hat-P-16', '00h38m17.59s +42d27m47.2s')) # Hat-P-16 + + veto1, score1 = dc.get_score(time, observer, observation1, sunrise=sunrise) + veto2, score2 = dc.get_score(time, observer, observation2, sunrise=sunrise) + + assert veto1 is False and veto2 is False + assert score2 > score1 + + +def test_moon_veto(observer): + mac = MoonAvoidance() + + time = Time('2016-08-13 10:00:00') + + moon = get_moon(time, observer.location) + + observation1 = Observation(Field('Sabik', '17h10m23s -15d43m30s')) # Sabik + + veto1, score1 = mac.get_score(time, observer, observation1, moon=moon) + + assert veto1 is True + + +def test_moon_avoidance(observer): + mac = MoonAvoidance() + + time = Time('2016-08-13 10:00:00') + + moon = get_moon(time, observer.location) + + observation1 = Observation(Field('HD189733', '20h00m43.7135s +22d42m39.0645s')) # HD189733 + observation2 = Observation(Field('Hat-P-16', '00h38m17.59s +42d27m47.2s')) # Hat-P-16 + + veto1, score1 = mac.get_score(time, observer, observation1, moon=moon) + veto2, score2 = mac.get_score(time, observer, observation2, moon=moon) + + assert veto1 is False and veto2 is False + assert score2 > score1 diff --git a/pool/shard007/Python/0070930_problem6.py b/pool/shard007/Python/0070930_problem6.py new file mode 100644 index 0000000000000000000000000000000000000000..01305526b7a6f98b09a1fdbfb891c4b6856f2aa1 --- /dev/null +++ b/pool/shard007/Python/0070930_problem6.py @@ -0,0 +1,35 @@ +#Project Euler Problem 1 @ http://projecteuler.net/problem=6 +#By Michael H. / Aonbyte @ http://github.com/aonbyte +#Problem 6: +# +#The sum of the squares of the first ten natural numbers is, +#12 + 22 + ... + 102 = 385 +#The square of the sum of the first ten natural numbers is, +#(1 + 2 + ... + 10)2 = 552 = 3025 +#Hence the difference between the sum of the squares of the first ten natural +#numbers and the square of the sum is 385 - 3025 = 2640 +# +#Find the difference between the sum of the squares of the first one hundred +#natural numbers and the square of the sum. + +def get_squares(inputList): + """Takes a list of integers and returns a list of the elements squared""" + return [element * element for element in inputList] + +def get_sum(inputList): + """Takes a list of integers and returns the sum of all elements in list""" + return sum(inputList) + +def sum_of_squares(inputList): + """Takes a list of integers and returns the sum of the squares of integers""" + return sum(get_squares(inputList)) + +numbers = range(1,101) #First one hundred natural numbers + +sumSquares = sum_of_squares(numbers) #Sum of the squares of first 100 natural numbers + +squareOfSum = get_sum(numbers) ** 2 #square of the sum of the first 100 natural numbers + +difference = squareOfSum - sumSquares + +print difference \ No newline at end of file diff --git a/pool/shard007/Python/0070932_views.py b/pool/shard007/Python/0070932_views.py new file mode 100644 index 0000000000000000000000000000000000000000..f88ae6a294cad86b551583c2d9af0da19f539230 --- /dev/null +++ b/pool/shard007/Python/0070932_views.py @@ -0,0 +1,76 @@ +# django imports +from django.conf import settings +from django.contrib.auth.decorators import permission_required +from django.db import connection +from django.shortcuts import render_to_response +from django.template import RequestContext + +# lfs_ab_tests imports +from lfs_ab_tests.models import OrderInformation + + +@permission_required("core.manage_shop", login_url="/login/") +def targets_by_theme(request, template_name="lfs_ab_tests/targets_by_theme.html"): + """ + Returns a report with targets by theme. + """ + targets = [] + for source, destination in getattr(settings, "LFS_AB_TESTS_TARGETS", []): + cursor = connection.cursor() + cursor.execute(""" + SELECT source, destination, source_url, destination_url, theme, count(*) + FROM lfs_ab_tests_targetinformation + WHERE source = '%s' + AND destination = '%s' + GROUP BY source, destination, theme""" % (source, destination)) + + for row in cursor.fetchall(): + targets.append({ + "source": row[0], + "destination": row[1], + "source_url": row[2], + "destination_url": row[3], + "theme": row[4], + "amount": row[5], + }) + + return render_to_response(template_name, RequestContext(request, { + "targets": targets, + })) + + +@permission_required("core.manage_shop", login_url="/login/") +def all_targets(request, template_name="lfs_ab_tests/all_targets.html"): + """ + Returns a report with all targets. + """ + targets = [] + for source, destination in getattr(settings, "LFS_AB_TESTS_TARGETS", []): + cursor = connection.cursor() + cursor.execute(""" + SELECT source, destination, source_url, destination_url, theme + FROM lfs_ab_tests_targetinformation + WHERE source = '%s' + AND destination = '%s'""" % (source, destination)) + + for row in cursor.fetchall(): + targets.append({ + "source": row[0], + "destination": row[1], + "source_url": row[2], + "destination_url": row[3], + "theme": row[4], + }) + + return render_to_response(template_name, RequestContext(request, { + "targets": targets, + })) + + +@permission_required("core.manage_shop", login_url="/login/") +def all_orders(request, template_name="lfs_ab_tests/all_orders.html"): + """ + """ + return render_to_response(template_name, RequestContext(request, { + "order_infos": OrderInformation.objects.all().order_by("-order__number"), + })) diff --git a/pool/shard007/Python/0070934_change_readnames2.py b/pool/shard007/Python/0070934_change_readnames2.py new file mode 100644 index 0000000000000000000000000000000000000000..99da5db9d3e5aa26354480d164f903f52a7751a5 --- /dev/null +++ b/pool/shard007/Python/0070934_change_readnames2.py @@ -0,0 +1,27 @@ +#!/usr/bin/python + +from __future__ import print_function +import sys +import os + +#Adds subscripts to reads generated by PBSIM + +if len(sys.argv) >= 3: + fastq_filename = sys.argv[1] + batchnum = sys.argv[2] +else: + print("usage: python change_readnames.py fastq_filename batchnum > fastq_out") + sys.exit(1) + +reads=open(fastq_filename,'r') + +lines = reads.readlines() + +for i in range(0,len(lines)): + line = lines[i] + if i % 2 == 0: + print (line.rstrip(),'_ccs_',batchnum,sep='') + else: + print (line.rstrip()), + +reads.close() diff --git a/pool/shard007/Python/0070937_test_vars.py b/pool/shard007/Python/0070937_test_vars.py new file mode 100644 index 0000000000000000000000000000000000000000..fb4e6bb2939c6836db89bbcc2cb4ebb20232a71d --- /dev/null +++ b/pool/shard007/Python/0070937_test_vars.py @@ -0,0 +1,35 @@ +import random +from pyinq.asserts import * +from pyinq.tags import * + +@testClass +class TestSequenceFunctions: + @before + def setUp(): + self.seq = range(10) + + @test + def test_shuffle(): + # make sure the shuffled TestSequenceFunctions.sequence does not lose any elements + random.shuffle(self.seq) + self.seq.sort() + assert_equal(self.seq, range(10)) + + # should raise an exception for an immutable TestSequenceFunctions.sequence + assert_raises(TypeError, random.shuffle, (1,2,3)) + + @test + def test_choice(): + element = random.choice(self.seq) + assert_true(element in self.seq) + + @test + def test_sample(): + assert_raises(ValueError, random.sample, self.seq, 20) + for element in random.sample(self.seq, 5): + #assert_true(element in self.seq) + assert_in(element,self.seq) + +@test(expect=NameError) +def outside_test(): + print self diff --git a/pool/shard007/Python/0070944_genericworker.py b/pool/shard007/Python/0070944_genericworker.py new file mode 100644 index 0000000000000000000000000000000000000000..117f51c04035c3c8ba6ee79571cdb8f1d66d50c6 --- /dev/null +++ b/pool/shard007/Python/0070944_genericworker.py @@ -0,0 +1,101 @@ +# +# Copyright (C) 2018 by YOUR NAME HERE +# +# This file is part of RoboComp +# +# RoboComp 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. +# +# RoboComp 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 RoboComp. If not, see . + +import sys, Ice, os +from PySide import QtGui, QtCore + +ROBOCOMP = '' +try: + ROBOCOMP = os.environ['ROBOCOMP'] +except KeyError: + print('$ROBOCOMP environment variable not set, using the default value /opt/robocomp') + ROBOCOMP = '/opt/robocomp' + +preStr = "-I/opt/robocomp/interfaces/ -I"+ROBOCOMP+"/interfaces/ --all /opt/robocomp/interfaces/" +Ice.loadSlice(preStr+"CommonBehavior.ice") +import RoboCompCommonBehavior + +additionalPathStr = '' +icePaths = [ '/opt/robocomp/interfaces' ] +try: + SLICE_PATH = os.environ['SLICE_PATH'].split(':') + for p in SLICE_PATH: + icePaths.append(p) + additionalPathStr += ' -I' + p + ' ' +except: + icePaths.append('/opt/robocomp/interfaces') + print('SLICE_PATH environment variable was not exported. Using only the default paths') + pass + +ice_CameraSimple = False +for p in icePaths: + if os.path.isfile(p+'/CameraSimple.ice'): + preStr = "-I/opt/robocomp/interfaces/ -I"+ROBOCOMP+"/interfaces/ " + additionalPathStr + " --all "+p+'/' + wholeStr = preStr+"CameraSimple.ice" + Ice.loadSlice(wholeStr) + ice_CameraSimple = True + break +if not ice_CameraSimple: + print('Couln\'t load CameraSimple') + sys.exit(-1) +from RoboCompCameraSimple import * +ice_EmotionRecognition = False +for p in icePaths: + if os.path.isfile(p+'/EmotionRecognition.ice'): + preStr = "-I/opt/robocomp/interfaces/ -I"+ROBOCOMP+"/interfaces/ " + additionalPathStr + " --all "+p+'/' + wholeStr = preStr+"EmotionRecognition.ice" + Ice.loadSlice(wholeStr) + ice_EmotionRecognition = True + break +if not ice_EmotionRecognition: + print('Couln\'t load EmotionRecognition') + sys.exit(-1) +from RoboCompEmotionRecognition import * + + +from emotionrecognitionI import * + + +class GenericWorker(QtCore.QObject): + kill = QtCore.Signal() + + + def __init__(self, mprx): + super(GenericWorker, self).__init__() + + + self.camerasimple_proxy = mprx["CameraSimpleProxy"] + + + self.mutex = QtCore.QMutex(QtCore.QMutex.Recursive) + self.Period = 30 + self.timer = QtCore.QTimer(self) + + + @QtCore.Slot() + def killYourSelf(self): + rDebug("Killing myself") + self.kill.emit() + + # \brief Change compute period + # @param per Period in ms + @QtCore.Slot(int) + def setPeriod(self, p): + print("Period changed", p) + Period = p + timer.start(Period) diff --git a/pool/shard007/Python/0070945_step.py b/pool/shard007/Python/0070945_step.py new file mode 100644 index 0000000000000000000000000000000000000000..a221100675fc686f1d6b41c5205d3482b42e5f24 --- /dev/null +++ b/pool/shard007/Python/0070945_step.py @@ -0,0 +1,36 @@ +""" Step model +""" +from conjureup.app_config import app + + +class StepModel: + + def __init__(self, step, path): + self.title = step.get('title', '') + self.description = step.get('description', '') + self.result = '' + self.viewable = step.get('viewable', False) + + self.additional_input = step.get('additional-input', []) + + def __getattr__(self, attr): + """ + Override attribute lookup since ConsoleUI doesn't implement + everything PegagusUI does. + """ + + def nofunc(*args, **kwargs): + app.log.debug(attr) + + try: + getattr(StepModel, attr) + except: + # Log the invalid attribute call + setattr(self.__class__, attr, nofunc) + return getattr(StepModel, attr) + + def __repr__(self): + return "".format(self.title, + self.description, + self.viewable, + self.path) diff --git a/pool/shard007/Python/0070953_font_table_ttf.py b/pool/shard007/Python/0070953_font_table_ttf.py new file mode 100644 index 0000000000000000000000000000000000000000..fbe5dc1fc98531a4fe84bc0758eb128a374b20ae --- /dev/null +++ b/pool/shard007/Python/0070953_font_table_ttf.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +# -*- noplot -*- +""" +matplotlib has support for freetype fonts. Here's a little example +using the 'table' command to build a font table that shows the glyphs +by character code. + +Usage python font_table_ttf.py somefile.ttf +""" + +import sys +import os + +import matplotlib +from matplotlib.ft2font import FT2Font +from matplotlib.font_manager import FontProperties +from pylab import figure, table, show, axis, title + +import six +from six import unichr + +# the font table grid + +labelc = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + 'A', 'B', 'C', 'D', 'E', 'F'] +labelr = ['00', '10', '20', '30', '40', '50', '60', '70', '80', '90', + 'A0', 'B0', 'C0', 'D0', 'E0', 'F0'] + +if len(sys.argv) > 1: + fontname = sys.argv[1] +else: + fontname = os.path.join(matplotlib.get_data_path(), + 'fonts', 'ttf', 'Vera.ttf') + +font = FT2Font(fontname) +codes = list(font.get_charmap().items()) +codes.sort() + +# a 16,16 array of character strings +chars = [['' for c in range(16)] for r in range(16)] +colors = [[(0.95, 0.95, 0.95) for c in range(16)] for r in range(16)] + +figure(figsize=(8, 4), dpi=120) +for ccode, glyphind in codes: + if ccode >= 256: + continue + r, c = divmod(ccode, 16) + s = unichr(ccode) + chars[r][c] = s + +lightgrn = (0.5, 0.8, 0.5) +title(fontname) +tab = table(cellText=chars, + rowLabels=labelr, + colLabels=labelc, + rowColours=[lightgrn]*16, + colColours=[lightgrn]*16, + cellColours=colors, + cellLoc='center', + loc='upper left') + +for key, cell in tab.get_celld().items(): + row, col = key + if row > 0 and col > 0: + cell.set_text_props(fontproperties=FontProperties(fname=fontname)) +axis('off') +show() diff --git a/pool/shard007/Python/0070956_models.py b/pool/shard007/Python/0070956_models.py new file mode 100644 index 0000000000000000000000000000000000000000..de6ec1c0e18ce8876e9340a01a809ffbf77b758b --- /dev/null +++ b/pool/shard007/Python/0070956_models.py @@ -0,0 +1,164 @@ +import collections +import itertools +import os +import re +from os.path import join + +from django.conf import settings +from django.contrib.auth.models import AbstractBaseUser, UserManager +from django.db import models +from django.shortcuts import get_object_or_404 +from django.utils import timezone + +from catalog.models import Category, Course + + +class CustomUserManager(UserManager): + PATTERN = re.compile(r'[\W_]+') + + def _create_user(self, netid, email, password, **extra_fields): + """ + Creates and saves a User with the given username, email and password. + """ + now = timezone.now() + if not netid: + raise ValueError('The given netid must be set') + email = self.normalize_email(email) + user = self.model(netid=netid, email=email, last_login=now, **extra_fields) + + user.set_password(password) + user.save(using=self._db) + return user + + def create_user(self, netid, email=None, password=None, **extra_fields): + return self._create_user(netid, email, password, **extra_fields) + + def create_superuser(self, netid, email, password, **extra_fields): + return self._create_user(netid, email, password, is_staff=True, **extra_fields) + + +class User(AbstractBaseUser): + + USERNAME_FIELD = 'netid' + REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] + DEFAULT_PHOTO = join(settings.STATIC_URL, "images/default.jpg") + objects = CustomUserManager() + + netid = models.CharField(max_length=20, unique=True) + created = models.DateTimeField(auto_now_add=True) + edited = models.DateTimeField(auto_now=True) + first_name = models.CharField(max_length=127) + last_name = models.CharField(max_length=127) + email = models.CharField(max_length=255, unique=True) + registration = models.CharField(max_length=80, blank=True) + welcome = models.BooleanField(default=True) + comment = models.TextField(blank=True, default='') + + register_method = models.CharField(max_length=32) + last_login_method = models.CharField(max_length=32) + + inferred_faculty = models.TextField(blank=True) + inscription_faculty = models.TextField(blank=True) + + is_staff = models.BooleanField(default=False) + is_academic = models.BooleanField(default=False) + is_representative = models.BooleanField(default=False) + + moderated_courses = models.ManyToManyField('catalog.Course', blank=True) + + notify_on_response = models.BooleanField(default=True) + notify_on_new_doc = models.BooleanField(default=True) + notify_on_new_thread = models.BooleanField(default=True) + notify_on_upload = True + + def __init__(self, *args, **kwargs): + self._moderated_courses = None + super().__init__(*args, **kwargs) + + @property + def name(self): + return "{0.first_name} {0.last_name}".format(self) + + def getPrograms(self): + """Returns a QS of the programs in which a course is followed by the user""" + blocs = Category.objects.filter(course__in=self.following_courses).select_related('parent') + programs = [bloc.parent.slug for bloc in blocs.all()] + return Category.objects.filter(level=2, slug__in=programs).annotate( + slug_=models.functions.Cast( + models.functions.Concat( + models.Value("mycourses-"), 'slug' + ), output_field=models.SlugField() + ), + ) + + def getBlocs(self, program_slug): + """Returns a QS of blocs that contain a course the user follows""" + return set(Category.objects.filter( + level=3, parent__slug=program_slug, + course__in=self.following_courses + )) + + @property + def following_courses(self): + return self.courses_set.all() + + def is_following(self, course: Course): + return self.courses_set.filter(slug=course.slug).exists() + + def has_module_perms(self, *args, **kwargs): + return True # TODO : is this a good idea ? + + def has_perm(self, perm_list, obj=None): + return self.is_staff + + def write_perm(self, obj): + if self.is_staff: + return True + + if obj is None: + return False + + if self._moderated_courses is None: + ids = [course.id for course in self.moderated_courses.only('id')] + self._moderated_courses = ids + + return obj.write_perm(self, self._moderated_courses) + + def fullname(self): + return self.name + + def get_short_name(self): + return self.netid + + def update_inscription_faculty(self): + inscription = self.inscription_set.order_by("-year").first() + if inscription: + self.inscription_faculty = inscription.faculty + self.save() + + def update_inferred_faculty(self): + courses = self.following_courses + categories = [x.categories.all() for x in courses] + categories = list(itertools.chain.from_iterable(categories)) + + faculties = [x.get_ancestors().filter(level=1).all() for x in categories] + faculties = list(itertools.chain.from_iterable(faculties)) + + counts = collections.Counter(faculties) + if counts: + faculty = counts.most_common()[0][0] + self.inferred_faculty = faculty.name + self.save() + + +class Inscription(models.Model): + user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) + faculty = models.CharField(max_length=80, blank=True, default='') + section = models.CharField(max_length=80, blank=True, default='') + year = models.PositiveIntegerField(blank=True, null=True) + + created = models.DateTimeField(auto_now_add=True) + edited = models.DateTimeField(auto_now=True) + + class Meta: + unique_together = ('user', 'section', 'faculty', 'year') diff --git a/pool/shard007/Python/0070959_browser.py b/pool/shard007/Python/0070959_browser.py new file mode 100644 index 0000000000000000000000000000000000000000..9a01db5ecdfe91812910c7780f7756039cc3d446 --- /dev/null +++ b/pool/shard007/Python/0070959_browser.py @@ -0,0 +1,205 @@ +# -*- coding: utf-8 -*- + +# Copyright(C) 2020 Ludovic LANGE +# +# This file is part of a weboob module. +# +# This weboob module 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 weboob module 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 weboob module. If not, see . + +from __future__ import unicode_literals + + +from weboob.browser import LoginBrowser, URL, need_login +from weboob.exceptions import BrowserIncorrectPassword +from datetime import datetime +from dateutil.relativedelta import relativedelta +from weboob.capabilities.bill import Subscription +import calendar + +from .pages import ( + LoginPage, + HomePage, + StatusPage, + EmployerPage, + EmployeesPage, + RegistrationPage, + RegistrationDashboardPage, + DirectDebitSummaryPage, + EmployeesDashboardPage, + CurrentFiscalAdvantagePage, + LastDayMonthPage, + DirectDebitsHeaderPage, + DirectDebitsDetailPage, + PayslipDownloadPage, + DirectDebitDownloadPage, + TaxCertificateDownloadPage, + TaxCertificatesPage, +) + + +class CesuBrowser(LoginBrowser): + BASEURL = 'https://www.cesu.urssaf.fr' + + logout = URL(r'/cesuwebdec/deconnexion$') + + login = URL(r'/info/accueil.html$', LoginPage) + + homepage = URL(r'/info/accueil\.login\.do$', HomePage) + + status = URL(r'/cesuwebdec/status', StatusPage) + employer = URL(r'/cesuwebdec/employeursIdentite/(?P.*)', EmployerPage) + employees = URL(r'/cesuwebdec/employeurs/(?P.*)/salaries', EmployeesPage) + registrations = URL(r'/cesuwebdec/employeurs/(?P.*)/declarationsby\?.*', RegistrationPage) + registrations_dashboard = URL(r'/cesuwebdec/employeurs/(?P.*)/declarationsTdBby\?.*', RegistrationDashboardPage) + direct_debits_summary = URL(r'/cesuwebdec/employeurs/(?P.*)/recapprelevements', DirectDebitSummaryPage) + employees_dashboard = URL(r'/cesuwebdec/salariesTdb?pseudoSiret=(?P.*)&maxResult=8', EmployeesDashboardPage) + current_fiscal_advantage = URL(r'/cesuwebdec/employeurs/(?P.*)/avantagefiscalencours', CurrentFiscalAdvantagePage) + last_day_month = URL(r'/cesuwebdec/employeurs/(?P.*)/dernierJourOuvreMois', LastDayMonthPage) + direct_debits_header = URL(r'/cesuwebdec/employeurs/(?P.*)/entetePrelevements\?.*', DirectDebitsHeaderPage) + direct_debits_detail = URL(r'/cesuwebdec/employeurs/(?P.*)/detailPrelevements\?periode=202001&type=IPVT&reference=0634675&idPrelevement=0', DirectDebitsDetailPage) + tax_certificates = URL(r'/cesuwebdec/employeurs/(?P.*)/attestationsfiscales', TaxCertificatesPage) + payslip_download = URL(r'/cesuwebdec/employeurs/(?P.*)/editions/bulletinSalairePE\?refDoc=(?P.*)', PayslipDownloadPage) + direct_debit_download = URL(r'/cesuwebdec/employeurs/(?P.*)/editions/avisPrelevement\?reference=(?P.*)&periode=(?P.*)&type=(?P.*)', DirectDebitDownloadPage) + tax_certificate_download = URL(r'/cesuwebdec/employeurs/(?P.*)/editions/attestation_fiscale_annee\?periode=(?P.*)', TaxCertificateDownloadPage) + + employer = None + compteur = 0 + + def do_login(self): + self.session.cookies.clear() + self.login.go() + self.session.headers.update( + { + "Accept": "application/json, text/javascript, */*; q=0.01", + "X-Requested-With": "XMLHttpRequest", + } + ) + self.page.login(self.username, self.password) + if not self.page.logged: + raise BrowserIncorrectPassword() + + self.status.go() + self.employer = self.page.get_object().get("numero") + + def do_logout(self): + self.logout.go() + self.session.cookies.clear() + + @need_login + def iter_subscription(self): + self.employees.go(employer=self.employer) + + for sub in self.page.iter_subscriptions(subscriber=None): + yield sub + + s = Subscription() + s.label = "Prélèvements" + s.id = "prelevements" + s._type = s.id + yield s + + s = Subscription() + s.label = "Attestations fiscales" + s.id = "taxcertificates" + s._type = s.id + yield s + + def _search_registrations( + self, subscription, begin_date, end_date, num_start, step + ): + self.registrations.go( + employer=self.employer, + params={ + "numInterneSalarie": subscription.id, + "dtDebutRecherche": begin_date.strftime("%Y%m%d"), + "dtFinRecherche": end_date.strftime("%Y%m%d"), + "numStart": num_start, + "nbAffiche": step, + "numeroOrdre": self.compteur, + }, + ) + self.compteur += 1 + + def _search_direct_debits(self, begin_date, end_date): + self.direct_debits_header.go( + employer=self.employer, + params={ + "dtDebut": begin_date.strftime("%Y%m%d"), + "dtFin": end_date.strftime("%Y%m%d"), + "numeroOrdre": self.compteur, + "nature": "", + }, + ) + self.compteur += 1 + + @need_login + def iter_documents(self, subscription): + self.compteur = 0 + if subscription._type == "employee": + + end_date = datetime.today() + # 5 years maximum + begin_date = end_date - relativedelta(years=+5) + + has_results = True + num_start = 0 + step = 24 + + while has_results: + self._search_registrations( + subscription, begin_date, end_date, num_start, step + ) + + num_start += step + + has_results = len(self.page.get_objects()) > 0 + # # No more documents + # if self.page.has_error_msg(): + # break + + for doc in self.page.iter_documents( + subscription=subscription.id, employer=self.employer + ): + yield doc + + elif subscription._type == "prelevements": + + # Start end of month + end_date = datetime.today() + end_date += relativedelta( + day=calendar.monthrange(end_date.year, end_date.month)[1], + hour=0, + minute=0, + second=0, + microsecond=0, + ) + # 1 year maximum ; beginning of month + begin_date = end_date - relativedelta(years=+1, day=1) + + self._search_direct_debits(begin_date, end_date) + + has_results = len(self.page.get_objects()) > 0 + + for doc in self.page.iter_documents( + subscription=subscription.id, employer=self.employer + ): + yield doc + + elif subscription._type == "taxcertificates": + + self.tax_certificates.go(employer=self.employer) + for doc in self.page.iter_documents( + subscription=subscription.id, employer=self.employer + ): + yield doc diff --git a/pool/shard007/Python/0070961_server_diagnostics.py b/pool/shard007/Python/0070961_server_diagnostics.py new file mode 100644 index 0000000000000000000000000000000000000000..968e7b6e135ee17e2666c374bc3f13705111cdc5 --- /dev/null +++ b/pool/shard007/Python/0070961_server_diagnostics.py @@ -0,0 +1,57 @@ +# Copyright 2011 OpenStack Foundation +# All Rights Reserved. +# +# 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. + +import webob.exc + +from nova.api.openstack import extensions +from nova import compute +from nova import exception + + +ALIAS = "os-server-diagnostics" +authorize = extensions.extension_authorizer('compute', 'v3:' + ALIAS) + + +class ServerDiagnosticsController(object): + @extensions.expected_errors(404) + def index(self, req, server_id): + context = req.environ["nova.context"] + authorize(context) + compute_api = compute.API() + try: + instance = compute_api.get(context, server_id, want_objects=True) + except exception.InstanceNotFound as e: + raise webob.exc.HTTPNotFound(e.format_message()) + + return compute_api.get_diagnostics(context, instance) + + +class ServerDiagnostics(extensions.V3APIExtensionBase): + """Allow Admins to view server diagnostics through server action.""" + + name = "ServerDiagnostics" + alias = ALIAS + version = 1 + + def get_resources(self): + parent_def = {'member_name': 'server', 'collection_name': 'servers'} + resources = [ + extensions.ResourceExtension(ALIAS, + ServerDiagnosticsController(), + parent=parent_def)] + return resources + + def get_controller_extensions(self): + return [] diff --git a/pool/shard007/Python/0070964_triangle_survey_gui.py b/pool/shard007/Python/0070964_triangle_survey_gui.py new file mode 100644 index 0000000000000000000000000000000000000000..34272709f4ad0ac0dc7d7b547d935fde03e2869a --- /dev/null +++ b/pool/shard007/Python/0070964_triangle_survey_gui.py @@ -0,0 +1,58 @@ +import numpy as np +from scipy.special import * +import scipy.linalg as lin +import FE +from Tkinter import * +import triangle +import matplotlib as mpl +mpl.use('TkAgg') +from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg +from matplotlib.figure import Figure +import matplotlib.pyplot as plt +import matplotlib.tri as tri +import sys + +# GUI for a triangle explorer + +class TriGUI: + + def __init__(self,root,canvas_width,canvas_height): + self.root=root + self.canvas_width = canvas_width + self.canvas_height = canvas_height + + self.moduli_space = {'vertices':np.array([[0.,0.],[1.,0.],[0.5,np.sqrt(3.)/2.]]),'triangles':[0,1,2]} + + self.fig, self.ax = mpl.pyplot.subplots() + self.ax.clear() + self.ax.autoscale(enable=False) + self.ax.axis('off') + self.canvas = FigureCanvasTkAgg(self.fig,master=root) + self.canvas.show() + self.canvas.get_tk_widget().pack() + + X = self.moduli_space['vertices'][:,0] + Y = self.moduli_space['vertices'][:,1] + outline = tri.Triangulation(X,Y) + self.ax.triplot(outline) + + #self.canvas.mpl_connect("button_press_event", self.setVertex) + + def quite(self): + self.root.destroy() + +class EigenfunctionGUI: + + def __init__(self,root,canvas_width,canvas_height,a,b,c): + self.root=root + self.canvas_width = canvas_width + + +if __name__ == '__main__': + root = Tk() + + T = TriGUI(root,600,600) + + root.mainloop() + + T.quit() diff --git a/pool/shard007/Python/0070965_gl_procs.py b/pool/shard007/Python/0070965_gl_procs.py new file mode 100644 index 0000000000000000000000000000000000000000..b1fffc4ca07568af57cc34cdd1d925f408f578a7 --- /dev/null +++ b/pool/shard007/Python/0070965_gl_procs.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python + +# (C) Copyright IBM Corporation 2004, 2005 +# All Rights Reserved. +# +# Permission is hereby granted, free of charge, to any person obtaining a +# copy of this software and associated documentation files (the "Software"), +# to deal in the Software without restriction, including without limitation +# on the rights to use, copy, modify, merge, publish, distribute, sub +# license, and/or sell copies of the Software, and to permit persons to whom +# the Software is furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice (including the next +# paragraph) shall be included in all copies or substantial portions of the +# Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL +# IBM AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# Authors: +# Ian Romanick + +import license +import gl_XML, glX_XML +import sys, getopt + +class PrintGlProcs(gl_XML.gl_print_base): + def __init__(self, es=False): + gl_XML.gl_print_base.__init__(self) + + self.es = es + self.name = "gl_procs.py (from Mesa)" + self.license = license.bsd_license_template % ( \ +"""Copyright (C) 1999-2001 Brian Paul All Rights Reserved. +(C) Copyright IBM Corporation 2004, 2006""", "BRIAN PAUL, IBM") + + + def printRealHeader(self): + print """ +/* This file is only included by glapi.c and is used for + * the GetProcAddress() function + */ + +typedef struct { + GLint Name_offset; +#if defined(NEED_FUNCTION_POINTER) || defined(GLX_INDIRECT_RENDERING) + _glapi_proc Address; +#endif + GLuint Offset; +} glprocs_table_t; + +#if !defined(NEED_FUNCTION_POINTER) && !defined(GLX_INDIRECT_RENDERING) +# define NAME_FUNC_OFFSET(n,f1,f2,f3,o) { n , o } +#elif defined(NEED_FUNCTION_POINTER) && !defined(GLX_INDIRECT_RENDERING) +# define NAME_FUNC_OFFSET(n,f1,f2,f3,o) { n , (_glapi_proc) f1 , o } +#elif defined(NEED_FUNCTION_POINTER) && defined(GLX_INDIRECT_RENDERING) +# define NAME_FUNC_OFFSET(n,f1,f2,f3,o) { n , (_glapi_proc) f2 , o } +#elif !defined(NEED_FUNCTION_POINTER) && defined(GLX_INDIRECT_RENDERING) +# define NAME_FUNC_OFFSET(n,f1,f2,f3,o) { n , (_glapi_proc) f3 , o } +#endif + +""" + return + + def printRealFooter(self): + print '' + print '#undef NAME_FUNC_OFFSET' + return + + def printFunctionString(self, name): + print ' "gl%s\\0"' % (name) + + def printBody(self, api): + print '' + print 'static const char gl_string_table[] =' + + base_offset = 0 + table = [] + for func in api.functionIterateByOffset(): + name = func.dispatch_name() + self.printFunctionString(func.name) + table.append((base_offset, "gl" + name, "gl" + name, "NULL", func.offset)) + + # The length of the function's name, plus 2 for "gl", + # plus 1 for the NUL. + + base_offset += len(func.name) + 3 + + + for func in api.functionIterateByOffset(): + for n in func.entry_points: + if n != func.name: + name = func.dispatch_name() + self.printFunctionString( n ) + + if func.has_different_protocol(n): + alt_name = "gl" + func.static_glx_name(n) + table.append((base_offset, "gl" + name, alt_name, alt_name, func.offset)) + else: + table.append((base_offset, "gl" + name, "gl" + name, "NULL", func.offset)) + + base_offset += len(n) + 3 + + + print ' ;' + print '' + print '' + print "#ifdef USE_MGL_NAMESPACE" + for func in api.functionIterateByOffset(): + for n in func.entry_points: + if (not func.is_static_entry_point(func.name)) or (func.has_different_protocol(n) and not func.is_static_entry_point(n)): + print '#define gl_dispatch_stub_%u mgl_dispatch_stub_%u' % (func.offset, func.offset) + break + print "#endif /* USE_MGL_NAMESPACE */" + print '' + print '' + print '#if defined(NEED_FUNCTION_POINTER) || defined(GLX_INDIRECT_RENDERING)' + for func in api.functionIterateByOffset(): + for n in func.entry_points: + if (not func.is_static_entry_point(func.name)) or (func.has_different_protocol(n) and not func.is_static_entry_point(n)): + print '%s GLAPIENTRY gl_dispatch_stub_%u(%s);' % (func.return_type, func.offset, func.get_parameter_string()) + break + + if self.es: + categories = {} + for func in api.functionIterateByOffset(): + for n in func.entry_points: + cat, num = api.get_category_for_name(n) + if (cat.startswith("es") or cat.startswith("GL_OES")): + if not categories.has_key(cat): + categories[cat] = [] + proto = 'GLAPI %s GLAPIENTRY %s(%s);' \ + % (func.return_type, "gl" + n, func.get_parameter_string(n)) + categories[cat].append(proto) + if categories: + print '' + print '/* OpenGL ES specific prototypes */' + print '' + keys = categories.keys() + keys.sort() + for key in keys: + print '/* category %s */' % key + print "\n".join(categories[key]) + print '' + + print '#endif /* defined(NEED_FUNCTION_POINTER) || defined(GLX_INDIRECT_RENDERING) */' + + print '' + print 'static const glprocs_table_t static_functions[] = {' + + for info in table: + print ' NAME_FUNC_OFFSET(%5u, %s, %s, %s, %d),' % info + + print ' NAME_FUNC_OFFSET(-1, NULL, NULL, NULL, 0)' + print '};' + return + + +def show_usage(): + print "Usage: %s [-f input_file_name] [-c]" % sys.argv[0] + print "-c Enable compatibility with OpenGL ES." + sys.exit(1) + +if __name__ == '__main__': + file_name = "gl_API.xml" + + try: + (args, trail) = getopt.getopt(sys.argv[1:], "f:c") + except Exception,e: + show_usage() + + es = False + for (arg,val) in args: + if arg == "-f": + file_name = val + elif arg == "-c": + es = True + + api = gl_XML.parse_GL_API(file_name, glX_XML.glx_item_factory()) + printer = PrintGlProcs(es) + printer.Print(api) diff --git a/pool/shard007/Python/0070967_sliceBL.py b/pool/shard007/Python/0070967_sliceBL.py new file mode 100644 index 0000000000000000000000000000000000000000..479489aeab6bbd3dc2d4fe088563ee8b6903fa09 --- /dev/null +++ b/pool/shard007/Python/0070967_sliceBL.py @@ -0,0 +1,105 @@ +"""Example for PyFRAP on how generate BL meshes around a ROI. + +Draws mesh and saves it if filename is given. + +USAGE: python sliceBL.py outputFilePath + +""" + +#Import necessary modules +from pyfrp.subclasses import pyfrp_embryo +from pyfrp.modules import pyfrp_misc_module +from pyfrp.modules import pyfrp_gmsh_IO_module + +from pyfrp.modules.pyfrp_term_module import * + +import numpy as np + +import matplotlib.pyplot as plt +from matplotlib import cm + +import csv +import sys +import os + +#-------------------------------------------------------- +# Define parameters +#-------------------------------------------------------- + +# Imaging depth +sliceDepth=36. +sliceWidth=5. + +# Resolution +dataResMu=566.79 +dataResPx=512 + +# Define bleached square (assuming its centered) +sidelength=2*73.71 + +#Try to make rim 100px wide +#rimFactor=0.8 +rimFactor=1.-101./316.74 + +# Define cone geometry +cylinderHeight=90.3332804037 +coneUpperRadius=635.3/2. +coneLowerRadius=448.5/2. + +# Slice +center=[249.00918273645539, 263.82920110192839] +imagingRadius=216.742098118 + +#-------------------------------------------------------- +# Embryo setup +#-------------------------------------------------------- + +# Create embryo +emb=pyfrp_embryo.embryo("Test") + +# Set experimental details +emb.setDataResMu(dataResMu) +emb.setSliceDepthMu(sliceDepth) +emb.offsetBleachedPx=[center[0]-sidelength/2.,center[1]-sidelength/2.] + +# Geometry +emb.setGeometry2Cone(center,coneUpperRadius,coneLowerRadius,cylinderHeight) + +# Update geometry properties in geo-file +emb.geometry.updateGeoFile() + +# Create default ROIs +emb.genDefaultROIs(emb.geometry.getCenter(),imagingRadius,rimFactor=rimFactor,sliceHeightPx=-sliceDepth) +emb.newAnalysis() + +# Add simulation and mesh +sim=emb.newSimulation() + +# Generate original mesh +sim.mesh.genMesh() + +# Read geo and add circle +dGeo=emb.geometry.readGeoFile() +v,a,l,sf=dGeo.addCircleByParameters(center,imagingRadius,-sliceDepth,35.,genSurface=True) + +# Add BLF +blf=dGeo.addBoundaryLayerField(hfar=35.,hwall_n=10.,hwall_t=10.,thickness=15.,Quads=0.) +blf.setAsBkgdField() +sf.addToBoundaryLayer(boundField=blf) + +# Update geometry +fnOut=emb.geometry.fnGeo.replace(".geo","_sliceBL.geo") +dGeo.writeToFile(fnOut) +emb.geometry.setFnGeo(fnOut) + +# Generate new mesh +sim.mesh.genMesh() + +# Show mesh +sim.mesh.plotMesh() + +# Save mesh +if len(sys.argv)>0: + sim.mesh.saveMeshToImg(sys.argv[1]) + +raw_input("Press to quit") diff --git a/pool/shard007/Python/0070968_test_dde.py b/pool/shard007/Python/0070968_test_dde.py new file mode 100644 index 0000000000000000000000000000000000000000..38e366c6d2878d1944128a342e2d19cd427b51e8 --- /dev/null +++ b/pool/shard007/Python/0070968_test_dde.py @@ -0,0 +1,16 @@ +import pytest +import timesynth as ts + + +def run_test(): + time_sampler = ts.TimeSampler(stop_time=20) + irregular_time_samples = time_sampler.sample_irregular_time(num_points=500, keep_percentage=50) + dde = ts.signals.MackeyGlass() + samples = dde.sample_vectorized(irregular_time_samples) + single_sample = dde.sample_next(irregular_time_samples[0], None, None) + return samples, single_sample + + +def test_dde(): + samples, single_sample = run_test() + assert len(samples) == 250 diff --git a/pool/shard007/Python/0070980_test_eels.py b/pool/shard007/Python/0070980_test_eels.py new file mode 100644 index 0000000000000000000000000000000000000000..4e035e070be3b9ff38b250215bad9e01ee536dbe --- /dev/null +++ b/pool/shard007/Python/0070980_test_eels.py @@ -0,0 +1,174 @@ +# Copyright 2007-2011 The HyperSpy developers +# +# This file is part of HyperSpy. +# +# HyperSpy 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. +# +# HyperSpy 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 HyperSpy. If not, see . + + +import numpy as np +import nose.tools + +import hyperspy.hspy as hp + + +class Test_Estimate_Elastic_Scattering_Threshold: + + def setUp(self): + # Create an empty spectrum + s = hp.signals.EELSSpectrumSimulation(np.zeros((3, 2, 1024))) + energy_axis = s.axes_manager.signal_axes[0] + energy_axis.scale = 0.02 + energy_axis.offset = -5 + + gauss = hp.components.Gaussian() + gauss.centre.value = 0 + gauss.A.value = 5000 + gauss.sigma.value = 0.5 + gauss2 = hp.components.Gaussian() + gauss2.sigma.value = 0.5 + # Inflexion point 1.5 + gauss2.A.value = 5000 + gauss2.centre.value = 5 + s.data[:] = (gauss.function(energy_axis.axis) + + gauss2.function(energy_axis.axis)) + self.signal = s + + def test_min_in_window_with_smoothing(self): + s = self.signal + thr = s.estimate_elastic_scattering_threshold( + window=5, + window_length=5, + tol=0.00001) + nose.tools.assert_true(np.allclose(thr.data, 2.5)) + + def test_min_in_window_without_smoothing_single_spectrum(self): + s = self.signal[0, 0] + thr = s.estimate_elastic_scattering_threshold( + window=5, + window_length=0, + tol=0.001) + nose.tools.assert_true(np.allclose(thr.data, 2.49)) + + def test_min_in_window_without_smoothing(self): + s = self.signal + thr = s.estimate_elastic_scattering_threshold( + window=5, + window_length=0, + tol=0.001) + nose.tools.assert_true(np.allclose(thr.data, 2.49)) + + def test_min_not_in_window(self): + # If I use a much lower window, this is the value that has to be + # returned as threshold. + s = self.signal + data = s.estimate_elastic_scattering_threshold(window=1.5, + tol=0.001).data + nose.tools.assert_true(np.all(np.isnan(data))) + + +class TestEstimateZLPCentre(): + + def setUp(self): + s = hp.signals.EELSSpectrumSimulation(np.diag(np.arange(1, 11))) + s.axes_manager[-1].scale = 0.1 + s.axes_manager[-1].offset = 100 + self.spectrum = s + + def test_estimate_zero_loss_peak_centre(self): + s = self.spectrum + nose.tools.assert_true( + np.allclose( + s.estimate_zero_loss_peak_centre().data, + np.arange( + 100, + 101, + 0.1))) + + +class TestAlignZLP(): + + def setUp(self): + s = hp.signals.EELSSpectrumSimulation(np.zeros((10, 100))) + self.scale = 0.1 + self.offset = -2 + eaxis = s.axes_manager.signal_axes[0] + eaxis.scale = self.scale + eaxis.offset = self.offset + self.izlp = eaxis.value2index(0) + self.bg = 2 + self.ishifts = np.array([0, 4, 2, -2, 5, -2, -5, -9, -9, -8]) + self.new_offset = self.offset - self.ishifts.min() * self.scale + s.data[np.arange(10), self.ishifts + self.izlp] = 10 + s.data += self.bg + s.axes_manager[-1].offset += 100 + self.spectrum = s + + def test_align_zero_loss_peak_calibrate_true(self): + s = self.spectrum + s.align_zero_loss_peak(calibrate=True, print_stats=False) + zlpc = s.estimate_zero_loss_peak_centre() + nose.tools.assert_true(np.allclose(zlpc.data.mean(), 0)) + nose.tools.assert_true(np.allclose(zlpc.data.std(), 0)) + + def test_align_zero_loss_peak_calibrate_false(self): + s = self.spectrum + s.align_zero_loss_peak(calibrate=False, print_stats=False) + zlpc = s.estimate_zero_loss_peak_centre() + nose.tools.assert_true(np.allclose(zlpc.data.std(), 0)) + + def test_also_aligns(self): + s = self.spectrum + s2 = s.deepcopy() + s.align_zero_loss_peak(calibrate=True, + print_stats=False, + also_align=[s2]) + zlpc = s2.estimate_zero_loss_peak_centre() + nose.tools.assert_equal(zlpc.data.mean(), 0) + nose.tools.assert_equal(zlpc.data.std(), 0) + + def test_align_zero_loss_peak_with_spike_signal_range(self): + s = self.spectrum + spike = np.zeros((10, 100)) + spike_amplitude = 20 + spike[:, 75] = spike_amplitude + s.data += spike + s.align_zero_loss_peak( + print_stats=False, subpixel=False, signal_range=(98., 102.)) + zlp_max = s.isig[-0.5:0.5].max(-1).data + # Max value in the original spectrum is 12, but due to the aligning + # the peak is split between two different channels. So 8 is the + # maximum value for the aligned spectrum + nose.tools.assert_true(np.allclose(zlp_max, 8)) + + +class TestPowerLawExtrapolation: + + def setUp(self): + s = hp.signals.EELSSpectrum(0.1 * np.arange(50, 250, 0.5) ** -3.) + s.metadata.Signal.binned = False + s.axes_manager[-1].offset = 50 + s.axes_manager[-1].scale = 0.5 + self.s = s + + def test_unbinned(self): + sc = self.s.isig[:300] + s = sc.power_law_extrapolation(extrapolation_size=100) + nose.tools.assert_true(np.allclose(s.data, self.s.data)) + + def test_binned(self): + self.s.data *= self.s.axes_manager[-1].scale + self.s.metadata.Signal.binned = True + sc = self.s.isig[:300] + s = sc.power_law_extrapolation(extrapolation_size=100) + nose.tools.assert_true(np.allclose(s.data, self.s.data)) diff --git a/pool/shard007/Python/0070984_volume.py b/pool/shard007/Python/0070984_volume.py new file mode 100644 index 0000000000000000000000000000000000000000..f7286403498a555edb43f7ec2a30c712369a4942 --- /dev/null +++ b/pool/shard007/Python/0070984_volume.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python +# Copyright 2010 United States Government as represented by the +# Administrator of the National Aeronautics and Space Administration. +# All Rights Reserved. +# +# 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. + +"""Starter script for Cinder Volume.""" + +import os + +import eventlet + +from cinder import objects + +if os.name == 'nt': + # eventlet monkey patching the os module causes subprocess.Popen to fail + # on Windows when using pipes due to missing non-blocking IO support. + eventlet.monkey_patch(os=False) +else: + eventlet.monkey_patch() + +import sys +import warnings + +warnings.simplefilter('once', DeprecationWarning) + +from oslo_config import cfg +from oslo_log import log as logging + +from cinder import i18n +i18n.enable_lazy() + +# Need to register global_opts +from cinder.common import config # noqa +from cinder import service +from cinder import utils +from cinder import version + + +deprecated_host_opt = cfg.DeprecatedOpt('host') +host_opt = cfg.StrOpt('backend_host', help='Backend override of host value.', + deprecated_opts=[deprecated_host_opt]) +cfg.CONF.register_cli_opt(host_opt) +CONF = cfg.CONF + + +def main(): + objects.register_all() + CONF(sys.argv[1:], project='cinder', + version=version.version_string()) + logging.setup(CONF, "cinder") + utils.monkey_patch() + launcher = service.get_launcher() + if CONF.enabled_backends: + for backend in CONF.enabled_backends: + CONF.register_opt(host_opt, group=backend) + backend_host = getattr(CONF, backend).backend_host + host = "%s@%s" % (backend_host or CONF.host, backend) + server = service.Service.create(host=host, + service_name=backend, + binary='cinder-volume') + launcher.launch_service(server) + else: + server = service.Service.create(binary='cinder-volume') + launcher.launch_service(server) + launcher.wait() diff --git a/pool/shard007/Python/0070988_nib_hash.py b/pool/shard007/Python/0070988_nib_hash.py new file mode 100644 index 0000000000000000000000000000000000000000..73c0cdd17a8ba940661f0dfd8791bcc3d119ec56 --- /dev/null +++ b/pool/shard007/Python/0070988_nib_hash.py @@ -0,0 +1,79 @@ +# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- +# vi: set ft=python sts=4 ts=4 sw=4 et: +# +# Copyright 2021 The NiPreps Developers +# +# 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. +# +# We support and encourage derived works from this project, please read +# about our expectations at +# +# https://www.nipreps.org/community/licensing/ +# +""" +Extracts the sha hash of the contents of a nifti file. +""" +from argparse import ArgumentParser, RawTextHelpFormatter +from hashlib import sha1 + +import nibabel as nb +from mriqc.bin import messages + + +def get_parser() -> ArgumentParser: + """ + A trivial parser. + + Returns + ------- + ArgumentParser + nib_hash execution parser + """ + + parser = ArgumentParser( + description="Compare two pandas dataframes.", + formatter_class=RawTextHelpFormatter, + ) + parser.add_argument("input_file", action="store", help="input nifti file") + return parser + + +def get_hash(nii_file: str) -> str: + """ + Computes the sha1 hash for a given NIfTI format file. + + Parameters + ---------- + nii_file : str + Path to *nii* file + + Returns + ------- + str + SHA1 hash + """ + data = nb.load(nii_file).get_data() + data.flags.writeable = False + return sha1(data.data.tobytes()).hexdigest() + + +def main(): + """Entry point.""" + file_name = get_parser().parse_args().input_file + sha = get_hash(file_name) + message = messages.HASH_REPORT.format(sha=sha, file_name=file_name) + print(message) + + +if __name__ == "__main__": + main() diff --git a/pool/shard007/Python/0071002_matchesfilter.py b/pool/shard007/Python/0071002_matchesfilter.py new file mode 100644 index 0000000000000000000000000000000000000000..ec15e9f85eb468add1c6d84d42e648cf23378894 --- /dev/null +++ b/pool/shard007/Python/0071002_matchesfilter.py @@ -0,0 +1,49 @@ +# +# Gramps - a GTK+/GNOME based genealogy program +# +# Copyright (C) 2002-2006 Donald N. Allingham +# Copyright (C) 2011 Tim G L Lyons +# +# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# + +# $Id$ + +#------------------------------------------------------------------------- +# +# Standard Python modules +# +#------------------------------------------------------------------------- +from ....const import GRAMPS_LOCALE as glocale +_ = glocale.get_translation().gettext + +#------------------------------------------------------------------------- +# +# GRAMPS modules +# +#------------------------------------------------------------------------- +from .._matchesfilterbase import MatchesFilterBase + +#------------------------------------------------------------------------- +# +# MatchesFilter +# +#------------------------------------------------------------------------- +class MatchesFilter(MatchesFilterBase): + """Rule that checks against another filter""" + + name = _('Citations matching the ') + description = _("Matches citations matched by the specified filter name") + namespace = 'Citation' diff --git a/pool/shard007/Python/0071004_TestModuleUtilsBasic.py b/pool/shard007/Python/0071004_TestModuleUtilsBasic.py new file mode 100644 index 0000000000000000000000000000000000000000..d1ee95a1a0ec39a448807fa07698baf292d847d4 --- /dev/null +++ b/pool/shard007/Python/0071004_TestModuleUtilsBasic.py @@ -0,0 +1,161 @@ +import os +import tempfile + +import unittest +from nose.tools import raises + +from ansible import errors +from ansible.module_common import ModuleReplacer +from ansible.utils import md5 as utils_md5 + +TEST_MODULE_DATA = """ +from ansible.module_utils.basic import * + +def get_module(): + return AnsibleModule( + argument_spec = dict(), + supports_check_mode = True, + no_log = True, + ) + +get_module() + +""" + +class TestModuleUtilsBasic(unittest.TestCase): + + def cleanup_temp_file(self, fd, path): + try: + os.close(fd) + os.remove(path) + except: + pass + + def cleanup_temp_dir(self, path): + try: + os.rmdir(path) + except: + pass + + def setUp(self): + # create a temporary file for the test module + # we're about to generate + self.tmp_fd, self.tmp_path = tempfile.mkstemp() + os.write(self.tmp_fd, TEST_MODULE_DATA) + + # template the module code and eval it + module_data, module_style, shebang = ModuleReplacer().modify_module(self.tmp_path, {}, "", {}) + + d = {} + exec(module_data, d, d) + self.module = d['get_module']() + + # module_utils/basic.py screws with CWD, let's save it and reset + self.cwd = os.getcwd() + + def tearDown(self): + self.cleanup_temp_file(self.tmp_fd, self.tmp_path) + # Reset CWD back to what it was before basic.py changed it + os.chdir(self.cwd) + + ################################################################################# + # run_command() tests + + # test run_command with a string command + def test_run_command_string(self): + (rc, out, err) = self.module.run_command("/bin/echo -n 'foo bar'") + self.assertEqual(rc, 0) + self.assertEqual(out, 'foo bar') + (rc, out, err) = self.module.run_command("/bin/echo -n 'foo bar'", use_unsafe_shell=True) + self.assertEqual(rc, 0) + self.assertEqual(out, 'foo bar') + + # test run_command with an array of args (with both use_unsafe_shell=True|False) + def test_run_command_args(self): + (rc, out, err) = self.module.run_command(['/bin/echo', '-n', "foo bar"]) + self.assertEqual(rc, 0) + self.assertEqual(out, 'foo bar') + (rc, out, err) = self.module.run_command(['/bin/echo', '-n', "foo bar"], use_unsafe_shell=True) + self.assertEqual(rc, 0) + self.assertEqual(out, 'foo bar') + + # test run_command with leading environment variables + @raises(SystemExit) + def test_run_command_string_with_env_variables(self): + self.module.run_command('FOO=bar /bin/echo -n "foo bar"') + + @raises(SystemExit) + def test_run_command_args_with_env_variables(self): + self.module.run_command(['FOO=bar', '/bin/echo', '-n', 'foo bar']) + + def test_run_command_string_unsafe_with_env_variables(self): + (rc, out, err) = self.module.run_command('FOO=bar /bin/echo -n "foo bar"', use_unsafe_shell=True) + self.assertEqual(rc, 0) + self.assertEqual(out, 'foo bar') + + # test run_command with a command pipe (with both use_unsafe_shell=True|False) + def test_run_command_string_unsafe_with_pipe(self): + (rc, out, err) = self.module.run_command('echo "foo bar" | cat', use_unsafe_shell=True) + self.assertEqual(rc, 0) + self.assertEqual(out, 'foo bar\n') + + # test run_command with a shell redirect in (with both use_unsafe_shell=True|False) + def test_run_command_string_unsafe_with_redirect_in(self): + (rc, out, err) = self.module.run_command('cat << EOF\nfoo bar\nEOF', use_unsafe_shell=True) + self.assertEqual(rc, 0) + self.assertEqual(out, 'foo bar\n') + + # test run_command with a shell redirect out (with both use_unsafe_shell=True|False) + def test_run_command_string_unsafe_with_redirect_out(self): + tmp_fd, tmp_path = tempfile.mkstemp() + try: + (rc, out, err) = self.module.run_command('echo "foo bar" > %s' % tmp_path, use_unsafe_shell=True) + self.assertEqual(rc, 0) + self.assertTrue(os.path.exists(tmp_path)) + md5sum = utils_md5(tmp_path) + self.assertEqual(md5sum, '5ceaa7ed396ccb8e959c02753cb4bd18') + except: + raise + finally: + self.cleanup_temp_file(tmp_fd, tmp_path) + + # test run_command with a double shell redirect out (append) (with both use_unsafe_shell=True|False) + def test_run_command_string_unsafe_with_double_redirect_out(self): + tmp_fd, tmp_path = tempfile.mkstemp() + try: + (rc, out, err) = self.module.run_command('echo "foo bar" >> %s' % tmp_path, use_unsafe_shell=True) + self.assertEqual(rc, 0) + self.assertTrue(os.path.exists(tmp_path)) + md5sum = utils_md5(tmp_path) + self.assertEqual(md5sum, '5ceaa7ed396ccb8e959c02753cb4bd18') + except: + raise + finally: + self.cleanup_temp_file(tmp_fd, tmp_path) + + # test run_command with data + def test_run_command_string_with_data(self): + (rc, out, err) = self.module.run_command('cat', data='foo bar') + self.assertEqual(rc, 0) + self.assertEqual(out, 'foo bar\n') + + # test run_command with binary data + def test_run_command_string_with_binary_data(self): + (rc, out, err) = self.module.run_command('cat', data='\x41\x42\x43\x44', binary_data=True) + self.assertEqual(rc, 0) + self.assertEqual(out, 'ABCD') + + # test run_command with a cwd set + def test_run_command_string_with_cwd(self): + tmp_path = tempfile.mkdtemp() + try: + (rc, out, err) = self.module.run_command('pwd', cwd=tmp_path) + self.assertEqual(rc, 0) + self.assertTrue(os.path.exists(tmp_path)) + self.assertEqual(out.strip(), os.path.realpath(tmp_path)) + except: + raise + finally: + self.cleanup_temp_dir(tmp_path) + + diff --git a/pool/shard007/Python/0071006_debug.py b/pool/shard007/Python/0071006_debug.py new file mode 100644 index 0000000000000000000000000000000000000000..9316383f63564808d32a02b4a79ba3b00cace4c4 --- /dev/null +++ b/pool/shard007/Python/0071006_debug.py @@ -0,0 +1,60 @@ +# -*- coding: utf8 -*- + +''' +Copyright 2009 Denis Derman (former developer) +Copyright 2011-2012 Peter Potrowl (current developer) + +This file is part of Pijnu. + +Pijnu 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. + +Pijnu 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 Pijnu. If not, see . +''' + +''' +Minimal test/debug sample +''' + +""" + +SEP : ' ' : drop +DOT : '.' +digit : [0..9] +integer : digit+ : join +real : integer DOT integer? : join +number : real / integer : toReal +moreNum : SEP number : liftNode +numbers : number (moreNum)* : extract + +""" + +from pijnu import * + +# with recursive patterns + + +### title: debug ### +### +def toReal(node): + node.value = float(node.value) + +### +SEP = Char(' ', format="' '")(drop) +DOT = Char('.', format="'.'") +digit = Klass(format='[0..9]', charset='0123456789') +integer = Repetition(digit, numMin=1, numMax=False, format='digit+')(join) +real = Sequence([integer, DOT, Option(integer, format='integer?')], format='integer DOT integer?')(join) +number = Choice([real, integer], format='real / integer')(toReal) +moreNum = Sequence([SEP, number], format='SEP number')(liftNode) +numbers = Sequence([number, Repetition(copy(moreNum), numMin=False, numMax=False, format='(moreNum)*')], format='number (moreNum)*')(extract) + +debugParser = Parser(locals(), 'numbers', 'debug', 'debug.py') diff --git a/pool/shard007/Python/0071008_lista07_lista02_questao12.py b/pool/shard007/Python/0071008_lista07_lista02_questao12.py new file mode 100644 index 0000000000000000000000000000000000000000..41a8c0bdf8229fea45e2f3bc0db6de65d737121e --- /dev/null +++ b/pool/shard007/Python/0071008_lista07_lista02_questao12.py @@ -0,0 +1,88 @@ +# ---------------------------------------------------------------------------------------------------------------------- +# Introdução a Programação de Computadores - IPC +# Universidade do Estado do Amazonas - UEA +# Prof. Jucimar Jr +# Gabriel barroso da Silva Lima 1715310011 +# Frederico Victor Alfaia Rodrigues 1515200030 +# André Luis Laborda neves 1515070006 +# Diego Reis Figueira 1515070169 +# Luis Gustavo Moura de Queiroz 1715310037 +# +# Deseja-se fazer a emissão da folha de pagamento +# de uma empresa. Para cada um dos n funcionários +# da empresa são dadas as seguintes informações: +# +# NOME +# SAL (salário) +# HED (horas extras diurnas) +# HEN (horas extras noturnas) +# ND (número de dependentes) +# FAL (faltas em horas) +# DE (descontos eventuais) +# REF (gastos com refeições feitas na empresa) +# VAL (vales retirados durante o mês). +# +# Emitir as seguintes informações: +# +# nome, +# salário, +# horas extras = HED * SAL/160 + HEN * 1.2 * SAL/160, +# salário família = ND * 0.05 * salário mínimo vigente, +# salário bruto = salário + horas extras + salário família. +# +# Descontos efetuados: +# +# INAMPS = 0.08 * SAL, +# faltas = FAL * SAL/160, +# refeições, +# vales, +# descontos eventuais, +# imposto de renda = 0.08 * salário bruto. +# +# Salário líquido = salário bruto - desconto total. + +matriz = [] +n = int(input()) + +for i in range (n): + + matriz.append([0]*9) + + matriz[i][0] = input("nome: ") + matriz[i][1] = int(input("salário: ")) + matriz[i][2] = int(input("horas extras diurnas: ")) + matriz[i][3] = int(input("horas extras noturnas: ")) + matriz[i][4] = int(input("número de dependentes: ")) + matriz[i][5] = int(input("faltas em horas: ")) + matriz[i][6] = int(input("descontos eventuais: ")) + matriz[i][7] = int(input("gastos com refeições feitas na empresa: ")) + matriz[i][8] = int(input("vales retirados durante o mês: ")) + +print(".") + +for i in range (n): + + exhoras = (matriz[i][2] * matriz[i][1]) / 160 + (matriz[i][3] * 1.2 * matriz[i][1]) / 160 + salfami = matriz[i][4] * 937 * 0.05 + salbruto = matriz[i][1] + exhoras + salfami + inamps = 0.08 * matriz[i][1] + faltas = (matriz[i][5] * matriz[i][1])/160 + impren = salbruto * 0.08 + destot = faltas + inamps + impren + matriz[i][6] + matriz[i][7] + matriz[i][8] + salliq = salbruto - destot + + print("--//--//--//--//--//--//--//--//--//--//--//--") + print("funcionário", n) + print("salário:", matriz[i][1]) + print("horas extras:", exhoras) + print("salário família:", salfami) + print("salário bruto:", salbruto) + print("...........................") + print("Descontos efetuados") + print("INAMPS:", inamps) + print("faltas:", faltas) + print("imposto de renda:", impren) + print("descontos totais:", destot) + print("...........................") + print("salário líquido:", salliq) + print("--//--//--//--//--//--//--//--//--//--//--//--") diff --git a/pool/shard007/Python/0071010_test_util.py b/pool/shard007/Python/0071010_test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..ace9bccaf5635696f92e4caf5005048900f6cedb --- /dev/null +++ b/pool/shard007/Python/0071010_test_util.py @@ -0,0 +1,66 @@ +""" +Test helpers for Site Configuration. +""" + +from functools import wraps +import contextlib + +from mock import patch + +from django.contrib.sites.models import Site + +from openedx.core.djangoapps.site_configuration.models import SiteConfiguration + + +def with_site_configuration(domain="test.localhost", configuration=None): + """ + A decorator to run a test with a configuration enabled. + + Args: + domain (str): domain name for the test site. + configuration (dict): configuration to use for the test site. + """ + # This decorator creates Site and SiteConfiguration instances for given domain + def _decorator(func): # pylint: disable=missing-docstring + @wraps(func) + def _decorated(*args, **kwargs): # pylint: disable=missing-docstring + # make a domain name out of directory name + site, __ = Site.objects.get_or_create(domain=domain, name=domain) + site_configuration, created = SiteConfiguration.objects.get_or_create( + site=site, + defaults={"enabled": True, "values": configuration}, + ) + if not created: + site_configuration.values = configuration + site_configuration.save() + + with patch('openedx.core.djangoapps.site_configuration.helpers.get_current_site_configuration', + return_value=site_configuration): + with patch('openedx.core.djangoapps.theming.helpers.get_current_site', return_value=site): + return func(*args, **kwargs) + return _decorated + return _decorator + + +@contextlib.contextmanager +def with_site_configuration_context(domain="test.localhost", configuration=None): + """ + A function to get a context manger to run a test with a configuration enabled. + + Args: + domain (str): domain name for the test site. + configuration (dict): configuration to use for the test site. + """ + site, __ = Site.objects.get_or_create(domain=domain, name=domain) + site_configuration, created = SiteConfiguration.objects.get_or_create( + site=site, + defaults={"enabled": True, "values": configuration}, + ) + if not created: + site_configuration.values = configuration + site_configuration.save() + + with patch('openedx.core.djangoapps.site_configuration.helpers.get_current_site_configuration', + return_value=site_configuration): + with patch('openedx.core.djangoapps.theming.helpers.get_current_site', return_value=site): + yield diff --git a/pool/shard007/Python/0071012_metric.py b/pool/shard007/Python/0071012_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..b3d606bc9004250905cb53b26ad3cc0404b5c50d --- /dev/null +++ b/pool/shard007/Python/0071012_metric.py @@ -0,0 +1,147 @@ +# coding=utf-8 + +import time +import re +import logging +from error import DiamondException + + +class Metric(object): + + _METRIC_TYPES = ['COUNTER', 'GAUGE'] + + def __init__(self, path, value, raw_value=None, timestamp=None, precision=0, + host=None, metric_type='COUNTER', ttl=None): + """ + Create new instance of the Metric class + + Takes: + path=string: string the specifies the path of the metric + value=[float|int]: the value to be submitted + timestamp=[float|int]: the timestamp, in seconds since the epoch + (as from time.time()) precision=int: the precision to apply. + Generally the default (2) should work fine. + """ + + # Validate the path, value and metric_type submitted + if (None in [path, value] or metric_type not in self._METRIC_TYPES): + raise DiamondException(("Invalid parameter when creating new " + "Metric with path: %r value: %r " + "metric_type: %r") + % (path, value, metric_type)) + + # If no timestamp was passed in, set it to the current time + if timestamp is None: + timestamp = int(time.time()) + else: + # If the timestamp isn't an int, then make it one + if not isinstance(timestamp, int): + try: + timestamp = int(timestamp) + except ValueError, e: + raise DiamondException(("Invalid timestamp when " + "creating new Metric %r: %s") + % (path, e)) + + # The value needs to be a float or an int. If it is, great. If not, + # try to cast it to one of those. + if not isinstance(value, (int, float)): + try: + if precision == 0: + value = round(float(value)) + else: + value = float(value) + except ValueError, e: + raise DiamondException(("Invalid value when creating new " + "Metric %r: %s") % (path, e)) + + self.path = path + self.value = value + self.raw_value = raw_value + self.timestamp = timestamp + self.precision = precision + self.host = host + self.metric_type = metric_type + self.ttl = ttl + + def __repr__(self): + """ + Return the Metric as a string + """ + if not isinstance(self.precision, (int, long)): + log = logging.getLogger('diamond') + log.warn('Metric %s does not have a valid precision', self.path) + self.precision = 0 + + # Set the format string + fstring = "%%s %%0.%if %%i\n" % self.precision + + # Return formated string + return fstring % (self.path, self.value, self.timestamp) + + @classmethod + def parse(cls, string): + """ + Parse a string and create a metric + """ + match = re.match(r'^(?P[A-Za-z0-9\.\-_]+)\s+' + + '\(?P[0-9\.]+)\s+' + + '(?P[0-9\.]+)(\n?)$', + string) + try: + groups = match.groupdict() + # TODO: get precision from value string + return Metric(groups['name'], + groups['value'], + float(groups['timestamp'])) + except: + raise DiamondException( + "Metric could not be parsed from string: %s." % string) + + def getPathPrefix(self): + """ + Returns the path prefix path + servers.host.cpu.total.idle + return "servers" + """ + # If we don't have a host name, assume it's just the first part of the + # metric path + if self.host is None: + return self.path.split('.')[0] + + offset = self.path.index(self.host) - 1 + return self.path[0:offset] + + def getCollectorPath(self): + """ + Returns collector path + servers.host.cpu.total.idle + return "cpu" + """ + # If we don't have a host name, assume it's just the third part of the + # metric path + if self.host is None: + return self.path.split('.')[2] + + offset = self.path.index(self.host) + offset += len(self.host) + 1 + endoffset = self.path.index('.', offset) + return self.path[offset:endoffset] + + def getMetricPath(self): + """ + Returns the metric path after the collector name + servers.host.cpu.total.idle + return "total.idle" + """ + # If we don't have a host name, assume it's just the fourth+ part of the + # metric path + if self.host is None: + path = self.path.split('.')[3:] + return '.'.join(path) + + prefix = '.'.join([self.getPathPrefix(), self.host, + self.getCollectorPath()]) + + offset = len(prefix) + 1 + return self.path[offset:] diff --git a/pool/shard007/Python/0071013_main.py b/pool/shard007/Python/0071013_main.py new file mode 100644 index 0000000000000000000000000000000000000000..5b61263d05bf307d677b60a7a7bb787ebbc0c466 --- /dev/null +++ b/pool/shard007/Python/0071013_main.py @@ -0,0 +1,31 @@ +""" + An implementation of the Flippy Flop data structure. + The Flippy Flop is backed by a list with a few quirks. +""" + +from random import randint + +class FlippyFlop(object): + def __init__(self): + self._data = [] + + @property + def count(self): + return len(self._data) + + def flip(self, element): + success = randint(0, 1) > 0 + if success: + position = randint(0, self.count) + self._data.insert(position, element) + return success + + def flop(self): + ret = None + if self.count > 0: + position = randint(0, self.count - 1) + ret = self._data[position] + shouldRemove = randint(0, 1) > 0 + if shouldRemove: + self._data.pop(position) + return ret diff --git a/pool/shard007/Python/0071016_googlecode_upload.py b/pool/shard007/Python/0071016_googlecode_upload.py new file mode 100644 index 0000000000000000000000000000000000000000..8e1315259d6f515a25e4f5df0c26dc43c6c781f9 --- /dev/null +++ b/pool/shard007/Python/0071016_googlecode_upload.py @@ -0,0 +1,316 @@ +#!/usr/bin/env python +# +# Copyright 2006, 2007 Google Inc. All Rights Reserved. +# Author: danderson@google.com (David Anderson) +# +# Script for uploading files to a Google Code project. +# +# This is intended to be both a useful script for people who want to +# streamline project uploads and a reference implementation for +# uploading files to Google Code projects. +# +# To upload a file to Google Code, you need to provide a path to the +# file on your local machine, a small summary of what the file is, a +# project name, and a valid account that is a member or owner of that +# project. You can optionally provide a list of labels that apply to +# the file. The file will be uploaded under the same name that it has +# in your local filesystem (that is, the "basename" or last path +# component). Run the script with '--help' to get the exact syntax +# and available options. +# +# Note that the upload script requests that you enter your +# googlecode.com password. This is NOT your Gmail account password! +# This is the password you use on googlecode.com for committing to +# Subversion and uploading files. You can find your password by going +# to http://code.google.com/hosting/settings when logged in with your +# Gmail account. If you have already committed to your project's +# Subversion repository, the script will automatically retrieve your +# credentials from there (unless disabled, see the output of '--help' +# for details). +# +# If you are looking at this script as a reference for implementing +# your own Google Code file uploader, then you should take a look at +# the upload() function, which is the meat of the uploader. You +# basically need to build a multipart/form-data POST request with the +# right fields and send it to https://PROJECT.googlecode.com/files . +# Authenticate the request using HTTP Basic authentication, as is +# shown below. +# +# Licensed under the terms of the Apache Software License 2.0: +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Questions, comments, feature requests and patches are most welcome. +# Please direct all of these to the Google Code users group: +# http://groups.google.com/group/google-code-hosting + +"""Google Code file uploader script. +""" + +__author__ = 'danderson@google.com (David Anderson)' + +import httplib +import os.path +import optparse +import getpass +import base64 +import sys + + +def get_svn_config_dir(): + """Return user's Subversion configuration directory.""" + try: + from win32com.shell.shell import SHGetFolderPath + import win32com.shell.shellcon + except ImportError: + # If we can't import the win32api, just use ~; this is right on unix, and + # returns not entirely unreasonable results on Windows. + return os.path.expanduser('~/.subversion') + + # We're on Windows with win32api; use APPDATA. + return os.path.join(SHGetFolderPath(0, win32com.shell.shellcon.CSIDL_APPDATA, + 0, 0).encode('utf-8'), + 'Subversion') + + +def get_svn_auth(project_name, config_dir): + """Return (username, password) for project_name in config_dir.""" + + # Default to returning nothing. + result = (None, None) + + try: + from svn.core import SVN_AUTH_CRED_SIMPLE, svn_config_read_auth_data + from svn.core import SubversionException + except ImportError: + return result + + realm = (' Google Code Subversion Repository' + % project_name) + + # auth may be none even if no exception is raised, e.g. if config_dir does + # not exist, or exists but has no entry for realm. + try: + auth = svn_config_read_auth_data(SVN_AUTH_CRED_SIMPLE, realm, config_dir) + except SubversionException: + auth = None + + if auth is not None: + try: + result = (auth['username'], auth['password']) + except KeyError: + # Missing the keys, so return nothing. + pass + + return result + + +def upload(file, project_name, user_name, password, summary, labels=None): + """Upload a file to a Google Code project's file server. + + Args: + file: The local path to the file. + project_name: The name of your project on Google Code. + user_name: Your Google account name. + password: The googlecode.com password for your account. + Note that this is NOT your global Google Account password! + summary: A small description for the file. + labels: an optional list of label strings with which to tag the file. + + Returns: a tuple: + http_status: 201 if the upload succeeded, something else if an + error occured. + http_reason: The human-readable string associated with http_status + file_url: If the upload succeeded, the URL of the file on Google + Code, None otherwise. + """ + # The login is the user part of user@gmail.com. If the login provided + # is in the full user@domain form, strip it down. + if '@' in user_name: + user_name = user_name[:user_name.index('@')] + + form_fields = [('summary', summary)] + if labels is not None: + form_fields.extend([('label', l.strip()) for l in labels]) + + content_type, body = encode_upload_request(form_fields, file) + + upload_host = '%s.googlecode.com' % project_name + upload_uri = '/files' + auth_token = base64.b64encode('%s:%s'% (user_name, password)) + headers = { + 'Authorization': 'Basic %s' % auth_token, + 'User-Agent': 'Googlecode.com uploader v0.9.4', + 'Content-Type': content_type, + } + + server = httplib.HTTPSConnection(upload_host) + server.request('POST', upload_uri, body, headers) + resp = server.getresponse() + server.close() + + if resp.status == 201: + location = resp.getheader('Location', None) + else: + location = None + return resp.status, resp.reason, location + + +def encode_upload_request(fields, file_path): + """Encode the given fields and file into a multipart form body. + + fields is a sequence of (name, value) pairs. file is the path of + the file to upload. The file will be uploaded to Google Code with + the same file name. + + Returns: (content_type, body) ready for httplib.HTTP instance + """ + BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' + CRLF = '\r\n' + + body = [] + + # Add the metadata about the upload first + for key, value in fields: + body.extend( + ['--' + BOUNDARY, + 'Content-Disposition: form-data; name="%s"' % key, + '', + value, + ]) + + # Now add the file itself + file_name = os.path.basename(file_path) + f = open(file_path, 'rb') + file_content = f.read() + f.close() + + body.extend( + ['--' + BOUNDARY, + 'Content-Disposition: form-data; name="filename"; filename="%s"' + % file_name, + # The upload server determines the mime-type, no need to set it. + 'Content-Type: application/octet-stream', + '', + file_content, + ]) + + # Finalize the form body + body.extend(['--' + BOUNDARY + '--', '']) + + return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) + + +def upload_find_auth(file_path, project_name, summary, user_name, password, labels=None, + config_dir=None, tries=3): + """Find credentials and upload a file to a Google Code project's file server. + + file_path, project_name, summary, and labels are passed as-is to upload. + + If config_dir is None, try get_svn_config_dir(); if it is 'none', skip + trying the Subversion configuration entirely. If user_name is not None, use + it for the first attempt; prompt for subsequent attempts. + + Args: + file_path: The local path to the file. + project_name: The name of your project on Google Code. + summary: A small description for the file. + labels: an optional list of label strings with which to tag the file. + config_dir: Path to Subversion configuration directory, 'none', or None. + user_name: Your Google account name. + tries: How many attempts to make. + """ + print password + + if user_name is None and password is None: + if config_dir != 'none': + # Try to load username/password from svn config for first try. + if config_dir is None: + config_dir = get_svn_config_dir() + (svn_username, password) = get_svn_auth(project_name, config_dir) + if user_name is None: + # If username was not supplied by caller, use svn config. + user_name = svn_username + else: + # Just initialize password for the first try. + password = None + + + while tries > 0: + if user_name is None: + # Read username if not specified or loaded from svn config, or on + # subsequent tries. + sys.stdout.write('Please enter your googlecode.com username: ') + sys.stdout.flush() + user_name = sys.stdin.readline().rstrip() + if password is None: + # Read password if not loaded from svn config, or on subsequent tries. + print 'Please enter your googlecode.com password.' + print '** Note that this is NOT your Gmail account password! **' + print 'It is the password you use to access Subversion repositories,' + print 'and can be found here: http://code.google.com/hosting/settings' + password = getpass.getpass() + + status, reason, url = upload(file_path, project_name, user_name, password, + summary, labels) + # Returns 403 Forbidden instead of 401 Unauthorized for bad + # credentials as of 2007-07-17. + if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: + # Rest for another try. + user_name = password = None + tries = tries - 1 + else: + # We're done. + break + + return status, reason, url + + +def main(): + parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' + '-p PROJECT [options] FILE') + parser.add_option('--config-dir', dest='config_dir', metavar='DIR', + help='read svn auth data from DIR' + ' ("none" means not to use svn auth data)') + parser.add_option('-s', '--summary', dest='summary', + help='Short description of the file') + parser.add_option('-p', '--project', dest='project', + help='Google Code project name') + parser.add_option('-u', '--user', dest='user', + help='Your Google Code username') + parser.add_option('-w', '--password', dest='pwd', + help='Your Google Code password') + parser.add_option('-l', '--labels', dest='labels', + help='An optional list of labels to attach to the file') + + options, args = parser.parse_args() + + if not options.summary: + parser.error('File summary is missing.') + elif not options.project: + parser.error('Project name is missing.') + elif len(args) < 1: + parser.error('File to upload not provided.') + elif len(args) > 1: + parser.error('Only one file may be specified.') + + file_path = args[0] + + if options.labels: + labels = options.labels.split(',') + else: + labels = None + + status, reason, url = upload_find_auth(file_path, options.project, + options.summary, options.user, options.pwd, labels, options.config_dir) + if url: + print 'The file was uploaded successfully.' + print 'URL: %s' % url + return 0 + else: + print 'An error occurred. Your file was not uploaded.' + print 'Google Code upload server said: %s (%s)' % (reason, status) + return 1 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/pool/shard007/Python/0071019_logger.py b/pool/shard007/Python/0071019_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..4a5647133fab80f4a99b73bc7b5a0adc6235232a --- /dev/null +++ b/pool/shard007/Python/0071019_logger.py @@ -0,0 +1,27 @@ +from ConfigParser import SafeConfigParser +import time +import picamera +from datetime import datetime + +config = SafeConfigParser() +config.read('/home/pi/surprise/config.ini') + +print config.get('main', 'trigger_time') # -> "value1" +start_time = config.get('main', 'trigger_time') +if config.getint('main', 'ran') == 0: + config.set('main', 'ran', '1') + with open('config.ini', 'w') as f: + config.write(f) + with picamera.PiCamera() as camera: + camera.hflip = True + camera.vflip = True + camera.start_preview() + time.sleep(2) + for filename in camera.capture_continuous('/home/pi/surprise/captures/img{counter:03d}.jpg'): + print('Captured %s' % filename) + time.sleep(60) # wait 1 minute + difference = datetime.now() - datetime.strptime(start_time,"%Y-%m-%d_%H%M%S") + if(difference.seconds/60 > 60): + print 'stopping' + # more that 60 minutes since started + break diff --git a/pool/shard007/Python/0071023_textwrap_test.py b/pool/shard007/Python/0071023_textwrap_test.py new file mode 100644 index 0000000000000000000000000000000000000000..ec02da49535191fbadd12f11d455d424d0dadd4c --- /dev/null +++ b/pool/shard007/Python/0071023_textwrap_test.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python + +from __future__ import absolute_import, division, unicode_literals + +import unittest +from cola import textwrap + + +class WordWrapTestCase(unittest.TestCase): + def setUp(self): + self.tabwidth = 8 + self.limit = None + + def wrap(self, text, break_on_hyphens=True): + return textwrap.word_wrap(text, self.tabwidth, self.limit, + break_on_hyphens=break_on_hyphens) + + def test_word_wrap(self): + self.limit = 16 + text = """ +12345678901 3 56 8 01 3 5 7 + +1 3 5""" + expect = """ +12345678901 3 56 +8 01 3 5 7 + +1 3 5""" + self.assertEqual(expect, self.wrap(text)) + + def test_word_wrap_dashes(self): + self.limit = 4 + text = '123-5' + expect = '123-5' + self.assertEqual(expect, self.wrap(text)) + + def test_word_wrap_leading_spaces(self): + self.limit = 4 + expect = '1234\n5' + + self.assertEqual(expect, self.wrap('1234 5')) + self.assertEqual(expect, self.wrap('1234 5')) + self.assertEqual(expect, self.wrap('1234 5')) + self.assertEqual(expect, self.wrap('1234 5')) + self.assertEqual(expect, self.wrap('1234 5')) + + expect = '123\n4' + self.assertEqual(expect, self.wrap('123 4')) + self.assertEqual(expect, self.wrap('123 4')) + self.assertEqual(expect, self.wrap('123 4')) + self.assertEqual(expect, self.wrap('123 4')) + self.assertEqual(expect, self.wrap('123 4')) + + def test_word_wrap_double_dashes(self): + self.limit = 4 + text = '12--5' + expect = '12--\n5' + self.assertEqual(expect, self.wrap(text, break_on_hyphens=True)) + + expect = '12--5' + self.assertEqual(expect, self.wrap(text, break_on_hyphens=False)) + + def test_word_wrap_many_lines(self): + self.limit = 2 + text = """ +aa + + +bb cc dd""" + expect = """ +aa + + +bb +cc +dd""" + self.assertEqual(expect, self.wrap(text)) + + def test_word_python_code(self): + self.limit = 78 + text = """ +if True: + print "hello world" +else: + print "hello world" + +""" + self.assertEqual(text, self.wrap(text)) + + def test_word_wrap_spaces(self): + self.limit = 2 + text = ' ' * 6 + self.assertEqual('', self.wrap(text)) + + def test_word_wrap_special_tag(self): + self.limit = 2 + text = """ +This test is so meta, even this sentence + +Cheered-on-by: Avoids word-wrap +C.f. This also avoids word-wrap +References: This also avoids word-wrap +See-also: This also avoids word-wrap +Related-to: This also avoids word-wrap +Link: This also avoids word-wrap +""" + + expect = """ +This +test +is +so +meta, +even +this +sentence + +Cheered-on-by: Avoids word-wrap +C.f. This also avoids word-wrap +References: This also avoids word-wrap +See-also: This also avoids word-wrap +Related-to: This also avoids word-wrap +Link: This also avoids word-wrap +""" + + self.assertEqual(self.wrap(text), expect) + + def test_word_wrap_space_at_start_of_wrap(self): + inputs = """0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 """ + expect = """0 1 2 3 4 5 6 7 8 9\n0 1 2 3 4 5 6 7 8""" + self.limit = 20 + actual = self.wrap(inputs) + self.assertEqual(expect, actual) + + def test_word_wrap_keeps_tabs_at_start(self): + inputs = """\tfirst line\n\n\tsecond line""" + expect = """\tfirst line\n\n\tsecond line""" + self.limit = 20 + actual = self.wrap(inputs) + self.assertEqual(expect, actual) + + def test_word_wrap_keeps_twospace_indents(self): + inputs = """first line\n\n* branch:\n line1\n line2\n""" + expect = """first line\n\n* branch:\n line1\n line2\n""" + self.limit = 20 + actual = self.wrap(inputs) + self.assertEqual(expect, actual) + + def test_word_wrap_ranges(self): + text = 'a bb ccc dddd\neeeee' + expect = 'a\nbb\nccc\ndddd\neeeee' + actual = textwrap.word_wrap(text, 8, 2) + self.assertEqual(expect, actual) + + expect = 'a bb\nccc\ndddd\neeeee' + actual = textwrap.word_wrap(text, 8, 4) + self.assertEqual(expect, actual) + + text = 'a bb ccc dddd\n\teeeee' + expect = 'a bb\nccc\ndddd\n\t\neeeee' + actual = textwrap.word_wrap(text, 8, 4) + self.assertEqual(expect, actual) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard007/Python/0071024_compute_mne_inverse_raw_in_label.py b/pool/shard007/Python/0071024_compute_mne_inverse_raw_in_label.py new file mode 100644 index 0000000000000000000000000000000000000000..c38199035fb34051608ffa26c40799cf4d9c3c21 --- /dev/null +++ b/pool/shard007/Python/0071024_compute_mne_inverse_raw_in_label.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +""" +.. _example-sLORETA: + +============================================= +Compute sLORETA inverse solution on raw data +============================================= + +Compute sLORETA inverse solution on raw dataset restricted +to a brain label and stores the solution in stc files for +visualisation. + +""" +# Author: Alexandre Gramfort +# +# License: BSD-3-Clause + +# %% + +import matplotlib.pyplot as plt + +import mne +from mne.datasets import sample +from mne.minimum_norm import apply_inverse_raw, read_inverse_operator + +print(__doc__) + +data_path = sample.data_path() +fname_inv = ( + data_path / 'MEG' / 'sample' / 'sample_audvis-meg-oct-6-meg-inv.fif') +fname_raw = data_path / 'MEG' / 'sample' / 'sample_audvis_raw.fif' +label_name = 'Aud-lh' +fname_label = data_path / 'MEG' / 'sample' / 'labels' / f'{label_name}.label' + +snr = 1.0 # use smaller SNR for raw data +lambda2 = 1.0 / snr ** 2 +method = "sLORETA" # use sLORETA method (could also be MNE or dSPM) + +# Load data +raw = mne.io.read_raw_fif(fname_raw) +inverse_operator = read_inverse_operator(fname_inv) +label = mne.read_label(fname_label) + +raw.set_eeg_reference('average', projection=True) # set average reference. +start, stop = raw.time_as_index([0, 15]) # read the first 15s of data + +# Compute inverse solution +stc = apply_inverse_raw(raw, inverse_operator, lambda2, method, label, + start, stop, pick_ori=None) + +# Save result in stc files +stc.save('mne_%s_raw_inverse_%s' % (method, label_name), overwrite=True) + +# %% +# View activation time-series +plt.plot(1e3 * stc.times, stc.data[::100, :].T) +plt.xlabel('time (ms)') +plt.ylabel('%s value' % method) +plt.show() diff --git a/pool/shard007/Python/0071028_test_stl.py b/pool/shard007/Python/0071028_test_stl.py new file mode 100644 index 0000000000000000000000000000000000000000..ad14273f342791af3daffae6d9b511596aaf605e --- /dev/null +++ b/pool/shard007/Python/0071028_test_stl.py @@ -0,0 +1,98 @@ +import ROOT +from rootpy import stl +from rootpy.stl import CPPType, generate +from rootpy.testdata import get_file +from rootpy.extern.pyparsing import ParseException + +from nose.plugins.attrib import attr +from nose.tools import assert_raises, assert_equal + +from multiprocessing import Pool + + +GOOD = [ + 'std::pair, double>*', + 'pair, vector >', + 'vector > >::iterator*', + 'map', + 'map >', + 'map > >', + 'vector', + 'vector', + 'vector', +] + +BAD = [ + 'pair,double>>', + 'pair,,vector >', + 'vector< > >', + 'int,string', + 'int,vector >', + 'vector >', + 'map > >,', +] + + +def test_parse(): + for template in GOOD: + assert_equal(template, str(CPPType.from_string(template))) + for template in BAD: + assert_raises(ParseException, CPPType.from_string, template) + + +@attr('slow') +def test_stl(): + generate('map >', ';') + generate('map >', ';') + generate('vector', ';TLorentzVector.h') + + ROOT.std.map('int,vector') + ROOT.std.map('int,vector') + ROOT.std.vector('TLorentzVector') + + temp = CPPType.from_string('vector > >') + temp.ensure_built() + + stl.vector('vector >') + stl.vector(stl.string)() + stl.vector('string')() + stl.vector(int) + + stl.map("string", "string") + stl.map(stl.string, stl.string) + stl.map(int, stl.string) + stl.map(stl.string, int) + stl.map("string", ROOT.TLorentzVector) + + histmap = stl.map("string", ROOT.TH1D)() + a = ROOT.TH1D("a", "a", 10, -1, 1) + histmap["a"] = a + + StrHist = stl.pair(stl.string, "TH1*") + + generate('pair::iterator,bool>', ';') + histptrmap = stl.map(stl.string, "TH1*")() + histptrmap.insert(StrHist("test", a)) + + assert histptrmap["test"] is a + +""" +This test frequently fails on Travis due to os.fork() not being able to +allocate memory. Disabling it for now until a solution is found. + +def load_tree(*args): + with get_file('test_dicts.root') as f: + t = f.data + # this will trigger the generation of the required dicts + t.create_buffer() + + +def test_dict_load(): + # test file locking + po = Pool() + po.map(load_tree, range(3)) +""" + +if __name__ == "__main__": + import nose + nose.runmodule() diff --git a/pool/shard007/Python/0071032_guess_language.py b/pool/shard007/Python/0071032_guess_language.py new file mode 100644 index 0000000000000000000000000000000000000000..648a06b126843b7a35898cccfc8929b00e44fc82 --- /dev/null +++ b/pool/shard007/Python/0071032_guess_language.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# GuessIt - A library for guessing information from filenames +# Copyright (c) 2012 Nicolas Wack +# +# GuessIt is free software; you can redistribute it and/or modify it under +# the terms of the Lesser GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# GuessIt 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 +# Lesser GNU General Public License for more details. +# +# You should have received a copy of the Lesser GNU General Public License +# along with this program. If not, see . +# + +from __future__ import unicode_literals +from guessit import Guess +from guessit.transfo import SingleNodeGuesser +from guessit.language import search_language +import logging + +log = logging.getLogger(__name__) + + +def guess_language(string, node, skip=None): + if skip: + relative_skip = [] + for entry in skip: + node_idx = entry['node_idx'] + span = entry['span'] + if node_idx == node.node_idx[:len(node_idx)]: + relative_span = (span[0] - node.offset + 1, span[1] - node.offset + 1) + relative_skip.append(relative_span) + skip = relative_skip + + language, span, confidence = search_language(string, skip=skip) + if language: + return (Guess({'language': language}, + confidence=confidence, + raw= string[span[0]:span[1]]), + span) + + return None, None + +guess_language.use_node = True + + +def process(mtree, *args, **kwargs): + SingleNodeGuesser(guess_language, None, log, *args, **kwargs).process(mtree) + # Note: 'language' is promoted to 'subtitleLanguage' in the post_process transfo diff --git a/pool/shard007/Python/0071033_utils.py b/pool/shard007/Python/0071033_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..58bba64a212d391a961495b8a876f744e19a6eef --- /dev/null +++ b/pool/shard007/Python/0071033_utils.py @@ -0,0 +1,40 @@ +from unittest.mock import MagicMock +from jobman.engines.local_engine import LocalEngine + +from .. houston import Houston + + +def generate_test_cfg(): + cfg = { + 'MC_DB_URI': 'sqlite://', + 'JOBMAN_CFG': { + 'jobman_db_uri': 'sqlite://', + 'engine': LocalEngine(db_uri='sqlite://') + }, + 'FLOW_QUEUE': { + 'key': 'houston_queue_flow', + 'queue_kwargs': { + 'queue_spec': {'item_type': 'flow'} + } + }, + 'JOB_QUEUE': { + 'key': 'houston_queue_job', + 'queue_kwargs': { + 'queue_spec': {'item_type': 'job'} + } + }, + 'ARTIFACT_HANDLER': MagicMock(return_value={}), + 'BUILD_JOBDIR_FN': MagicMock(return_value={}), + } + return cfg + + +def generate_test_houston(cfg_overrides=None, houston_kwargs=None, + ensure_tables=True, ensure_queues=True): + cfg = {**generate_test_cfg(), **(cfg_overrides or {})} + houston = Houston(cfg=cfg, **(houston_kwargs or {})) + if ensure_tables: + houston.db.ensure_tables() + if ensure_queues: + houston.utils.ensure_queues() + return houston diff --git a/pool/shard007/Python/0071040_test_qos_driver.py b/pool/shard007/Python/0071040_test_qos_driver.py new file mode 100644 index 0000000000000000000000000000000000000000..c9e276c72abe8a48772c888908a67e0874df1f64 --- /dev/null +++ b/pool/shard007/Python/0071040_test_qos_driver.py @@ -0,0 +1,104 @@ +# 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. + +import mock +from oslo_utils import uuidutils + +from neutron import context +from neutron.objects.qos import policy +from neutron.objects.qos import rule +from neutron.plugins.ml2.drivers.openvswitch.agent.extension_drivers import ( + qos_driver) +from neutron.tests.unit.plugins.ml2.drivers.openvswitch.agent import ( + ovs_test_base) + + +class QosOVSAgentDriverTestCase(ovs_test_base.OVSAgentConfigTestBase): + + def setUp(self): + super(QosOVSAgentDriverTestCase, self).setUp() + self.context = context.get_admin_context() + self.qos_driver = qos_driver.QosOVSAgentDriver() + self.qos_driver.initialize() + self.qos_driver.br_int = mock.Mock() + self.qos_driver.br_int.get_egress_bw_limit_for_port = mock.Mock( + return_value=(1000, 10)) + self.get = self.qos_driver.br_int.get_egress_bw_limit_for_port + self.qos_driver.br_int.del_egress_bw_limit_for_port = mock.Mock() + self.delete = self.qos_driver.br_int.delete_egress_bw_limit_for_port + self.qos_driver.br_int.create_egress_bw_limit_for_port = mock.Mock() + self.create = self.qos_driver.br_int.create_egress_bw_limit_for_port + self.rule = self._create_bw_limit_rule_obj() + self.qos_policy = self._create_qos_policy_obj([self.rule]) + self.port = self._create_fake_port() + + def _create_bw_limit_rule_obj(self): + rule_obj = rule.QosBandwidthLimitRule() + rule_obj.id = uuidutils.generate_uuid() + rule_obj.max_kbps = 2 + rule_obj.max_burst_kbps = 200 + rule_obj.obj_reset_changes() + return rule_obj + + def _create_qos_policy_obj(self, rules): + policy_dict = {'id': uuidutils.generate_uuid(), + 'tenant_id': uuidutils.generate_uuid(), + 'name': 'test', + 'description': 'test', + 'shared': False, + 'rules': rules} + policy_obj = policy.QosPolicy(self.context, **policy_dict) + policy_obj.obj_reset_changes() + return policy_obj + + def _create_fake_port(self): + self.port_name = 'fakeport' + + class FakeVifPort(object): + port_name = self.port_name + + return {'vif_port': FakeVifPort()} + + def test_create_new_rule(self): + self.qos_driver.br_int.get_egress_bw_limit_for_port = mock.Mock( + return_value=(None, None)) + self.qos_driver.create(self.port, self.qos_policy) + # Assert create is the last call + self.assertEqual( + 'create_egress_bw_limit_for_port', + self.qos_driver.br_int.method_calls[-1][0]) + self.assertEqual(0, self.delete.call_count) + self.create.assert_called_once_with( + self.port_name, self.rule.max_kbps, + self.rule.max_burst_kbps) + + def test_create_existing_rules(self): + self.qos_driver.create(self.port, self.qos_policy) + self._assert_rule_create_updated() + + def test_update_rules(self): + self.qos_driver.update(self.port, self.qos_policy) + self._assert_rule_create_updated() + + def test_delete_rules(self): + self.qos_driver.delete(self.port, self.qos_policy) + self.delete.assert_called_once_with(self.port_name) + + def _assert_rule_create_updated(self): + # Assert create is the last call + self.assertEqual( + 'create_egress_bw_limit_for_port', + self.qos_driver.br_int.method_calls[-1][0]) + + self.create.assert_called_once_with( + self.port_name, self.rule.max_kbps, + self.rule.max_burst_kbps) diff --git a/pool/shard007/Python/0071048_linear.py b/pool/shard007/Python/0071048_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..9aab819eb8ea326007ac7ed40d684911dc9073b7 --- /dev/null +++ b/pool/shard007/Python/0071048_linear.py @@ -0,0 +1,77 @@ +"""Linear Estimators.""" +# Copyright 2015-present The Scikit Flow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +from tensorflow.contrib.learn.python.learn.estimators import _sklearn +from tensorflow.contrib.learn.python.learn.estimators.base import TensorFlowEstimator +from tensorflow.contrib.learn.python.learn import models + + +class TensorFlowLinearRegressor(TensorFlowEstimator, _sklearn.RegressorMixin): + """TensorFlow Linear Regression model.""" + + def __init__(self, n_classes=0, batch_size=32, steps=200, optimizer="Adagrad", + learning_rate=0.1, clip_gradients=5.0, continue_training=False, + config=None, verbose=1): + + super(TensorFlowLinearRegressor, self).__init__( + model_fn=models.linear_regression_zero_init, n_classes=n_classes, + batch_size=batch_size, steps=steps, optimizer=optimizer, + learning_rate=learning_rate, clip_gradients=clip_gradients, + continue_training=continue_training, config=config, + verbose=verbose) + + @property + def weights_(self): + """Returns weights of the linear regression.""" + return self.get_tensor_value('linear_regression/weights:0') + + @property + def bias_(self): + """Returns bias of the linear regression.""" + return self.get_tensor_value('linear_regression/bias:0') + + +class TensorFlowLinearClassifier(TensorFlowEstimator, _sklearn.ClassifierMixin): + """TensorFlow Linear Classifier model.""" + + def __init__(self, n_classes, batch_size=32, steps=200, optimizer="Adagrad", + learning_rate=0.1, class_weight=None, clip_gradients=5.0, + continue_training=False, config=None, + verbose=1): + + super(TensorFlowLinearClassifier, self).__init__( + model_fn=models.logistic_regression_zero_init, n_classes=n_classes, + batch_size=batch_size, steps=steps, optimizer=optimizer, + learning_rate=learning_rate, class_weight=class_weight, + clip_gradients=clip_gradients, + continue_training=continue_training, config=config, + verbose=verbose) + + @property + def weights_(self): + """Returns weights of the linear classifier.""" + return self.get_tensor_value('logistic_regression/weights:0') + + @property + def bias_(self): + """Returns weights of the linear classifier.""" + return self.get_tensor_value('logistic_regression/bias:0') + + +TensorFlowRegressor = TensorFlowLinearRegressor +TensorFlowClassifier = TensorFlowLinearClassifier diff --git a/pool/shard007/Python/0071050_GridTest.py b/pool/shard007/Python/0071050_GridTest.py new file mode 100644 index 0000000000000000000000000000000000000000..2cd29c03f2da5a33f20fe31408c5c6c50dbafa52 --- /dev/null +++ b/pool/shard007/Python/0071050_GridTest.py @@ -0,0 +1,144 @@ +import os +import pytest +import scipy as sp +import numpy as np +import openpnm as op +from pathlib import Path + + +class GridTest: + + def setup_class(self): + self.ws = op.Workspace() + self.ws.clear() + self.proj = self.ws.new_project() + self.net = op.network.Cubic(shape=[2, 2, 2], project=self.proj) + Ps = self.net.pores('top') + Ts = self.net.find_neighbor_throats(pores=Ps) + self.geo1 = op.geometry.GenericGeometry(network=self.net, pores=Ps, + throats=Ts) + Ps = self.net.pores('bottom') + Ts = ~self.net.to_mask(throats=Ts) + self.geo2 = op.geometry.GenericGeometry(network=self.net, pores=Ps, + throats=Ts) + self.phase1 = op.phase.GenericPhase(network=self.net) + self.phase2 = op.phase.GenericPhase(network=self.net) + self.phys11 = op.physics.GenericPhysics(network=self.net, + phase=self.phase1, + geometry=self.geo1) + self.phys12 = op.physics.GenericPhysics(network=self.net, + phase=self.phase1, + geometry=self.geo2) + self.phys21 = op.physics.GenericPhysics(network=self.net, + phase=self.phase2, + geometry=self.geo1) + self.phys22 = op.physics.GenericPhysics(network=self.net, + phase=self.phase2, + geometry=self.geo2) + + def test_add_and_remove_rows_and_cols(self): + self.setup_class() + g = self.proj.grid + assert g.shape == (3, 3) + g.add_col() + assert g.shape == (3, 4) + g.drop_col(3) + assert g.shape == (3, 3) + g.add_row() + assert g.shape == (4, 3) + g.drop_row(3) + assert g.shape == (3, 3) + + def test_add_row_and_col_at_given_positions(self): + self.setup_class() + g = self.proj.grid + g.add_row(1) + assert g[1] == ['---', '---', '---'] + g.add_col(1) + assert g[:][1] == ['---', '---', '---', '---'] + + def test_nrows_ncols(self): + self.setup_class() + g = self.proj.grid + assert g.nrows == 3 + g.add_row() + assert g.nrows == 4 + assert g.ncols == 3 + g.add_col() + assert g.ncols == 4 + + def test_size_and_nnz(self): + self.setup_class() + g = self.proj.grid + assert g.size == 9 + assert g.nnz == 9 + p = op.phase.GenericPhase(network=self.net) + g = self.proj.grid + assert g.size == 12 + assert g.nnz == 10 + + def test_changing_blank(self): + self.setup_class() + p = op.phase.GenericPhase(network=self.net) + g = self.proj.grid + r = g.row(2) + assert '---' in r + g.blank = '===' + r = g.row(2) + assert '===' in r + + def test_set_col_and_row(self): + self.setup_class() + g = self.proj.grid + g.set_col(0, None) + assert None in g.col(0) + g.set_row(0, None) + assert None in g.row(0) + + def test_index_and_header(self): + self.setup_class() + g = self.proj.grid + assert g.header._grid.table_data == [g.row(0)] + assert g.index._grid.table_data == [[i] for i in g.col(0)] + + def test_phases_and_geometries(self): + self.setup_class() + g = self.proj.grid + assert g.phases() == ['phase_01', 'phase_02'] + assert g.geometries() == ['geo_01', 'geo_02'] + + def test_get_col_and_row_by_number_and_name(self): + self.setup_class() + g = self.proj.grid + a = g.get_col(0) + b = g.get_col('net_01') + assert a._grid.table_data == b._grid.table_data + a = g.get_row(1) + b = g.get_row('geo_01') + assert a._grid.table_data == b._grid.table_data + + def test_set_row_and_col(self): + self.setup_class() + g = self.proj.grid + g.set_row_and_col(row='x', col='z', val='z') + assert g[-1][-1] == 'z' + g.set_row_and_col(row='x', col='z', val='zz') + assert g[-1][-1] == 'zz' + + def test_style_change(self): + self.setup_class() + g = self.proj.grid + assert g.style == 'ascii' + g.style = 'double' + assert g.style == 'double' + + +if __name__ == '__main__': + + t = GridTest() + self = t + t.setup_class() + for item in t.__dir__(): + if item.startswith('test'): + print('running test: '+item) + t.__getattribute__(item)() diff --git a/pool/shard007/Python/0071055_init__.py b/pool/shard007/Python/0071055_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7fd93eea2f951f5765fc04a386f35a799956cbb4 --- /dev/null +++ b/pool/shard007/Python/0071055_init__.py @@ -0,0 +1,53 @@ +# django-salesforce +# +# by Phil Christensen +# (c) 2012-2013 Freelancers Union (http://www.freelancersunion.org) +# See LICENSE.md for details +# +""" +Salesforce Database backend for Django. + +No code in this directory is used with standard databases, even if a standard +database is used for running some application tests on objects defined by +SalesforceModel. All code for SF models that can be used with non SF databases +should be located directly in the 'salesforce' directory in files 'models.py', +'fields.py', 'router.py', 'admin.py', 'backend/manager.py'. + +Most of code here (in salesforce.backend) is private. (undocumented like other +Django backends and can be changed anytime. Therefore it should not be used by apps) +The only public code here is `salesforce/backend/manager.py`. + +Structure: + salesforce/*.py - Code that is to be used instead of some standard + django.db classes. + salesforce/backend/*.py - Private code equivalent to django.db.backend.some_backend + salesforce/dbapi/*.py - Database driver independent on Django + +Incorrectly located files: (It is better not to change it now.) + backend/manager.py => manager.py + auth.py => dbapi/auth.py +""" + +import logging +import re + +import django + +DJANGO_21_PLUS = django.VERSION[:2] >= (2, 1) +DJANGO_22_PLUS = django.VERSION[:2] >= (2, 2) +DJANGO_30_PLUS = django.VERSION[:2] >= (3, 0) +DJANGO_31_PLUS = django.VERSION[:2] >= (3, 1) +DJANGO_32_PLUS = django.VERSION[:2] >= (3, 2) +DJANGO_40_PLUS = django.VERSION[:2] >= (4, 0) +is_dev_version = django.VERSION[3:] and re.match('(alpha|beta|rc)', django.VERSION[3]) +if django.VERSION[:2] < (2, 0) or django.VERSION[:2] > (4, 0) and not is_dev_version: + raise ImportError("Django version between 2.0 and 4.0 is required " + "for this django-salesforce.") + # Usually three or more blocking issues can be expected by every + # new major Django version. Strict check before support is better. + + # New Django development versions are enabled without any restriction, but + # new stable Django versions must be verified before they can be enabled here. + + +log = logging.getLogger(__name__) diff --git a/pool/shard007/Python/0071056_inwx_calls.py b/pool/shard007/Python/0071056_inwx_calls.py new file mode 100644 index 0000000000000000000000000000000000000000..7890a9e5883acc7d320bff6af7cbf3d40fbb6377 --- /dev/null +++ b/pool/shard007/Python/0071056_inwx_calls.py @@ -0,0 +1,43 @@ +# TODO: delete, create domain entry, update (delete+create) +from inwx_managed_python_lib.inwx import domrobot, prettyprint, getOTP + + +api_url = "https://api.domrobot.com/xmlrpc/" + +class inwx: + def __init__(self): + self.inwx_conn = None + + def login(self, username, password): + self.inwx_conn = domrobot(api_url, False) + self.inwx_conn.account.login({'lang': 'en', 'user': username, 'pass': password}) + + return True # TODO: check if login was successful + + def create_sub_domain(self, domain, tld, ip): + create_result = self.inwx_conn.nameserver.createRecord({ + "type": "A", + "content": ip, + "name": domain, + "domain": tld + }) + + print create_result + + return True # TODO: check if creation was successful + + def delete_sub_domain(self, domain_id): + delete_result = self.inwx_conn.nameserver.deleteRecord({ + "id": domain_id + }) + + return True # TODO: check if delete was successful + + def update_sub_domain(self, domain, tld, domain_id, ip): + if self.delete_sub_domain(domain_id): + self.create_sub_domain(domain, tld, ip) + + return True # TODO: check if update was successful + + def get_domain_info(self, tld): + return self.inwx_conn.nameserver.info({'domain': tld}) diff --git a/pool/shard007/Python/0071061_odeintwrapper.py b/pool/shard007/Python/0071061_odeintwrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..cfcaf3a69b6efd4fb26dc12ffb16e4c1a9b98baa --- /dev/null +++ b/pool/shard007/Python/0071061_odeintwrapper.py @@ -0,0 +1,12 @@ +def odeint(f, y0, t, args, Dfun=None, integrator='dop853', **kwargs): + """Provides a odeint-like wrapper around the other ode routines from scipy.""" + def f_ode(t, y): + return f(y, t, *args) + integrator = ode(f_ode, jac=Dfun) + integrator.set_integrator(integrator, **kwargs) + integrator.set_initial_value(y0, t[0]) + ys = np.empty((len(t), len(y0))) + for i, ti in enumerate(t): + y = integrator.integrate(ti) + ys[i] = y + return ys diff --git a/pool/shard007/Python/0071065_prepare_code.py b/pool/shard007/Python/0071065_prepare_code.py new file mode 100644 index 0000000000000000000000000000000000000000..791ff810c5123888e5a87607309ac56d30e51e8b --- /dev/null +++ b/pool/shard007/Python/0071065_prepare_code.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +import os.path +import os +from tools import * + +def find_app_root(dirname): + if not dirname: + raise Exception("Illegal argument : None") + current_dir = os.path.abspath(".") + parent_dir = current_dir + while True: + target = os.path.join(parent_dir, dirname) + if os.path.isdir(target): + return target + parent_dir = os.path.dirname(current_dir) + if parent_dir == current_dir: + return None + current_dir = parent_dir + +def get_repo_projects(repodir): + """ + @args: repodir: xxx/.repo/ + """ + +print(find_app_root(".repo")) +shell_call('repo forall -c "git reset --hard"') +shell_call('repo forall -c "git clean -xdf"') +#shell_call('repo forall -c "git checkout build/berlin/1061"') +#shell_say_call('repo forall -c "git checkout yzyu/1061/ub1204_ics 2>/dev/null"') +#shell_say_call('repo forall -c "git diff build/berlin/1061 HEAD"') diff --git a/pool/shard007/Python/0071070_setup.py b/pool/shard007/Python/0071070_setup.py new file mode 100644 index 0000000000000000000000000000000000000000..6cf22b591f1fa30c1af88a697037aaa2ea08a085 --- /dev/null +++ b/pool/shard007/Python/0071070_setup.py @@ -0,0 +1,18 @@ +from setuptools import setup + +with open("README.md") as readme_file: + description = readme_file.read() + +with open("requirements.txt") as requirements_file: + requirements = requirements_file.readlines() + +setup( + name="demo_at", + version="0.1.0", + description="A demo of Python's project with automated tests.", + long_description=description, + url="https://github.com/tatools/demo-python", + packages=["demo_python_at"], + install_requires=requirements, + license="Apache-2.0", +) diff --git a/pool/shard007/Python/0071086_plugin.py b/pool/shard007/Python/0071086_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..bc31da47a3d0996c75768e6387effdac232ccb66 --- /dev/null +++ b/pool/shard007/Python/0071086_plugin.py @@ -0,0 +1,30 @@ +""" +Please see the documentation in FlaskXMLRPC. +""" +import amsoil.core.pluginmanager as pm +import amsoil.core.log +logger=amsoil.core.log.getLogger('flaskrpcs') + +from flaskxmlrpc import FlaskXMLRPC +from flaskserver import FlaskServer + +def setup(): + config = pm.getService("config") + # create default configurations (if they are not already in the database) + config.install("flask.bind", "0.0.0.0", "IP to bind the Flask RPC to.") + config.install("flask.fcgi_port", 9001, "Port to bind the Flask RPC to (FCGI server).") + config.install("flask.app_port", 8001, "Port to bind the Flask RPC to (standalone server).") + config.install("flask.debug", True, "Write logging messages for the Flask RPC server.") + config.install("flask.fcgi", False, "Use FCGI server instead of the development server.") + config.install("flask.force_client_cert", True, "Only applies if flask.debug is set: Determines if the client _must_ present a certificate. No validation is performed.") + + + # create and register the RPC server + flaskserver = FlaskServer() + pm.registerService('rpcserver', flaskserver) + + # create and register the XML-RPC server + xmlrpc = FlaskXMLRPC(flaskserver) + pm.registerService('xmlrpc', xmlrpc) + + # TODO create and register the JSON-RPC server \ No newline at end of file diff --git a/pool/shard007/Python/0071087_151_Reverse_Words_in_a_String.py b/pool/shard007/Python/0071087_151_Reverse_Words_in_a_String.py new file mode 100644 index 0000000000000000000000000000000000000000..0aa8c5f7340b1b34b19ab07296145f581b69752a --- /dev/null +++ b/pool/shard007/Python/0071087_151_Reverse_Words_in_a_String.py @@ -0,0 +1,41 @@ +class Solution(object): + + # Op1: Cheat + def reverseWords(self, s): + """ + :type s: str + :rtype: str + """ + return ' '.join(s.split()[::-1]) + + # Op2: One-pass O(n) runtime, O(1) space + def reverseWords2(self, s): + ans = '' + j = len(s) + for i in reversed(range(len(s))): + if s[i] == ' ': + j = i + elif i == 0 or s[i - 1] == ' ': + if ans: + ans += ' ' + ans += s[i:j] + return ans + + # Op3: One-pass O(n) runtime, O(1) space + def reverseWords3(self, s): + s += ' ' + output = '' + i = 0 + for j in range(len(s)): + if s[j] == ' ': + if j > i: + output = s[i:j] + ' ' + output + i = j + 1 + return output[:-1] + + +s = 'hey wahtas up' +test = Solution() +print(test.reverseWords(s)) +print(test.reverseWords2(s)) +print(test.reverseWords3(s)) diff --git a/pool/shard007/Python/0071089_pylibmc_tests.py b/pool/shard007/Python/0071089_pylibmc_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..13b8458e683a98daa5843e0f6bd9184415bc74fb --- /dev/null +++ b/pool/shard007/Python/0071089_pylibmc_tests.py @@ -0,0 +1,90 @@ +# BSD 3-Clause License +# +# Copyright (c) 2019, Elasticsearch BV +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# * Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import os + +import pytest + +from elasticapm.conf.constants import TRANSACTION +from elasticapm.traces import capture_span + +pylibmc = pytest.importorskip("pylibmc") + +pytestmark = [pytest.mark.pylibmc] + +if "MEMCACHED_HOST" not in os.environ: + pytestmark.append(pytest.mark.skip("Skipping pylibmc tests, no MEMCACHED_HOST environment variable set")) + + +@pytest.mark.integrationtest +def test_pylibmc(instrument, elasticapm_client): + elasticapm_client.begin_transaction("transaction.test") + host = os.environ.get("MEMCACHED_HOST", "localhost") + with capture_span("test_memcached", "test"): + conn = pylibmc.Client([host + ":11211"]) + conn.set("mykey", "a") + assert "a" == conn.get("mykey") + assert {"mykey": "a"} == conn.get_multi(["mykey", "myotherkey"]) + elasticapm_client.end_transaction("BillingView") + + transactions = elasticapm_client.events[TRANSACTION] + spans = elasticapm_client.spans_for_transaction(transactions[0]) + + expected_signatures = {"test_memcached", "Client.set", "Client.get", "Client.get_multi"} + + assert {t["name"] for t in spans} == expected_signatures + + assert spans[0]["name"] == "Client.set" + assert spans[0]["type"] == "cache" + assert spans[0]["subtype"] == "memcached" + assert spans[0]["action"] == "query" + assert spans[0]["parent_id"] == spans[3]["id"] + + assert spans[1]["name"] == "Client.get" + assert spans[1]["type"] == "cache" + assert spans[1]["subtype"] == "memcached" + assert spans[1]["action"] == "query" + assert spans[1]["parent_id"] == spans[3]["id"] + assert spans[1]["context"]["destination"] == { + "address": host, + "port": 11211, + "service": {"name": "", "resource": "memcached", "type": ""}, + } + + assert spans[2]["name"] == "Client.get_multi" + assert spans[2]["type"] == "cache" + assert spans[2]["subtype"] == "memcached" + assert spans[2]["action"] == "query" + assert spans[2]["parent_id"] == spans[3]["id"] + + assert spans[3]["name"] == "test_memcached" + assert spans[3]["type"] == "test" + + assert len(spans) == 4 diff --git a/pool/shard007/Python/0071102_run.py b/pool/shard007/Python/0071102_run.py new file mode 100644 index 0000000000000000000000000000000000000000..ffc3631c0bd09e1ad9a1b46761657c9ef0f759ff --- /dev/null +++ b/pool/shard007/Python/0071102_run.py @@ -0,0 +1,55 @@ +import sys +from path import path + +PROJECT_ROOT = path(__file__).abspath().dirname().dirname() + +VIRTUALENV = path(sys.executable).abspath().dirname().dirname() + + +sys.path.append(PROJECT_ROOT) +sys.path.append(PROJECT_ROOT / 'apps') + +from heartbeat import Heartbeat +from what_apps.meta.alerts import local_red_alert +import requests + + + +HEARTBEATS = Heartbeat.__subclasses__() + +class HeartBeatRunner(object): + error_messages = [] + + def run(self): + for HeartbeatChild in HEARTBEATS: #HeartbeatChild here is a class (a subclass of the Heartbeat class) + + heartbeat = HeartbeatChild() + + if not heartbeat.is_skipped(): +# try: + heartbeat.run() +# except Exception, e: +# self.error_messages.append(e) + + + if not heartbeat.passed(): + error_message = heartbeat.alert_failure() + self.error_messages.append(error_message) + + + #OK, now that we've run anything, let's figure out what kind of shape we're in. + if self.error_messages: + #Bad shape. Time for red alert. + alert_message = 'Heartbeat Failure. \n' + for message in self.error_messages: + alert_message += "%s \n" % message + local_red_alert(alert_message) + else: + #Everything went ok - there are no error messages. + report_response = requests.post(resources.HEARTBEAT_SUCSESS_URL) + + + +if __name__ == "__main__": + hbr = HeartBeatRunner() + hbr.run() diff --git a/pool/shard007/Python/0071105_bom.py b/pool/shard007/Python/0071105_bom.py new file mode 100644 index 0000000000000000000000000000000000000000..844977c322f4bfe5de463f1a116262e0de7acdab --- /dev/null +++ b/pool/shard007/Python/0071105_bom.py @@ -0,0 +1,109 @@ +#!/usr/bin/python3 +# +# adapted from bom_csv_grouped_by_value.py + +from __future__ import print_function + +# Import the KiCad python helper module and the csv formatter +import kicad_netlist_reader +import csv +import sys +import natsort +import os +import argparse + +def main(): + # Set up a simple argument parser. + parser = argparse.ArgumentParser(description="KiCad BOM script") + parser.add_argument('-d', dest='digikey', action='store_true', + help="Truncate references for Digi-Key orders") + parser.add_argument('-s', dest='single', action='store_true', + help="Output single reference per row") + parser.add_argument('infile', metavar='', type=str, + help='input xml BOM file from KiCad') + parser.add_argument('-q', dest='quantity', type=int, default=1, + help='Number of boards') + args = parser.parse_args() + + # Generate an instance of a generic netlist, and load the netlist tree from + # the command line option. If the file doesn't exist, execution will stop + net = kicad_netlist_reader.netlist(args.infile) + + # Open a file to write to, if the file cannot be opened output to stdout + # instead + filename, file_extension = os.path.splitext(args.infile) + outfile = filename + ".csv" + try: + f = open(outfile, 'w') + except IOError: + e = "Can't open output file for writing: " + outfile + print(__file__, ":", e, file=sys.stderr) + f = sys.stdout + + # subset the components to those wanted in the BOM, controlled + # by block in kicad_netlist_reader.py + components = net.getInterestingComponents() + + compfields = net.gatherComponentFieldUnion(components) + partfields = net.gatherLibPartFieldUnion() + + # remove Reference, Value, Datasheet, and Footprint, they will come from 'columns' below + partfields -= set( ['Reference', 'Value', 'Datasheet', 'Footprint'] ) + + columnset = compfields | partfields # union + + # prepend an initial 'hard coded' list and put the enchillada into list 'columns' + columns = ['Item', 'Qty', 'Reference(s)', 'Value', 'LibPart', 'Footprint', 'Datasheet'] + sorted(list(columnset)) + + # Create a new csv writer object to use as the output formatter + out = csv.writer(f, lineterminator='\n', delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL) + + row = [] + + # Get all of the components in groups of matching parts + values + # (see kicad_netlist_reader.py) + if args.single: + grouped = [[c] for c in components] + else: + grouped = net.groupComponents(components) + + # Output header row + out.writerow(columns) + + # Output component information organized by group, aka as collated: + item = 0 + for group in grouped: + del row[:] + refs = [] + + # Add the reference of every component in the group and keep a reference + # to the component so that the other data can be filled in once per group + for component in group: + refs.append(component.getRef()) + c = component + + ref_string = ", ".join(natsort.natsorted(refs)) + if args.digikey and len(ref_string) > 48: + ref_string = ref_string[:45] + "..." + + # Fill in the component groups common data + # columns = ['Item', 'Qty', 'Reference(s)', 'Value', 'LibPart', 'Footprint', 'Datasheet'] + sorted(list(columnset)) + item += 1 + row.append( item ) + row.append( len(group) * args.quantity ) + row.append( ref_string ) + row.append( c.getValue() ) + row.append( c.getLibName() + ":" + c.getPartName() ) + row.append( net.getGroupFootprint(group) ) + row.append( net.getGroupDatasheet(group) ) + + # from column 7 upwards, use the fieldnames to grab the data + for field in columns[7:]: + row.append( net.getGroupField(group, field) ); + + out.writerow(row) + + f.close() + +if __name__ == "__main__": + main() diff --git a/pool/shard007/Python/0071116_urbandictionary.py b/pool/shard007/Python/0071116_urbandictionary.py new file mode 100644 index 0000000000000000000000000000000000000000..c36c90327ddd213d1e36415f71f7899f9648d1e1 --- /dev/null +++ b/pool/shard007/Python/0071116_urbandictionary.py @@ -0,0 +1,27 @@ +from core import Module, on_command +from core.util import threaded +import requests + + +class UrbanDictionary(Module): + _template_undefined = "{user}: That word is not defined" + _template_response = "{word} - {definition:.100}" + _base_url = "http://api.urbandictionary.com/v0/{endpoint}" + + @on_command('ud') + @threaded + def command_urban(self, bot, channel, user, message): + message = message.strip() + params = {} + if message == '': + url = self._base_url.format(endpoint='random') + else: + url = self._base_url.format(endpoint='define') + params['term'] = message + + response = requests.get(url, params=params).json() + if len(response['list']) is 0: + bot.message(channel, self._template_undefined.format(user=user)) + else: + data = response['list'][0] + bot.message(channel, self._template_response.format(**data)) diff --git a/pool/shard007/Python/0071122_test_list_acl.py b/pool/shard007/Python/0071122_test_list_acl.py new file mode 100644 index 0000000000000000000000000000000000000000..fc47e779e49e3cfc2abbc65cb186f222e17ed04b --- /dev/null +++ b/pool/shard007/Python/0071122_test_list_acl.py @@ -0,0 +1,33 @@ +''' + Test list creation +''' + +import unittest +from wirecurly.configuration import list, node + + +class testListCreation(unittest.TestCase): + ''' + Test menu creation + ''' + + def setUp(self): + ''' + list fixtures for tests + ''' + self.list = list.List('gateways','deny') + + def test_list_dict_ok(self): + ''' + Test that list is properly serialized + ''' + assert isinstance(self.list.todict(), dict) + + def test_adding_node(self): + ''' + Test if a node is properly add to a list + ''' + n = node.Node('allow', '10.10.10.10/32') + self.list.addNode(n) + nl = self.list.getNodes() + assert nl[0].todict() == {'tag': 'node', 'attrs': {'cidr': '10.10.10.10/32', 'type': 'allow'}} diff --git a/pool/shard007/Python/0071127_spinner.py b/pool/shard007/Python/0071127_spinner.py new file mode 100644 index 0000000000000000000000000000000000000000..ab99b12ef3208c67e04642718aa59579cbb5108c --- /dev/null +++ b/pool/shard007/Python/0071127_spinner.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +from __future__ import absolute_import, print_function + +import sys +import time +from functools import wraps +from concurrent.futures import ThreadPoolExecutor + +try: + SPINSTR = unicode +except NameError as namerr: + SPINSTR = str + +BOX1 = u'⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏' +BOX2 = u'⠋⠙⠚⠞⠖⠦⠴⠲⠳⠓' +BOX3 = u'⠄⠆⠇⠋⠙⠸⠰⠠⠰⠸⠙⠋⠇⠆' +BOX4 = u'⠋⠙⠚⠒⠂⠂⠒⠲⠴⠦⠖⠒⠐⠐⠒⠓⠋' +BOX5 = u'⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠴⠲⠒⠂⠂⠒⠚⠙⠉⠁' +BOX6 = u'⠈⠉⠋⠓⠒⠐⠐⠒⠖⠦⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈' +BOX7 = u'⠁⠁⠉⠙⠚⠒⠂⠂⠒⠲⠴⠤⠄⠄⠤⠠⠠⠤⠦⠖⠒⠐⠐⠒⠓⠋⠉⠈⠈' +SPIN1 = u'|/-\\' +SPIN2 = u'◴◷◶◵' +SPIN3 = u'◰◳◲◱' +SPIN4 = u'◐◓◑◒' +SPIN5 = u'▉▊▋▌▍▎▏▎▍▌▋▊▉' +SPIN6 = u'▌▄▐▀' +SPIN7 = u'╫╪' +SPIN8 = u'■□▪▫' +SPIN9 = u'←↑→↓' +DEFAULT = BOX1 + + +class Spinner(object): + def __init__(self, words, frames=DEFAULT): + self.frames = frames + self.length = len(frames) + self.position = 0 + self.words = words + + def current(self): + return self.frames[self.position] + + def next(self): + current_frame = self.current() + self.position = (self.position + 1) % self.length + return SPINSTR(current_frame) + + def reset(self): + self.position = 0 + + def __call__(self, func): + @wraps(func) + def wrapper(*args, **kwargs): + with ThreadPoolExecutor(max_workers=1) as executor: + future = executor.submit(func, *args, **kwargs) + while future.running(): + sys.stdout.flush() + print(SPINSTR("\r{0} {1} ").format(self.words, self.next()), end="") + sys.stdout.flush() + time.sleep(0.15) + print(SPINSTR("\r{0}.....{1}").format(self.words, "[Done]"), end="\n") + return future.result() + return wrapper + + + +def spinner(words="", spin_style=DEFAULT, ending="\n"): + spinner = Spinner(spin_style) + + def decorator(func): + @wraps(func) + def wrapper(*args, **kwargs): + with ThreadPoolExecutor(max_workers=1) as executor: + future = executor.submit(func, *args, **kwargs) + + while future.running(): + sys.stdout.flush() + print(SPINSTR("\r{0} {1} ").format(words, spinner.next()), end="") + sys.stdout.flush() + time.sleep(0.15) + print(SPINSTR("\r{0}.....{1}").format(words, "[Done]"), end=ending) + return future.result() + return wrapper + return decorator diff --git a/pool/shard007/Python/0071132_xbgfSlice.py b/pool/shard007/Python/0071132_xbgfSlice.py new file mode 100644 index 0000000000000000000000000000000000000000..989ef396af1c58d26e89a23cae08fef0d6b81765 --- /dev/null +++ b/pool/shard007/Python/0071132_xbgfSlice.py @@ -0,0 +1,28 @@ +#!/usr/bin/python +import os +import sys +import string +import elementtree.ElementTree as ET +import slpsns +import slicing + +def main(xbgfFile): + xbgfDir = '/'.join(xbgfFile.split('/')[:-1]) + if xbgfDir == '': + xbgfDir = './' + elif xbgfDir[-1]!='/': + xbgfDir += '/' + print 'Slicing...' + sliced = slicing.sliceFile(xbgfDir,xbgfDir,xbgfFile.split('/')[-1].replace('.xbgf','')) + return + +if __name__ == "__main__": + if len(sys.argv) == 2: + slpsns.init(ET) + apply(main,sys.argv[1:6]) + else: + print '''This tool takes an XBGF file and slices it. + +Usage:''' + print ' ',sys.argv[0],'' + sys.exit(1) diff --git a/pool/shard007/Python/0071135_test_auto_FEAT.py b/pool/shard007/Python/0071135_test_auto_FEAT.py new file mode 100644 index 0000000000000000000000000000000000000000..850030250270bdbed7218484efa4e4b92a66ca09 --- /dev/null +++ b/pool/shard007/Python/0071135_test_auto_FEAT.py @@ -0,0 +1,37 @@ +# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT +from ....testing import assert_equal +from ..model import FEAT + + +def test_FEAT_inputs(): + input_map = dict(args=dict(argstr='%s', + ), + environ=dict(nohash=True, + usedefault=True, + ), + fsf_file=dict(argstr='%s', + mandatory=True, + position=0, + ), + ignore_exception=dict(nohash=True, + usedefault=True, + ), + output_type=dict(), + terminal_output=dict(nohash=True, + ), + ) + inputs = FEAT.input_spec() + + for key, metadata in list(input_map.items()): + for metakey, value in list(metadata.items()): + yield assert_equal, getattr(inputs.traits()[key], metakey), value + + +def test_FEAT_outputs(): + output_map = dict(feat_dir=dict(), + ) + outputs = FEAT.output_spec() + + for key, metadata in list(output_map.items()): + for metakey, value in list(metadata.items()): + yield assert_equal, getattr(outputs.traits()[key], metakey), value diff --git a/pool/shard007/Python/0071142_ts_server.py b/pool/shard007/Python/0071142_ts_server.py new file mode 100644 index 0000000000000000000000000000000000000000..12edea9467879c9f67000c4f8e0315875ae0bb64 --- /dev/null +++ b/pool/shard007/Python/0071142_ts_server.py @@ -0,0 +1,58 @@ +""" +Created on Sat Apr 27 2013 + +This provides the timestamping service as a WSGI app. + +@author: Brian Visel +""" + +import os + +import bottle +from bottle import get, put, post, request, response # route, run + +import config +import exception +from stamp import TimeStampInterface + + +DEBUG = True + +interface = TimeStampInterface(config.algorithm, config.policy, + os.path.sep.join([config.data_dir, + config.config]), + config.signer, config.passin, config.inkey, + config.chain, config.use_token) + + +@get('/') +def index_get(): + return "Timestamp Server" + + +#@route('/', method='PUT') +@put('/') +def index_put(): + return request.body.read() + + +@post('/') +def index_post(): + try: + response.content_type = 'application/timestamp-reply' + return interface.stamp_request(request.body.read()) + except exception.OpenSSLError as e: + return '\n'.join([e.stdout.decode('utf-8'), e.stderr.decode('utf-8'), + str(e.command)]) + +#run(host='timestamp', port=8080, server='gunicorn', +# workers=4, log_syslog=True) + +app = bottle.default_app() + +# Debugging.. +bottle.debug(DEBUG) +app.catchall = False + +if __name__ == "__main__": + app.run() \ No newline at end of file diff --git a/pool/shard007/Python/0071144_ltc_daemon.py b/pool/shard007/Python/0071144_ltc_daemon.py new file mode 100644 index 0000000000000000000000000000000000000000..016db3fc8e5ea2bb4b97b6073d206c556ff96e26 --- /dev/null +++ b/pool/shard007/Python/0071144_ltc_daemon.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python +import paydaemon +from paydaemon.paydaemon import PAYDaemon +from litecoinrpc.connection import LitecoinConnection +from modules.fixedpoint import FixedPoint + +DEBUG = 1 + +class LTCDaemon(PAYDaemon): + + def __init__(self,pidfile): + PAYDaemon.__init__(self,pidfile,'LTC','BTC',LitecoinConnection) + # config + PAYDaemon.COIN_MIN_FREEPOOL = 10 + PAYDaemon.SMULT = FixedPoint('100000000',8) + PAYDaemon.MINAMNT = FixedPoint('0.01',8) + PAYDaemon.FEEPERCT = FixedPoint('0.2',8) + PAYDaemon.TRANSFEE = FixedPoint('10000',8) + + +if __name__ == "__main__": + daemon = LTCDaemon('/tmp/daemon-ltc.pid') + if DEBUG: + daemon.run() + else: + if len(sys.argv) == 2: + if 'start' == sys.argv[1]: + daemon.start() + elif 'stop' == sys.argv[1]: + daemon.stop() + elif 'restart' == sys.argv[1]: + daemon.restart() + else: + print "Unknown command" + sys.exit(2) + sys.exit(0) + else: + print "usage: %s start|stop|restart [debug]" % sys.argv[0] + sys.exit(2) diff --git a/pool/shard007/Python/0071152_init__.py b/pool/shard007/Python/0071152_init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6e5a9aa7c4597516e5073b1dfb36f24b2b5bc9bb --- /dev/null +++ b/pool/shard007/Python/0071152_init__.py @@ -0,0 +1,66 @@ +#################################################################################################### +# +# PySpice - A Spice Package for Python +# Copyright (C) 2014 Fabrice Salvaire +# +# 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 . +# +#################################################################################################### + +#################################################################################################### + +from . import BasicElement +from . import HighLevelElement +from .Netlist import Netlist, ElementParameterMetaClass + +#################################################################################################### + +def _get_elements(module): + element_classes = [] + for item in module.__dict__.values(): + if (type(item) is ElementParameterMetaClass + and item.prefix is not None + ): + element_classes.append(item) + return element_classes + +#################################################################################################### +# +# Add a method to create elements to the Netlist class +# + +spice_elements = _get_elements(BasicElement) +high_level_elements = _get_elements(HighLevelElement) + +for element_class in spice_elements + high_level_elements: + + def _make_function(element_class): + def function(self, *args, **kwargs): + element = element_class(*args, **kwargs) + self._add_element(element) + return element + return function + + if element_class in spice_elements and hasattr(element_class, 'alias'): + function_name = element_class.alias + else: + function_name = element_class.__name__ + + setattr(Netlist, function_name, _make_function(element_class)) + +#################################################################################################### +# +# End +# +#################################################################################################### diff --git a/pool/shard007/Python/0071161_map.py b/pool/shard007/Python/0071161_map.py new file mode 100644 index 0000000000000000000000000000000000000000..6fddf9903ede23c538782d549136d86eaf7feb8b --- /dev/null +++ b/pool/shard007/Python/0071161_map.py @@ -0,0 +1,77 @@ +''' + @author Gabriel +''' +import numpy as np +import cv2 +import random +from scipy import misc +from scipy.ndimage import rotate + +pixel_buoy=6 +alto=58 +ancho=34 + + +def new_map(x,y): + mapa=np.full((x,y,3),0,dtype=np.uint8) + return mapa + +def plot_map(mapa): + copia=mapa.copy() + h,w,c=mapa.shape + x1=int(h/2-(ancho/2)); + y1=int(w/2-(alto/2)); + x2=int(h/2+(ancho/2)); + y2=int(w/2+(alto/2)); + cx=int(h/2) + cy=int(w/2) + cv2.rectangle(copia,(x1,y1),(x2,y2),(0,255,0),1,8) + cv2.line(copia,(cx,cy),(cx,cy-25),(0,0,255),1,8) + cv2.imshow('mapa',copia) + cv2.waitKey(0) + +def rotate_map(mapa, angle): + #mapa=misc.imrotate(mapa,angle,interp='nearest') + mapa = rotate(mapa, angle, mode = 'constant',reshape=False) + return mapa + +def translate_map(mapa,dx,dy): + cols,rows,ch=mapa.shape + M=np.float32([[1,0,dx],[0,1,dy]]) + mapa=cv2.warpAffine(mapa,M,(cols,rows)) + return mapa + +def add_buoy(mapa,x,y): + cv2.circle(mapa,(x,y),pixel_buoy,255,-1,8) + +def add_lidar(mapa,points): + for point in points: + mapa[point[0]][point[1]]=[0,255,0] + return mapa + + +#Nuevo mapa +boat_map=new_map(400,400) + +#Dibujar boya +add_buoy(boat_map,100,150) +add_buoy(boat_map,100,150) + +#Mostrar mapa +plot_map(boat_map) + +#Rotar mapa +for angulo in range(0,180,10): + boat_map=rotate_map(boat_map,5) + plot_map(boat_map) + +#Trasladar mapa 1 en x +for x in range(0,10): + boat_map=translate_map(boat_map,5,0) + plot_map(boat_map) + +#Trasladar mapa -1 en y +for y in range(0,30): + boat_map=translate_map(boat_map,0,-5) + plot_map(boat_map) + diff --git a/pool/shard007/Python/0071162_util.py b/pool/shard007/Python/0071162_util.py new file mode 100644 index 0000000000000000000000000000000000000000..ce705bb9a87f3e232ed7232b4aa007f37e6169af --- /dev/null +++ b/pool/shard007/Python/0071162_util.py @@ -0,0 +1,59 @@ +# Copyright 2020 DeepMind Technologies Limited. All Rights Reserved. +# +# 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. +# ============================================================================== +"""Util.""" +import collections + +from absl import logging +import dm_env +import numpy as np +import tree + +# Can represent either a single transition, a trajectory, or a batch of +# trajectories. +Transition = collections.namedtuple('Transition', + ['timestep', 'agent_out', 'agent_state']) + + +def _preprocess_none(t) -> np.ndarray: + if t is None: + return np.array(0., dtype=np.float32) + else: + return np.asarray(t) + + +def preprocess_step(timestep: dm_env.TimeStep) -> dm_env.TimeStep: + if timestep.discount is None: + timestep = timestep._replace(discount=1.) + return tree.map_structure(_preprocess_none, timestep) + + +class NullLogger: + """Logger that does nothing.""" + + def write(self, _): + pass + + def close(self): + pass + + +class AbslLogger: + """Writes to logging.info.""" + + def write(self, d): + logging.info(d) + + def close(self): + pass diff --git a/pool/shard007/Python/0071169_linear_svc.py b/pool/shard007/Python/0071169_linear_svc.py new file mode 100644 index 0000000000000000000000000000000000000000..8d0a24d7322a46fc89959771249944d6d76b96e3 --- /dev/null +++ b/pool/shard007/Python/0071169_linear_svc.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python + +""" +LinearSVC +""" + +__author__ = "Manan Kalra" +__email__ = "manankalr29@gmail.com" + + +import nltk +from nltk.classify.scikitlearn import SklearnClassifier # wrapper to include the scikit-learn algorithms +from main import naive_bayes as original +from sklearn.svm import LinearSVC + + +linear_svc_classifier = SklearnClassifier(LinearSVC()) +linear_svc_classifier.train(original.training_set) +linear_svc_accuracy = nltk.classify.accuracy(linear_svc_classifier, original.testing_set) * 100 + +print("\nBernoulli NB Accuracy: ", linear_svc_accuracy) diff --git a/pool/shard007/Python/0071173_test.py b/pool/shard007/Python/0071173_test.py new file mode 100644 index 0000000000000000000000000000000000000000..73bd130d51e55c2b97c84a727c70940630acb41c --- /dev/null +++ b/pool/shard007/Python/0071173_test.py @@ -0,0 +1,57 @@ +#!/usr/bin/env python +# accessionator 0.0.1 test suite +# Generated by dx-app-wizard. + +import json, os, time, unittest + +import dxpy +import dxpy.app_builder + +from dxpy.exceptions import DXAPIError + +src_dir = os.path.join(os.path.dirname(__file__), "..") +test_resources_dir = os.path.join(src_dir, "test", "resources") + +def makeInputs(): + # Please fill in this method to generate default inputs for your app. + return {} + +class Testaccessionator(unittest.TestCase): + @classmethod + def setUpClass(cls): + # Upload the app to the Platform. + cls.base_input = makeInputs() + bundled_resources = dxpy.app_builder.upload_resources(src_dir) + try: + app_name = os.path.basename(os.path.abspath(src_dir)) + "_test" + except OSError: + app_name = "test_app" + applet_basename = app_name + "_" + str(int(time.time())) + cls.applet_id, _ignored_applet_spec = dxpy.app_builder.upload_applet(src_dir, bundled_resources, override_name=applet_basename) + + @classmethod + def tearDownClass(cls): + # Clean up by removing the app we created. + try: + dxpy.api.container_remove_objects(dxpy.WORKSPACE_ID, {"objects": [cls.applet_id]}) + except DXAPIError as e: + print "Error removing %s during cleanup; ignoring." % (cls.applet_id,) + print e + + def setUp(self): + pass + + def tearDown(self): + pass + + def test_base_input(self): + """ + Tests the app with a basic input. + """ + job = dxpy.DXApplet(self.applet_id).run(self.base_input) + print "Waiting for %s to complete" % (job.get_id(),) + job.wait_on_done() + print json.dumps(job.describe()["output"]) + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard007/Python/0071174_interaction_rules.py b/pool/shard007/Python/0071174_interaction_rules.py new file mode 100644 index 0000000000000000000000000000000000000000..29c1f8f069e3d649bea1e657ae0d077b452e8431 --- /dev/null +++ b/pool/shard007/Python/0071174_interaction_rules.py @@ -0,0 +1,53 @@ +from .orm_signal_handler import orm_signal_handler +from specifyweb.specify import models +from .exceptions import BusinessRuleException +from django.db import connection +from specifyweb.specify.api import parse_uri + +def get_availability(prep, iprepid, iprepid_fld): + args = [prep.id] + sql = """ + select p.countAmt - coalesce(sum(lp.quantity-lp.quantityresolved),0) - coalesce(sum(gp.quantity),0) - coalesce(sum(ep.quantity),0) + from preparation p + left join loanpreparation lp on lp.preparationid = p.preparationid + left join giftpreparation gp on gp.preparationid = p.preparationid + left join exchangeoutprep ep on ep.PreparationID = p.PreparationID + where p.preparationid = %s """ + if iprepid is not None: + sql += "and " + iprepid_fld + " != %s " + args.append(iprepid) + + sql += "group by p.preparationid" + + cursor = connection.cursor() + cursor.execute(sql, args) + row = cursor.fetchone() + if row is None: + return prep.countamt + else: + return row[0]; + +@orm_signal_handler('pre_save', 'Loanpreparation') +def loanprep_quantity_must_be_lte_availability(ipreparation): + if ipreparation.preparation is not None: + available = get_availability(ipreparation.preparation, ipreparation.id, "loanpreparationid") or 0 + quantity = ipreparation.quantity or 0 + quantityresolved = ipreparation.quantityresolved or 0 + if available < (quantity - quantityresolved): + raise BusinessRuleException(f"loan preparation quantity exceeds availability ({ipreparation.id}: {quantity - quantityresolved} {available})") + +@orm_signal_handler('pre_save', 'Giftpreparation') +def giftprep_quantity_must_be_lte_availability(ipreparation): + if ipreparation.preparation is not None: + available = get_availability(ipreparation.preparation, ipreparation.id, "giftpreparationid") or 0 + quantity = ipreparation.quantity or 0 + if available < quantity: + raise BusinessRuleException(f"gift preparation quantity exceeds availability ({ipreparation.id}: {quantity} {available})") + +@orm_signal_handler('pre_save', 'Exchangeoutprep') +def exchangeoutprep_quantity_must_be_lte_availability(ipreparation): + if ipreparation.preparation is not None: + available = get_availability(ipreparation.preparation, ipreparation.id, "exchangeoutprepid") or 0 + quantity = ipreparation.quantity or 0 + if available < quantity: + raise BusinessRuleException("exchangeout preparation quantity exceeds availability ({ipreparation.id}: {quantity} {available})") diff --git a/pool/shard007/Python/0071183_test_pool_slots_available_dep.py b/pool/shard007/Python/0071183_test_pool_slots_available_dep.py new file mode 100644 index 0000000000000000000000000000000000000000..2045a7bf2b6ba1a3d291bd2ce0f8858788c57a5d --- /dev/null +++ b/pool/shard007/Python/0071183_test_pool_slots_available_dep.py @@ -0,0 +1,62 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# 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. +# pylint: disable=no-value-for-parameter + +import unittest +from unittest.mock import Mock, patch + +from airflow.models import Pool +from airflow.ti_deps.dependencies_states import EXECUTION_STATES +from airflow.ti_deps.deps.pool_slots_available_dep import PoolSlotsAvailableDep +from airflow.utils.session import create_session +from tests.test_utils import db + + +class TestPoolSlotsAvailableDep(unittest.TestCase): + def setUp(self): + db.clear_db_pools() + with create_session() as session: + test_pool = Pool(pool='test_pool') + session.add(test_pool) + session.commit() + + def tearDown(self): + db.clear_db_pools() + + @patch('airflow.models.Pool.open_slots', return_value=0) + # pylint: disable=unused-argument + def test_pooled_task_reached_concurrency(self, mock_open_slots): + ti = Mock(pool='test_pool', pool_slots=1) + assert not PoolSlotsAvailableDep().is_met(ti=ti) + + @patch('airflow.models.Pool.open_slots', return_value=1) + # pylint: disable=unused-argument + def test_pooled_task_pass(self, mock_open_slots): + ti = Mock(pool='test_pool', pool_slots=1) + assert PoolSlotsAvailableDep().is_met(ti=ti) + + @patch('airflow.models.Pool.open_slots', return_value=0) + # pylint: disable=unused-argument + def test_running_pooled_task_pass(self, mock_open_slots): + for state in EXECUTION_STATES: + ti = Mock(pool='test_pool', state=state, pool_slots=1) + assert PoolSlotsAvailableDep().is_met(ti=ti) + + def test_task_with_nonexistent_pool(self): + ti = Mock(pool='nonexistent_pool', pool_slots=1) + assert not PoolSlotsAvailableDep().is_met(ti=ti) diff --git a/pool/shard007/Python/0071184_extract_paths.py b/pool/shard007/Python/0071184_extract_paths.py new file mode 100644 index 0000000000000000000000000000000000000000..833eec2c1b8a176b487d4e663a737b9502b49eda --- /dev/null +++ b/pool/shard007/Python/0071184_extract_paths.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python +# Copyright 2017, 2018 Google, Inc. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import itertools +import sys + +import spacy +import tensorflow as tf + +tf.flags.DEFINE_string('corpus', '', 'Filename of corpus') +tf.flags.DEFINE_string('labeled_pairs', '', 'Filename of labeled pairs') +tf.flags.DEFINE_string('output', '', 'Filename of output file') +FLAGS = tf.flags.FLAGS + + +def get_path(mod_token, head_token): + """Returns the path between a modifier token and a head token.""" + # Compute the path from the root to each token. + mod_ancestors = list(reversed(list(mod_token.ancestors))) + head_ancestors = list(reversed(list(head_token.ancestors))) + + # If the paths don't start at the same place (odd!) then there is no path at + # all. + if (not mod_ancestors or not head_ancestors + or mod_ancestors[0] != head_ancestors[0]): + return None + + # Eject elements from the common path until we reach the first differing + # ancestor. + ix = 1 + while (ix < len(mod_ancestors) and ix < len(head_ancestors) + and mod_ancestors[ix] == head_ancestors[ix]): + ix += 1 + + # Construct the path. TODO: add "satellites", possibly honor sentence + # ordering between modifier and head rather than just always traversing from + # the modifier to the head? + path = ['/'.join(('', mod_token.pos_, mod_token.dep_, '>'))] + + path += ['/'.join((tok.lemma_, tok.pos_, tok.dep_, '>')) + for tok in reversed(mod_ancestors[ix:])] + + root_token = mod_ancestors[ix - 1] + path += ['/'.join((root_token.lemma_, root_token.pos_, root_token.dep_, '^'))] + + path += ['/'.join((tok.lemma_, tok.pos_, tok.dep_, '<')) + for tok in head_ancestors[ix:]] + + path += ['/'.join(('', head_token.pos_, head_token.dep_, '<'))] + + return '::'.join(path) + + +def main(_): + nlp = spacy.load('en_core_web_sm') + + # Grab the set of labeled pairs for which we wish to collect paths. + with tf.gfile.GFile(FLAGS.labeled_pairs) as fh: + parts = (l.decode('utf-8').split('\t') for l in fh.read().splitlines()) + labeled_pairs = {(mod, head): rel for mod, head, rel in parts} + + # Create a mapping from each head to the modifiers that are used with it. + mods_for_head = { + head: set(hm[1] for hm in head_mods) + for head, head_mods in itertools.groupby( + sorted((head, mod) for (mod, head) in labeled_pairs.iterkeys()), + lambda (head, mod): head)} + + # Collect all the heads that we know about. + heads = set(mods_for_head.keys()) + + # For each sentence that contains a (head, modifier) pair that's in our set, + # emit the dependency path that connects the pair. + out_fh = sys.stdout if not FLAGS.output else tf.gfile.GFile(FLAGS.output, 'w') + in_fh = sys.stdin if not FLAGS.corpus else tf.gfile.GFile(FLAGS.corpus) + + num_paths = 0 + for line, sen in enumerate(in_fh, start=1): + if line % 100 == 0: + print('\rProcessing line %d: %d paths' % (line, num_paths), + end='', file=sys.stderr) + + sen = sen.decode('utf-8').strip() + doc = nlp(sen) + + for head_token in doc: + head_text = head_token.text.lower() + if head_text in heads: + mods = mods_for_head[head_text] + for mod_token in doc: + mod_text = mod_token.text.lower() + if mod_text in mods: + path = get_path(mod_token, head_token) + if path: + label = labeled_pairs[(mod_text, head_text)] + line = '\t'.join((mod_text, head_text, label, path, sen)) + print(line.encode('utf-8'), file=out_fh) + num_paths += 1 + + out_fh.close() + +if __name__ == '__main__': + tf.app.run() diff --git a/pool/shard007/Python/0071186_replicated_map_size_codec.py b/pool/shard007/Python/0071186_replicated_map_size_codec.py new file mode 100644 index 0000000000000000000000000000000000000000..de73651a23857a7e42a2d0139b8bc0e17bb4c419 --- /dev/null +++ b/pool/shard007/Python/0071186_replicated_map_size_codec.py @@ -0,0 +1,22 @@ +from hazelcast.protocol.builtin import FixSizedTypesCodec +from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer, RESPONSE_HEADER_SIZE +from hazelcast.protocol.builtin import StringCodec + +# hex: 0x0D0200 +_REQUEST_MESSAGE_TYPE = 852480 +# hex: 0x0D0201 +_RESPONSE_MESSAGE_TYPE = 852481 + +_REQUEST_INITIAL_FRAME_SIZE = REQUEST_HEADER_SIZE +_RESPONSE_RESPONSE_OFFSET = RESPONSE_HEADER_SIZE + + +def encode_request(name): + buf = create_initial_buffer(_REQUEST_INITIAL_FRAME_SIZE, _REQUEST_MESSAGE_TYPE) + StringCodec.encode(buf, name, True) + return OutboundMessage(buf, True) + + +def decode_response(msg): + initial_frame = msg.next_frame() + return FixSizedTypesCodec.decode_int(initial_frame.buf, _RESPONSE_RESPONSE_OFFSET) diff --git a/pool/shard007/Python/0071189_201_reg_good_ok.py b/pool/shard007/Python/0071189_201_reg_good_ok.py new file mode 100644 index 0000000000000000000000000000000000000000..9b5a9f962deb93d7b815f38166ad3d3dae773166 --- /dev/null +++ b/pool/shard007/Python/0071189_201_reg_good_ok.py @@ -0,0 +1,23 @@ +# $Id$ +import inc_sip as sip +import inc_sdp as sdp + +pjsua = "--null-audio --id=sip:CLIENT --registrar sip:127.0.0.1:$PORT " + \ + "--username user --realm python --password passwd --auto-update-nat=0" + +req1 = sip.RecvfromTransaction("Initial registration", 401, + include=["REGISTER sip"], + exclude=["Authorization"], + resp_hdr=["WWW-Authenticate: Digest realm=\"python\", nonce=\"1234\""], + expect="SIP/2.0 401" + ) + +req2 = sip.RecvfromTransaction("Registration retry with auth", 200, + include=["REGISTER sip", "Authorization:", + "realm=\"python\"", "username=\"user\"", + "nonce=\"1234\"", "response="], + expect="registration success" + ) + +recvfrom_cfg = sip.RecvfromCfg("Successful registration test", + pjsua, [req1, req2]) diff --git a/pool/shard007/Python/0071190_test_metadata.py b/pool/shard007/Python/0071190_test_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..e4b8079d6d6d915967447bed791b3806226c6b54 --- /dev/null +++ b/pool/shard007/Python/0071190_test_metadata.py @@ -0,0 +1,51 @@ +import unittest + +from robot.model.metadata import Metadata +from robot.utils import PY2, PY3 +from robot.utils.asserts import assert_equal, assert_true + + +if PY3: + unicode = str + + +class TestMetadata(unittest.TestCase): + + def test_normalizetion(self): + md = Metadata([('m1', 'xxx'), ('M2', 'xxx'), ('m_3', 'xxx'), + ('M1', 'YYY'), ('M 3', 'YYY')]) + assert_equal(dict(md), {'m1': 'YYY', 'M2': 'xxx', 'm_3': 'YYY'}) + + def test_unicode(self): + assert_equal(unicode(Metadata()), u'{}') + d = {'a': 1, 'B': 'two', u'\xe4': u'nelj\xe4'} + assert_equal(unicode(Metadata(d)), u'{a: 1, B: two, \xe4: nelj\xe4}') + + def test_non_string_items(self): + md = Metadata([('number', 42), ('boolean', True), (1, 'one')]) + assert_equal(md['number'], '42') + assert_equal(md['boolean'], 'True') + assert_equal(md['1'], 'one') + md['number'] = 1.0 + md['boolean'] = False + md['new'] = [] + md[True] = '' + assert_equal(md['number'], '1.0') + assert_equal(md['boolean'], 'False') + assert_equal(md['new'], '[]') + assert_equal(md['True'], '') + md.setdefault('number', 99) + md.setdefault('setdefault', 99) + assert_equal(md['number'], '1.0') + assert_equal(md['setdefault'], '99') + + if PY2: + def test_str(self): + assert_equal(str(Metadata()), '{}') + d = {'a': 1, 'B': 'two', u'\xe4': u'nelj\xe4'} + assert_equal(str(Metadata(d)), + u'{a: 1, B: two, \xe4: nelj\xe4}'.encode('UTF-8')) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard007/Python/0071191_meta_data.py b/pool/shard007/Python/0071191_meta_data.py new file mode 100644 index 0000000000000000000000000000000000000000..1bc9e758f9a5e038ade2f03cb8a17452ba008011 --- /dev/null +++ b/pool/shard007/Python/0071191_meta_data.py @@ -0,0 +1,152 @@ +import os + +from django.db import models +from odk_logger.models import XForm + +from hashlib import md5 +from django.conf import settings + + +def upload_to(instance, filename): + if instance.data_type == 'media': + return os.path.join(settings.MEDIA_ROOT, + instance.xform.user.username, + 'formid-media', + filename + ) + return os.path.join(settings.MEDIA_ROOT, + instance.xform.user.username, + 'docs', + filename + ) + + +def unique_type_for_form(xform, data_type, data_value=None, data_file=None): + result = type_for_form(xform, data_type) + if not len(result): + result = MetaData(data_type=data_type, xform=xform) + result.save() + else: + result = result[0] + if data_value: + result.data_value = data_value + result.save() + if data_file: + if result.data_value is None or result.data_value == '': + result.data_value = data_file.name + result.data_file = data_file + result.data_file_type = data_file.content_type + result.save() + return result + + +def type_for_form(xform, data_type): + return MetaData.objects.filter(xform=xform, data_type=data_type) + + +class MetaData(models.Model): + + CROWDFORM_USERS = 'crowdform_users' + + xform = models.ForeignKey(XForm) + data_type = models.CharField(max_length=255) + data_value = models.CharField(max_length=255) + data_file = models.FileField(upload_to=upload_to, null=True) + data_file_type = models.CharField(max_length=255, null=True) + + @property + def hash(self): + if self.data_file.storage.exists(self.data_file.name): + return u'%s' % md5(self.data_file.read()).hexdigest() + return u'' + + @staticmethod + def public_link(xform, data_value=None): + data_type = 'public_link' + if data_value is False: + data_value = 'False' + metadata = unique_type_for_form(xform, data_type, data_value) + # make text field a boolean + if metadata.data_value == 'True': + return True + else: + return False + + @staticmethod + def form_license(xform, data_value=None): + data_type = 'form_license' + return unique_type_for_form(xform, data_type, data_value) + + @staticmethod + def data_license(xform, data_value=None): + data_type = 'data_license' + return unique_type_for_form(xform, data_type, data_value) + + @staticmethod + def source(xform, data_value=None, data_file=None): + data_type = 'source' + return unique_type_for_form(xform, data_type, data_value, data_file) + + @staticmethod + def supporting_docs(xform, data_file=None): + data_type = 'supporting_doc' + if data_file: + doc = MetaData(data_type=data_type, xform=xform, + data_value=data_file.name, + data_file=data_file, + data_file_type=data_file.content_type) + doc.save() + + return type_for_form(xform, data_type) + + @staticmethod + def crowdform_users(xform, data_value=None): + data_type = MetaData.CROWDFORM_USERS + if data_value: + doc, created = MetaData.objects.get_or_create( + data_type=data_type, + xform=xform, + data_value=data_value) + doc.save() + return type_for_form(xform, data_type) + + @staticmethod + def media_upload(xform, data_file=None): + data_type = 'media' + if data_file: + if data_file.content_type in ['image/jpeg', 'image/png', + 'audio/mpeg', 'video/3gpp', + 'audio/wav', + 'audio/x-m4a', 'audio/mp3', + 'application/csv', 'application/zip']: + media = MetaData(data_type=data_type, xform=xform, + data_value=data_file.name, + data_file=data_file, + data_file_type=data_file.content_type) + media.save() + return type_for_form(xform, data_type) + + @staticmethod + def mapbox_layer_upload(xform, data=None): + data_type = 'mapbox_layer' + if data and not MetaData.objects.filter(xform=xform, + data_type='mapbox_layer'): + s = '' + for key in data: + s = s + data[key] + '||' + mapbox_layer = MetaData(data_type=data_type, xform=xform, + data_value=s) + mapbox_layer.save() + if type_for_form(xform, data_type): + values = type_for_form(xform, data_type)[0].data_value.split('||') + data_values = {} + data_values['map_name'] = values[0] + data_values['link'] = values[1] + data_values['attribution'] = values[2] + data_values['id'] = type_for_form(xform, data_type)[0].id + return data_values + else: + return None + + class Meta: + app_label = 'main' diff --git a/pool/shard007/Python/0071192_tweet.py b/pool/shard007/Python/0071192_tweet.py new file mode 100644 index 0000000000000000000000000000000000000000..cb3fd5861b288d4e6312515ea982c632d59182bf --- /dev/null +++ b/pool/shard007/Python/0071192_tweet.py @@ -0,0 +1,68 @@ +import time +import os +import tweepy +import sqlite3 +import datetime +from config import * + +auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) +auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET) + +api = tweepy.API(auth) + +def set_interval(func, sec): + """ + Execute func every sec seconds. + """ + while True: + func() + time.sleep(sec) + +def initialize_nouns_db(): + """ + Dump the contents of nouns.txt into a SQLite database + """ + db = sqlite3.connect("nouns.db") + cursor = db.cursor() + cursor.execute('''CREATE TABLE nouns (noun text, tweeted integer, tweet_datetime text)''') + with open("nouns.txt") as nouns: + for noun in nouns: + noun = noun.strip() + query_noun = [noun] + cursor.execute('''INSERT INTO nouns VALUES (?, 0, 'none')''', query_noun) + print("%s has been inserted into nouns.db" % noun) + db.commit() + db.close() + +def find_noun(): + """ + Find a noun from the list, then return and delete it. + """ + db = sqlite3.connect("nouns.db") + cursor = db.cursor() + cursor.execute('''SELECT noun FROM nouns WHERE tweeted = 0 ORDER BY RANDOM() LIMIT 1;''') + noun = cursor.fetchone()[0] + print(noun) + cursor.execute('''UPDATE nouns SET tweeted=1, tweet_datetime=? WHERE noun==?;''', + (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), noun)) + db.commit() + db.close() + return noun + +def send_tweet(noun): + """ + Submits a tweet when given a noun. + """ + tweet = "Data-driven %s" % noun + api.update_status(status = tweet) + print("Successfully posted tweet: ", tweet) + +def find_noun_and_tweet(): + noun = find_noun() + send_tweet(noun) + +if __name__ == "__main__": + if not os.path.isfile("nouns.db"): + initialize_nouns_db() + + set_interval(find_noun_and_tweet, 21600) diff --git a/pool/shard007/Python/0071204_deck.py b/pool/shard007/Python/0071204_deck.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd7351468e11f42d4f96133857fcb1e3aba84ff --- /dev/null +++ b/pool/shard007/Python/0071204_deck.py @@ -0,0 +1,77 @@ +"""baraja.deck + +the deck module contains classes and functions for representing card decks. + +""" +from copy import copy +import random + +from baraja import card + + +class Deck(object): + """a deck of cards + + This object is a stateful representation of a deck of cards. + + In all card sequences returned from a Deck, item [-1] is considered to be + the top of that stack. + + """ + def __init__(self, sourcelist): + """create a deck by passing in a list of card objects + + New decks are shuffled once. + + """ + self._master_deck = tuple(sourcelist) + self._drawn = [] + self._undrawn = list(sourcelist) + self.shuffle() + + def draw(self): + """draw a card + + Pop a card from undrawn and push it to drawn, returning a copy of + the card or None if the deck is empty. + + """ + try: + c = self._undrawn.pop() + self._drawn.append(c) + return copy(c) + except IndexError: + return None + + @property + def drawn(self): + """return a copy of the list of drawn cards""" + return tuple(self._drawn) + + def shuffle(self): + """shuffle the undrawn and drawn cards together""" + self._undrawn.extend(self._drawn) + del self._drawn[:] + random.shuffle(self._undrawn) + + @property + def undrawn(self): + """return a copy of the undrawn card list""" + return tuple(self._undrawn) + + +class PlayingCardDeck(Deck): + """a french style deck + + This deck contains 52 cards in four suits with value 1 through 13 in each. + With 1, 11, 12, and 13 representing Ace, Jack, Queen, and King + repsectively. + + """ + def __init__(self): + """create a deck of french style playing cards""" + cardlist = [] + for suit in card.PlayingCard.SUITS: + for value in range(1, 14): + cardlist.append(card.PlayingCard(value, suit)) + super(PlayingCardDeck, self).__init__(sourcelist=cardlist) diff --git a/pool/shard007/Python/0071214_plncli.py b/pool/shard007/Python/0071214_plncli.py new file mode 100644 index 0000000000000000000000000000000000000000..cef2e99ee71eb35380025bfc4198e53335e29fc4 --- /dev/null +++ b/pool/shard007/Python/0071214_plncli.py @@ -0,0 +1,34 @@ +import twisted.web.client +import json +import urllib + +# getPage Method +cookies = {} + +def parseResult(data): + data = json.loads(data) + return data + +def getPbxPage(page, postdata): + postdata = urllib.urlencode(postdata) + d = twisted.web.client.getPage('https://pbx.lorea.org/' + page, + cookies = cookies, + method = 'POST', + headers = {'Content-Type': 'application/x-www-form-urlencoded', 'Host': 'pbx.lorea.org'}, + postdata = postdata, + followRedirect = 0) + d.addCallback(parseResult) + return d + +def getCredit(user, password): + d = getPbxPage('login', {'login': user, 'password': password, 'action': 'login_agent'}) + return d + +def transferCredit(user_ext, amount): + d = getPbxPage('credit/transfer', {'user': user_ext, 'credit': amount}) + return d + +def createCredit(user_ext, amount): + d = getPbxPage('credit/add', {'user': user_ext, 'credit': amount}) + return d + diff --git a/pool/shard007/Python/0071215_centraltabs.py b/pool/shard007/Python/0071215_centraltabs.py new file mode 100644 index 0000000000000000000000000000000000000000..7d04d6b5d401af66e7116ccc13a35db11e6d0b4f --- /dev/null +++ b/pool/shard007/Python/0071215_centraltabs.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# Copyright 2007 Troy Melhase +# Distributed under the terms of the GNU General Public License v2 +# Author: Troy Melhase + +from functools import partial +from sys import platform + +from PyQt4.QtCore import Qt +from PyQt4.QtGui import QIcon, QStandardItem + +from profit.lib import importItem, logging +from profit.lib import BasicHandler, Signals, DataRoles, instance +from profit.lib.gui import makeUrlItem, symbolIcon +from profit.lib.widgets.localtabwidget import LocalTabWidget + + +class CentralTabs(LocalTabWidget, BasicHandler): + """ CentralTabs -> tab widget with extra special powers + + """ + def __init__(self, parent=None): + """ Initializer. + + @param parent ancestor of this widget + """ + LocalTabWidget.__init__(self, parent) + self.createHandlers = [ + self.createBrowserTab, + self.createTickerPlotTab, + self.createTickerPlotFromView, + self.createDisplayTab + ] + app, connect, createTab = instance(), self.connect, self.createTab + connect(app, Signals.itemActivated, createTab) + connect(app, Signals.openUrl, createTab) + connect(app, Signals.tickerClicked, createTab) + self.requestSession() + + def createTab(self, value): + """ Create or display a tab from a value + + @param value string or model item + @return None + """ + for handler in self.createHandlers: + try: + if handler(value): + break + except (Exception, ), exc: + msg = 'Exception (debug): %r:%s (h:%s)' + logging.debug(msg, exc, exc, handler, ) + + def createBrowserTab(self, item): + """ Creates a new web browser tab. + + @param value string or model item + @return True if display widget created, otherwise None + """ + from profit.lib.widgets.webbrowser import WebBrowserDisplay + if isinstance(item, (basestring, )): + item = makeUrlItem(item) + if item.data(DataRoles.url).isValid(): + url = item.data(DataRoles.url).toString() + title = item.data(DataRoles.urlTitle).toString() + widget = WebBrowserDisplay(self) + widget.basicConfig(url) + index = self.addTab(widget, title) + icon = item.icon() + if icon.isNull(): + icon = QIcon(":/images/icons/www.png") + self.setTextIconCurrentTab(index, title, icon) + loadHandler = partial(self.resetBrowserTab, browser=widget) + self.connect(widget, Signals.loadFinished, loadHandler) + return True + + def createTickerPlotFromView(self, data): + """ + + """ + from profit.workbench.tickerplotdisplay import TickerPlotDisplay + try: + tid, sym = data[0:2] + except (TypeError, ValueError, ): + return + sym = sym or self.symbolName(tid) + icon = symbolIcon(sym) if sym else QIcon(':/images/icons/kchart.png') + sym = sym or '%s' % tid + widget = TickerPlotDisplay(self) + session = self.session + widget.setSessionPlot(session, session.maps.ticker, tid) + index = self.addTab(widget, sym) + self.setTextIconCurrentTab(index, sym, icon) + return True + + def symbolName(self, tickerId): + """ Returns the symbol name given a ticker id. + + This should reference self.session.models.contracts instead. + """ + symbols = self.session.strategy.symbols() + try: + return dict([(b, a) for a, b in symbols.items()])[tickerId] or '' + except (KeyError, ): + return '' + + def createTickerPlotTab(self, item): + """ Creates or displays a ticker plot tab. + + @param value string or model item + @return True if display widget created, otherwise None + """ + from profit.workbench.tickerplotdisplay import TickerPlotDisplay + tickerId, tickerIdValid = item.data(DataRoles.tickerId).toInt() + symbol = str(item.data(DataRoles.tickerSymbol).toString()) + if tickerIdValid and self.setCurrentLabel(symbol): + return True + if tickerIdValid: + widget = TickerPlotDisplay(self) + session = self.session + widget.setSessionPlot(session, session.maps.ticker, tickerId) + index = self.addTab(widget, symbol) + icon = QIcon(item.data(Qt.DecorationRole)) + self.setTextIconCurrentTab(index, symbol, icon) + return True + + def createDisplayTab(self, item): + """ Creates or displays a name-based display. + + @param value string or model item + @return True if display widget created, otherwise None + """ + text = str(item.data().toString()) + if self.setCurrentLabel(text): + return True + name = str(item.data(DataRoles.displayImportName).toString()) + if name: + cls = importItem(name) + widget = cls(self) + index = self.addTab(widget, text) + icon = QIcon(item.data(Qt.DecorationRole)) + self.setTextIconCurrentTab(index, text, icon) + return True + + def resetBrowserTab(self, okay, browser=None): + """ Reconfigures a tab based on a web browser widget state. + + @param okay True if browser page load is finished + @keyparam browser=None WebBrowserDispay object + @return None + """ + if not okay or not browser: + return + index = self.indexOf(browser) + title = tooltip = str(browser.title()) + if len(title) > 13: + title = title[0:13] + '...' + self.setTabText(index, title) + self.setTabToolTip(index, tooltip) diff --git a/pool/shard007/Python/0071216_base.py b/pool/shard007/Python/0071216_base.py new file mode 100644 index 0000000000000000000000000000000000000000..5e8e7f357bd906c51181b312afbd1104f24fcc9d --- /dev/null +++ b/pool/shard007/Python/0071216_base.py @@ -0,0 +1,255 @@ +# Copyright 2019 Virgil Dupras +# +# This software is licensed under the "GPLv3" License as described in the "LICENSE" file, +# which should be included with this package. The terms are also available at +# http://www.gnu.org/licenses/gpl-3.0.html + +import datetime +import re + +from core.util import dedupe, nonone +from core.trans import tr + +from ..const import AccountType +from ..exception import FileFormatError +from ..model._ccore import ( + AccountList, TransactionList, UnsupportedCurrencyError, amount_parse, Transaction) +from ..model.currency import Currencies +from ..model.oven import Oven + +# date formats to use for format guessing +# there is not one test for each single format +# The order of the fields depending on the separator is different because we try to minimize the +# possibility of errors. Most american users use the slash separator with month as a first field +# and most european users have dot or hyphen seps with the first field being the day. + +BASE_DATE_FORMATS = [ + '%m/%d/%y', '%m/%d/%Y', '%d/%m/%Y', '%d/%m/%y', '%Y/%m/%d', '%d/%b/%Y', '%d/%b/%y' +] +EXTRA_DATE_SEPS = ['.', '-', ' '] +DATE_FORMATS = BASE_DATE_FORMATS[:] +# Re-add all date formats with their separator replaced +for sep in EXTRA_DATE_SEPS: + for base_format in BASE_DATE_FORMATS: + DATE_FORMATS.append(base_format.replace('/', sep)) +# Finally, add special formats +DATE_FORMATS += ['%m/%d\'%y', '%Y%m%d'] + +POSSIBLE_PATTERNS = [ + r'[\d/.\- ]{6,10}', + r'\d{1,2}[/.\- ]\w{3}[/.\- ]\d{2,4}', + r"\d{1,2}/\d{1,2}'\d{2,4}", +] +re_possibly_a_date = re.compile('|'.join(POSSIBLE_PATTERNS)) + +def parse_amount(string, currency, **kwargs): + try: + return amount_parse( + string, currency, with_expression=False, **kwargs) + except UnsupportedCurrencyError: + msg = tr( + "Unsupported currency: {}. Aborting load. Did you disable a currency plugin?" + ).format(currency) + raise FileFormatError(msg) + +def get_account_type(type): + if type in AccountType.All: + return type + else: + return AccountType.Asset + +def get_account(accounts, accountname, auto_create_type): + if accountname: + account = accounts.find(accountname) + if account is None: + auto_create_type = get_account_type(auto_create_type) + account = accounts.create( + accountname, accounts.default_currency, auto_create_type) + else: + account = None + return account + +def process_split(accounts, accountname, str_amount, currency=None, strict_currency=False): + # this amount is just to determine the auto_create_type + if currency: + str_amount += currency + amount = parse_amount(str_amount, accounts.default_currency, strict_currency=strict_currency) + auto_create_type = AccountType.Income if amount >= 0 else AccountType.Expense + account = get_account(accounts, accountname, auto_create_type) + currency = account.currency if account is not None else accounts.default_currency + amount = parse_amount(str_amount, currency, strict_currency=strict_currency) + return account, amount + +def clean_date(str_date): + # return str_date without garbage around (such as timestamps) or None if impossible + match = re_possibly_a_date.search(str_date) + return match.group() if match is not None else None + +def guess_date_format(str_dates, formats_to_try): + if not str_dates: + return None + for format in dedupe(formats_to_try): + for str_date in str_dates: + try: + datetime.datetime.strptime(str_date, format) + except ValueError: + break + else: + return format + return None + +def parse_date_str(date_str, date_format): + """Parses date_str using date_format and perform heuristic fixes if needed. + """ + result = datetime.datetime.strptime(date_str, date_format).date() + if result.year < 1900: + # we have a typo in the house. Just use 2000 + last-two-digits + year = (result.year % 100) + 2000 + result = result.replace(year=year) + return result + +class Loader: + """Base interface for loading files containing financial information to load into moneyGuru. + + To use it, just call load() and then fetch the accounts & transactions. This information is in + the form of lists of dicts. The transactions are sorted in order of date. + """ + FILE_OPEN_MODE = 'rt' + FILE_ENCODING = 'utf-8' + # Native date format is a format native to the file type. It doesn't necessarily means that it's + # the only possible date format in it, but it's the one that will be tried first when guessing + # (before the default date format). If guessing never occurs, it will be the parsing date format. + # This format is a sys format (%-based) + NATIVE_DATE_FORMAT = None + # Some extra date formats to try before standard date guessing order + EXTRA_DATE_FORMATS = None + + def __init__(self, default_currency, default_date_format=None): + self.default_currency = default_currency + self.default_date_format = default_date_format + self.accounts = AccountList(default_currency) + self.transactions = TransactionList() + self.oven = Oven(self.accounts, self.transactions, None) + # The Loader subclass should set parsing_date_format to the format used (system-type) when + # parsing dates. This format is used in the ImportWindow. It is also used in + # self.parse_date_str as a default value + self.parsing_date_format = self.NATIVE_DATE_FORMAT + + # --- Private + def _fetch_currencies(self): + # Fetch rates if needed + start_date = min((t.date for t in self.transactions), default=datetime.date.max) + currencies = {a.currency for a in self.accounts} + for txn in self.transactions: + for split in txn.splits: + if split.amount: + currencies.add(split.amount.currency_code) + Currencies.get_rates_db().ensure_rates(start_date, list(currencies)) + + # --- Virtual + def _parse(self, infile): + """Parse infile and raise FileFormatError if infile is not the right format. Don't bother + with an exception message, app.MoneyGuru will re-raise it with a message if needed. + """ + raise NotImplementedError() + + def _load(self): + """Use the parsed info to fill the appropriate account/txn info with the start_* and flush_* + methods. + """ + raise NotImplementedError() + + def _post_load(self): + """Perform post load processing, such as duplicate removal + """ + pass + + # --- Protected + def guess_date_format(self, str_dates): + totry = DATE_FORMATS + extra = [] + if self.NATIVE_DATE_FORMAT: + extra.append(self.NATIVE_DATE_FORMAT) + if self.EXTRA_DATE_FORMATS: + extra += self.EXTRA_DATE_FORMATS + if self.default_date_format: + extra.append(self.default_date_format) + return guess_date_format(str_dates, extra + totry) + + def get_currency(self, code): + try: + if code and Currencies.has(code): + return code + except ValueError: + pass + return self.default_currency + + # --- Public + def parse(self, filename): + """Parses 'filename' and raises FileFormatError if appropriate.""" + try: + if 't' in self.FILE_OPEN_MODE: + kw = {'encoding': self.FILE_ENCODING, 'errors': 'ignore'} + else: + kw = {} + with open(filename, self.FILE_OPEN_MODE, **kw) as infile: + self._parse(infile) + except IOError: + raise FileFormatError() + + def load(self): + """Loads the parsed info into self.accounts and self.transactions. + + You must have called parse() before calling this. + """ + self._load() + self._post_load() + self.oven.cook(datetime.date.min, until_date=None) + self._fetch_currencies() + +class TransactionInfo: + def __init__(self): + self.date = None + self.description = None + self.payee = None + self.checkno = None + self.account = None + self.transfer = None + self.amount = None + self.currency = None + self.reference = None # will be applied to all splits + self.splits = [] + + def is_valid(self): + return bool(self.date and ((self.account and self.amount) or self.splits)) + + def load(self, accounts): + description = self.description + payee = self.payee + checkno = self.checkno + date = self.date + account = amount = None + if self.account: + account, amount = process_split(accounts, self.account, self.amount, self.currency) + transaction = Transaction(date, description, payee, checkno, account, amount) + for str_account, str_amount, memo in self.splits: + account, amount = process_split( + accounts, str_account, str_amount, None) + # splits are only used for QIF and in QIF, amounts are reversed + amount *= -1 + memo = nonone(memo, '') + split = transaction.new_split() + split.account = account + split.amount = amount + split.memo = memo + while len(transaction.splits) < 2: + transaction.new_split() + transaction.balance() + if self.reference is not None: + for split in transaction.splits: + if split.reference is None: + split.reference = self.reference + return transaction + + def add_split(self, account, amount, memo): + self.splits.append((account, amount, memo)) diff --git a/pool/shard007/Python/0071222_zsh_completions.py b/pool/shard007/Python/0071222_zsh_completions.py new file mode 100644 index 0000000000000000000000000000000000000000..fd959db85e99a625bdc0e56979997c00c7eaaa54 --- /dev/null +++ b/pool/shard007/Python/0071222_zsh_completions.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2016 Christoph Reiter +# +# Permission is hereby granted, free of charge, to any person obtaining +# a copy of this software and associated documentation files (the +# "Software"), to deal in the Software without restriction, including +# without limitation the rights to use, copy, modify, merge, publish, +# distribute, sublicense, and/or sell copies of the Software, and to +# permit persons to whom the Software is furnished to do so, subject to +# the following conditions: +# +# The above copyright notice and this permission notice shall be included +# in all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +import os + +from .util import Command + + +class install_zsh_completions(Command): + + user_options = [] + + def initialize_options(self): + self.install_dir = None + self.zsh_completions = [] + self.outfiles = [] + + def finalize_options(self): + self.set_undefined_options('install', + ('install_data', 'install_dir')) + + self.zsh_completions = self.distribution.zsh_completions + + def get_outputs(self): + return self.outfiles + + def run(self): + basepath = os.path.join( + self.install_dir, 'share', 'zsh', 'vendor-completions') + out = self.mkpath(basepath) + self.outfiles.extend(out or []) + for src, dest in self.zsh_completions: + (out, _) = self.copy_file(src, os.path.join(basepath, dest)) + self.outfiles.append(out) diff --git a/pool/shard007/Python/0071224_server.py b/pool/shard007/Python/0071224_server.py new file mode 100644 index 0000000000000000000000000000000000000000..14e52b7951c86d51ccf119072a0c1ba88e03749f --- /dev/null +++ b/pool/shard007/Python/0071224_server.py @@ -0,0 +1,55 @@ +__author__ = 'masudurrahman' + +import sys +from twisted.protocols import ftp +from twisted.protocols.ftp import FTPFactory, FTPAnonymousShell, FTPRealm, FTP, FTPShell, IFTPShell +from twisted.cred.portal import Portal +from twisted.cred import checkers +from twisted.cred.checkers import AllowAnonymousAccess, FilePasswordDB +from twisted.internet import reactor +from twisted.python import log +from twisted.internet.defer import succeed, failure + +def opsCall(obj): + print "Processing", obj.fObj.name + return "Completed" + +## EITHER WE USE THE PRE-MADE FTP SHELL, WHICH COULD WORK, OR: +## MAKE AN FTP SHELL TO HANDLE THE REQUESTS FOR FILES +## METHODS NEEDED: CREATE, RENAME, UPDATE, DELETE for files +## METHODS NEEDED: access, list, changeDir, makeDir + +class MyFTPRealm(FTPRealm): + + def __init__( self, anonymousRoot, userHome="/home", callback=None ): + FTPRealm.__init__( self, anonymousRoot, userHome=userHome ) + self.callback = callback + + def requestAvatar(self, avatarId, mind, *interfaces): + print "TRYING TO LOG IN" + for iface in interfaces: + if iface is IFTPShell: + + if avatarId is checkers.ANONYMOUS: + avatar = FTPShell(self.anonymousRoot) + + else: + avatar = FTPShell(self.getHomeDirectory(avatarId)) + + return (IFTPShell, avatar, + getattr(avatar, 'logout', lambda: None)) + + raise NotImplementedError("Only IFTPShell interface is supported by this realm") + + +if __name__ == "__main__": + + p = Portal(MyFTPRealm('./'),[AllowAnonymousAccess(), FilePasswordDB("pass1.dat")]) + #p = Portal(MyFTPRealm('/no_anon_access/', userHome="/tmp/", callback=opsCall),[FilePasswordDB("pass.dat"), ]) + f = ftp.FTPFactory(p) + f.welcomeMessage = "CS3240 Team 4 Project" + + log.startLogging(sys.stdout) + + reactor.listenTCP(21, f) + reactor.run() diff --git a/pool/shard007/Python/0071225_StartWizard.py b/pool/shard007/Python/0071225_StartWizard.py new file mode 100644 index 0000000000000000000000000000000000000000..aba896a5b22936bfa914f5c3819fa8f2bd5cd9ec --- /dev/null +++ b/pool/shard007/Python/0071225_StartWizard.py @@ -0,0 +1,36 @@ +from Wizard import wizardManager +from Screens.WizardLanguage import WizardLanguage +from Screens.Rc import Rc +from Tools.HardwareInfo import HardwareInfo + +from boxbranding import getBoxType + +from Components.Pixmap import Pixmap, MovingPixmap, MultiPixmap +from Components.config import config, ConfigBoolean, configfile, ConfigSubsection + +from LanguageSelection import LanguageWizard + +config.misc.firstrun = ConfigBoolean(default = True) +config.misc.languageselected = ConfigBoolean(default = True) + +class StartWizard(WizardLanguage, Rc): + def __init__(self, session, silent = True, showSteps = False, neededTag = None): + self.xmlfile = ["startwizard.xml"] + WizardLanguage.__init__(self, session, showSteps = False) + Rc.__init__(self) + self["wizard"] = Pixmap() + + def markDone(self): + # setup remote control, all stb have same settings except dm8000 which uses a different settings + if HardwareInfo().get_device_name() == 'dm8000': + config.misc.rcused.value = 0 + else: + config.misc.rcused.value = 1 + config.misc.rcused.save() + + config.misc.firstrun.value = 0 + config.misc.firstrun.save() + configfile.save() + +wizardManager.registerWizard(LanguageWizard, config.misc.languageselected.value, priority = 5) +wizardManager.registerWizard(StartWizard, config.misc.firstrun.value, priority = 20) diff --git a/pool/shard007/Python/0071226_weshare.py b/pool/shard007/Python/0071226_weshare.py new file mode 100644 index 0000000000000000000000000000000000000000..306bce3dbd259bc55a16367c5f4fd92a54bd7bb9 --- /dev/null +++ b/pool/shard007/Python/0071226_weshare.py @@ -0,0 +1,46 @@ +""" +grifthost urlresolver plugin +Copyright (C) 2015 tknorris + +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 . +""" + +import re +from lib import helpers +from urlresolver9 import common +from urlresolver9.resolver import UrlResolver, ResolverError + +class WeShareResolver(UrlResolver): + name = "weshare.me" + domains = ["weshare.me"] + pattern = '(?://|\.)(weshare\.me)/(?:services/mediaplayer/site/_embed(?:\.max)?\.php\?u=)?([A-Za-z0-9]+)' + + def __init__(self): + self.net = common.Net() + + def get_media_url(self, host, media_id): + web_url = self.get_url(host, media_id) + headers = {'User-Agent': common.FF_USER_AGENT} + html = self.net.http_GET(web_url, headers=headers).content + sources = helpers.scrape_sources(html) + if not sources: + match = re.search('''href="([^"]+)[^>]+>\(download\)''', html, re.DOTALL) + if match: + sources = [('Download', match.group(1))] + + headers['Referer'] = web_url + return helpers.pick_source(sources) + helpers.append_headers(headers) + + def get_url(self, host, media_id): + return 'https://weshare.me/services/mediaplayer/site/_embed.max.php?u=%s' % (media_id) diff --git a/pool/shard007/Python/0071228_06_spacy_linguistic_features.py b/pool/shard007/Python/0071228_06_spacy_linguistic_features.py new file mode 100644 index 0000000000000000000000000000000000000000..d570640e041c9a2360625de89d8cc34247e52fc1 --- /dev/null +++ b/pool/shard007/Python/0071228_06_spacy_linguistic_features.py @@ -0,0 +1,29 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- +# +""" +cd /Users/brunoflaven/Documents/02_copy/_000_IA_bruno_light/_my_article_python-explorations/git_repo_python_explorations_nlp/article_4_miscellaneous_examples_nlp_spacy + + +python 06_spacy_linguistic_features.py + +""" + +import spacy + +nlp = spacy.load("en_core_web_sm") +doc = nlp("San Francisco considers banning sidewalk delivery robots") + +# document level +ents = [(e.text, e.start_char, e.end_char, e.label_) for e in doc.ents] +print(ents) + +# token level +ent_san = [doc[0].text, doc[0].ent_iob_, doc[0].ent_type_] +ent_francisco = [doc[1].text, doc[1].ent_iob_, doc[1].ent_type_] +print(ent_san) # ['San', 'B', 'GPE'] +print(ent_francisco) # ['Francisco', 'I', 'GPE'] + + + + diff --git a/pool/shard007/Python/0071234_tests.py b/pool/shard007/Python/0071234_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..b5c10f0041c606241723d171262d13647bc8f9b3 --- /dev/null +++ b/pool/shard007/Python/0071234_tests.py @@ -0,0 +1,41 @@ +import unittest + +import json + +import sys +sys.path.append("..") +from distrowatch import get_versions + +class TestVersions(unittest.TestCase): + + def setUp(self): + pass + + def test_get_libs(self): + libs = get_versions.get_libs() + test_libs = {"pinned_req": "1.0\n"} + self.assertEqual(libs, test_libs) + + def test_check_lib(self): + current = "1.1.0" + bug = "1.1.1" + minor = "1.2.1" + major = "2.1.1" + none = "1.1.0" + none2 = "1.1" + self.assertEqual("none", get_versions.check_lib(current, none)) + self.assertEqual("none", get_versions.check_lib(current, none2)) + self.assertEqual("bug", get_versions.check_lib(current, bug)) + self.assertEqual("minor", get_versions.check_lib(current, minor)) + self.assertEqual("major", get_versions.check_lib(current, major)) + + def test_create_json(self): + distros = {"minor": ["somelib"], + "major": ["otherlib", "finallib"]} + get_versions.create_json(distros) + f = open("distros.json") + saved = json.load(f) + self.assertEqual(saved, distros) + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/pool/shard007/Python/0071236_test_google_config.py b/pool/shard007/Python/0071236_test_google_config.py new file mode 100644 index 0000000000000000000000000000000000000000..78207605830106793ccad44157978aa7ccba5f74 --- /dev/null +++ b/pool/shard007/Python/0071236_test_google_config.py @@ -0,0 +1,193 @@ +"""Test the Cloud Google Config.""" +import pytest + +from homeassistant.components.cloud import GACTIONS_SCHEMA +from homeassistant.components.cloud.google_config import CloudGoogleConfig +from homeassistant.components.google_assistant import helpers as ga_helpers +from homeassistant.const import EVENT_HOMEASSISTANT_STARTED, HTTP_NOT_FOUND +from homeassistant.core import CoreState, State +from homeassistant.helpers.entity_registry import EVENT_ENTITY_REGISTRY_UPDATED +from homeassistant.util.dt import utcnow + +from tests.async_mock import AsyncMock, Mock, patch +from tests.common import async_fire_time_changed + + +@pytest.fixture +def mock_conf(hass, cloud_prefs): + """Mock Google conf.""" + return CloudGoogleConfig( + hass, + GACTIONS_SCHEMA({}), + "mock-user-id", + cloud_prefs, + Mock(claims={"cognito:username": "abcdefghjkl"}), + ) + + +async def test_google_update_report_state(mock_conf, hass, cloud_prefs): + """Test Google config responds to updating preference.""" + await mock_conf.async_initialize() + await mock_conf.async_connect_agent_user("mock-user-id") + + with patch.object(mock_conf, "async_sync_entities") as mock_sync, patch( + "homeassistant.components.google_assistant.report_state.async_enable_report_state" + ) as mock_report_state: + await cloud_prefs.async_update(google_report_state=True) + await hass.async_block_till_done() + + assert len(mock_sync.mock_calls) == 1 + assert len(mock_report_state.mock_calls) == 1 + + +async def test_sync_entities(aioclient_mock, hass, cloud_prefs): + """Test sync devices.""" + config = CloudGoogleConfig( + hass, + GACTIONS_SCHEMA({}), + "mock-user-id", + cloud_prefs, + Mock(auth=Mock(async_check_token=AsyncMock())), + ) + + with patch( + "hass_nabucasa.cloud_api.async_google_actions_request_sync", + return_value=Mock(status=HTTP_NOT_FOUND), + ) as mock_request_sync: + assert await config.async_sync_entities("user") == HTTP_NOT_FOUND + assert len(mock_request_sync.mock_calls) == 1 + + +async def test_google_update_expose_trigger_sync( + hass, legacy_patchable_time, cloud_prefs +): + """Test Google config responds to updating exposed entities.""" + config = CloudGoogleConfig( + hass, + GACTIONS_SCHEMA({}), + "mock-user-id", + cloud_prefs, + Mock(claims={"cognito:username": "abcdefghjkl"}), + ) + await config.async_initialize() + await config.async_connect_agent_user("mock-user-id") + + with patch.object(config, "async_sync_entities") as mock_sync, patch.object( + ga_helpers, "SYNC_DELAY", 0 + ): + await cloud_prefs.async_update_google_entity_config( + entity_id="light.kitchen", should_expose=True + ) + await hass.async_block_till_done() + async_fire_time_changed(hass, utcnow()) + await hass.async_block_till_done() + + assert len(mock_sync.mock_calls) == 1 + + with patch.object(config, "async_sync_entities") as mock_sync, patch.object( + ga_helpers, "SYNC_DELAY", 0 + ): + await cloud_prefs.async_update_google_entity_config( + entity_id="light.kitchen", should_expose=False + ) + await cloud_prefs.async_update_google_entity_config( + entity_id="binary_sensor.door", should_expose=True + ) + await cloud_prefs.async_update_google_entity_config( + entity_id="sensor.temp", should_expose=True + ) + await hass.async_block_till_done() + async_fire_time_changed(hass, utcnow()) + await hass.async_block_till_done() + + assert len(mock_sync.mock_calls) == 1 + + +async def test_google_entity_registry_sync(hass, mock_cloud_login, cloud_prefs): + """Test Google config responds to entity registry.""" + config = CloudGoogleConfig( + hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data["cloud"] + ) + await config.async_initialize() + await config.async_connect_agent_user("mock-user-id") + + with patch.object( + config, "async_schedule_google_sync_all" + ) as mock_sync, patch.object(ga_helpers, "SYNC_DELAY", 0): + # Created entity + hass.bus.async_fire( + EVENT_ENTITY_REGISTRY_UPDATED, + {"action": "create", "entity_id": "light.kitchen"}, + ) + await hass.async_block_till_done() + + assert len(mock_sync.mock_calls) == 1 + + # Removed entity + hass.bus.async_fire( + EVENT_ENTITY_REGISTRY_UPDATED, + {"action": "remove", "entity_id": "light.kitchen"}, + ) + await hass.async_block_till_done() + + assert len(mock_sync.mock_calls) == 2 + + # Entity registry updated with relevant changes + hass.bus.async_fire( + EVENT_ENTITY_REGISTRY_UPDATED, + { + "action": "update", + "entity_id": "light.kitchen", + "changes": ["entity_id"], + }, + ) + await hass.async_block_till_done() + + assert len(mock_sync.mock_calls) == 3 + + # Entity registry updated with non-relevant changes + hass.bus.async_fire( + EVENT_ENTITY_REGISTRY_UPDATED, + {"action": "update", "entity_id": "light.kitchen", "changes": ["icon"]}, + ) + await hass.async_block_till_done() + + assert len(mock_sync.mock_calls) == 3 + + # When hass is not started yet we wait till started + hass.state = CoreState.starting + hass.bus.async_fire( + EVENT_ENTITY_REGISTRY_UPDATED, + {"action": "create", "entity_id": "light.kitchen"}, + ) + await hass.async_block_till_done() + + assert len(mock_sync.mock_calls) == 3 + + with patch.object(config, "async_sync_entities_all") as mock_sync: + hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED) + await hass.async_block_till_done() + assert len(mock_sync.mock_calls) == 1 + + +async def test_google_config_expose_entity_prefs(mock_conf, cloud_prefs): + """Test Google config should expose using prefs.""" + entity_conf = {"should_expose": False} + await cloud_prefs.async_update( + google_entity_configs={"light.kitchen": entity_conf}, + google_default_expose=["light"], + ) + + state = State("light.kitchen", "on") + + assert not mock_conf.should_expose(state) + entity_conf["should_expose"] = True + assert mock_conf.should_expose(state) + + entity_conf["should_expose"] = None + assert mock_conf.should_expose(state) + + await cloud_prefs.async_update( + google_default_expose=["sensor"], + ) + assert not mock_conf.should_expose(state) diff --git a/pool/shard007/Python/0071243_api_test.py b/pool/shard007/Python/0071243_api_test.py new file mode 100644 index 0000000000000000000000000000000000000000..4b70b9bd66faef0d1fa521bdb89023f100d47bde --- /dev/null +++ b/pool/shard007/Python/0071243_api_test.py @@ -0,0 +1,143 @@ +# Copyright (c) 2015 Intel Research and Development Ireland Ltd. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import unittest +import mock +import os +import experimental_framework.common as common +from experimental_framework.api import FrameworkApi +from experimental_framework.benchmarking_unit import BenchmarkingUnit +import experimental_framework.benchmarks.\ + instantiation_validation_benchmark as iv + + +class DummyBenchmarkingUnit(BenchmarkingUnit): + + def __init__(self): + BenchmarkingUnit.__init__(self) + + @staticmethod + def get_available_test_cases(): + return ['BenchA', 'BenchB'] + + @staticmethod + def get_required_benchmarks(required_benchmarks): + common.BASE_DIR = "base_dir/" + return [iv.InstantiationValidationBenchmark('benchmark', dict())] + + +class DummyBenchmarkingUnit2(BenchmarkingUnit): + + counter_init = 0 + counter_finalize = 0 + counter_run = 0 + + def __init__(self, base_heat_template, credentials, + heat_template_parameters, iterations, test_cases): + DummyBenchmarkingUnit.counter_init = 0 + DummyBenchmarkingUnit.counter_finalize = 0 + DummyBenchmarkingUnit.counter_run = 0 + + def initialize(self): + DummyBenchmarkingUnit2.counter_init += 1 + + def run_benchmarks(self): + DummyBenchmarkingUnit2.counter_run += 1 + + def finalize(self): + DummyBenchmarkingUnit2.counter_finalize += 1 + + +class TestGeneratesTemplate(unittest.TestCase): + def setUp(self): + pass + + def tearDown(self): + pass + + @mock.patch('experimental_framework.common.init') + def test_init_for_success(self, mock_init): + FrameworkApi.init() + mock_init.assert_called_once_with(api=True) + + # @mock.patch('experimental_framework.benchmarking_unit.BenchmarkingUnit.' + # 'get_available_test_cases', + # side_effect=DummyBenchmarkingUnit.get_available_test_cases) + # def test_get_available_test_cases_for_success(self, mock_bench): + # expected = ['BenchA', 'BenchB'] + # output = FrameworkApi.get_available_test_cases() + # self.assertEqual(expected, output) + + @mock.patch('experimental_framework.benchmarking_unit.BenchmarkingUnit.' + 'get_required_benchmarks', + side_effect=DummyBenchmarkingUnit.get_required_benchmarks) + def test_get_test_case_features_for_success(self, mock_get_req_bench): + expected = dict() + expected['description'] = 'Instantiation Validation Benchmark' + expected['parameters'] = [ + iv.THROUGHPUT, + iv.VLAN_SENDER, + iv.VLAN_RECEIVER] + expected['allowed_values'] = dict() + expected['allowed_values'][iv.THROUGHPUT] = \ + map(str, range(0, 100)) + expected['allowed_values'][iv.VLAN_SENDER] = \ + map(str, range(-1, 4096)) + expected['allowed_values'][iv.VLAN_RECEIVER] = \ + map(str, range(-1, 4096)) + expected['default_values'] = dict() + expected['default_values'][iv.THROUGHPUT] = '1' + expected['default_values'][iv.VLAN_SENDER] = '-1' + expected['default_values'][iv.VLAN_RECEIVER] = '-1' + + test_case = 'instantiation_validation_benchmark.' \ + 'InstantiationValidationBenchmark' + output = FrameworkApi.get_test_case_features(test_case) + self.assertEqual(expected, output) + + def test__get_test_case_features__for_failure(self): + self.assertRaises( + ValueError, FrameworkApi.get_test_case_features, 111) + + @mock.patch('experimental_framework.common.init') + @mock.patch('experimental_framework.common.LOG') + @mock.patch('experimental_framework.common.get_credentials') + @mock.patch('experimental_framework.heat_template_generation.' + 'generates_templates') + @mock.patch('experimental_framework.benchmarking_unit.BenchmarkingUnit', + side_effect=DummyBenchmarkingUnit2) + def test_execute_framework_for_success(self, mock_b_unit, mock_heat, + mock_credentials, mock_log, + mock_common_init): + common.TEMPLATE_DIR = "{}/{}/".format( + os.getcwd(), 'tests/data/generated_templates' + ) + + test_cases = dict() + iterations = 1 + heat_template = 'VTC_base_single_vm_wait.tmp' + heat_template_parameters = dict() + deployment_configuration = '' + openstack_credentials = dict() + openstack_credentials['ip_controller'] = '' + openstack_credentials['heat_url'] = '' + openstack_credentials['user'] = '' + openstack_credentials['password'] = '' + openstack_credentials['auth_uri'] = '' + openstack_credentials['project'] = '' + FrameworkApi.execute_framework( + test_cases, iterations, heat_template, + heat_template_parameters, deployment_configuration, + openstack_credentials) diff --git a/pool/shard007/Python/0071246_check_snmp_large_storage.py b/pool/shard007/Python/0071246_check_snmp_large_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..f97282f5fe7c71158902d0079c78ff1bbaab7e40 --- /dev/null +++ b/pool/shard007/Python/0071246_check_snmp_large_storage.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python + +# check_snmp_large_storage.py - Check the used / free disk space of a device via SNMP +# (using the HOST-RESOURCES-MIB hrStorageSize). + +# Copyright (C) 2016-2019 rsmuc + +# This file is part of "Health Monitoring Plugins". + +# "Health Monitoring Plugins" 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. + +# "Health Monitoring Plugins" 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 "Health Monitoring Plugins". If not, see . + +# Import PluginHelper and some utility constants from the Plugins module + +from __future__ import absolute_import, division, print_function +from pynag.Plugins import ok +import health_monitoring_plugins.storage + +if __name__ == '__main__': + # pylint: disable=C0103 + helper = health_monitoring_plugins.SnmpHelper() + + helper.parser.add_option('-p', '--partition', + dest='partition', + help='The disk / partition you want to monitor', + type='str') + helper.parser.add_option('-u', '--unit', dest="targetunit", + help="The unit you want to have (MB, GB, TB)", default="GB") + helper.parser.add_option('-s', '--scan', dest='scan_flag', default=False, action="store_true", + help='Show all available storages') + + helper.parse_arguments() + + sess = health_monitoring_plugins.SnmpSession(**helper.get_snmp_args()) + + # The default return value should be always OK + helper.status(ok) + + storage = health_monitoring_plugins.storage.Storage(sess) + + # if no partition is set, we will do a scan; or if scan_flag is set + if helper.options.partition == "" or \ + helper.options.partition is None or \ + helper.options.scan_flag: + # Device information + # run_scan() + storage.run_scan(helper, sess) + + # the check for the defined partition + else: + storage.check_partition(helper, sess) + + helper.check_all_metrics() + + # Print out plugin information and exit nagios-style + helper.exit() diff --git a/pool/shard007/Python/0071252_test_classifiers.py b/pool/shard007/Python/0071252_test_classifiers.py new file mode 100644 index 0000000000000000000000000000000000000000..4b6a240a454d7084d86b90d6d4eeee54b66f349e --- /dev/null +++ b/pool/shard007/Python/0071252_test_classifiers.py @@ -0,0 +1,98 @@ +#!/usr/bin/python2.7 +import sys +sys.path.append("../tools/") +from time import time +from sklearn.metrics import accuracy_score +import numpy as np +from sklearn.datasets import make_classification + +# Construct dataset +train_features,train_labels=make_classification(n_informative=2, n_redundant=0, n_repeated=0,n_classes=2, n_features=2) +test_features=train_features +test_labels=train_labels + + + + +def test_gaussian_naive_bayes(train_features, train_labels, test_features, test_labels): + from sklearn.naive_bayes import GaussianNB + from toygaussiannb import ToyGaussianNB + + clf=GaussianNB() + # train sklearn bayes + t0=time() + clf.fit(train_features, train_labels) + skl=clf.predict(test_features) + print "training and predict time sklearn:", round(time()-t0, 3), "s" + #print clf.theta_[0,:10] + + # train my bayes + t0=time() + clf=ToyGaussianNB() + clf.fit(train_features, train_labels) + myn,__=clf.predict(test_features) + + print "training and predict time toy bayes:", round(time()-t0, 3), "s" + + # compare results + print "acc of sklearn naive bayes:", accuracy_score(test_labels, skl) + print "acc of my naive bayes:", accuracy_score(test_labels, myn) + print "matching between sklearn and my naive bayes:", accuracy_score(skl,myn) + +def test_decision_tree(train_features, train_labels, test_features, test_labels): + from sklearn.tree import DecisionTreeClassifier + from toydecisiontree import ToyDecisionTree + + clf=DecisionTreeClassifier(criterion='entropy') + # train sklearn tree + t0=time() + clf.fit(train_features, train_labels) + skl=clf.predict(test_features) + print "training and predict time sklearn decision tree:", round(time()-t0, 3), "s" + #print clf.theta_[0,:10] + + # train my tree + t0=time() + clf=ToyDecisionTree() + clf.fit(train_data=train_features, train_labels=train_labels) + myn,__=clf.predict(test_features) + + print "training and predict time my decision tree:", round(time()-t0, 3), "s" + + # compare results + print "acc of sklearn decision tree:", accuracy_score(test_labels, skl) + print "acc of my decision tree:", accuracy_score(test_labels, myn) + print "matching between sklearn and my decision tree:", accuracy_score(skl,myn) + + + +def test_kmeans(train_features, test_features): + from sklearn.cluster import KMeans + from toykmeans import ToyKMeans + + tkm=ToyKMeans(n_clusters=4, n_iterations=200) + # provide same initialization for centroids + centroids=tkm.random_init(train_features) + tkm.centroids_=centroids + print "toykmeans clusters" + t0=time() + print tkm.fit(train_features) + print "fit time for ToyKMeans:", round(time()-t0, 3), "s" + + skm=KMeans(n_clusters=4,init=centroids, max_iter=200, n_init=1) + t0=time() + skm.fit(train_features) + print "sklearn kmeans clusters" + t1=time()-t0 + print skm.cluster_centers_ + print "fit time for sklearn KMeans:", round(t1, 3), "s" + + print "Close-enough numeric match between sklearn and toy kmeans:", np.allclose(tkm.centroids_.astype(float).flatten() ,skm.cluster_centers_.astype(float).flatten()) + + + +if __name__ == "__main__": + # test_gaussian_naive_bayes( train_features, train_labels, test_features, test_labels) + # test_decision_tree(train_features, train_labels, test_features, test_labels) + test_kmeans(train_features, test_features) + diff --git a/pool/shard007/Python/0071256_GameMasterGUI.py b/pool/shard007/Python/0071256_GameMasterGUI.py new file mode 100644 index 0000000000000000000000000000000000000000..c79105ed0e312df96cbcbf6fe63eaa2c52dbce18 --- /dev/null +++ b/pool/shard007/Python/0071256_GameMasterGUI.py @@ -0,0 +1,155 @@ +from Tkinter import * +import os +import tkMessageBox + + +def list_files(path): + """ + Web: http://stackoverflow.com/questions/3207219/how-to-list-all-files-of-a-directory-in-python + Username: Apogentus + :param path: + :return: + """ + # returns a list of names (with extension, without full path) of all files + # in folder path + files = [] + for name in os.listdir(path): + if os.path.isfile(os.path.join(path, name)): + if name != "__init__.py" and name.endswith(".py"): + files.append(name) + return files + + +def print_list(list): + num = 0 + for name in list: + print str(num) + ". " + name + num += 1 + + +def print_this(choice): + print choice + + +def print_player_max(): + console.insert(END, "The current player count is: " + maxPlayerCount.get() + "\n") + + +def select_game_type(): + console.insert(END, "The selected game type is now: " + selectedGameType.get() + "\n") + + +def select_tournament_type(): + console.insert(END, "The selected tournament type is now: " + selectedTournamentType.get() + "\n") + + +def open_registration(): + console.insert(END, "Registration Open\n") + + +def close_registration(): + console.insert(END, "Registration Closed\n") + + +def get_tournament_status(): + console.insert(END, "The tournament is currently: ...\n") + + +def start_tournament(): + console.insert(END, "The tournament has been started.\n") + + +def end_tournament(): + if tkMessageBox.askyesno("End Tournament", "Are you sure you want to end this tournament?"): + console.insert(END, "The tournament has been stopped\n") + + +def set_ip(): + console.insert(END, "The IP Address is now: " + ip.get() + "\n") + + +def set_port(): + console.insert(END, "The Port is now set to: " + port.get() + "\n") + + +def print_connections(): + console.insert(END, "Here's your list of connections...:\n") + + +main = Tk() +main.wm_title("Game Master Client") + + +# +# THIS BLOCK JUST FOR POPULATING THE LISTS, NEEDS TO CHANGE +# + +os.chdir("..") +os.chdir(os.curdir + "/AvailableGames") +result = os.path.abspath(os.curdir) + "/" +listy = list_files(result) + +os.chdir("..") +os.chdir(os.curdir + "/AvailableTournaments") +result = os.path.abspath(os.curdir) + "/" +tourney = list_files(result) + +########################################################## + +#GAME TYPE +gameTypeLabel = Label(main, text="Choose a game type:").grid(row=0, column=0) +selectedGameType = StringVar() +selectedGameType.set("...") +gameTypeMenu = OptionMenu(main, selectedGameType, *listy, command='').grid(row=0, column=1) +gameTypeButton = Button(main, text="Select", command=select_game_type).grid(row=0, column=2, columnspan=2) + +#TOURNAMENT TYPE +tourneyTypeLabel = Label(main, text="Choose a tournament type:").grid(row=1, column=0) +selectedTournamentType = StringVar() +selectedTournamentType.set("...") +tournamentTypeMenu = OptionMenu(main, selectedTournamentType, *tourney, command='').grid(row=1, column=1) +tournamentTypeButton = Button(main, text="Select", command=select_tournament_type).grid(row=1, column=2, columnspan=2) + +#Open/Close Registration +registrationLabel = Label(main, text="Registration Status:").grid(row=2, column=0) +registrationStatus = Label(main, text="(Current)").grid(row=2, column=1) +openRegistrationButton = Button(main, text="Open", command=open_registration).grid(row=2, column=2) +closeRegistrationButton = Button(main, text="Close", command=close_registration).grid(row=2, column=3) + +#SET MAX PLAYERS +setMaxPlayersLabel = Label(main, text="Set the maximum number of players:").grid(row=3, column=0) +maxPlayerCount = StringVar() +maxPlayerCount.set("0") +setMaxPlayerField = Entry(main, width=10, textvariable=maxPlayerCount).grid(row=3, column=1) +setMaxPlayerButton = Button(main, text="Select", command=print_player_max).grid(row=3, column=2, columnspan=2) + +#GameStatus +gameStatusLabel = Label(main, text="Tournament Status:").grid(row=4, column=0) +gameStatusButton = Button(main, text="STATUS", command=get_tournament_status).grid(row=4, column=1) +start = Button(main, text="Start", command=start_tournament).grid(row=4, column=2) +end = Button(main, text="End", command=end_tournament).grid(row=4, column=3) + +#SetIP +setIPLabel = Label(main, text="Set the IP Address:").grid(row=5, column=0) +ip = StringVar() +ip.set("0.0.0.0") +setIPField = Entry(main, width=10, textvariable=ip).grid(row=5, column=1) +setIPButton = Button(main, text="Select", command=set_ip).grid(row=5, column=2, columnspan=2) + +#SetPort +setPortLabel = Label(main, text="Set the Port:").grid(row=6, column=0) +port = StringVar() +port.set("12345") +setPortField = Entry(main, width=10, textvariable=port).grid(row=6, column=1) +setPortButton = Button(main, text="Select", command=set_port).grid(row=6, column=2, columnspan=2) + +#LIST CONNECTED PLAYERS +connectionsLabel = Label(main, text="Number of players connected:").grid(row=7, column=0) +connectionsButton = Button(main, text="4 Connections", command='').grid(row=7, column=1) +viewConnectionsButton = Button(main, text="View", command=print_connections).grid(row=7, column=2, columnspan=2) + +#console +console = Text(main, bg="#434A54", fg="white") +console.grid(row=8, columnspan=4) + +main.mainloop() \ No newline at end of file diff --git a/pool/shard007/Python/0071262_test_endpoint.py b/pool/shard007/Python/0071262_test_endpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..0aed3220c8601e7840dd0450305b8e9021fdfba0 --- /dev/null +++ b/pool/shard007/Python/0071262_test_endpoint.py @@ -0,0 +1,38 @@ +# Licensed under the Apache License, Version 2.0 (the "License"); you may +# not use this file except in compliance with the License. You may obtain +# a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations +# under the License. + +from functional.tests.identity.v2 import test_identity + + +class EndpointTests(test_identity.IdentityTests): + + def test_endpoint_create(self): + self._create_dummy_endpoint() + + def test_endpoint_delete(self): + endpoint_id = self._create_dummy_endpoint(add_clean_up=False) + raw_output = self.openstack( + 'endpoint delete %s' % endpoint_id) + self.assertEqual(0, len(raw_output)) + + def test_endpoint_list(self): + endpoint_id = self._create_dummy_endpoint() + raw_output = self.openstack('endpoint list') + self.assertInOutput(endpoint_id, raw_output) + items = self.parse_listing(raw_output) + self.assert_table_structure(items, self.ENDPOINT_LIST_HEADERS) + + def test_endpoint_show(self): + endpoint_id = self._create_dummy_endpoint() + raw_output = self.openstack('endpoint show %s' % endpoint_id) + items = self.parse_show(raw_output) + self.assert_show_fields(items, self.ENDPOINT_FIELDS) diff --git a/pool/shard007/Python/0071263_functions.py b/pool/shard007/Python/0071263_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..b87887f82c66ef2ae5cd86a38e752ac329659f65 --- /dev/null +++ b/pool/shard007/Python/0071263_functions.py @@ -0,0 +1,155 @@ +__author__ = 'Tom Schaul, tom@idsia.ch' + +from scipy import array, exp, tanh, clip, log, dot, sqrt, power, pi, tan, diag, rand, real_if_close +from scipy.linalg import inv, det, svd, logm, expm2 + + +def semilinear(x): + """ This function ensures that the values of the array are always positive. It is + x+1 for x=>0 and exp(x) for x<0. """ + try: + # assume x is a numpy array + shape = x.shape + x.flatten() + x = x.tolist() + except AttributeError: + # no, it wasn't: build shape from length of list + shape = (1, len(x)) + def f(val): + if val < 0: + # exponential function for x<0 + return safeExp(val) + else: + # linear function for x>=0 + return val + 1.0 + return array(map(f, x)).reshape(shape) + + +def semilinearPrime(x): + """ This function is the first derivative of the semilinear function (above). + It is needed for the backward pass of the module. """ + try: + # assume x is a numpy array + shape = x.shape + x.flatten() + x = x.tolist() + except AttributeError: + # no, it wasn't: build shape from length of list + shape = (1, len(x)) + def f(val): + if val < 0: + # exponential function for x<0 + return safeExp(val) + else: + # linear function for x>=0 + return 1.0 + return array(map(f, x)).reshape(shape) + + +def safeExp(x): + """ Bounded range for the exponential function (won't produce inf or NaN). """ + return exp(clip(x, -500, 500)) + + +def sigmoid(x): + """ Logistic sigmoid function. """ + return 1. / (1. + safeExp(-x)) + + +def sigmoidPrime(x): + """ Derivative of logistic sigmoid. """ + tmp = sigmoid(x) + return tmp * (1 - tmp) + + +def tanhPrime(x): + """ Derivative of tanh. """ + tmp = tanh(x) + return 1 - tmp * tmp + + +def ranking(R): + """ Produces a linear ranking of the values in R. """ + l = sorted(list(enumerate(R)), cmp=lambda a, b: cmp(a[1], b[1])) + l = sorted(list(enumerate(l)), cmp=lambda a, b: cmp(a[1], b[1])) + return array(map(lambda (r, dummy): r, l)) + + +def expln(x): + """ This continuous function ensures that the values of the array are always positive. + It is ln(x+1)+1 for x >= 0 and exp(x) for x < 0. """ + def f(val): + if val < 0: + # exponential function for x < 0 + return exp(val) + else: + # natural log function for x >= 0 + return log(val + 1.0) + 1 + try: + result = array(map(f, x)) + except TypeError: + result = array(f(x)) + + return result + + +def explnPrime(x): + """ This function is the first derivative of the expln function (above). + It is needed for the backward pass of the module. """ + def f(val): + if val < 0: + # exponential function for x<0 + return exp(val) + else: + # linear function for x>=0 + return 1.0 / (val + 1.0) + try: + result = array(map(f, x)) + except TypeError: + result = array(f(x)) + + return result + + +def multivariateNormalPdf(z, x, sigma): + """ The pdf of a multivariate normal distribution (not in scipy). + The sample z and the mean x should be 1-dim-arrays, and sigma a square 2-dim-array. """ + assert len(z.shape) == 1 and len(x.shape) == 1 and len(x) == len(z) and sigma.shape == (len(x), len(z)) + tmp = -0.5 * dot(dot((z - x), inv(sigma)), (z - x)) + res = (1. / power(2.0 * pi, len(z) / 2.)) * (1. / sqrt(det(sigma))) * exp(tmp) + return res + + +def simpleMultivariateNormalPdf(z, detFactorSigma): + """ Assuming z has been transformed to a mean of zero and an identity matrix of covariances. + Needs to provide the determinant of the factorized (real) covariance matrix. """ + dim = len(z) + return exp(-0.5 * dot(z, z)) / (power(2.0 * pi, dim / 2.) * detFactorSigma) + + +def multivariateCauchy(mu, sigma, onlyDiagonal=True): + """ Generates a sample according to a given multivariate Cauchy distribution. """ + if not onlyDiagonal: + u, s, d = svd(sigma) + coeffs = sqrt(s) + else: + coeffs = diag(sigma) + r = rand(len(mu)) + res = coeffs * tan(pi * (r - 0.5)) + if not onlyDiagonal: + res = dot(d, dot(res, u)) + return res + mu + + +def approxChiFunction(dim): + """ Returns Chi (expectation of the length of a normal random vector) + approximation according to: Ostermeier 1997. """ + dim = float(dim) + return sqrt(dim) * (1 - 1 / (4 * dim) + 1 / (21 * dim ** 2)) + + +def sqrtm(M): + """ Returns the symmetric semi-definite positive square root of a matrix. """ + r = real_if_close(expm2(0.5 * logm(M)), 1e-8) + return (r + r.T) / 2 + diff --git a/pool/shard007/Python/0071270_middlewares.py b/pool/shard007/Python/0071270_middlewares.py new file mode 100644 index 0000000000000000000000000000000000000000..d303037f57d5719476870846926fd0050a54cd21 --- /dev/null +++ b/pool/shard007/Python/0071270_middlewares.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- + +# Define here the models for your spider middleware +# +# See documentation in: +# http://doc.scrapy.org/en/latest/topics/spider-middleware.html + +from scrapy import signals + + +class SegurowebComArSpiderMiddleware(object): + # Not all methods need to be defined. If a method is not defined, + # scrapy acts as if the spider middleware does not modify the + # passed objects. + + @classmethod + def from_crawler(cls, crawler): + # This method is used by Scrapy to create your spiders. + s = cls() + crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) + return s + + def process_spider_input(response, spider): + # Called for each response that goes through the spider + # middleware and into the spider. + + # Should return None or raise an exception. + return None + + def process_spider_output(response, result, spider): + # Called with the results returned from the Spider, after + # it has processed the response. + + # Must return an iterable of Request, dict or Item objects. + for i in result: + yield i + + def process_spider_exception(response, exception, spider): + # Called when a spider or process_spider_input() method + # (from other spider middleware) raises an exception. + + # Should return either None or an iterable of Response, dict + # or Item objects. + pass + + def process_start_requests(start_requests, spider): + # Called with the start requests of the spider, and works + # similarly to the process_spider_output() method, except + # that it doesn’t have a response associated. + + # Must return only requests (not items). + for r in start_requests: + yield r + + def spider_opened(self, spider): + spider.logger.info('Spider opened: %s' % spider.name) diff --git a/pool/shard007/Python/0071276_spy.py b/pool/shard007/Python/0071276_spy.py new file mode 100644 index 0000000000000000000000000000000000000000..ae269531d4da315bf097eb51d7500d22ca935659 --- /dev/null +++ b/pool/shard007/Python/0071276_spy.py @@ -0,0 +1,40 @@ +import os +import fnmatch +import mimetypes + +def list_files(startpath): + script_path = os.path.join(os.path.dirname(os.path.abspath( __file__ )),startpath) + for root, dirs, files in os.walk(script_path): + level = root.replace(script_path, '').count(os.sep) + indent = ' ' * 4 * (level) + print('{}{}/'.format(indent, os.path.basename(root))) + subindent = ' ' * 4 * (level + 1) + for f in files: + print('{}{}'.format(subindent, f)) + +def contents(path): + script_path = os.path.join(os.path.dirname(os.path.abspath( __file__ )),path) + matches = [] + for root, dirnames, filenames in os.walk(script_path): + for filename in fnmatch.filter(filenames, '*.*'): + matches.append(os.path.join(root, filename)) + + for file in matches: + print("-----------------------------------------------------------------") + print("Opening :-") + print(os.path.relpath(file,script_path)) + if mimetypes.guess_type(file)[0] != None: + f = open(file, "r") + print(f.read()) + else: + print("**** file is not ascii (possibly executable) ****") + +def main(): + print("I am a spy program, looking for test input, test output, and instructor solutions.") + print("==================================================================================") + list_files("..") + print("==================================================================================") + contents("..") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/pool/shard007/Python/0071279_test_tests.py b/pool/shard007/Python/0071279_test_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..99c3fa53d37698e086246b1401b3b587d37e6335 --- /dev/null +++ b/pool/shard007/Python/0071279_test_tests.py @@ -0,0 +1,76 @@ +import unittest + +import enum +import subprocess +from pathlib import Path + +from g1.devtools import tests + + +class TestEnum(enum.Enum): + P = 1 + Q = 2 + + +class DelTest(unittest.TestCase): + + def test_resurrecting_self(self): + + class Resurrect: + + def __del__(self): + Resurrect.dont_recycle_me = self + + with self.assertRaisesRegex(AssertionError, r'is not None'): + tests.assert_del_not_resurrecting(self, Resurrect) + + +@unittest.skipUnless(tests.is_gcc_available(), 'gcc unavailable') +class CFixtureTest(unittest.TestCase, tests.CFixture): + + HEADERS = (Path(__file__).absolute().parent / 'testdata' / 'test.h', ) + + def test_run_c_code(self): + stdout = self.run_c_code( + r''' + #include + int main() { + printf("Hello, world!\n"); + return 0; + } + ''' + ) + self.assertEqual(stdout, b'Hello, world!\n') + + def test_assert_c_expr(self): + self.assert_c_expr('1') # This should not raise. + with self.assertRaises(subprocess.CalledProcessError): + self.assert_c_expr('0') + + def test_get_c_vars(self): + + self.assertEqual(self.get_c_vars({}), {}) + + self.assertEqual( + self.get_c_vars({ + 'x': int, + 's': str, + }), + { + 'x': 1, + 's': 'Hello, world!\n', + }, + ) + + def test_get_enum_members(self): + self.assertEqual(self.get_enum_members(TestEnum), TestEnum.__members__) + + +class SpawnTest(unittest.TestCase): + + def test_spawn(self): + self.assertEqual(tests.spawn(lambda x: x + 1, 1).result(), 2) + + +if __name__ == '__main__': + unittest.main() diff --git a/pool/shard007/Python/0071281_calculations.py b/pool/shard007/Python/0071281_calculations.py new file mode 100644 index 0000000000000000000000000000000000000000..acda162a5cf8aeada528b29a57fe5f44191b4126 --- /dev/null +++ b/pool/shard007/Python/0071281_calculations.py @@ -0,0 +1,120 @@ +# -*- coding: utf-8 -*- + +""" +This module provides base classes for calculations. All calculations should +inherit from one of the calcs in this module. +""" + +from carousel.core import logging, CommonBase, Registry, UREG, Parameter +from carousel.core.calculators import Calculator + +LOGGER = logging.getLogger(__name__) + + +class CalcParameter(Parameter): + """ + Fields for calculations. + """ + _attrs = ['dependencies', 'always_calc', 'frequency', 'formula', 'args', + 'returns', 'calculator', 'is_dynamic'] + + +class CalcRegistry(Registry): + """ + A registry for calculations. Each key is a calculation. The value + of each calculation is split into 2 dictionaries: "static" and + "dynamic". Static calculations occur once at the beginning of a simulation + and dynamic calculations occur at every interval. The contents of either + the "static" or "dynamic" key is an ordered list of formulas, their + arguments and return values. + + Calculations can list `dependencies `_ that must be + calculated first. Calculations marked as `always_calc` will not be limited + by thresholds set in simulations. The frequency determines how often to + dynamic calculations occur. Frequency can be given in intervals or can list + a quantity of time, _EG:_ ``2 * UREG.hours``. + """ + #: meta names + meta_names = ['dependencies', 'always_calc', 'frequency', 'calculator', + 'is_dynamic', 'calc_source'] + + def register(self, new_calc, *args, **kwargs): + """ + Register calculations and meta data. + + * ``dependencies`` - list of prerequisite calculations + * ``always_calc`` - ``True`` if calculation ignores thresholds + * ``frequency`` - frequency of calculation in intervals or units of time + + :param new_calc: register new calculation + """ + kwargs.update(zip(self.meta_names, args)) + # dependencies should be a list of other calculations + if isinstance(kwargs['dependencies'], basestring): + kwargs['dependencies'] = [kwargs['dependencies']] + # call super method, now meta can be passed as args or kwargs. + super(CalcRegistry, self).register(new_calc, **kwargs) + + +class CalcBase(CommonBase): + """ + Base calculation meta class. + """ + _path_attr = 'calcs_path' + _file_attr = 'calcs_file' + _param_cls = CalcParameter + + def __new__(mcs, name, bases, attr): + # use only with Calc subclasses + if not CommonBase.get_parents(bases, CalcBase): + return super(CalcBase, mcs).__new__(mcs, name, bases, attr) + # set _meta combined from bases + attr = mcs.set_meta(bases, attr) + # set param file full path if calculations path and file specified or + # try to set parameters from class attributes except private/magic + attr = mcs.set_param_file_or_parameters(attr) + return super(CalcBase, mcs).__new__(mcs, name, bases, attr) + + +class Calc(object): + """ + A class for all calculations. + """ + __metaclass__ = CalcBase + + def __init__(self): + meta = getattr(self, CalcBase._meta_attr) + parameters = getattr(self, CalcBase._param_attr) + #: ``True`` if always calculated (day and night) + self.always_calc = dict.fromkeys( + parameters, getattr(meta, 'always_calc', False) + ) + freq = getattr(meta, 'frequency', [1, '']) + #: frequency calculation is calculated in intervals or units of time + self.frequency = dict.fromkeys(parameters, freq[0] * UREG(str(freq[1]))) + #: dependencies + self.dependencies = dict.fromkeys( + parameters, getattr(meta, 'dependencies', []) + ) + #: name of :class:`Calc` superclass + self.calc_source = dict.fromkeys(parameters, self.__class__.__name__) + #: calculator + self.calculator = dict.fromkeys( + parameters, getattr(meta, 'calculator', Calculator) + ) + #: ``True`` if calculations are dynamic, ``False`` if static + self.is_dynamic = dict.fromkeys( + parameters, getattr(meta, 'is_dynamic', False) + ) + #: calculations + self.calcs = {} + for k, v in parameters.iteritems(): + self.calcs[k] = { + key: v[key] for key in ('formula', 'args', 'returns') + } + keys = ('dependencies', 'always_calc', 'frequency', 'calculator', + 'is_dynamic') + for key in keys: + value = v.get(key) + if value is not None: + getattr(self, key)[k] = value diff --git a/pool/shard007/Python/0071283_owrandomforest.py b/pool/shard007/Python/0071283_owrandomforest.py new file mode 100644 index 0000000000000000000000000000000000000000..1ed048c5811b9defcf3b4608cde92c577824cdb5 --- /dev/null +++ b/pool/shard007/Python/0071283_owrandomforest.py @@ -0,0 +1,192 @@ +# -*- coding: utf-8 -*- + +from PyQt4 import QtGui +from PyQt4.QtGui import QLabel, QGridLayout +from PyQt4.QtCore import Qt + +from Orange.data import Table +from Orange.classification.random_forest import (RandomForestLearner, + RandomForestClassifier) +from Orange.widgets import widget, settings, gui +from Orange.widgets.utils.owlearnerwidget import OWProvidesLearner +from Orange.widgets.utils.sql import check_sql_input + + +class OWRandomForest(OWProvidesLearner, widget.OWWidget): + name = "Random Forest Classification" + description = "Random forest classification algorithm." + icon = "icons/RandomForest.svg" + + inputs = [("Data", Table, "set_data")] + OWProvidesLearner.inputs + outputs = [("Learner", RandomForestLearner), + ("Model", RandomForestClassifier)] + + want_main_area = False + resizing_enabled = False + + LEARNER = RandomForestLearner + + learner_name = settings.Setting("RF Classification Learner") + n_estimators = settings.Setting(10) + max_features = settings.Setting(5) + use_max_features = settings.Setting(False) + random_state = settings.Setting(0) + use_random_state = settings.Setting(False) + max_depth = settings.Setting(3) + use_max_depth = settings.Setting(False) + max_leaf_nodes = settings.Setting(5) + use_max_leaf_nodes = settings.Setting(True) + index_output = settings.Setting(0) + + def __init__(self): + super().__init__() + + self.data = None + self.preprocessors = None + + # Learner name + box = gui.widgetBox(self.controlArea, self.tr("Name")) + gui.lineEdit(box, self, "learner_name") + + # Basic properties + form = QGridLayout() + basic_box = gui.widgetBox( + self.controlArea, "Basic properties", orientation=form) + + form.addWidget(QLabel(self.tr("Number of trees in the forest: ")), + 0, 0, Qt.AlignLeft) + spin = gui.spin(basic_box, self, "n_estimators", minv=1, maxv=1e4, + callback=self.settingsChanged, addToLayout=False, + controlWidth=50) + form.addWidget(spin, 0, 1, Qt.AlignRight) + + max_features_cb = gui.checkBox( + basic_box, self, "use_max_features", + callback=self.settingsChanged, addToLayout=False, + label="Consider a number of best attributes at each split") + + max_features_spin = gui.spin( + basic_box, self, "max_features", 2, 50, addToLayout=False, + callback=self.settingsChanged, controlWidth=50) + + form.addWidget(max_features_cb, 1, 0, Qt.AlignLeft) + form.addWidget(max_features_spin, 1, 1, Qt.AlignRight) + + random_state_cb = gui.checkBox( + basic_box, self, "use_random_state", callback=self.settingsChanged, + addToLayout=False, label="Use seed for random generator:") + random_state_spin = gui.spin( + basic_box, self, "random_state", 0, 2 ** 31 - 1, addToLayout=False, + callback=self.settingsChanged, controlWidth=50) + + form.addWidget(random_state_cb, 2, 0, Qt.AlignLeft) + form.addWidget(random_state_spin, 2, 1, Qt.AlignRight) + self._max_features_spin = max_features_spin + self._random_state_spin = random_state_spin + + # Growth control + form = QGridLayout() + growth_box = gui.widgetBox( + self.controlArea, "Growth control", orientation=form) + + max_depth_cb = gui.checkBox( + growth_box, self, "use_max_depth", + label="Set maximal depth of individual trees", + callback=self.settingsChanged, + addToLayout=False) + + max_depth_spin = gui.spin( + growth_box, self, "max_depth", 2, 50, addToLayout=False, + callback=self.settingsChanged) + + form.addWidget(max_depth_cb, 3, 0, Qt.AlignLeft) + form.addWidget(max_depth_spin, 3, 1, Qt.AlignRight) + + max_leaf_nodes_cb = gui.checkBox( + growth_box, self, "use_max_leaf_nodes", + label="Stop splitting nodes with maximum instances: ", + callback=self.settingsChanged, addToLayout=False) + + max_leaf_nodes_spin = gui.spin( + growth_box, self, "max_leaf_nodes", 0, 100, addToLayout=False, + callback=self.settingsChanged) + + form.addWidget(max_leaf_nodes_cb, 4, 0, Qt.AlignLeft) + form.addWidget(max_leaf_nodes_spin, 4, 1, Qt.AlignRight) + self._max_depth_spin = max_depth_spin + self._max_leaf_nodes_spin = max_leaf_nodes_spin + + # Index on the output +# gui.doubleSpin(self.controlArea, self, "index_output", 0, 10000, 1, +# label="Index of tree on the output") + + box = gui.widgetBox(self.controlArea, True, orientation="horizontal") + box.layout().addWidget(self.report_button) + gui.separator(box, 20) + gui.button(box, self, "&Apply", callback=self.apply, default=True) + + self.settingsChanged() + self.apply() + + @check_sql_input + def set_data(self, data): + """Set the input train data set.""" + self.data = data + if data is not None: + self.apply() + + def apply(self): + common_args = dict() + common_args["n_estimators"] = self.n_estimators + if self.use_max_features: + common_args["max_features"] = self.max_features + if self.use_random_state: + common_args["random_state"] = self.random_state + if self.use_max_depth: + common_args["max_depth"] = self.max_depth + if self.use_max_leaf_nodes: + common_args["max_leaf_nodes"] = self.max_leaf_nodes + + learner = self.LEARNER(preprocessors=self.preprocessors, **common_args) + learner.name = self.learner_name + model = None + + if self.data is not None: + self.error(0) + if not learner.check_learner_adequacy(self.data.domain): + self.error(0, learner.learner_adequacy_err_msg) + else: + model = learner(self.data) + model.name = self.learner_name + + self.send("Learner", learner) + self.send("Model", model) + + def settingsChanged(self): + self._max_features_spin.setEnabled(self.use_max_features) + self._random_state_spin.setEnabled(self.use_random_state) + self._max_depth_spin.setEnabled(self.use_max_depth) + self._max_leaf_nodes_spin.setEnabled(self.use_max_leaf_nodes) + + def send_report(self): + self.report_items((("Name", self.learner_name),)) + self.report_items( + "Model parameters", + (("Number of trees", self.n_estimators), + ("Maximal number of considered features", + self.max_features if self.use_max_features else "unlimited"), + ("Fixed random seed", self.use_random_state and self.random_state), + ("Maximal tree depth", + self.max_depth if self.use_max_depth else "unlimited"), + ("Stop splitting nodes with maximum instances", + self.max_leaf_nodes if self.use_max_leaf_nodes else "unlimited"))) + if self.data: + self.report_data("Data", self.data) + + +if __name__ == "__main__": + app = QtGui.QApplication([]) + w = OWRandomForest() + w.set_data(Table("iris")) + w.show() + app.exec_() diff --git a/pool/shard007/Python/0071289_run_ppr.py b/pool/shard007/Python/0071289_run_ppr.py new file mode 100644 index 0000000000000000000000000000000000000000..880dab91c9d9a3c7d53204bb1f530eeb4d14de18 --- /dev/null +++ b/pool/shard007/Python/0071289_run_ppr.py @@ -0,0 +1,52 @@ +from qfiles_io import gen_ppr +import subprocess as sub +from numpy import array +from mython import gen_qsub +import sys +import os + +if len(sys.argv) < 2: + print "Input is DFT file names that generates the ppr input." + exit() + +# Real k-points +#kpoints = np.array([1,3,8,10,27,29,34,36]) - 1 # 2x2x2 +kpoints = array([1,3,8,10,27,29,34,36]) - 1 # 2x2x2 +#kpoints = array([1,4,17,20,93,96,109,112]) - 1 # 4x4x4 +#kpoints = array([1,5,30,34,227,231,256,260]) - 1 + +wd = os.getcwd() +for dftloc in sys.argv[1:]: + dftfn = dftloc.split('/')[-1] + roots = [dftfn.replace('.d12','_{k}'.format(k=k)) for k in kpoints] + gamma = roots[0] + loc = '/'.join(dftloc.split('/')[:-1]) + + os.chdir(wd + '/' + loc) + + pprfns = [gen_ppr(root,gosling="/home/busemey2/bin/gosling", + jast=gamma+'.opt.jast2') for root in roots] + + pc = [] + pc += ['module load openmpi/1.4-gcc+ifort'] + pc += ['module load gcc/4.7.1'] + pc += ['module load intel/11.1'] + + for root in roots: + if not os.path.isfile(root+".dmc.tracele"): + print "Swapping endian of %s."%(root+".dmc.trace") + sub.call("/home/busemey2/bin/swap_endian {0} {1}".format( + root+".dmc.trace",root+".dmc.tracele"), + shell=True) + + for pprfn in pprfns: + qin = gen_qsub('~/bin/qwalk {0}'.format(pprfn), + stdout=pprfn+'.out', + name='/'.join((os.getcwd(),pprfn)), + time='04:00:00', + nn=2, + queue='secondary', + prep_commands=pc) + print sub.check_output('qsub '+qin,shell=True) + + os.chdir(wd) diff --git a/pool/shard007/Python/0071294_models.py b/pool/shard007/Python/0071294_models.py new file mode 100644 index 0000000000000000000000000000000000000000..a75bb2c6c145bdb2d39040d3b4788217cc76f42d --- /dev/null +++ b/pool/shard007/Python/0071294_models.py @@ -0,0 +1,167 @@ +from django.db import models +from network.exceptions import MacNotFound +from network.providers import registry + + +class SwitchManager(models.Manager): + + def flip_vlan(self, mac, vlan_number=None): + + found_mac = False + enabled_switches = super(SwitchManager, self).get_queryset().filter(enabled=True) + + for switch in enabled_switches: + try: + switch.flip_vlan(mac, vlan_number) + except MacNotFound, e: + continue + + found_mac = True + + return found_mac + + +class UplinkPort(models.Model): + port = models.IntegerField() + switch = models.ForeignKey('network.Switch', related_name='uplink_ports') + + class Meta: + unique_together = ( + ('port', 'switch'), + ) + + def __unicode__(self): + return '%s' % self.port + + +class Switch(models.Model): + + name = models.CharField(max_length=50) + ip = models.GenericIPAddressField() + port = models.IntegerField(default=22) + + username = models.CharField(max_length=50) + password = models.CharField(max_length=50) + + switch_vlan_dirty = models.ForeignKey('network.VLAN', verbose_name='Dirty', + blank='true', null='true', + related_name='switch_vlan_dirty', + limit_choices_to={'vlan_type': 'DI'}) + + switch_vlan_clean = models.ForeignKey('network.VLAN', verbose_name='Clean', + blank='true', null='true', + related_name='switch_vlan_clean', + limit_choices_to={'vlan_type': 'CL'},) + + ports = models.IntegerField(default=24, verbose_name='# of Ports') + + requires_authentication = models.BooleanField(default=True) + + provider = models.CharField(max_length=30, choices=registry.as_choices(), verbose_name='Type') + + enabled = models.BooleanField(default=False) + + objects = SwitchManager() + + _provider_cache = None + + class Meta: + verbose_name_plural = 'Switches' + + def __unicode__(self): + return '{0} ({1})'.format(self.name, self.ip) + + def get_provider(self): + if not self._provider_cache: + return registry.by_id(self.provider) + return self._provider_cache + + def connect(self): + provider = self.get_provider() + provider.connect(self) + ''' + def get_shell(self): + provider = self.get_provider() + provider.get_interactive_shell() + ''' + def get_shell(self): + provider = self.get_provider() + provider.invoke_shell() + # Clean the initial data buffer + provider.receive_data() + + def run_cmd(self, cmd): + provider = self.get_provider() + provider.run_command(cmd) + output = provider.receive_data() + return output + + def set_vlan(self, vlan_number): + pass + + def set_port_vlan(self, vlan_number): + ports = self.uplink_ports.values_list('port', flat=True) + + def flip_vlan(self, mac, vlan_number=None): + + if not vlan_number: + vlan_number = self.switch_vlan_clean.vlan_num + + self.connect() + + try: + + self.get_shell() + + port = self.get_provider().find_mac_address(mac) + self.get_provider().change_vlan(port, vlan_number) + + except MacNotFound, e: + self.disconnect() + raise MacNotFound() + + except Exception, e: + pass + + finally: + self.disconnect() + + ''' + def get_channel(self): + self.connect() + provider = self.get_provider() + chan = provider.invoke_shell() + + return chan + ''' + def disconnect(self): + provider = self.get_provider() + provider.disconnect() + + +class VLAN(models.Model): + # Types of VLANs + DIRTY = 'DI' + CLEAN = 'CL' + NONE = 'NO' + + PUBLIC_VLANS = ( + DIRTY, + CLEAN, + ) + + TYPES_OF_VLANS = ( + (DIRTY, 'Dirty'), + (CLEAN, 'Clean'), + (NONE, 'None'), + ) + + vlan_name = models.CharField(max_length=50, verbose_name='Name') + vlan_num = models.IntegerField(verbose_name='VLAN #') + vlan_type = models.CharField(max_length=2, verbose_name='Type', + choices=TYPES_OF_VLANS, default=NONE) + vlan_desc = models.TextField(verbose_name='Description', + null='true', blank='true') + + def __unicode__(self): + return '{0}'.format(self.vlan_name) \ No newline at end of file diff --git a/pool/shard007/Python/0071299_nonparam.py b/pool/shard007/Python/0071299_nonparam.py new file mode 100644 index 0000000000000000000000000000000000000000..eac9d14612ff4f1276edbc4e4e5f6e8119d7aa92 --- /dev/null +++ b/pool/shard007/Python/0071299_nonparam.py @@ -0,0 +1,119 @@ +#emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- +#ex: set sts=4 ts=4 sw=4 et: +### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## +# +# See the COPYING file distributed along with the PTSA package for the +# copyright and license terms. +# +### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## + +# global imports +import numpy as np +from scipy.stats import ttest_ind, ttest_1samp, norm +import sys + +def gen_perms(dat, group_var, nperms): + """ + Generate permutations within a group variable, but across conditions. + + There is no need to sort your data as this method will shuffle the + indices properly. + + """ + # grab the unique groups + ugrp = np.unique(dat[group_var]) + + # save indices for each unique group + grpind = {u:np.nonzero(dat[group_var]==u)[0] for u in ugrp} + + # set the base permutation indices for each unique group + p_ind = {u:np.arange(len(grpind[u])) for u in ugrp} + + # start with actual data + perms = [np.arange(len(dat))] + + # loop and shuffle for each perm + for p in xrange(nperms): + # set the starting indices + ind = np.arange(len(dat)) + + # loop over each group + for u in ugrp: + # permute the indices for that group + perm = np.random.permutation(p_ind[u]) + + # insert the permuted group indices into the base index + np.put(ind,grpind[u],grpind[u][perm]) + + # append the shuffled perm to the list of permutations + perms.append(ind) + + # turn the final perms into an array + perms = np.array(perms) + return perms + + + +def ttest_ind_z_one_sided(X,Y): + # do the test + t,p = ttest_ind(X,Y) + + # convert the pvals to one-sided tests based on the t + p = (p/2.)+np.finfo(p.dtype).eps + p[t>0] = 1-p[t>0] + + # convert the p to a z + z = norm.ppf(p) + + return z + + +def permutation_test(X, Y=None, parametric=True, iterations=1000): + """ + Perform a permutation test on paired or non-paired data. + + Observations must be on the first axis. + """ + # see if paired or not and concat data + if Y is None: + paired = True + data = X + nX = len(X) + else: + paired = False + data = np.r_[X,Y] + nX = len(X) + nY = len(Y) + + # currently no non-parametric + if not parametric: + raise NotImplementedError("Currently only parametric stats are supported.") + + # perform stats + z_boot = [] + if paired: + # paired stat + raise NotImplementedError("Currently only non-paired stats are supported.") + # first on actual data + #t,p = ttest_1samp(data) + else: + # non-paired + # first on actual data + z = ttest_ind_z_one_sided(data[:nX],data[nX:]) + + # now on random shuffles + sys.stdout.write('%d: '%iterations) + for i in xrange(iterations): + # shuffle it + sys.stdout.write('%d '%i) + sys.stdout.flush() + np.random.shuffle(data) + z_boot.append(ttest_ind_z_one_sided(data[:nX],data[nX:])) + sys.stdout.write('\n') + sys.stdout.flush() + + # convert z_boot to array + z_boot = np.asarray(z_boot) + + # return those z values + return z, z_boot diff --git a/pool/shard007/Python/0071300_generate.py b/pool/shard007/Python/0071300_generate.py new file mode 100644 index 0000000000000000000000000000000000000000..6cda568a1d52a81c0b8ef609b93a5b4f4b589a89 --- /dev/null +++ b/pool/shard007/Python/0071300_generate.py @@ -0,0 +1,33 @@ +import os +import re + +from jinja2 import Environment, FileSystemLoader + + +env = Environment(loader=FileSystemLoader('.')) + + +def generate(source_filename, target_filename): + print 'generate %s' % source_filename + template = env.get_template(source_filename) + + html = template.render() + + with open(target_filename, 'w') as f: + f.write(html) + + +def get_template_files(): + def get_filename(f): + return os.path.splitext(f)[0] + + return [ + get_filename(f) for f in os.listdir('.') + if f.endswith('.tmpl') + ] + + +for f in get_template_files(): + source_filename = '%s.tmpl' % f + target_filename = '../examples/%s.html' % f + generate(source_filename, target_filename) diff --git a/pool/shard007/Python/0071302_admin.py b/pool/shard007/Python/0071302_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..af6d4327857f5cf041f044b2696e5908f41cf531 --- /dev/null +++ b/pool/shard007/Python/0071302_admin.py @@ -0,0 +1,35 @@ +from django.contrib import admin +from django.contrib.auth.admin import UserAdmin +from django.contrib.auth.models import User +from django.contrib.sessions.models import Session +from django.utils.translation import ugettext, ugettext_lazy as _ +from heliosinstitution.models import Institution, InstitutionUserProfile + + +class SessionAdmin(admin.ModelAdmin): + def _session_data(self, obj): + return obj.get_decoded() + list_display = ['session_key', '_session_data', 'expire_date'] + + +class HeliosInstitutionAdmin(admin.ModelAdmin): + list_display = ('name', 'short_name', 'main_phone') + + +class InstitutionUserProfileAdmin(admin.ModelAdmin): + exclude = ('info', 'token') + list_display = ('helios_user', 'email', 'institution') + + +class UserAdmin(admin.ModelAdmin): + fieldsets = ( + (None, {'fields': ('username',)}), + (_('Permissions'), {'fields': ('groups', )}), + ) + + +admin.site.register(InstitutionUserProfile, InstitutionUserProfileAdmin) +admin.site.register(Institution, HeliosInstitutionAdmin) +admin.site.unregister(User) +admin.site.register(User, UserAdmin) +admin.site.register(Session, SessionAdmin) diff --git a/pool/shard007/Python/0071303_test_update_wsdl.py b/pool/shard007/Python/0071303_test_update_wsdl.py new file mode 100644 index 0000000000000000000000000000000000000000..5cc6d4b688ee6d438f4e1e85000b53fbe20b0a42 --- /dev/null +++ b/pool/shard007/Python/0071303_test_update_wsdl.py @@ -0,0 +1,81 @@ +# Copyright 2016 Osvaldo Santana Neto +# +# 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. + + +import tempfile +from unittest import mock +from unittest.mock import call + +from requests import HTTPError + +from correios.update_wsdl import WSDLUpdater + +from .vcr import vcr + + +def get_wsdl_updater(path): + response_mock = mock.MagicMock() + response_mock.text = "response value" + session = mock.MagicMock() + session.get.return_value = response_mock + + return WSDLUpdater(wsdl_path=path, session=session) + + +@vcr.use_cassette +def test_basic_update(): + with tempfile.TemporaryDirectory() as wsdl_path: + wsdl_updater = WSDLUpdater(wsdl_path=wsdl_path) + wsdl_updater.update_all() + + +def test_wsdl_updater_download(): + with tempfile.TemporaryDirectory() as wsdl_path: + wsdl_updater = get_wsdl_updater(wsdl_path) + wsdl_updater.download_wsdl('https://example.com/service.wsdl', 'service-production.wsdl') + + wsdl_updater.session.get.assert_called_once_with('https://example.com/service.wsdl') + + printed = wsdl_updater.output.getvalue() + assert 'Updating file: service-production.wsdl URL: https://example.com/service.wsdl' in printed + assert 'Successfully create file:' in printed + assert 'Updated with success' in printed + + +def test_wsdl_update_all(): + with tempfile.TemporaryDirectory() as wsdl_path: + wsdl_updater = get_wsdl_updater(wsdl_path) + wsdl_updater.update_all() + wsdl_updater.session.get.assert_has_calls([ + call('https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente?wsdl'), + call('https://apphom.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente?wsdl'), + call('https://webservice.correios.com.br/service/rastro/Rastro.wsdl'), + call('http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx?WSDL'), + ], any_order=True) + + +def test_wsdl_download_error(): + response_mock = mock.MagicMock() + response_mock.text = "response value" + session = mock.MagicMock() + session.get.side_effect = HTTPError("test error") + + wsdl_updater = WSDLUpdater(wsdl_path="", session=session) + wsdl_updater.update_all() + + printed = wsdl_updater.output.getvalue() + assert ('Updating file: AtendeCliente-production.wsdl ' + 'URL: https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente?wsdl') in printed + assert ("Error downloading https://apps.correios.com.br/SigepMasterJPA/AtendeClienteService/AtendeCliente?wsdl: " + "test error") in printed diff --git a/pool/shard007/Python/0071310_test_validation.py b/pool/shard007/Python/0071310_test_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..e16a442f04cf52bf34267aae0cec3f978d386154 --- /dev/null +++ b/pool/shard007/Python/0071310_test_validation.py @@ -0,0 +1,42 @@ +# Copyright 2016 Capital One Services, LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import absolute_import, division, print_function, unicode_literals + +import argparse + +from .common import BaseTest +from c7n.commands import validate as validate_yaml_policies + + +class CommandsValidateTest(BaseTest): + + def test_failed_validation(self): + yaml_validate_options = argparse.Namespace( + command = 'c7n.commands.validate', + config = None, + configs = [ + 'tests/data/test_policies/ebs-BADVALIDATION.yml', + 'tests/data/test_policies/ami-GOODVALIDATION.yml' + ], + debug=False, + subparser='validate', + verbose=False + ) + with self.assertRaises(SystemExit) as exit: + validate_yaml_policies(yaml_validate_options) + # if there is a bad policy in the batch being validated, there should be an exit 1 + self.assertEqual(exit.exception.code, 1) + yaml_validate_options.configs.remove('tests/data/test_policies/ebs-BADVALIDATION.yml') + # if there are only good policy, it should exit none + self.assertIsNone(validate_yaml_policies(yaml_validate_options)) diff --git a/pool/shard007/Python/0071319_core_TS3clients.py b/pool/shard007/Python/0071319_core_TS3clients.py new file mode 100644 index 0000000000000000000000000000000000000000..3554c119109ccc5f4a7e328a15bc6cce8fbf4d30 --- /dev/null +++ b/pool/shard007/Python/0071319_core_TS3clients.py @@ -0,0 +1,68 @@ +from ts3tools import ts3tools +import time + +name = 'core.TS3clients' +base = None + +# get a centralized clientlist to avoid spamming server commands for clientlists every second +nextClientlistInterval = 2 +nextClientlist = 0 +clientlist = {} +nextGrouplistInterval = 30 +nextGrouplist = 0 +grouplist = {} + +def setup(ts3base): + global base + base = ts3base + # register class to ts3eventscripts + base.register_class(name, core_TS3clients) + +class core_TS3clients: + def __init__(self, ts3base): + pass + + # get list of connected clients + def clientlist(self, flags='-uid -away -voice -times -groups -info -icon -country'): + global clientlist, nextClientlist + if nextClientlist <= time.time(): + clientlist = ts3tools.parse_raw_data(base.send_receive('clientlist ' + flags), 'clid') + nextClientlist = time.time() + nextClientlistInterval + return clientlist + + # get list of groups + def grouplist(self): + global grouplist, nextGrouplist + if nextGrouplist <= time.time(): + grouplist = ts3tools.parse_raw_data(base.send_receive('servergrouplist'), 'sgid') + nextGrouplist = time.time() + nextGrouplistInterval + return grouplist + + def clientmove(self, clid, cid): + clidstring = '' + if isinstance(clid, list): + i = False + for one in clid: + if i is False: + clidstring += one + i = True + else: + clidstring += '|' + one + else: + clidstring = clid + return ts3tools.parse_raw_data(base.send_receive('clientmove clid=' + clidstring + ' cid=' + cid)) + + def clientinfo(self, clid): + query = base.send_receive('clientinfo clid=' + clid) + parsed = ts3tools.parse_raw_answer(query) + return parsed + + def client_add_servergroup(self, sgid, cldbid): + query = base.send_receive('servergroupaddclient sgid=' + sgid + ' cldbid=' + cldbid) + parsed = ts3tools.parse_raw_answer(query) + return parsed + + def client_del_servergroup(self, sgid, cldbid): + query = base.send_receive('servergroupdelclient sgid=' + sgid + ' cldbid=' + cldbid) + parsed = ts3tools.parse_raw_answer(query) + return parsed diff --git a/pool/shard007/Python/0071323_test_utils.py b/pool/shard007/Python/0071323_test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8fa6fd8c1747e263c109fc1eeff0566b1453d150 --- /dev/null +++ b/pool/shard007/Python/0071323_test_utils.py @@ -0,0 +1,140 @@ +import numpy as np +from nose.tools import raises, eq_ +import shutil +import os +from hyperopt.utils import fast_isin +from hyperopt.utils import get_most_recent_inds +from hyperopt.utils import temp_dir, working_dir, get_closest_dir, path_split_all + + +def test_fast_isin(): + Y = np.random.randint(0, 10000, size=(100, )) + X = np.arange(10000) + Z = fast_isin(X, Y) + D = np.unique(Y) + D.sort() + T1 = (X[Z] == D).all() + + X = np.array(range(10000) + range(10000)) + Z = fast_isin(X, Y) + T2 = (X[Z] == np.append(D, D.copy())).all() + + X = np.random.randint(0, 100, size = (40, )) + X.sort() + Y = np.random.randint(0, 100, size = (60, )) + Y.sort() + + XinY = np.array([ind for ind in range(len(X)) if X[ind] in Y]) + YinX = np.array([ind for ind in range(len(Y)) if Y[ind] in X]) + + T3 = (fast_isin(X, Y).nonzero()[0] == XinY).all() + T4 = (fast_isin(Y, X).nonzero()[0] == YinX).all() + + assert T1 & T2 & T3 & T4 + + +def test_get_most_recent_inds(): + test_data = [] + most_recent_data = [] + for ind in range(300): + k = np.random.randint(1,6) + for _ind in range(k): + test_data.append({'_id': ind, 'version':_ind}) + most_recent_data.append({'_id': ind, 'version': _ind}) + rng = np.random.RandomState(0) + p = rng.permutation(len(test_data)) + test_data_rearranged = [test_data[_p] for _p in p] + rind = get_most_recent_inds(test_data_rearranged) + test_data_rearranged_most_recent = [test_data_rearranged[idx] for idx in rind] + assert all([t in most_recent_data for t in test_data_rearranged_most_recent]) + assert len(test_data_rearranged_most_recent) == len(most_recent_data) + + test_data = [{'_id':0, 'version':1}] + + assert get_most_recent_inds(test_data).tolist() == [0] + + test_data = [{'_id':0, 'version':1}, {'_id':0, 'version':2}] + assert get_most_recent_inds(test_data).tolist() == [1] + + test_data = [{'_id':0, 'version':1}, {'_id':0, 'version':2}, + {'_id':1, 'version':1}] + + assert get_most_recent_inds(test_data).tolist() == [1, 2] + + test_data = [{'_id': -1, 'version':1}, {'_id':0, 'version':1}, + {'_id':0, 'version':2}, {'_id':1, 'version':1}] + + assert get_most_recent_inds(test_data).tolist() == [0, 2, 3] + + test_data = [{'_id': -1, 'version':1}, {'_id':0, 'version':1}, + {'_id':0, 'version':2}, {'_id':0, 'version':2}] + + assert get_most_recent_inds(test_data).tolist() == [0, 3] + +@raises(RuntimeError) +def test_temp_dir_pardir(): + with temp_dir("../test_temp_dir"): + pass + +def test_temp_dir(): + fn = "test_temp_dir" + if os.path.exists(fn): + print "Path %s exists, not running test_temp_dir()" % fn + return + try: + assert not os.path.exists(fn) + with temp_dir(fn): + assert os.path.exists(fn) + assert os.path.exists(fn) + os.rmdir(fn) + + assert not os.path.exists(fn) + with temp_dir(fn, erase_after=True): + assert os.path.exists(fn) + assert not os.path.exists(fn) + finally: + if os.path.isdir(fn): + os.rmdir(fn) + +def test_path_split_all(): + ll = "foo bar baz".split() + path = os.path.join(*ll) + eq_(list(path_split_all(path)), ll) + +def test_temp_dir_sentinel(): + from os.path import join, isdir, exists, abspath + basedir = "test_temp_dir_sentinel" + fn = join(basedir, "foo", "bar") + if exists(basedir): + print "Path %s exists, not running test_temp_dir_sentinel()" % basedir + return + os.makedirs(basedir) + eq_(get_closest_dir(fn)[0], basedir) + eq_(get_closest_dir(fn)[1], "foo") + sentinel = join(basedir, "foo.inuse") + try: + with temp_dir(fn, erase_after=True, with_sentinel=True): + assert isdir(fn) + assert exists(sentinel) + # simulate work + open(join(fn, "dummy.txt"), "w").close() + # work file should be deleted together with directory + assert not exists(fn) + assert not exists(join(basedir, "foo")) + # basedir should still exist, though! + assert isdir(basedir) + finally: + if isdir(basedir): + shutil.rmtree(basedir) + +def test_workdir(): + fn = "test_work_dir" + os.makedirs(fn) + try: + assert fn not in os.getcwd() + with working_dir(fn): + assert fn in os.getcwd() + assert fn not in os.getcwd() + finally: + if os.path.isdir(fn): + os.rmdir(fn) diff --git a/pool/shard007/Python/0071324_tsv.py b/pool/shard007/Python/0071324_tsv.py new file mode 100644 index 0000000000000000000000000000000000000000..3b8303e83f9e369edfc77f1dc902cc0303559a4c --- /dev/null +++ b/pool/shard007/Python/0071324_tsv.py @@ -0,0 +1,30 @@ +import sys + + +# Like 'import json' / 'import yaml', except.. tab data. +def loads(str_data): + return NotImplementedError() + + +def load(handle): + return NotImplementedError() + + +def dump(data, handle=sys.stdout): + for row in data: + handle.write("%s\n" % "\t".join(map(str, row))) + + +def dumps(data): + output = "" + for row in data: + output += "%s\n" % "\t".join(map(str, row)) + return output + + +def dump_line(row, handle=sys.stdout): + dump([row], handle=handle) + + +def dumps_line(row): + return dumps([row]) diff --git a/pool/shard007/Python/0071326_emails.py b/pool/shard007/Python/0071326_emails.py new file mode 100644 index 0000000000000000000000000000000000000000..3bd0f6cf02dc13546cf901319c5b29ca3c4c6013 --- /dev/null +++ b/pool/shard007/Python/0071326_emails.py @@ -0,0 +1,13 @@ +from django.contrib.sites.models import Site +from django.templatetags.static import static + +from ..core.utils import build_absolute_uri + + +def get_email_base_context(): + site = Site.objects.get_current() + logo_url = build_absolute_uri(static('images/logo-light.svg')) + return { + 'domain': site.domain, + 'logo_url': logo_url, + 'site_name': site.name} diff --git a/pool/shard007/Python/0071328_stock_ageing.py b/pool/shard007/Python/0071328_stock_ageing.py new file mode 100644 index 0000000000000000000000000000000000000000..d8a8dc72ea7bebb0451fa5c5cffd1107c1297aae --- /dev/null +++ b/pool/shard007/Python/0071328_stock_ageing.py @@ -0,0 +1,94 @@ +# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors +# License: GNU General Public License v3. See license.txt + +from __future__ import unicode_literals +import frappe +from frappe.utils import date_diff + +def execute(filters=None): + + columns = get_columns() + item_details = get_fifo_queue(filters) + to_date = filters["to_date"] + data = [] + for item, item_dict in item_details.items(): + fifo_queue = item_dict["fifo_queue"] + details = item_dict["details"] + if not fifo_queue: continue + + average_age = get_average_age(fifo_queue, to_date) + earliest_age = date_diff(to_date, fifo_queue[0][1]) + latest_age = date_diff(to_date, fifo_queue[-1][1]) + + data.append([item, details.item_name, details.description, details.item_group, + details.brand, average_age, earliest_age, latest_age, details.stock_uom]) + + return columns, data + +def get_average_age(fifo_queue, to_date): + batch_age = age_qty = total_qty = 0.0 + for batch in fifo_queue: + batch_age = date_diff(to_date, batch[1]) + age_qty += batch_age * batch[0] + total_qty += batch[0] + + return (age_qty / total_qty) if total_qty else 0.0 + +def get_columns(): + return ["Item Code:Link/Item:100", "Item Name::100", "Description::200", + "Item Group:Link/Item Group:100", "Brand:Link/Brand:100", "Average Age:Float:100", + "Earliest:Int:80", "Latest:Int:80", "UOM:Link/UOM:100"] + +def get_fifo_queue(filters): + item_details = {} + for d in get_stock_ledger_entries(filters): + item_details.setdefault(d.name, {"details": d, "fifo_queue": []}) + fifo_queue = item_details[d.name]["fifo_queue"] + if d.actual_qty > 0: + fifo_queue.append([d.actual_qty, d.posting_date]) + else: + qty_to_pop = abs(d.actual_qty) + while qty_to_pop: + batch = fifo_queue[0] if fifo_queue else [0, None] + if 0 < batch[0] <= qty_to_pop: + # if batch qty > 0 + # not enough or exactly same qty in current batch, clear batch + qty_to_pop -= batch[0] + fifo_queue.pop(0) + else: + # all from current batch + batch[0] -= qty_to_pop + qty_to_pop = 0 + + return item_details + +def get_stock_ledger_entries(filters): + return frappe.db.sql("""select + item.name, item.item_name, item_group, brand, description, item.stock_uom, + actual_qty, posting_date + from `tabStock Ledger Entry` sle, + (select name, item_name, description, stock_uom, brand, item_group + from `tabItem` {item_conditions}) item + where item_code = item.name and + company = %(company)s and + posting_date <= %(to_date)s + {sle_conditions} + order by posting_date, posting_time, sle.name"""\ + .format(item_conditions=get_item_conditions(filters), + sle_conditions=get_sle_conditions(filters)), filters, as_dict=True) + +def get_item_conditions(filters): + conditions = [] + if filters.get("item_code"): + conditions.append("item_code=%(item_code)s") + if filters.get("brand"): + conditions.append("brand=%(brand)s") + + return "where {}".format(" and ".join(conditions)) if conditions else "" + +def get_sle_conditions(filters): + conditions = [] + if filters.get("warehouse"): + conditions.append("warehouse=%(warehouse)s") + + return "and {}".format(" and ".join(conditions)) if conditions else "" \ No newline at end of file diff --git a/pool/shard007/Python/0071331_test_replay_state.py b/pool/shard007/Python/0071331_test_replay_state.py new file mode 100644 index 0000000000000000000000000000000000000000..178c249e1d304275ea0b8e20d690a3cd73468546 --- /dev/null +++ b/pool/shard007/Python/0071331_test_replay_state.py @@ -0,0 +1,58 @@ +"""Tests for the data module.""" + +from datetime import datetime +import os +import mock +import shutil + +import pytest + + +@pytest.fixture +def zip_path(): + return os.path.join("tests", "datasets", "test_export.zip") + + +@pytest.mark.slow +class TestReplayState(object): + @pytest.fixture + def cleanup(self): + yield + shutil.rmtree("data") + + @pytest.fixture + def experiment(self): + from dlgr.demos.bartlett1932.experiment import Bartlett1932 + + yield Bartlett1932() + + bartlett_export = os.path.join("tests", "datasets", "bartlett_bots.zip") + + @pytest.fixture + def scrubber(self, experiment, db_session): + with experiment.restore_state_from_replay( + "bartlett-test", session=db_session, zip_path=self.bartlett_export + ) as scrubber: + yield scrubber + + def test_scrub_forwards(self, scrubber): + target = datetime(2017, 6, 23, 12, 0, 29, 941148) + with mock.patch( + "dlgr.demos.bartlett1932.experiment.Bartlett1932.replay_event" + ) as replay_event: + replay_event.assert_not_called() + scrubber(target) + assert replay_event.call_count == 4 + scrubber(datetime.now()) + assert replay_event.call_count == 5 + + def test_cannot_scrub_backwards(self, scrubber): + target = datetime(2017, 6, 23, 12, 0, 29, 941148) + with mock.patch( + "dlgr.demos.bartlett1932.experiment.Bartlett1932.replay_event" + ) as replay_event: + replay_event.assert_not_called() + scrubber(datetime.now()) + assert replay_event.call_count == 5 + with pytest.raises(NotImplementedError): + scrubber(target) diff --git a/pool/shard007/Python/0071336_tenants.py b/pool/shard007/Python/0071336_tenants.py new file mode 100644 index 0000000000000000000000000000000000000000..7b5bac15587bfa80acaf589498184d4d53bfe3c5 --- /dev/null +++ b/pool/shard007/Python/0071336_tenants.py @@ -0,0 +1,47 @@ +# COPYRIGHT 2014 Rackspace +# +# Author: Betsy Luzader +# +# 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. + +import pecan + +from designate.openstack.common import log as logging +from designate.api.v2.controllers import rest +from designate.api.v2.views.extensions import reports as reports_view + +LOG = logging.getLogger(__name__) + + +class TenantsController(rest.RestController): + + _view = reports_view.TenantsView() + + @pecan.expose(template='json:', content_type='application/json') + def get_all(self): + request = pecan.request + context = pecan.request.environ['context'] + + tenants = self.central_api.find_tenants(context) + + return self._view.list(context, request, tenants) + + @pecan.expose(template='json:', content_type='application/json') + def get_one(self, tenant_id): + """Get Tenant""" + request = pecan.request + context = request.environ['context'] + + tenant = self.central_api.get_tenant(context, tenant_id) + + return self._view.show_detail(context, request, tenant) diff --git a/pool/shard007/Python/0071339_big_table_count.py b/pool/shard007/Python/0071339_big_table_count.py new file mode 100644 index 0000000000000000000000000000000000000000..b3cdc30947223a4f80a6d16d283e3d7e5297305f --- /dev/null +++ b/pool/shard007/Python/0071339_big_table_count.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- + + +def execute_rule(**kwargs): + username = kwargs.get("username") + db_cursor = kwargs.get("db_cursor") + tab_phy_size = kwargs.get("tab_phy_size") + weight = kwargs.get("weight") + max_score = kwargs.get("max_score") + sql = """ + SELECT count(*) + FROM + (SELECT segment_name, + u.segment_type, + sum(bytes) / 1024 / 1024 AS tab_space + FROM dba_segments u + WHERE u.segment_type IN ('TABLE', + 'TABLE PARTITION', + 'TABLE SUBPARTITION') + AND u.owner = '@username@' + AND u.segment_name NOT LIKE '%BIN%' + GROUP BY u.owner, + u.segment_name, + u.segment_type) + WHERE tab_space >= @tab_phy_size@ + """ + sql = sql.replace("@username@", username).\ + replace("@tab_phy_size@", str(tab_phy_size)) + db_cursor.execute(sql) + records1 = db_cursor.fetchall() + sql = """ + SELECT count(*) + FROM dba_objects t + WHERE t.owner='@username@' + AND t.object_type='TABLE' + """ + db_cursor.execute(sql.replace("@username@", username)) + records2 = db_cursor.fetchall() + + try: + ratio = float("%0.2f" % float(records1[0][0] / records2[0][0])) + except ZeroDivisionError: + ratio = 0 + if ratio >= float(weight): + scores = max_score + else: + scores = 0 + + if scores > 0: + return [[records1[0][0], records2[0][0], ratio]], scores + else: + return [], 0 diff --git a/pool/shard007/Python/0071343_api.py b/pool/shard007/Python/0071343_api.py new file mode 100644 index 0000000000000000000000000000000000000000..804d9dadf2966b2d06aab65c5debb7e9ca9ac659 --- /dev/null +++ b/pool/shard007/Python/0071343_api.py @@ -0,0 +1,156 @@ +import copy + +import requests + +from . import responses +from .exceptions import ResponseError, ShipwireError, TimeoutError + +""" Add or remove methods and API calls here. """ +METHODS = { + 'order': { + 'create': ['POST', 'orders'], + 'get': ['GET', 'orders', ''], + 'modify': ['PUT', 'orders', ''], + 'cancel': ['POST', 'orders', '/cancel'], + 'holds': ['GET', 'orders', '/holds'], + 'clear_holds': ['POST', 'orders', '/holds/clear'], + 'items': ['GET', 'orders', '/items'], + 'returns': ['GET', 'orders', '/returns'], + 'trackings': ['GET', 'orders', '/trackings'], + 'list': ['GET', 'orders'], + 'split_orders': ['GET', 'orders', '/splitOrders'], + }, + 'orders': { + 'list': ['GET', 'orders'] + }, + 'stock': { + 'products': ['GET', 'stock'] + }, + 'rate': { + 'quote': ['POST', 'rate'] + }, + 'receiving': { + 'list': ['GET', 'receivings'], + 'create': ['POST', 'receivings'], + 'get': ['GET', 'receivings', ''], + 'modify': ['PUT', 'receivings', ''], + 'cancel': ['POST', 'receivings', '/cancel'], + 'cancel_labels': ['POST', 'receivings', '/labels/cancel'], + 'holds': ['GET', 'receivings', '/holds'], + 'instructions_recipients': ['GET', 'receivings', + '/instructionsRecipients'], + 'items': ['GET', 'receivings', '/items'], + 'shipments': ['GET', 'receivings', '/shipments'], + 'trackings': ['GET', 'receivings', '/trackings'], + 'labels': ['GET', 'receivings', '/labels'], + }, + 'returns': { + 'list': ['GET', 'returns'], + 'create': ['POST', 'returns'], + 'get': ['GET', 'returns', ''], + 'cancel': ['POST', 'returns', '/cancel'], + 'holds': ['GET', 'returns', '/holds'], + 'items': ['GET', 'returns', '/items'], + 'trackings': ['GET', 'returns', '/trackings'], + 'labels': ['GET', 'returns', '/labels'], + }, + 'webhooks': { + 'list': ['GET', 'webhooks'], + 'create': ['POST', 'webhooks'], + 'get': ['GET', 'webhooks', ''], + 'modify': ['PUT', 'webhooks', ''], + 'delete': ['DELETE', 'webhooks', ''] + }, + 'secrets': { + 'list': ['GET', 'secret'], + 'create': ['POST', 'secret'], + 'get': ['GET', 'secret', ''], + 'delete': ['DELETE', 'secret', ''] + } +} + + +class Shipwire(): + """ Shipwire API class.""" + def __init__(self, username='neil@example.com', password='your-password', + host='api.shipwire.com', api_version=3, secure=True, + raise_on_errors=False, timeout=None, **kwargs): + self.host = host + self.api_version = api_version + self.auth = requests.auth.HTTPBasicAuth(username, password) + self.secure = secure + self.resource = False + self.method = False + self.call_params = False + self.json = '' + self.uri = '' + self.raise_on_errors = raise_on_errors + self.timeout = timeout + + def __getattr__(self, name): + if name.startswith('__') or self.method: + """ can't chain another attribute after the method and + when __ the copying causes recurssion. """ + raise AttributeError(name) + elif self.resource: + if name in list(METHODS[self.resource].keys()): + self.method = name + else: + raise ShipwireError('The \'%s\' attribute is not currently defined.' + % name) + else: # since self.resource and method_call_dict are empty this must be resource. + if name in METHODS: + self.resource = name + else: + raise ShipwireError('The \'%s\' resource is not currently defined.' + % name) + new_instance = copy.copy(self) + self.resource = self.method = False + return new_instance + + def __call__(self, *args, **kwargs): + if self.method is False: # only run calls on methods, not resources. + raise ShipwireError('Parameters can only be passed to specific methods.') + if 'json' in kwargs: + self.json = kwargs.pop('json') + self.call_params = kwargs + return self._call_api() + + def _call_api(self): + self.uri = uri = self._make_uri() + endpoint = METHODS[self.resource][self.method] + http_method = endpoint[0] + + try: + res = requests.request(http_method, uri, auth=self.auth, + params=self.call_params, + json=self.json, timeout=self.timeout) + except requests.exceptions.Timeout as exc: + raise TimeoutError(exc) + + if res.status_code >= 400 and self.raise_on_errors: + raise ResponseError(res) + + # wrap response is response classes. + return getattr(responses, self._class_name())(res, self) + + def _class_name(self): + return '%sResponse' % self.method.capitalize() + + def _make_uri(self): + endpoint = METHODS[self.resource][self.method] + number_words = len(endpoint) + protocol = 'https' if self.secure else 'http' + resource = endpoint[1] + base = "%s://%s/api/v%s" % (protocol, self.host, + self.api_version) + if number_words == 2: #ex: ['GET', 'orders'] + uri = "%s/%s" % (base, resource) + elif number_words == 3: #ex: ['GET', 'orders', 'returns'] + if 'id' not in self.call_params: + raise ShipwireError('An \'id\' is required for this api call.') + method = endpoint[2] + uri = "%s/%s/%s%s" % (base, resource, + self.call_params.get('id'), + method) + return uri diff --git a/pool/shard008/C/0129377_pb_language_preference_msg.c b/pool/shard008/C/0129377_pb_language_preference_msg.c new file mode 100644 index 0000000000000000000000000000000000000000..1a288abb5ca8efdcdf8cbac638134de86b129c70 --- /dev/null +++ b/pool/shard008/C/0129377_pb_language_preference_msg.c @@ -0,0 +1,179 @@ +/* + * Copyright (C) 2010 Sansar Choinyambuu + * HSR Hochschule fuer Technik Rapperswil + * + * 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. See . + * + * 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. + */ + +#include "pb_language_preference_msg.h" + +#include +#include +#include + +typedef struct private_pb_language_preference_msg_t private_pb_language_preference_msg_t; + +/** + * PB-Language-Preference message (see section 4.10 of RFC 5793) + * + * 0 1 2 3 + * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Language Preference (Variable Length) | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + */ + +#define PB_LANG_PREFIX "Accept-Language: " +#define PB_LANG_PREFIX_LEN strlen(PB_LANG_PREFIX) + +/** + * Private data of a pb_language_preference_msg_t object. + * + */ +struct private_pb_language_preference_msg_t { + /** + * Public pb_access_recommendation_msg_t interface. + */ + pb_language_preference_msg_t public; + + /** + * PB-TNC message type + */ + pen_type_t type; + + /** + * Language preference + */ + chunk_t language_preference; + + /** + * Encoded message + */ + chunk_t encoding; +}; + +METHOD(pb_tnc_msg_t, get_type, pen_type_t, + private_pb_language_preference_msg_t *this) +{ + return this->type; +} + +METHOD(pb_tnc_msg_t, get_encoding, chunk_t, + private_pb_language_preference_msg_t *this) +{ + return this->encoding; +} + +METHOD(pb_tnc_msg_t, build, void, + private_pb_language_preference_msg_t *this) +{ + if (this->encoding.ptr) + { + return; + } + this->encoding = chunk_cat("cc", + chunk_create(PB_LANG_PREFIX, PB_LANG_PREFIX_LEN), + this->language_preference); +} + +METHOD(pb_tnc_msg_t, process, status_t, + private_pb_language_preference_msg_t *this, uint32_t *offset) +{ + chunk_t lang; + + if (this->encoding.len >= PB_LANG_PREFIX_LEN && + memeq(this->encoding.ptr, PB_LANG_PREFIX, PB_LANG_PREFIX_LEN)) + { + lang = chunk_skip(this->encoding, PB_LANG_PREFIX_LEN); + this->language_preference = lang.len ? chunk_clone(lang) : chunk_empty; + } + else + { + DBG1(DBG_TNC, "language preference must be preceded by '%s'", + PB_LANG_PREFIX); + *offset = 0; + return FAILED; + } + + if (this->language_preference.len && + this->language_preference.ptr[this->language_preference.len-1] == '\0') + { + DBG1(DBG_TNC, "language preference must not be null terminated"); + *offset = PB_LANG_PREFIX_LEN + this->language_preference.len - 1; + return FAILED; + } + + return SUCCESS; +} + +METHOD(pb_tnc_msg_t, destroy, void, + private_pb_language_preference_msg_t *this) +{ + free(this->encoding.ptr); + free(this->language_preference.ptr); + free(this); +} + +METHOD(pb_language_preference_msg_t, get_language_preference, chunk_t, + private_pb_language_preference_msg_t *this) +{ + return this->language_preference; +} + +/** + * See header + */ +pb_tnc_msg_t *pb_language_preference_msg_create_from_data(chunk_t data) +{ + private_pb_language_preference_msg_t *this; + + INIT(this, + .public = { + .pb_interface = { + .get_type = _get_type, + .get_encoding = _get_encoding, + .build = _build, + .process = _process, + .destroy = _destroy, + }, + .get_language_preference = _get_language_preference, + }, + .type = { PEN_IETF, PB_MSG_LANGUAGE_PREFERENCE }, + .encoding = chunk_clone(data), + ); + + return &this->public.pb_interface; +} + +/** + * See header + */ +pb_tnc_msg_t *pb_language_preference_msg_create(chunk_t language_preference) +{ + private_pb_language_preference_msg_t *this; + + INIT(this, + .public = { + .pb_interface = { + .get_type = _get_type, + .get_encoding = _get_encoding, + .build = _build, + .process = _process, + .destroy = _destroy, + }, + .get_language_preference = _get_language_preference, + }, + .type = { PEN_IETF, PB_MSG_LANGUAGE_PREFERENCE }, + .language_preference = chunk_clone(language_preference), + ); + + return &this->public.pb_interface; +} diff --git a/pool/shard008/C/0129379_amp_thread_local_slot_pthreads.c b/pool/shard008/C/0129379_amp_thread_local_slot_pthreads.c new file mode 100644 index 0000000000000000000000000000000000000000..ce0801d59b53f94c420541fad3df56701f5a77c7 --- /dev/null +++ b/pool/shard008/C/0129379_amp_thread_local_slot_pthreads.c @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2009-2010, Bjoern Knafla + * http://www.bjoernknafla.com/ + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Bjoern Knafla + * Parallelization + AI + Gamedev Consulting nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * @file + * + * Shallow wrapper around Pthreads thread-specific data. + */ + + + +#include "amp_raw_thread_local_slot.h" + + +#include +#include +#include + +#include "amp_stddef.h" +#include "amp_return_code.h" + + + +int amp_raw_thread_local_slot_init(amp_thread_local_slot_key_t key) +{ + assert(NULL != key); + + int retval = pthread_key_create(&(key->key), NULL); + switch (retval) { + case 0: + /* retval already equals AMP_SUCCESS */ + break; + case ENOMEM: + /* retval already equals AMP_NOMEM */ + break; + case EAGAIN: + retval = AMP_ERROR; + break; + default: + assert(0); /* Programming error */ + retval = AMP_ERROR; + } + + return retval; +} + + + +int amp_raw_thread_local_slot_finalize(amp_thread_local_slot_key_t key) +{ + int retval = pthread_key_delete(key->key); + if (0 != retval) { + assert(0); /* Programming error */ + retval = AMP_ERROR; + } + + return retval; +} + + + +int amp_thread_local_slot_set_value(amp_thread_local_slot_key_t key, + void *value) +{ + int retval = pthread_setspecific(key->key, value); + switch (retval) { + case 0: + /* retval already equals AMP_SUCCESS */ + break; + case ENOMEM: + /* retval already equals AMP_NOMEM */ + break; + default: /* EINVAL - programming error */ + assert(0); + retval = AMP_ERROR; + } + + return retval; +} + + + +void* amp_thread_local_slot_value(amp_thread_local_slot_key_t key) +{ + /** + * TODO: @todo Add a debug status flag to check if a key has been + * initialized correctly. + */ + return pthread_getspecific(key->key); +} + + diff --git a/pool/shard008/C/0129380_board_setup.c b/pool/shard008/C/0129380_board_setup.c new file mode 100644 index 0000000000000000000000000000000000000000..a9f0336e1f1fd626cca60c57748c1430be64c8f4 --- /dev/null +++ b/pool/shard008/C/0129380_board_setup.c @@ -0,0 +1,138 @@ +/* + * + * BRIEF MODULE DESCRIPTION + * 4G Systems MTX-1 board setup. + * + * Copyright 2003, 2008 MontaVista Software Inc. + * Author: MontaVista Software, Inc. + * Bruno Randolf + * + * 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 SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN + * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * 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., + * 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include +#include + +#include +#include + +#include + +char irq_tab_alchemy[][5] __initdata = { + [0] = { -1, AU1500_PCI_INTA, AU1500_PCI_INTA, 0xff, 0xff }, /* IDSEL 00 - AdapterA-Slot0 (top) */ + [1] = { -1, AU1500_PCI_INTB, AU1500_PCI_INTA, 0xff, 0xff }, /* IDSEL 01 - AdapterA-Slot1 (bottom) */ + [2] = { -1, AU1500_PCI_INTC, AU1500_PCI_INTD, 0xff, 0xff }, /* IDSEL 02 - AdapterB-Slot0 (top) */ + [3] = { -1, AU1500_PCI_INTD, AU1500_PCI_INTC, 0xff, 0xff }, /* IDSEL 03 - AdapterB-Slot1 (bottom) */ + [4] = { -1, AU1500_PCI_INTA, AU1500_PCI_INTB, 0xff, 0xff }, /* IDSEL 04 - AdapterC-Slot0 (top) */ + [5] = { -1, AU1500_PCI_INTB, AU1500_PCI_INTA, 0xff, 0xff }, /* IDSEL 05 - AdapterC-Slot1 (bottom) */ + [6] = { -1, AU1500_PCI_INTC, AU1500_PCI_INTD, 0xff, 0xff }, /* IDSEL 06 - AdapterD-Slot0 (top) */ + [7] = { -1, AU1500_PCI_INTD, AU1500_PCI_INTC, 0xff, 0xff }, /* IDSEL 07 - AdapterD-Slot1 (bottom) */ +}; + +extern int (*board_pci_idsel)(unsigned int devsel, int assert); +int mtx1_pci_idsel(unsigned int devsel, int assert); + +static void mtx1_reset(char *c) +{ + /* Hit BCSR.SYSTEM_CONTROL[SW_RST] */ + au_writel(0x00000000, 0xAE00001C); +} + +static void mtx1_power_off(void) +{ + printk(KERN_ALERT "It's now safe to remove power\n"); + while (1) + asm volatile (".set mips3 ; wait ; .set mips1"); +} + +void __init board_setup(void) +{ + alchemy_gpio2_enable(); + +#if defined(CONFIG_USB_OHCI_HCD) || defined(CONFIG_USB_OHCI_HCD_MODULE) + /* Enable USB power switch */ + alchemy_gpio_direction_output(204, 0); +#endif /* defined(CONFIG_USB_OHCI_HCD) || defined(CONFIG_USB_OHCI_HCD_MODULE) */ + +#ifdef CONFIG_PCI +#if defined(__MIPSEB__) + au_writel(0xf | (2 << 6) | (1 << 4), Au1500_PCI_CFG); +#else + au_writel(0xf, Au1500_PCI_CFG); +#endif + board_pci_idsel = mtx1_pci_idsel; +#endif + + /* Initialize sys_pinfunc */ + au_writel(SYS_PF_NI2, SYS_PINFUNC); + + /* Initialize GPIO */ + au_writel(0xFFFFFFFF, SYS_TRIOUTCLR); + alchemy_gpio_direction_output(0, 0); /* Disable M66EN (PCI 66MHz) */ + alchemy_gpio_direction_output(3, 1); /* Disable PCI CLKRUN# */ + alchemy_gpio_direction_output(1, 1); /* Enable EXT_IO3 */ + alchemy_gpio_direction_output(5, 0); /* Disable eth PHY TX_ER */ + + /* Enable LED and set it to green */ + alchemy_gpio_direction_output(211, 1); /* green on */ + alchemy_gpio_direction_output(212, 0); /* red off */ + + pm_power_off = mtx1_power_off; + _machine_halt = mtx1_power_off; + _machine_restart = mtx1_reset; + + printk(KERN_INFO "4G Systems MTX-1 Board\n"); +} + +int +mtx1_pci_idsel(unsigned int devsel, int assert) +{ +#define MTX_IDSEL_ONLY_0_AND_3 0 +#if MTX_IDSEL_ONLY_0_AND_3 + if (devsel != 0 && devsel != 3) { + printk(KERN_ERR "*** not 0 or 3\n"); + return 0; + } +#endif + + if (assert && devsel != 0) + /* Suppress signal to Cardbus */ + gpio_set_value(1, 0); /* set EXT_IO3 OFF */ + else + gpio_set_value(1, 1); /* set EXT_IO3 ON */ + + au_sync_udelay(1); + return 1; +} + +static int __init mtx1_init_irq(void) +{ + set_irq_type(AU1500_GPIO204_INT, IRQF_TRIGGER_HIGH); + set_irq_type(AU1500_GPIO201_INT, IRQF_TRIGGER_LOW); + set_irq_type(AU1500_GPIO202_INT, IRQF_TRIGGER_LOW); + set_irq_type(AU1500_GPIO203_INT, IRQF_TRIGGER_LOW); + set_irq_type(AU1500_GPIO205_INT, IRQF_TRIGGER_LOW); + + return 0; +} +arch_initcall(mtx1_init_irq); diff --git a/pool/shard008/C/0129382_acl_entries.c b/pool/shard008/C/0129382_acl_entries.c new file mode 100644 index 0000000000000000000000000000000000000000..9fc9cf51697c4214f24739627fc59b22c9a0e4ce --- /dev/null +++ b/pool/shard008/C/0129382_acl_entries.c @@ -0,0 +1,75 @@ +/* Return the number of entries in an ACL. + + Copyright (C) 2002-2003, 2005-2016 Free Software Foundation, Inc. + + 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 . + + Written by Paul Eggert and Andreas Gruenbacher. */ + +#include + +#include "acl-internal.h" + +/* This file assumes POSIX-draft like ACLs + (Linux, FreeBSD, Mac OS X, IRIX, Tru64). */ + +/* Return the number of entries in ACL. + Return -1 and set errno upon failure to determine it. */ + +int +acl_entries (acl_t acl) +{ + int count = 0; + + if (acl != NULL) + { +#if HAVE_ACL_FIRST_ENTRY /* Linux, FreeBSD, Mac OS X */ +# if HAVE_ACL_TYPE_EXTENDED /* Mac OS X */ + /* acl_get_entry returns 0 when it successfully fetches an entry, + and -1/EINVAL at the end. */ + acl_entry_t ace; + int got_one; + + for (got_one = acl_get_entry (acl, ACL_FIRST_ENTRY, &ace); + got_one >= 0; + got_one = acl_get_entry (acl, ACL_NEXT_ENTRY, &ace)) + count++; +# else /* Linux, FreeBSD */ + /* acl_get_entry returns 1 when it successfully fetches an entry, + and 0 at the end. */ + acl_entry_t ace; + int got_one; + + for (got_one = acl_get_entry (acl, ACL_FIRST_ENTRY, &ace); + got_one > 0; + got_one = acl_get_entry (acl, ACL_NEXT_ENTRY, &ace)) + count++; + if (got_one < 0) + return -1; +# endif +#else /* IRIX, Tru64 */ +# if HAVE_ACL_TO_SHORT_TEXT /* IRIX */ + /* Don't use acl_get_entry: it is undocumented. */ + count = acl->acl_cnt; +# endif +# if HAVE_ACL_FREE_TEXT /* Tru64 */ + /* Don't use acl_get_entry: it takes only one argument and does not + work. */ + count = acl->acl_num; +# endif +#endif + } + + return count; +} diff --git a/pool/shard008/C/0129383_spi_lld.c b/pool/shard008/C/0129383_spi_lld.c new file mode 100644 index 0000000000000000000000000000000000000000..8e717355acbeb52d2baae45e51a01163d54be5d0 --- /dev/null +++ b/pool/shard008/C/0129383_spi_lld.c @@ -0,0 +1,337 @@ +/* + ChibiOS - Copyright (C) 2006..2016 Giovanni Di Sirio + + 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. +*/ + +/** + * @file LPC214x/spi_lld.c + * @brief LPC214x low level SPI driver code. + * + * @addtogroup SPI + * @{ + */ + +#include "hal.h" + +#if HAL_USE_SPI || defined(__DOXYGEN__) + +/*===========================================================================*/ +/* Driver exported variables. */ +/*===========================================================================*/ + +#if LPC214x_SPI_USE_SSP || defined(__DOXYGEN__) +/** @brief SPI1 driver identifier.*/ +SPIDriver SPID1; +#endif + +/*===========================================================================*/ +/* Driver local variables and types. */ +/*===========================================================================*/ + +/*===========================================================================*/ +/* Driver local functions. */ +/*===========================================================================*/ + +/** + * @brief Preloads the transmit FIFO. + * + * @param[in] spip pointer to the @p SPIDriver object + */ +static void ssp_fifo_preload(SPIDriver *spip) { + SSP *ssp = spip->ssp; + uint32_t n = spip->txcnt > LPC214x_SSP_FIFO_DEPTH ? + LPC214x_SSP_FIFO_DEPTH : spip->txcnt; + + while(((ssp->SSP_SR & SR_TNF) != 0) && (n > 0)) { + if (spip->txptr != NULL) { + if ((ssp->SSP_CR0 & CR0_DSSMASK) > CR0_DSS8BIT) + ssp->SSP_DR = *(uint16_t *)spip->txptr++; + else + ssp->SSP_DR = *(uint8_t *)spip->txptr++; + } + else + ssp->SSP_DR = 0xFFFFFFFF; + n--; + spip->txcnt--; + } +} + +#if defined(__GNUC__) +__attribute__((noinline)) +#endif +/** + * @brief Common IRQ handler. + * + * @param[in] spip pointer to the @p SPIDriver object + */ +static void serve_interrupt(SPIDriver *spip) { + SSP *ssp = spip->ssp; + + if ((ssp->SSP_MIS & MIS_ROR) != 0) { + /* The overflow condition should never happen because priority is given + to receive but a hook macro is provided anyway...*/ + LPC214x_SPI_SSP_ERROR_HOOK(); + } + ssp->SSP_ICR = ICR_RT | ICR_ROR; + while ((ssp->SSP_SR & SR_RNE) != 0) { + if (spip->rxptr != NULL) { + if ((ssp->SSP_CR0 & CR0_DSSMASK) > CR0_DSS8BIT) + *(uint16_t *)spip->rxptr++ = ssp->SSP_DR; + else + *(uint8_t *)spip->rxptr++ = ssp->SSP_DR; + } + else + (void)ssp->SSP_DR; + if (--spip->rxcnt == 0) { + osalDbgAssert(spip->txcnt == 0, "counter out of synch"); + /* Stops the IRQ sources.*/ + ssp->SSP_IMSC = 0; + /* Portable SPI ISR code defined in the high level driver, note, it is + a macro.*/ + _spi_isr_code(spip); + return; + } + } + ssp_fifo_preload(spip); + if (spip->txcnt == 0) + ssp->SSP_IMSC = IMSC_ROR | IMSC_RT | IMSC_RX; +} + +/*===========================================================================*/ +/* Driver interrupt handlers. */ +/*===========================================================================*/ + +#if LPC214x_SPI_USE_SSP || defined(__DOXYGEN__) +/** + * @brief SPI1 interrupt handler. + * + * @isr + */ +CH_IRQ_HANDLER(SPI1IrqHandler) { + + CH_IRQ_PROLOGUE(); + + serve_interrupt(&SPID1); + VICVectAddr = 0; + + CH_IRQ_EPILOGUE(); +} +#endif + +/*===========================================================================*/ +/* Driver exported functions. */ +/*===========================================================================*/ + +/** + * @brief Low level SPI driver initialization. + * + * @notapi + */ +void spi_lld_init(void) { + +#if LPC214x_SPI_USE_SSP + spiObjectInit(&SPID1); + SPID1.ssp = SSPBase; + SetVICVector(SPI1IrqHandler, LPC214x_SPI_SSP_IRQ_PRIORITY, SOURCE_SPI1); +#endif +} + +/** + * @brief Configures and activates the SPI peripheral. + * + * @param[in] spip pointer to the @p SPIDriver object + * + * @notapi + */ +void spi_lld_start(SPIDriver *spip) { + + if (spip->state == SPI_STOP) { + /* Clock activation.*/ +#if LPC214x_SPI_USE_SSP + if (&SPID1 == spip) { + PCONP = (PCONP & PCALL) | PCSPI1; + VICIntEnable = INTMASK(SOURCE_SPI1); + } +#endif + } + /* Configuration.*/ + spip->ssp->SSP_CR1 = 0; + /* Emptying the receive FIFO, it happens to not be empty while debugging.*/ + while (spip->ssp->SSP_SR & SR_RNE) + (void) spip->ssp->SSP_DR; + spip->ssp->SSP_ICR = ICR_RT | ICR_ROR; + spip->ssp->SSP_CR0 = spip->config->cr0; + spip->ssp->SSP_CPSR = spip->config->cpsr; + spip->ssp->SSP_CR1 = CR1_SSE; +} + +/** + * @brief Deactivates the SPI peripheral. + * + * @param[in] spip pointer to the @p SPIDriver object + * + * @notapi + */ +void spi_lld_stop(SPIDriver *spip) { + + if (spip->state != SPI_STOP) { + spip->ssp->SSP_CR1 = 0; + spip->ssp->SSP_CR0 = 0; + spip->ssp->SSP_CPSR = 0; +#if LPC214x_SPI_USE_SSP + if (&SPID1 == spip) { + PCONP = (PCONP & PCALL) & ~PCSPI1; + VICIntEnClear = INTMASK(SOURCE_SPI1); + } +#endif + } +} + +/** + * @brief Asserts the slave select signal and prepares for transfers. + * + * @param[in] spip pointer to the @p SPIDriver object + * + * @notapi + */ +void spi_lld_select(SPIDriver *spip) { + + palClearPad(spip->config->ssport, spip->config->sspad); +} + +/** + * @brief Deasserts the slave select signal. + * @details The previously selected peripheral is unselected. + * + * @param[in] spip pointer to the @p SPIDriver object + * + * @notapi + */ +void spi_lld_unselect(SPIDriver *spip) { + + palSetPad(spip->config->ssport, spip->config->sspad); +} + +/** + * @brief Ignores data on the SPI bus. + * @details This function transmits a series of idle words on the SPI bus and + * ignores the received data. This function can be invoked even + * when a slave select signal has not been yet asserted. + * + * @param[in] spip pointer to the @p SPIDriver object + * @param[in] n number of words to be ignored + * + * @notapi + */ +void spi_lld_ignore(SPIDriver *spip, size_t n) { + + spip->rxptr = NULL; + spip->txptr = NULL; + spip->rxcnt = spip->txcnt = n; + ssp_fifo_preload(spip); + spip->ssp->SSP_IMSC = IMSC_ROR | IMSC_RT | IMSC_TX | IMSC_RX; +} + +/** + * @brief Exchanges data on the SPI bus. + * @details This asynchronous function starts a simultaneous transmit/receive + * operation. + * @post At the end of the operation the configured callback is invoked. + * @note The buffers are organized as uint8_t arrays for data sizes below or + * equal to 8 bits else it is organized as uint16_t arrays. + * + * @param[in] spip pointer to the @p SPIDriver object + * @param[in] n number of words to be exchanged + * @param[in] txbuf the pointer to the transmit buffer + * @param[out] rxbuf the pointer to the receive buffer + * + * @notapi + */ +void spi_lld_exchange(SPIDriver *spip, size_t n, + const void *txbuf, void *rxbuf) { + + spip->rxptr = rxbuf; + spip->txptr = txbuf; + spip->rxcnt = spip->txcnt = n; + ssp_fifo_preload(spip); + spip->ssp->SSP_IMSC = IMSC_ROR | IMSC_RT | IMSC_TX | IMSC_RX; +} + +/** + * @brief Sends data over the SPI bus. + * @details This asynchronous function starts a transmit operation. + * @post At the end of the operation the configured callback is invoked. + * @note The buffers are organized as uint8_t arrays for data sizes below or + * equal to 8 bits else it is organized as uint16_t arrays. + * + * @param[in] spip pointer to the @p SPIDriver object + * @param[in] n number of words to send + * @param[in] txbuf the pointer to the transmit buffer + * + * @notapi + */ +void spi_lld_send(SPIDriver *spip, size_t n, const void *txbuf) { + + spip->rxptr = NULL; + spip->txptr = txbuf; + spip->rxcnt = spip->txcnt = n; + ssp_fifo_preload(spip); + spip->ssp->SSP_IMSC = IMSC_ROR | IMSC_RT | IMSC_TX | IMSC_RX; +} + +/** + * @brief Receives data from the SPI bus. + * @details This asynchronous function starts a receive operation. + * @post At the end of the operation the configured callback is invoked. + * @note The buffers are organized as uint8_t arrays for data sizes below or + * equal to 8 bits else it is organized as uint16_t arrays. + * + * @param[in] spip pointer to the @p SPIDriver object + * @param[in] n number of words to receive + * @param[out] rxbuf the pointer to the receive buffer + * + * @notapi + */ +void spi_lld_receive(SPIDriver *spip, size_t n, void *rxbuf) { + + spip->rxptr = rxbuf; + spip->txptr = NULL; + spip->rxcnt = spip->txcnt = n; + ssp_fifo_preload(spip); + spip->ssp->SSP_IMSC = IMSC_ROR | IMSC_RT | IMSC_TX | IMSC_RX; +} + +/** + * @brief Exchanges one frame using a polled wait. + * @details This synchronous function exchanges one frame using a polled + * synchronization method. This function is useful when exchanging + * small amount of data on high speed channels, usually in this + * situation is much more efficient just wait for completion using + * polling than suspending the thread waiting for an interrupt. + * + * @param[in] spip pointer to the @p SPIDriver object + * @param[in] frame the data frame to send over the SPI bus + * @return The received data frame from the SPI bus. + */ +uint16_t spi_lld_polled_exchange(SPIDriver *spip, uint16_t frame) { + + spip->ssp->SSP_DR = (uint32_t)frame; + while ((spip->ssp->SSP_SR & SR_RNE) == 0) + ; + return (uint16_t)spip->ssp->SSP_DR; +} + +#endif /* HAL_USE_SPI */ + +/** @} */ diff --git a/pool/shard008/C/0129384_options.c b/pool/shard008/C/0129384_options.c new file mode 100644 index 0000000000000000000000000000000000000000..e71ac00b0b114c6d3e0c854fb3c193021f54c6ec --- /dev/null +++ b/pool/shard008/C/0129384_options.c @@ -0,0 +1,48 @@ +#include "options.h" + +#include +#include + + +typedef struct Options { + int count; + char **values; +} Options; + +Options *Options_create(int argument_count, char **argument_values) +{ + Options *options = malloc(sizeof(Options)); + + // only count options, don't count the command itself + options->count = argument_count - 1; + + // increment to the first option, to avoid saving the command itself + argument_values++; + + options->values = argument_values; + + return options; +} + +void Options_destroy(Options *options) +{ + if (options != NULL) { + free(options); + + options = NULL; + } +} + +int Options_get_count(Options *options) +{ + return options->count; +} + +const char *Options_get_value(Options *options, int index) +{ + if (options->values[index] != NULL) { + return options->values[index]; + } + + return NULL; +} diff --git a/pool/shard008/C/0129388_lpc_17xx_PIN.c b/pool/shard008/C/0129388_lpc_17xx_PIN.c new file mode 100644 index 0000000000000000000000000000000000000000..b386efcad42d181263b8927b49fc134157b63ee8 --- /dev/null +++ b/pool/shard008/C/0129388_lpc_17xx_PIN.c @@ -0,0 +1,20 @@ +/* + * PIN.cpp + * + * Created on: 12/06/2011 + * Author: Alejandro + */ + +#include "PIN.h" +#include "lpc17xx_pinsel.h" + +// La unica funcion que me interesa de un PIN es el constructor +void PIN_Init(int pin){ + PINSEL_CFG_Type PinCfg; + PinCfg.Portnum = PN_GET_PORT(pin); + PinCfg.Pinnum = PN_GET_BIT (pin); + PinCfg.Funcnum = PN_GET_FUNC(pin); + PinCfg.Pinmode = PN_GET_MODE(pin); + PinCfg.OpenDrain = PN_GET_OD (pin); + PINSEL_ConfigPin(&PinCfg); +} diff --git a/pool/shard008/C/0129395_config.c b/pool/shard008/C/0129395_config.c new file mode 100644 index 0000000000000000000000000000000000000000..b424d85537b42c2080f8f999de736c1bc8018e9a --- /dev/null +++ b/pool/shard008/C/0129395_config.c @@ -0,0 +1,209 @@ +/* + * ./config.c -- Handles reading and writing the fircd configuration file + * + * Copyright (C) 2013 Matt Kilgore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License v2 as published by the + * Free Software Foundation. + */ + +#include "global.h" + +#include +#include +#include +#include +#include + +#include "debug.h" +#include "network.h" +#include "confuse.h" +#include "config.h" + +struct config prog_config; + +static const char default_config_file[] = "~/.fircdrc"; + +static int login_type_callback(cfg_t *cfg, cfg_opt_t *opt, const char *value, void *result); + +static cfg_opt_t network_opts[] = { + CFG_STR ("server", NULL, CFGF_NODEFAULT), + CFG_INT ("port", 6667, CFGF_NONE), + CFG_BOOL ("remove-files-on-close", 0, CFGF_NONE), + CFG_STR ("nickname", NULL, CFGF_NODEFAULT), + CFG_STR ("realname", NULL, CFGF_NONE), + CFG_STR ("password", NULL, CFGF_NONE), + CFG_INT_CB ("login-type", LOGIN_NONE, CFGF_NONE, login_type_callback), + CFG_STR_LIST ("channels", NULL, CFGF_NONE), + CFG_END() +}; + +static cfg_opt_t main_opts[] = { + CFG_SEC ("network", network_opts, CFGF_MULTI | CFGF_TITLE | CFGF_NO_TITLE_DUPES), + CFG_BOOL ("stay-in-forground", cfg_false, CFGF_NONE), + CFG_BOOL ("remove-files-on-close", cfg_false, CFGF_NONE), + CFG_STR_LIST ("auto-login", NULL, CFGF_NONE), + CFG_STR ("root-directory", "/tmp/irc", CFGF_NONE), + CFG_END() +}; + +static int stringcasecmp(const char *s1, const char *s2) +{ + for (; *s1 && *s2; s1++, s2++) + if ((*s1 | 32) != (*s2 | 32)) + return 1; + + if (*s1 || *s2) + return 1; + + return 0; +} + +static int login_type_callback(cfg_t *cfg, cfg_opt_t *opt, const char *value, void *result) +{ + if (stringcasecmp(value, "nickserv") == 0) { + *(int *)result = LOGIN_NICKSERV; + } else if (stringcasecmp(value, "sasl") == 0) { + *(int *)result = LOGIN_SASL; + } else if (stringcasecmp(value, "none") == 0) { + *(int *)result = LOGIN_NONE; + } else { + cfg_error(cfg, "Invalid value for option '%s': %s", cfg_opt_name(opt), value); + return -1; + } + return 0; +} + +static char *sstrdup(const char *s) +{ + if (s != NULL) + return strdup(s); + else + return NULL; +} + +void config_init(void) +{ + memset(&prog_config, 0, sizeof(struct config)); + + prog_config.root_directory = strdup("/tmp/irc"); +} + +static void add_network(cfg_t *network) +{ + unsigned int i; + cfg_opt_t *opt; + struct network *net = malloc(sizeof(struct network)); + + network_init(net); + net->name = sstrdup(cfg_title(network)); + net->url = sstrdup(cfg_getstr(network, "server")); + net->portno = cfg_getint(network, "port"); + + opt = cfg_getopt(network, "remove-files-on-close"); + if (opt->was_set) + net->conf.remove_files_on_close = cfg_opt_getnbool(opt, 0); + else + net->conf.remove_files_on_close = prog_config.net_global_conf.remove_files_on_close; + + net->nickname = sstrdup(cfg_getstr(network, "nickname")); + net->realname = sstrdup(cfg_getstr(network, "realname")); + net->password = sstrdup(cfg_getstr(network, "password")); + net->login_type = cfg_getint(network, "login-type"); + + for (i = 0; i < cfg_size(network, "channels"); i++) + network_add_channel(net, cfg_getnstr(network, "channels", i)); + + net->next = prog_config.first; + prog_config.first = net; +} + +int config_read(void) +{ + int i; + int ret, size; + cfg_t *cfg; + const char *filename; + + if (prog_config.arg_no_config) + return 0; + + cfg = cfg_init(main_opts, CFGF_NONE); + + if (prog_config.config_file) + filename = prog_config.config_file; + else + filename = default_config_file; + + switch(cfg_parse(cfg, filename)) { + case CFG_FILE_ERROR: + ret = 2; + goto cleanup; + case CFG_PARSE_ERROR: + printf("Error reading configuration file '%s': %s\n", filename, strerror(errno)); + ret = 1; + goto cleanup; + case CFG_SUCCESS: + break; + } + + if (cfg) { + prog_config.stay_in_forground = cfg_getbool(cfg, "stay-in-forground"); + if (prog_config.arg_stay_in_forground) + prog_config.stay_in_forground = 1; + + prog_config.net_global_conf.remove_files_on_close = cfg_getbool(cfg, "remove-files-on-close"); + if (prog_config.root_directory) + free(prog_config.root_directory); + prog_config.root_directory = strdup(cfg_getstr(cfg, "root-directory")); + + size = cfg_size(cfg, "network"); + for (i = 0; i < size; i++) + add_network(cfg_getnsec(cfg, "network", i)); + + size = cfg_size(cfg, "auto-login"); + if (size > 0) { + DEBUG_PRINT("Array size: %d", size); + for (i = 0; i < size; i++) + config_add_auto_login(cfg_getnstr(cfg, "auto-login", i)); + } + + ret = 0; + } else { + ret = 1; + } + +cleanup: + cfg_free(cfg); + return ret; +} + +void config_clear(void) +{ + int i; + + network_clear_all(prog_config.first); + + free(prog_config.root_directory); + free(prog_config.config_file); + + ARRAY_FOREACH(prog_config.auto_login, i) + free(prog_config.auto_login.arr[i]); + ARRAY_FREE(prog_config.auto_login); +} + +void config_add_auto_login(const char *login) +{ + int i, size; + ARRAY_FOREACH(prog_config.auto_login, i) + if (strcmp(prog_config.auto_login.arr[i], login) == 0) + return ; + + size = ARRAY_SIZE(prog_config.auto_login); + ARRAY_RESIZE(prog_config.auto_login, size + 1); + prog_config.auto_login.arr[size] = strdup(login); + + return ; +} + diff --git a/pool/shard008/C/0129397_ReversedLinkedList.c b/pool/shard008/C/0129397_ReversedLinkedList.c new file mode 100644 index 0000000000000000000000000000000000000000..66878178b2945b0ec54171bc621e0586f70a2f0d --- /dev/null +++ b/pool/shard008/C/0129397_ReversedLinkedList.c @@ -0,0 +1,282 @@ +// Arup Guha +// 10/24/01 edited 2/24/04 for COP 3502 Lecture +// Linked List Example + +#include +#include + +// Struct used to form a linked list of integers. +struct ll { + int data; + struct ll *next; +}; + +void print(struct ll *front); + +struct ll* insert_front(struct ll *front, int num); +struct ll* insert_inorder(struct ll *front, int num); +struct ll* insert_back(struct ll *front, int num); + +struct ll* deleteNode(struct ll *front, int num); +struct ll* deleteRec(struct ll *front, int num); +struct ll* reverse(struct ll *front) ; + +struct ll * reverseRec( struct ll * front , struct ll * previous); + +void dellist(struct ll *p); + +int main() { + + // Test reverse of 4 item list. + struct ll* myList = NULL; + myList = insert_front(myList, 7); + myList = insert_front(myList, 3); + myList = insert_front(myList, 6); + myList = insert_front(myList, 10); + print(myList); + myList = reverse(myList); + print(myList); + + return 0; +} + +// Pre-condition: front points to the head of a linked list structure. +// Post-condition: each value in the list will be printed, in order. +void print(struct ll *front) { + + while (front !=NULL) { + printf("%d ", front->data); + front = front -> next; + } + printf("\n"); +} + +// Pre-condition: front points to the head of a linked list structure. +// Post-condition: if val is stored in the list, 1 will be returned, +// otherwise 0 will be. +int search(struct ll *front, int val) { + while (front != NULL) { + if (front->data == val) + return 1; + front = front->next; + } + return 0; + +} + +// Pre-condition: front points to the head of a linked list structure. +// Post-condition: a new node storing num will be inserted to the front of +// this list and a pointer to this node will be returned. +struct ll* insert_front(struct ll *front, int num) { + + struct ll *temp; + + // Create temp node and link it to front. + temp = (struct ll*)malloc(sizeof(struct ll)); + temp->data = num; + temp->next = front; + + // Return the new front of the list. + return temp; +} + +// Pre-condition: front points to the head of a linked list structure. +// Post-condition: a new node containing num will be created and added +// to the end of the linked listed pointed to by front. +struct ll* insert_back(struct ll *front, int num) { + + struct ll *temp; + struct ll *begin; + + // Create the new node. + temp = (struct ll*)malloc(sizeof(struct ll)); + temp->data = num; + temp->next = NULL; + + // Store front of the linked list + begin = front; + + // Take care of case inserting into an empty list. + if (front == NULL) + return temp; + + // Use front to iterate to the right spot to insert temp. + while (front->next != NULL) + front = front->next; + + // Insert temp. + front->next = temp; + + // Return a pointer to the front of the list. + return begin; +} + + +// Pre-condition: front points to the head of a linked list structure that +// has its nodes arranged in ascending numerical order. +// Post-condition: a new node containing num will be created and added +// into the appropriate position in the linked list +// front and a pointer to the front of this new linked +// list will be returned. +struct ll* insert_inorder(struct ll *front, int num) { + + struct ll *temp; + struct ll *iter; + struct ll *savelink; + + // Create the new node. + temp = (struct ll*)malloc(sizeof(struct ll)); + temp->data = num; + temp->next = NULL; + + // Take care of case inserting into an empty list. + if (front == NULL) + return temp; + + if (num < front->data) { + temp->next = front; + return temp; + } + + // Start iter at the front of the linked list. + iter = front; + + // Use front to iterate to the right spot to insert temp. + while (iter->next != NULL && iter->next->data < num) + iter = iter->next; + + // Save the node to patch to. + savelink = iter->next; + + // Insert temp. + iter->next = temp; + temp->next = savelink; + + // Return a pointer to the front of the list. + return front; +} + + +// Pre-condition: front points to the head of a linked list structure. +// Post-condition: The first node that contains the value num will be +// removed from the list. A pointer to the front of the +// list will be returned. If no such value is stored, +// the list will remain unchanged. +struct ll* deleteNode(struct ll *front, int num) { + + struct ll *temp, *del; + temp = front; + + // Only need to delete if the list is not null. + if (temp != NULL) { + + // Take care of the case where first node needs to be deleted. + if (temp->data == num) { + del = temp -> next; + free(temp); + return del; + } + // Otherwise, loop until you find the node to delete and do so. + while (temp->next != NULL) { + if (temp ->next->data == num) { + del = temp -> next; + temp->next = temp ->next->next; + free(del); + return front; + } + temp = temp -> next; + } + + } + return front; +} +// Pre-condition: front points to the head of a linked list structure. +// Post-condition: The first node that contains the value num will be +// removed from the list. A pointer to the front of the +// list will be returned. If no such value is stored, +// the list will remain unchanged. +struct ll* deleteRec(struct ll *front, int num) { + + // No item in list, no delete to do. + if (front == NULL) + return NULL; + + // Deleting the first item. + if (front->data == num) { + + // This is the list to return. + struct ll* retval = front->next; + + // Need to free the deleted node. + free(front); + + return retval; + } + + // We can try to delete num from the rest of the list. + struct ll* rest = deleteRec(front->next, num); + + // Attach the rest of the list to what is returned from the recursive call. + front->next = rest; + + return front; // This is unchanged. +} + + + +// Pre-condition: front points to the head of a linked list structure. +// Post-condition: The node pointers will be rearranged so that the +// nodes are connected in reverse order and a pointer +// to the new front of the list (the old back) is +// returned. +struct ll* reverse(struct ll *front) { + + /*** ADD CODE IN HERE - YOU PROBABLY WON'T RETURN FRONT... ***/ + struct ll * temp; + struct ll * previous = NULL; + while(front != NULL) { + temp = front->next; + front->next = previous; + previous = front; + front = temp; + } + return previous; +} + +/*** + * Recursive solution for reversing a linked list. + */ +struct ll * reverseRec( struct ll * front , struct ll * previous) +{ + struct ll * temp; + if(front->next == NULL) { + front->next = previous; + return front; + } else { + temp = reverseRec(front->next, front); + front->next = previous; + return temp; + } +} +//reversedHead = reverse(head, NULL); + + + +// Pre-condition: p points to a linked list. +// Post-condition: All the memory for the linked list pointed to by p is +// freed for use. +void dellist(struct ll *p) { + + struct ll *temp; + + // Recursively free each element in the list. + if (p !=NULL) { + temp = p -> next; + dellist(temp); + free(p); + } +} + + + + diff --git a/pool/shard008/C/0129399_nm-dhcp4-config.c b/pool/shard008/C/0129399_nm-dhcp4-config.c new file mode 100644 index 0000000000000000000000000000000000000000..d77f86697efaf59aea233d0eef7319f1fbcce59c --- /dev/null +++ b/pool/shard008/C/0129399_nm-dhcp4-config.c @@ -0,0 +1,189 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */ +/* + * 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 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. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301 USA. + * + * Copyright 2008 - 2011 Red Hat, Inc. + * Copyright 2008 Novell, Inc. + */ + +#include + +#include "nm-dhcp4-config.h" +#include "nm-dbus-interface.h" +#include "nm-types-private.h" +#include "nm-object-private.h" +#include "nm-utils.h" + +G_DEFINE_TYPE (NMDhcp4Config, nm_dhcp4_config, NM_TYPE_OBJECT) + +#define NM_DHCP4_CONFIG_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), NM_TYPE_DHCP4_CONFIG, NMDhcp4ConfigPrivate)) + +typedef struct { + DBusGProxy *proxy; + + GHashTable *options; +} NMDhcp4ConfigPrivate; + +enum { + PROP_0, + PROP_OPTIONS, + + LAST_PROP +}; + +static void +nm_dhcp4_config_init (NMDhcp4Config *config) +{ + NMDhcp4ConfigPrivate *priv = NM_DHCP4_CONFIG_GET_PRIVATE (config); + + priv->options = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); +} + +static gboolean +demarshal_dhcp4_options (NMObject *object, GParamSpec *pspec, GValue *value, gpointer field) +{ + NMDhcp4ConfigPrivate *priv = NM_DHCP4_CONFIG_GET_PRIVATE (object); + GHashTable *new_options; + GHashTableIter iter; + const char *key; + GValue *opt; + + g_hash_table_remove_all (priv->options); + + new_options = g_value_get_boxed (value); + if (new_options) { + g_hash_table_iter_init (&iter, new_options); + while (g_hash_table_iter_next (&iter, (gpointer) &key, (gpointer) &opt)) + g_hash_table_insert (priv->options, g_strdup (key), g_value_dup_string (opt)); + } + + _nm_object_queue_notify (object, NM_DHCP4_CONFIG_OPTIONS); + return TRUE; +} + +static void +init_dbus (NMObject *object) +{ + NMDhcp4ConfigPrivate *priv = NM_DHCP4_CONFIG_GET_PRIVATE (object); + const NMPropertiesInfo property_info[] = { + { NM_DHCP4_CONFIG_OPTIONS, &priv->options, demarshal_dhcp4_options }, + { NULL }, + }; + + NM_OBJECT_CLASS (nm_dhcp4_config_parent_class)->init_dbus (object); + + priv->proxy = _nm_object_new_proxy (object, NULL, NM_DBUS_INTERFACE_DHCP4_CONFIG); + _nm_object_register_properties (object, + priv->proxy, + property_info); +} + +static void +finalize (GObject *object) +{ + NMDhcp4ConfigPrivate *priv = NM_DHCP4_CONFIG_GET_PRIVATE (object); + + if (priv->options) + g_hash_table_destroy (priv->options); + + g_object_unref (priv->proxy); + + G_OBJECT_CLASS (nm_dhcp4_config_parent_class)->finalize (object); +} + +static void +get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec) +{ + NMDhcp4Config *self = NM_DHCP4_CONFIG (object); + + switch (prop_id) { + case PROP_OPTIONS: + g_value_set_boxed (value, nm_dhcp4_config_get_options (self)); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +nm_dhcp4_config_class_init (NMDhcp4ConfigClass *config_class) +{ + GObjectClass *object_class = G_OBJECT_CLASS (config_class); + NMObjectClass *nm_object_class = NM_OBJECT_CLASS (config_class); + + g_type_class_add_private (config_class, sizeof (NMDhcp4ConfigPrivate)); + + /* virtual methods */ + object_class->get_property = get_property; + object_class->finalize = finalize; + + nm_object_class->init_dbus = init_dbus; + + /* properties */ + + /** + * NMDhcp4Config:options: + * + * The #GHashTable containing options of the configuration. + * + * Type: GLib.HashTable(utf8,GObject.Value) + **/ + g_object_class_install_property + (object_class, PROP_OPTIONS, + g_param_spec_boxed (NM_DHCP4_CONFIG_OPTIONS, "", "", + G_TYPE_HASH_TABLE, + G_PARAM_READABLE | + G_PARAM_STATIC_STRINGS)); +} + +/** + * nm_dhcp4_config_get_options: + * @config: a #NMDhcp4Config + * + * Gets all the options contained in the configuration. + * + * Returns: (transfer none) (element-type utf8 GObject.Value): the #GHashTable containing strings for keys and values. + * This is the internal copy used by the configuration, and must not be modified. + **/ +GHashTable * +nm_dhcp4_config_get_options (NMDhcp4Config *config) +{ + g_return_val_if_fail (NM_IS_DHCP4_CONFIG (config), NULL); + + return NM_DHCP4_CONFIG_GET_PRIVATE (config)->options; +} + +/** + * nm_dhcp4_config_get_one_option: + * @config: a #NMDhcp4Config + * @option: the option to retrieve + * + * Gets one option by option name. + * + * Returns: the configuration option's value. This is the internal string used by the + * configuration, and must not be modified. + **/ +const char * +nm_dhcp4_config_get_one_option (NMDhcp4Config *config, const char *option) +{ + g_return_val_if_fail (NM_IS_DHCP4_CONFIG (config), NULL); + + return g_hash_table_lookup (nm_dhcp4_config_get_options (config), option); +} diff --git a/pool/shard008/C/0129403_strokestyle.c b/pool/shard008/C/0129403_strokestyle.c new file mode 100644 index 0000000000000000000000000000000000000000..abbb66201ce3f570bf44ee9202b7762c0cb0ce3d --- /dev/null +++ b/pool/shard008/C/0129403_strokestyle.c @@ -0,0 +1,123 @@ +/* + * WinDrawLib + * Copyright (c) 2018 Antonio Scuri + * Copyright (c) 2015-2016 Martin Mitas + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "misc.h" +#include "lock.h" +#include "backend-d2d.h" +#include "backend-gdix.h" + + +static WD_HSTROKESTYLE +wdCreateStrokeStyleImpl(UINT dashStyle, const float* dashes, UINT dashesCount, UINT lineCap, UINT lineJoin) +{ + if(d2d_enabled()) { + HRESULT hr; + c_D2D1_STROKE_STYLE_PROPERTIES p; + c_ID2D1StrokeStyle *s; + + p.startCap = lineCap; + p.endCap = lineCap; + p.dashCap = lineCap; + p.lineJoin = lineJoin; + p.miterLimit = 1.0f; + p.dashStyle = dashStyle; + p.dashOffset = 0.0f; + + wd_lock(); + hr = c_ID2D1Factory_CreateStrokeStyle(d2d_factory, &p, dashes, dashesCount, &s); + wd_unlock(); + if (FAILED(hr)) { + WD_TRACE_HR("wdCreateStrokeStyleImpl: " + "ID2D1Factory::CreateStrokeStyle() failed."); + return NULL; + } + + return (WD_HSTROKESTYLE)s; + } + else { + gdix_strokestyle_t* s; + + s = (gdix_strokestyle_t*) malloc( + WD_OFFSETOF(gdix_strokestyle_t, dashes) + dashesCount * sizeof(float)); + if (s == NULL) { + WD_TRACE("wdCreateStrokeStyleImpl: malloc() failed."); + return NULL; + } + + s->dashStyle = dashStyle; + s->lineCap = lineCap; + s->lineJoin = lineJoin; + s->dashesCount = dashesCount; + if(dashesCount > 0) + memcpy(s->dashes, dashes, dashesCount * sizeof(float)); + + return (WD_HSTROKESTYLE)s; + } +} + + +WD_HSTROKESTYLE +wdCreateStrokeStyle(UINT dashStyle, UINT lineCap, UINT lineJoin) +{ + #define DASH_LEN 4.25f + #define DOT_LEN 1.25f + #define SPACE_LEN 3.75f + + static const float pattern_dash[] = { DASH_LEN, SPACE_LEN }; + static const float pattern_dot[] = { DOT_LEN, SPACE_LEN }; + static const float pattern_dash_dot[] = { DASH_LEN, SPACE_LEN, DOT_LEN, SPACE_LEN }; + static const float pattern_dash_dot_dot[] = { DASH_LEN, SPACE_LEN, DOT_LEN, SPACE_LEN, DOT_LEN, SPACE_LEN }; + + static const struct { + int style_id; + const float* pattern; + UINT pattern_size; + } style_data[] = { + { 0, NULL, 0 }, + { 5, pattern_dash, WD_SIZEOF_ARRAY(pattern_dash) }, + { 5, pattern_dot, WD_SIZEOF_ARRAY(pattern_dot) }, + { 5, pattern_dash_dot, WD_SIZEOF_ARRAY(pattern_dash_dot) }, + { 5, pattern_dash_dot_dot, WD_SIZEOF_ARRAY(pattern_dash_dot_dot) } + }; + + return wdCreateStrokeStyleImpl(style_data[dashStyle].style_id, + style_data[dashStyle].pattern, style_data[dashStyle].pattern_size, + lineCap, lineJoin); +} + +WD_HSTROKESTYLE +wdCreateStrokeStyleCustom(const float* dashes, UINT dashesCount, UINT lineCap, UINT lineJoin) +{ + return wdCreateStrokeStyleImpl(5 /* CUSTOM */, dashes, dashesCount, lineCap, lineJoin); +} + +void +wdDestroyStrokeStyle(WD_HSTROKESTYLE hStrokeStyle) +{ + if(d2d_enabled()) { + c_ID2D1StrokeStyle_Release((c_ID2D1StrokeStyle*) hStrokeStyle); + } else { + free((gdix_strokestyle_t*) hStrokeStyle); + } +} diff --git a/pool/shard008/C/0129404_validation.c b/pool/shard008/C/0129404_validation.c new file mode 100644 index 0000000000000000000000000000000000000000..2dd49204cbff7c479b30003d39fabec3dcea7ec9 --- /dev/null +++ b/pool/shard008/C/0129404_validation.c @@ -0,0 +1,64 @@ +/* +* Copyright (C) Actility, SA. All Rights Reserved. +* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License version +* 2 only, as published by the Free Software Foundation. +* +* 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 version 2 for more details (a copy is +* included at /legal/license.txt). +* +* You should have received a copy of the GNU General Public License +* version 2 along with this work; if not, write to the Free Software +* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +* 02110-1301 USA +* +* Please contact Actility, SA., 4, rue Ampere 22300 LANNION FRANCE +* or visit www.actility.com if you need additional +* information or have any questions. +*/ + +#include +#include +#include + +#include "iec_debug.h" +#include "mxml-reduce.h" +#include "validation.h" + +int TraceDebug=1; +int TraceLevel=9; + +int main(int ac, char **av) { + int err=0; + + rtl_tracelevel(TraceLevel); + + while (--ac) { + char *file = *++av; + RTL_TRDBG (TRACE_DETAIL, "Validation %s\n", file); + + FILE *fp = fopen(file, "r"); + void *script = mxmlSAXLoadFile (NULL , fp , MXML_OPAQUE_CALLBACK, iec_sax_cb, NULL); + mxmlReduceAttrs (script); + fclose (fp); + + int rc; + if (script) { + rc = PLCvalidation(script); + } + else rc = -1; + + if (rc < 0) { + RTL_TRDBG (TRACE_DETAIL, "\033[31;7m%s validation FAILED\033[0m\n", file); + err ++; + } + else + RTL_TRDBG (TRACE_DETAIL, "\033[32;7m%s validation SUCCESS\033[0m\n", file); + } + exit (err); +} diff --git a/pool/shard008/C/0129406_test-qcow2.c b/pool/shard008/C/0129406_test-qcow2.c new file mode 100644 index 0000000000000000000000000000000000000000..9a6c3e8b35ae96bf81dde0b745c438f95567800a --- /dev/null +++ b/pool/shard008/C/0129406_test-qcow2.c @@ -0,0 +1,55 @@ +/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ + +/*** + This file is part of systemd. + + Copyright 2015 Lennart Poettering + + systemd 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. + + systemd 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 systemd; If not, see . +***/ + +#include "log.h" +#include "util.h" + +#include "qcow2-util.h" + +int main(int argc, char *argv[]) { + _cleanup_close_ int sfd = -1, dfd = -1; + int r; + + if (argc != 3) { + log_error("Needs two arguments."); + return EXIT_FAILURE; + } + + sfd = open(argv[1], O_RDONLY|O_CLOEXEC|O_NOCTTY); + if (sfd < 0) { + log_error_errno(errno, "Can't open source file: %m"); + return EXIT_FAILURE; + } + + dfd = open(argv[2], O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0666); + if (dfd < 0) { + log_error_errno(errno, "Can't open destination file: %m"); + return EXIT_FAILURE; + } + + r = qcow2_convert(sfd, dfd); + if (r < 0) { + log_error_errno(r, "Failed to unpack: %m"); + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} diff --git a/pool/shard008/C/0129408_serial.c b/pool/shard008/C/0129408_serial.c new file mode 100644 index 0000000000000000000000000000000000000000..a2d4e2338ae4214d7512de22dfe4ce042c2f58b5 --- /dev/null +++ b/pool/shard008/C/0129408_serial.c @@ -0,0 +1,182 @@ +/* + * COPYRIGHT (C) 2018, Real-Thread Information Technology Ltd + * + * SPDX-License-Identifier: Apache-2.0 + * Change Logs: + * Date Author Notes + * 2013-03-30 Bernard the first verion + */ + +#include +#include +#include + +#include + +#include "serial.h" + +struct hw_uart_device +{ + uint32_t instance; + int irqno; +}; + +static void rt_hw_uart_isr(int irqno, void *param) +{ + struct rt_serial_device *serial = (struct rt_serial_device *)param; + + rt_hw_serial_isr(serial, RT_SERIAL_EVENT_RX_IND); +} + +static rt_err_t uart_configure(struct rt_serial_device *serial, struct serial_configure *cfg) +{ + struct hw_uart_device *uart; + uint32_t baudrate; + uint8_t parity, stopbits, datasize, flowcontrol; + + RT_ASSERT(serial != RT_NULL); + uart = (struct hw_uart_device *)serial->parent.user_data; + + baudrate = cfg->baud_rate; + switch (cfg->data_bits) + { + case DATA_BITS_8: + datasize = EIGHTBITS; + break; + case DATA_BITS_7: + datasize = SEVENBITS; + break; + } + if (cfg->stop_bits == STOP_BITS_1) stopbits = STOPBITS_ONE; + else if (cfg->stop_bits == STOP_BITS_2) stopbits = STOPBITS_TWO; + + parity = PARITY_NONE; + flowcontrol = FLOWCTRL_OFF; + + /* initailize UART */ + // uart_init(uart->instance, baudrate, parity, stopbits, datasize, flowcontrol); + + rt_hw_interrupt_install(uart->irqno, rt_hw_uart_isr, serial, "uart"); + rt_hw_interrupt_mask(uart->irqno); + + /* Set the IRQ mode for the Rx FIFO */ + uart_set_FIFO_mode(uart->instance, RX_FIFO, 1, IRQ_MODE); + + return RT_EOK; +} + +static rt_err_t uart_control(struct rt_serial_device *serial, int cmd, void *arg) +{ + struct hw_uart_device *uart; + + RT_ASSERT(serial != RT_NULL); + uart = (struct hw_uart_device *)serial->parent.user_data; + + switch (cmd) + { + case RT_DEVICE_CTRL_CLR_INT: + /* disable rx irq */ + rt_hw_interrupt_mask(uart->irqno); + break; + + case RT_DEVICE_CTRL_SET_INT: + /* enable rx irq */ + rt_hw_interrupt_umask(uart->irqno); + break; + } + + return RT_EOK; +} + +static int uart_putc(struct rt_serial_device *serial, char c) +{ + struct hw_uart_device *uart; + + RT_ASSERT(serial != RT_NULL); + uart = (struct hw_uart_device *)serial->parent.user_data; + + uart_putchar(uart->instance, (uint8_t*)&c); + + return 1; +} + +static int uart_getc(struct rt_serial_device *serial) +{ + int ch; + struct hw_uart_device *uart; + + RT_ASSERT(serial != RT_NULL); + uart = (struct hw_uart_device *)serial->parent.user_data; + + ch = uart_getchar(uart->instance); + if (ch == NONE_CHAR) ch = -1; + + return ch; +} + +static const struct rt_uart_ops _uart_ops = +{ + uart_configure, + uart_control, + uart_putc, + uart_getc, +}; + +#ifdef RT_USING_UART0 +/* UART device driver structure */ +static struct hw_uart_device _uart0_device = +{ + HW_UART0, + IMX_INT_UART0 +}; +static struct rt_serial_device _serial0; +#endif + +#ifdef RT_USING_UART1 +/* UART1 device driver structure */ +static struct hw_uart_device _uart1_device = +{ + HW_UART1, + IMX_INT_UART1 +}; +static struct rt_serial_device _serial1; +#endif + +int rt_hw_uart_init(void) +{ + struct hw_uart_device *uart; + struct serial_configure config; + + config.baud_rate = BAUD_RATE_115200; + config.bit_order = BIT_ORDER_LSB; + config.data_bits = DATA_BITS_8; + config.parity = PARITY_NONE; + config.stop_bits = STOP_BITS_1; + config.invert = NRZ_NORMAL; + config.bufsz = RT_SERIAL_RB_BUFSZ; + +#ifdef RT_USING_UART0 + uart = &_uart0_device; + + _serial0.ops = &_uart_ops; + _serial0.config = config; + + /* register UART1 device */ + rt_hw_serial_register(&_serial0, "uart0", + RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX, + uart); +#endif + +#ifdef RT_USING_UART1 + uart = &_uart1_device; + _serial1.ops = &_uart_ops; + _serial1.config = config; + + /* register UART1 device */ + rt_hw_serial_register(&_serial1, "uart1", + RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX, uart); +#endif + + return 0; +} +INIT_BOARD_EXPORT(rt_hw_uart_init); diff --git a/pool/shard008/C/0129409_picirq.c b/pool/shard008/C/0129409_picirq.c new file mode 100644 index 0000000000000000000000000000000000000000..aeee0322874381504ac09ce58479fd032c7ff2c4 --- /dev/null +++ b/pool/shard008/C/0129409_picirq.c @@ -0,0 +1,110 @@ +/* + * + * Copyright (c) 2013 Brian Swetland + * Copyright (c) 2006-2009 Frans Kaashoek, Robert Morris, Russ Cox, + * Massachusetts Institute of Technology + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +// Intel 8259A programmable interrupt controllers. + +#include +#include +#include + +// I/O Addresses of the two programmable interrupt controllers +#define IO_PIC1 0x20 // Master (IRQs 0-7) +#define IO_PIC2 0xA0 // Slave (IRQs 8-15) + +#define IRQ_SLAVE 2 // IRQ at which slave connects to master + +// Current IRQ mask. +// Initial IRQ mask has interrupt 2 enabled (for slave 8259A). +static ushort irqmask = 0xFFFF & ~(1<> 8); +} + +void +picenable(int irq) +{ + picsetmask(irqmask & ~(1<_refcount, 1); + FBI_ASSERT(newrefcount > 0); + return fbt; +} + +static void mc_fbtrace_decref(mc_fbtrace_t* fbt) { + FBI_ASSERT(fbt); + int newrefcount = __sync_add_and_fetch(&fbt->_refcount, -1); + FBI_ASSERT(newrefcount >= 0); + if (newrefcount == 0) { + free(fbt); + } +} + +static mc_fbtrace_t* new_mc_fbtrace() { + mc_fbtrace_t* fbt = calloc(1, sizeof(*fbt)); + if (fbt == NULL) { + dbg_debug("Error while allocating memory for mc_fbtrace_t object"); + return fbt; + } + mc_fbtrace_incref(fbt); + return fbt; +} + +mc_fbtrace_info_t* new_mc_fbtrace_info(int is_copy) { + mc_fbtrace_info_t* fbt_i = calloc(1, sizeof(*fbt_i)); + if (fbt_i == NULL) { + dbg_debug("Error while allocating memory for mc_fbtrace_info_t object"); + return fbt_i; + } + fbt_i->_refcount = 1; + if (!is_copy) { + fbt_i->fbtrace = new_mc_fbtrace(); + if (fbt_i->fbtrace == NULL) { + free(fbt_i); + return NULL; + } + } + return fbt_i; +} + +mc_fbtrace_info_t* mc_fbtrace_info_deep_copy(const mc_fbtrace_info_t* orig) { + mc_fbtrace_info_t* new_copy = new_mc_fbtrace_info(1); + memcpy(new_copy, orig, sizeof(mc_fbtrace_info_t)); + if (orig->fbtrace) { + mc_fbtrace_incref(orig->fbtrace); + } + return new_copy; +} + +void mc_fbtrace_info_decref(mc_fbtrace_info_t* fbt_i) { + if (!fbt_i) { + return; + } + int newrefcount = __sync_add_and_fetch(&fbt_i->_refcount, -1); + FBI_ASSERT(newrefcount >= 0); + if (newrefcount == 0) { + if (fbt_i->fbtrace) { + mc_fbtrace_decref(fbt_i->fbtrace); + } + free(fbt_i); + } +} + +mc_fbtrace_info_t* mc_fbtrace_info_incref(mc_fbtrace_info_t* fbt_i) { + if (!fbt_i) { + return NULL; + } + int newrefcount = __sync_add_and_fetch(&fbt_i->_refcount, 1); + FBI_ASSERT(newrefcount > 0); + return fbt_i; +} diff --git a/pool/shard008/C/0129414_h2_ssl_proxy.c b/pool/shard008/C/0129414_h2_ssl_proxy.c new file mode 100644 index 0000000000000000000000000000000000000000..6340d3f4033ebeaa99378850ca9ba9216b388374 --- /dev/null +++ b/pool/shard008/C/0129414_h2_ssl_proxy.c @@ -0,0 +1,220 @@ +/* + * + * Copyright 2015-2016, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "test/core/end2end/end2end_tests.h" + +#include +#include + +#include +#include +#include + +#include "src/core/channel/channel_args.h" +#include "src/core/security/credentials.h" +#include "src/core/support/env.h" +#include "src/core/support/tmpfile.h" +#include "src/core/support/string.h" +#include "test/core/end2end/data/ssl_test_data.h" +#include "test/core/end2end/fixtures/proxy.h" +#include "test/core/util/port.h" +#include "test/core/util/test_config.h" + +typedef struct fullstack_secure_fixture_data { + grpc_end2end_proxy *proxy; +} fullstack_secure_fixture_data; + +static grpc_server *create_proxy_server(const char *port) { + grpc_server *s = grpc_server_create(NULL, NULL); + grpc_ssl_pem_key_cert_pair pem_cert_key_pair = {test_server1_key, + test_server1_cert}; + grpc_server_credentials *ssl_creds = + grpc_ssl_server_credentials_create(NULL, &pem_cert_key_pair, 1, 0, NULL); + GPR_ASSERT(grpc_server_add_secure_http2_port(s, port, ssl_creds)); + grpc_server_credentials_release(ssl_creds); + return s; +} + +static grpc_channel *create_proxy_client(const char *target) { + grpc_channel *channel; + grpc_channel_credentials *ssl_creds = + grpc_ssl_credentials_create(NULL, NULL, NULL); + grpc_arg ssl_name_override = {GRPC_ARG_STRING, + GRPC_SSL_TARGET_NAME_OVERRIDE_ARG, + {"foo.test.google.fr"}}; + grpc_channel_args client_args; + client_args.num_args = 1; + client_args.args = &ssl_name_override; + channel = grpc_secure_channel_create(ssl_creds, target, &client_args, NULL); + grpc_channel_credentials_release(ssl_creds); + return channel; +} + +static const grpc_end2end_proxy_def proxy_def = {create_proxy_server, + create_proxy_client}; + +static grpc_end2end_test_fixture chttp2_create_fixture_secure_fullstack( + grpc_channel_args *client_args, grpc_channel_args *server_args) { + grpc_end2end_test_fixture f; + fullstack_secure_fixture_data *ffd = + gpr_malloc(sizeof(fullstack_secure_fixture_data)); + memset(&f, 0, sizeof(f)); + + ffd->proxy = grpc_end2end_proxy_create(&proxy_def); + + f.fixture_data = ffd; + f.cq = grpc_completion_queue_create(NULL); + + return f; +} + +static void process_auth_failure(void *state, grpc_auth_context *ctx, + const grpc_metadata *md, size_t md_count, + grpc_process_auth_metadata_done_cb cb, + void *user_data) { + GPR_ASSERT(state == NULL); + cb(user_data, NULL, 0, NULL, 0, GRPC_STATUS_UNAUTHENTICATED, NULL); +} + +static void chttp2_init_client_secure_fullstack( + grpc_end2end_test_fixture *f, grpc_channel_args *client_args, + grpc_channel_credentials *creds) { + fullstack_secure_fixture_data *ffd = f->fixture_data; + f->client = grpc_secure_channel_create( + creds, grpc_end2end_proxy_get_client_target(ffd->proxy), client_args, + NULL); + GPR_ASSERT(f->client != NULL); + grpc_channel_credentials_release(creds); +} + +static void chttp2_init_server_secure_fullstack( + grpc_end2end_test_fixture *f, grpc_channel_args *server_args, + grpc_server_credentials *server_creds) { + fullstack_secure_fixture_data *ffd = f->fixture_data; + if (f->server) { + grpc_server_destroy(f->server); + } + f->server = grpc_server_create(server_args, NULL); + grpc_server_register_completion_queue(f->server, f->cq, NULL); + GPR_ASSERT(grpc_server_add_secure_http2_port( + f->server, grpc_end2end_proxy_get_server_port(ffd->proxy), server_creds)); + grpc_server_credentials_release(server_creds); + grpc_server_start(f->server); +} + +void chttp2_tear_down_secure_fullstack(grpc_end2end_test_fixture *f) { + fullstack_secure_fixture_data *ffd = f->fixture_data; + grpc_end2end_proxy_destroy(ffd->proxy); + gpr_free(ffd); +} + +static void chttp2_init_client_simple_ssl_secure_fullstack( + grpc_end2end_test_fixture *f, grpc_channel_args *client_args) { + grpc_channel_credentials *ssl_creds = + grpc_ssl_credentials_create(NULL, NULL, NULL); + grpc_arg ssl_name_override = {GRPC_ARG_STRING, + GRPC_SSL_TARGET_NAME_OVERRIDE_ARG, + {"foo.test.google.fr"}}; + grpc_channel_args *new_client_args = + grpc_channel_args_copy_and_add(client_args, &ssl_name_override, 1); + chttp2_init_client_secure_fullstack(f, new_client_args, ssl_creds); + grpc_channel_args_destroy(new_client_args); +} + +static int fail_server_auth_check(grpc_channel_args *server_args) { + size_t i; + if (server_args == NULL) return 0; + for (i = 0; i < server_args->num_args; i++) { + if (strcmp(server_args->args[i].key, FAIL_AUTH_CHECK_SERVER_ARG_NAME) == + 0) { + return 1; + } + } + return 0; +} + +static void chttp2_init_server_simple_ssl_secure_fullstack( + grpc_end2end_test_fixture *f, grpc_channel_args *server_args) { + grpc_ssl_pem_key_cert_pair pem_cert_key_pair = {test_server1_key, + test_server1_cert}; + grpc_server_credentials *ssl_creds = + grpc_ssl_server_credentials_create(NULL, &pem_cert_key_pair, 1, 0, NULL); + if (fail_server_auth_check(server_args)) { + grpc_auth_metadata_processor processor = {process_auth_failure, NULL, NULL}; + grpc_server_credentials_set_auth_metadata_processor(ssl_creds, processor); + } + chttp2_init_server_secure_fullstack(f, server_args, ssl_creds); +} + +/* All test configurations */ + +static grpc_end2end_test_config configs[] = { + {"chttp2/simple_ssl_fullstack", + FEATURE_MASK_SUPPORTS_DELAYED_CONNECTION | + FEATURE_MASK_SUPPORTS_PER_CALL_CREDENTIALS, + chttp2_create_fixture_secure_fullstack, + chttp2_init_client_simple_ssl_secure_fullstack, + chttp2_init_server_simple_ssl_secure_fullstack, + chttp2_tear_down_secure_fullstack}, +}; + +int main(int argc, char **argv) { + size_t i; + FILE *roots_file; + size_t roots_size = strlen(test_root_cert); + char *roots_filename; + + grpc_test_init(argc, argv); + + /* Set the SSL roots env var. */ + roots_file = gpr_tmpfile("chttp2_simple_ssl_fullstack_test", &roots_filename); + GPR_ASSERT(roots_filename != NULL); + GPR_ASSERT(roots_file != NULL); + GPR_ASSERT(fwrite(test_root_cert, 1, roots_size, roots_file) == roots_size); + fclose(roots_file); + gpr_setenv(GRPC_DEFAULT_SSL_ROOTS_FILE_PATH_ENV_VAR, roots_filename); + + grpc_init(); + + for (i = 0; i < sizeof(configs) / sizeof(*configs); i++) { + grpc_end2end_tests(argc, argv, configs[i]); + } + + grpc_shutdown(); + + /* Cleanup. */ + remove(roots_filename); + gpr_free(roots_filename); + + return 0; +} diff --git a/pool/shard008/C/0129416_apollo.c b/pool/shard008/C/0129416_apollo.c new file mode 100644 index 0000000000000000000000000000000000000000..be7e6cce826cb676b9622fb5425a67d1e09b353a --- /dev/null +++ b/pool/shard008/C/0129416_apollo.c @@ -0,0 +1,66 @@ +/* Copyright 2013-2014 IBM Corp. + * + * 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. + */ + + +#include +#include +#include +#include + +#include "ibm-fsp.h" +#include "lxvpd.h" + +static bool apollo_probe(void) +{ + return dt_node_is_compatible(dt_root, "ibm,apollo"); +} + +static void apollo_setup_phb(struct phb *phb, unsigned int index) +{ + struct dt_node *ioc_node; + + /* Grab the device-tree node of the IOC */ + ioc_node = phb->dt_node->parent; + if (!ioc_node) + return; + + /* + * Process the pcie slot entries from the lx vpd lid + * + * FIXME: We currently assume chip 1 always, this will have to be + * fixed once we understand the right way to get the BRxy/BRxy "x" + * "x" value. (this actually seems to work...) + */ + lxvpd_process_slot_entries(phb, ioc_node, 1, index); +} + +DECLARE_PLATFORM(apollo) = { + .name = "Apollo", + .probe = apollo_probe, + .init = ibm_fsp_init, + .exit = ibm_fsp_exit, + .cec_power_down = ibm_fsp_cec_power_down, + .cec_reboot = ibm_fsp_cec_reboot, + .pci_setup_phb = apollo_setup_phb, + .pci_get_slot_info = lxvpd_get_slot_info, + .nvram_info = fsp_nvram_info, + .nvram_start_read = fsp_nvram_start_read, + .nvram_write = fsp_nvram_write, + .elog_commit = elog_fsp_commit, + .start_preload_resource = fsp_start_preload_resource, + .resource_loaded = fsp_resource_loaded, + .sensor_read = ibm_fsp_sensor_read, +}; diff --git a/pool/shard008/C/0129419_Jumping_on_the_Clouds_Revisited.c b/pool/shard008/C/0129419_Jumping_on_the_Clouds_Revisited.c new file mode 100644 index 0000000000000000000000000000000000000000..ba5f62ed914e6e0d9d5c9681ed29a6dbca46ea04 --- /dev/null +++ b/pool/shard008/C/0129419_Jumping_on_the_Clouds_Revisited.c @@ -0,0 +1,32 @@ +#include +#include +#include +#include +#include +#include +#include + +int main(){ + int n; + int E=100; + int k; + scanf("%d %d",&n,&k); + int *c = malloc(sizeof(int) * n); + for(int c_i = 0; c_i < n; c_i++){ + scanf("%d",&c[c_i]); + } + int i=1; + while(i!=0) + { static int j=0; + j=(j+k)%n; + if(c[j]==0) + E-=1; + else + E-=3; + i=j; + } + printf("%d",E); + + + return 0; +} diff --git a/pool/shard008/C/0129420_dfa.c b/pool/shard008/C/0129420_dfa.c new file mode 100644 index 0000000000000000000000000000000000000000..f25dfbb3d53f6254188a0cae67848ba3f3575bd0 --- /dev/null +++ b/pool/shard008/C/0129420_dfa.c @@ -0,0 +1,132 @@ +/* + * Chronomaster DFA Format Demuxer + * Copyright (c) 2011 Konstantin Shishkov + * + * This file is part of FFmpeg. + * + * FFmpeg 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. + * + * FFmpeg 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 FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include + +#include "libavutil/intreadwrite.h" +#include "avformat.h" +#include "internal.h" + +static int dfa_probe(AVProbeData *p) +{ + if (p->buf_size < 4 || AV_RL32(p->buf) != MKTAG('D', 'F', 'I', 'A')) + return 0; + + if (AV_RL32(p->buf + 16) != 0x80) + return AVPROBE_SCORE_MAX / 4; + + return AVPROBE_SCORE_MAX; +} + +static int dfa_read_header(AVFormatContext *s) +{ + AVIOContext *pb = s->pb; + AVStream *st; + int frames; + int version; + uint32_t mspf; + + if (avio_rl32(pb) != MKTAG('D', 'F', 'I', 'A')) { + av_log(s, AV_LOG_ERROR, "Invalid magic for DFA\n"); + return AVERROR_INVALIDDATA; + } + + version = avio_rl16(pb); + frames = avio_rl16(pb); + + st = avformat_new_stream(s, NULL); + if (!st) + return AVERROR(ENOMEM); + + st->codec->codec_type = AVMEDIA_TYPE_VIDEO; + st->codec->codec_id = AV_CODEC_ID_DFA; + st->codec->width = avio_rl16(pb); + st->codec->height = avio_rl16(pb); + mspf = avio_rl32(pb); + if (!mspf) { + av_log(s, AV_LOG_WARNING, "Zero FPS reported, defaulting to 10\n"); + mspf = 100; + } + avpriv_set_pts_info(st, 24, mspf, 1000); + avio_skip(pb, 128 - 16); // padding + st->duration = frames; + + if (ff_alloc_extradata(st->codec, 2)) + return AVERROR(ENOMEM); + AV_WL16(st->codec->extradata, version); + if (version == 0x100) { + st->sample_aspect_ratio = (AVRational){2, 1}; + } + return 0; +} + +static int dfa_read_packet(AVFormatContext *s, AVPacket *pkt) +{ + AVIOContext *pb = s->pb; + uint32_t frame_size; + int ret, first = 1; + + if (avio_feof(pb)) + return AVERROR_EOF; + + if (av_get_packet(pb, pkt, 12) != 12) + return AVERROR(EIO); + while (!avio_feof(pb)) { + if (!first) { + ret = av_append_packet(pb, pkt, 12); + if (ret < 0) { + av_free_packet(pkt); + return ret; + } + } else + first = 0; + frame_size = AV_RL32(pkt->data + pkt->size - 8); + if (frame_size > INT_MAX - 4) { + av_log(s, AV_LOG_ERROR, "Too large chunk size: %"PRIu32"\n", frame_size); + return AVERROR(EIO); + } + if (AV_RL32(pkt->data + pkt->size - 12) == MKTAG('E', 'O', 'F', 'R')) { + if (frame_size) { + av_log(s, AV_LOG_WARNING, + "skipping %"PRIu32" bytes of end-of-frame marker chunk\n", + frame_size); + avio_skip(pb, frame_size); + } + return 0; + } + ret = av_append_packet(pb, pkt, frame_size); + if (ret < 0) { + av_free_packet(pkt); + return ret; + } + } + + return 0; +} + +AVInputFormat ff_dfa_demuxer = { + .name = "dfa", + .long_name = NULL_IF_CONFIG_SMALL("Chronomaster DFA"), + .read_probe = dfa_probe, + .read_header = dfa_read_header, + .read_packet = dfa_read_packet, + .flags = AVFMT_GENERIC_INDEX, +}; diff --git a/pool/shard008/C/0129425_qtouch_debug_frame.c b/pool/shard008/C/0129425_qtouch_debug_frame.c new file mode 100644 index 0000000000000000000000000000000000000000..5bd5b10d9da76f34e73bd7b752fc5e281ae9a9ed --- /dev/null +++ b/pool/shard008/C/0129425_qtouch_debug_frame.c @@ -0,0 +1,204 @@ +/*! \file ****************************************************************** + * + * \brief file for Qtouch debug frame handling. + * + * These files contain two functions that are used to decode or encode the Qtouch debug message + * + * - Compiler: IAR EWAVR32 and GNU GCC for AVR32 + * - Supported devices: All AVR32 devices with a USB module can be used. + * - AppNote: + * + * \author Atmel Corporation: http://www.atmel.com \n + * Support and FAQ: http://www.atmel.com/design-support/ + * + ***************************************************************************/ + +/* Copyright (c) 2009-2014 Atmel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an Atmel + * AVR product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + /** + * Support and FAQ: visit Atmel Support + */ +#include "qtouch_debug_frame.h" +#include +#include "pal.h" + + +/** @defgroup QDebug-Target QDebug Related API's(Target) +* +*/ + +/* === GLOBALS ============================================================= */ +// RX USB frame and serial buffer +struct hid_frames hid_rx_frame[4]; +uint8_t RF4CE_RX_Buffer[RX_BUFFER_SIZE]; + +unsigned int rx_index =0; + +// TX USB frame and serial buffer +struct hid_frames hid_tx_frame[MAX_RX_PACKET_NUMBER]; +unsigned int tx_index =0; + +uint8_t data_to_transfer_qt_cont = 0; +/* === MACROS ============================================================== */ + +/* === IMPLEMENTATION ====================================================== */ + +/** + * @brief This function gets a message from QTouch Studio over USB and rebuilds + * it in a single message for RF4CE transfer to the Touch Remote. + + * @param frame a frame received from USB + * @ingroup QDebug-Target + */ +int get_message(struct hid_frames frame,uint8_t *RF4CE_RX_Buffer) +{ + int index=0; + int i=0; + int j=0; + /** + * Error Handling + */ + if((frame.protocol_id!=QDEBUG_PROTOCOL_ID)|| + (frame.packetNumber!=tx_index+1) || + (frame.packetNumber>frame.packetCount)) + { + // Flush Message if QDEBUG_PROTOCOL_ID is not correct + tx_index=0; + return MESSAGE_ERROR; + } + + /** + * Store incoming packet in tx_frame_structure + */ + hid_tx_frame[tx_index++]=frame; + + /** + * if we have a full packet, this can be transmitted over air + * to the AVR477 Remote + */ + if(frame.packetCount==frame.packetNumber) { + + // rebuild and send message to Qtouch device + for(i=0;i RX_BUFFER_SIZE) + return MESSAGE_ERROR; + + tx_index=0; + return MESSAGE_READY; + } + return MESSAGE_PENDING; +} + +/** + * @brief This function transfers received RF4CE Touch data to QTouch Studio + * over USB HID + + * @param message a pointer to the rx_buffer from RF4CE + * @param size of the message stored in the rx_buffer + + * @ingroup QDebug-Target + */ +void send_message(char *message, unsigned int size) +{ + int index=0; + int i=0; + int j=0; + int k=0; + int num_packet=0; + + if(size>PAYLOAD_SIZE*MAX_TX_PACKET_NUMBER) + return; + + // Compute num Packet + num_packet=(size/PAYLOAD_SIZE)+1; + + switch(message[4]) + { + case QT_SIGN_ON: + i=0; + data_to_transfer_qt_cont = 1; + break; + + case QT_GLOBAL_CONFIG: + i=1; + data_to_transfer_qt_cont = 1; + break; + + case QT_SENSOR_CONFIG: + i=2; + data_to_transfer_qt_cont = 1; + break; + + case QT_SIGNALS: + i=0; + data_to_transfer_qt_cont = 2; + break; + + case QT_REFERENCES: + i=0; + data_to_transfer_qt_cont = 3; + break; + + case QT_DELTAS: + i=0; + data_to_transfer_qt_cont = 4; + break; + + case QT_STATES: + i=0; + data_to_transfer_qt_cont = 5; + break; + + default: + i=15; + break; + } + + for(k = 0;k + * + * 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 . + * + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +#define G_LOG_DOMAIN "ide-workspace-actions" + +#include "config.h" + +#include "ide-gui-global.h" +#include "ide-gui-private.h" + +static void +ide_workspace_actions_close (GSimpleAction *action, + GVariant *param, + gpointer user_data) +{ + IdeWorkspace *self = user_data; + + g_assert (G_IS_SIMPLE_ACTION (action)); + g_assert (IDE_IS_WORKSPACE (self)); + + gtk_window_close (GTK_WINDOW (self)); +} + +static void +ide_workspace_actions_show_menu (GSimpleAction *action, + GVariant *param, + gpointer user_data) +{ + IdeWorkspace *self = user_data; + GtkWidget *titlebar; + + g_assert (G_IS_SIMPLE_ACTION (action)); + g_assert (IDE_IS_WORKSPACE (self)); + + titlebar = gtk_window_get_titlebar (GTK_WINDOW (self)); + if (GTK_IS_STACK (titlebar)) + titlebar = gtk_stack_get_visible_child (GTK_STACK (titlebar)); + + if (IDE_IS_HEADER_BAR (titlebar)) + _ide_header_bar_show_menu (IDE_HEADER_BAR (titlebar)); +} + +static void +ide_workspace_actions_surface (GSimpleAction *action, + GVariant *param, + gpointer user_data) +{ + IdeWorkspace *self = user_data; + const gchar *surface; + + g_assert (G_IS_SIMPLE_ACTION (action)); + g_assert (param != NULL); + g_assert (g_variant_is_of_type (param, G_VARIANT_TYPE_STRING)); + g_assert (IDE_IS_WORKSPACE (self)); + + surface = g_variant_get_string (param, NULL); + + ide_workspace_set_visible_surface_name (self, surface); +} + +static void +ide_workspace_actions_command (GSimpleAction *action, + GVariant *param, + gpointer user_data) +{ + IdeCommandManager *command_manager; + IdeWorkspace *self = user_data; + const gchar *command; + IdeContext *context; + + g_assert (G_IS_SIMPLE_ACTION (action)); + g_assert (param != NULL); + g_assert (g_variant_is_of_type (param, G_VARIANT_TYPE_STRING)); + g_assert (IDE_IS_WORKSPACE (self)); + + command = g_variant_get_string (param, NULL); + context = ide_widget_get_context (GTK_WIDGET (self)); + command_manager = ide_command_manager_from_context (context); + + _ide_command_manager_execute (command_manager, self, command); +} + +static const GActionEntry actions[] = { + { "show-menu", ide_workspace_actions_show_menu }, + { "surface", ide_workspace_actions_surface, "s" }, + { "close", ide_workspace_actions_close }, + { "command", ide_workspace_actions_command, "s" }, +}; + +void +_ide_workspace_init_actions (IdeWorkspace *self) +{ + g_return_if_fail (IDE_IS_WORKSPACE (self)); + + g_action_map_add_action_entries (G_ACTION_MAP (self), + actions, + G_N_ELEMENTS (actions), + self); +} diff --git a/pool/shard008/C/0129430_irq-kev7a400.c b/pool/shard008/C/0129430_irq-kev7a400.c new file mode 100644 index 0000000000000000000000000000000000000000..cf51a57c8624b15ef16644c09b017402b85199e5 --- /dev/null +++ b/pool/shard008/C/0129430_irq-kev7a400.c @@ -0,0 +1,92 @@ +/* arch/arm/mach-lh7a40x/irq-kev7a400.c + * + * Copyright (C) 2004 Coastal Environmental Systems + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + */ + +#include +#include + +#include +#include +#include +#include + +#include "common.h" + + /* KEV7a400 CPLD IRQ handling */ + +static u16 CPLD_IRQ_mask; /* Mask for CPLD IRQs, 1 == unmasked */ + +static void +lh7a400_ack_cpld_irq (u32 irq) +{ + CPLD_CL_INT = 1 << (irq - IRQ_KEV7A400_CPLD); +} + +static void +lh7a400_mask_cpld_irq (u32 irq) +{ + CPLD_IRQ_mask &= ~(1 << (irq - IRQ_KEV7A400_CPLD)); + CPLD_WR_PB_INT_MASK = CPLD_IRQ_mask; +} + +static void +lh7a400_unmask_cpld_irq (u32 irq) +{ + CPLD_IRQ_mask |= 1 << (irq - IRQ_KEV7A400_CPLD); + CPLD_WR_PB_INT_MASK = CPLD_IRQ_mask; +} + +static struct +irq_chip lh7a400_cpld_chip = { + .name = "CPLD", + .ack = lh7a400_ack_cpld_irq, + .mask = lh7a400_mask_cpld_irq, + .unmask = lh7a400_unmask_cpld_irq, +}; + +static void +lh7a400_cpld_handler (unsigned int irq, struct irq_desc *desc) +{ + u32 mask = CPLD_LATCHED_INTS; + irq = IRQ_KEV_7A400_CPLD; + for (; mask; mask >>= 1, ++irq) { + if (mask & 1) + desc[irq].handle (irq, desc); + } +} + + /* IRQ initialization */ + +void __init +lh7a400_init_board_irq (void) +{ + int irq; + + for (irq = IRQ_KEV7A400_CPLD; + irq < IRQ_KEV7A400_CPLD + NR_IRQ_KEV7A400_CPLD; ++irq) { + set_irq_chip (irq, &lh7a400_cpld_chip); + set_irq_handler (irq, handle_edge_irq); + set_irq_flags (irq, IRQF_VALID); + } + set_irq_chained_handler (IRQ_CPLD, kev7a400_cpld_handler); + + /* Clear all CPLD interrupts */ + CPLD_CL_INT = 0xff; /* CPLD_INTR_MMC_CD | CPLD_INTR_ETH_INT; */ + + + GPIO_GPIOINTEN = 0; /* Disable all GPIO interrupts */ + barrier(); + GPIO_INTTYPE1 + = (GPIO_INTR_PCC1_CD | GPIO_INTR_PCC1_CD); /* Edge trig. */ + GPIO_INTTYPE2 = 0; /* Falling edge & low-level */ + GPIO_GPIOFEOI = 0xff; /* Clear all GPIO interrupts */ + GPIO_GPIOINTEN = 0xff; /* Enable all GPIO interrupts */ + + init_FIQ(); +} diff --git a/pool/shard008/C/0129432_count1.c b/pool/shard008/C/0129432_count1.c new file mode 100644 index 0000000000000000000000000000000000000000..e8e4ed3c9240398aa028619acd3408d6f736feef --- /dev/null +++ b/pool/shard008/C/0129432_count1.c @@ -0,0 +1,88 @@ +/* + * count1.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads4w - POSIX Threads for Windows + * Copyright 1998 John E. Bossom + * Copyright 1999-2018, Pthreads4w contributors + * + * Homepage: https://sourceforge.net/projects/pthreads4w/ + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * + * https://sourceforge.net/p/pthreads4w/wiki/Contributors/ + * + * 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. + * + * -------------------------------------------------------------------------- + * + * Description: + * Test some basic assertions about the number of threads at runtime. + */ + +#include "test.h" + +#define NUMTHREADS (30) + +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +static pthread_t threads[NUMTHREADS]; +static unsigned numThreads = 0; + +void * +myfunc(void *arg) +{ + pthread_mutex_lock(&lock); + numThreads++; + pthread_mutex_unlock(&lock); + + Sleep(1000); + return 0; +} +int +main() +{ + int i; + int maxThreads = sizeof(threads) / sizeof(pthread_t); + + /* + * Spawn NUMTHREADS threads. Each thread should increment the + * numThreads variable, sleep for one second. + */ + for (i = 0; i < maxThreads; i++) + { + assert(pthread_create(&threads[i], NULL, myfunc, 0) == 0); + } + + /* + * Wait for all the threads to exit. + */ + for (i = 0; i < maxThreads; i++) + { + assert(pthread_join(threads[i], NULL) == 0); + } + + /* + * Check the number of threads created. + */ + assert((int) numThreads == maxThreads); + + /* + * Success. + */ + return 0; +} diff --git a/pool/shard008/C/0129433_ad_ntfs_close.c b/pool/shard008/C/0129433_ad_ntfs_close.c new file mode 100644 index 0000000000000000000000000000000000000000..37994b852bed17d85c9c6c260506b656edffab10 --- /dev/null +++ b/pool/shard008/C/0129433_ad_ntfs_close.c @@ -0,0 +1,30 @@ +/* -*- Mode: C; c-basic-offset:4 ; -*- */ +/* + * + * Copyright (C) 1997 University of Chicago. + * See COPYRIGHT notice in top-level directory. + */ + +#include "ad_ntfs.h" + +void ADIOI_NTFS_Close(ADIO_File fd, int *error_code) +{ + int err; + static char myname[] = "ADIOI_NTFS_Close"; + + err = CloseHandle(fd->fd_sys); + /* --BEGIN ERROR HANDLING-- */ + if (err == FALSE) + { + char errMsg[ADIOI_NTFS_ERR_MSG_MAX]; + err = GetLastError(); + ADIOI_NTFS_Strerror(err, errMsg, ADIOI_NTFS_ERR_MSG_MAX); + *error_code = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE, + myname, __LINE__, MPI_ERR_IO, + "**io", + "**io %s", errMsg); + return; + } + /* --END ERROR HANDLING-- */ + *error_code = MPI_SUCCESS; +} diff --git a/pool/shard008/C/0129437_gwin32volumemonitor.c b/pool/shard008/C/0129437_gwin32volumemonitor.c new file mode 100644 index 0000000000000000000000000000000000000000..c9db68a8a21ed8e508cafcf2f01b1323888ee102 --- /dev/null +++ b/pool/shard008/C/0129437_gwin32volumemonitor.c @@ -0,0 +1,255 @@ +/* GIO - GLib Input, Output and Streaming Library + * + * Copyright (C) 2006-2007 Red Hat, Inc. + * Copyright (C) 2008 Hans Breuer + * + * 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. + * + * You should have received a copy of the GNU Lesser General + * Public License along with this library; if not, see . + * + * Author: Alexander Larsson + * David Zeuthen + * Hans Breuer + */ + +#include "config.h" + +#include + +#include +#include "glibintl.h" + +#include "gwin32volumemonitor.h" +#include "gwin32mount.h" +#include "gmount.h" +#include "giomodule.h" + +#include + +struct _GWin32VolumeMonitor { + GNativeVolumeMonitor parent; +}; + +#define g_win32_volume_monitor_get_type _g_win32_volume_monitor_get_type +G_DEFINE_TYPE_WITH_CODE (GWin32VolumeMonitor, g_win32_volume_monitor, G_TYPE_NATIVE_VOLUME_MONITOR, + g_io_extension_point_implement (G_NATIVE_VOLUME_MONITOR_EXTENSION_POINT_NAME, + g_define_type_id, + "win32", + 0)); + +/** + * get_viewable_logical_drives: + * + * Returns the list of logical and viewable drives as defined by + * GetLogicalDrives() and the registry keys + * Software\Microsoft\Windows\CurrentVersion\Policies\Explorer under + * HKLM or HKCU. If neither key exists the result of + * GetLogicalDrives() is returned. + * + * Returns: bitmask with same meaning as returned by GetLogicalDrives() + */ +static guint32 +get_viewable_logical_drives (void) +{ + guint viewable_drives = GetLogicalDrives (); + HKEY key; + + DWORD var_type = REG_DWORD; //the value's a REG_DWORD type + DWORD no_drives_size = 4; + DWORD no_drives; + gboolean hklm_present = FALSE; + + if (RegOpenKeyEx (HKEY_LOCAL_MACHINE, + "Software\\Microsoft\\Windows\\" + "CurrentVersion\\Policies\\Explorer", + 0, KEY_READ, &key) == ERROR_SUCCESS) + { + if (RegQueryValueEx (key, "NoDrives", NULL, &var_type, + (LPBYTE) &no_drives, &no_drives_size) == ERROR_SUCCESS) + { + /* We need the bits that are set in viewable_drives, and + * unset in no_drives. + */ + viewable_drives = viewable_drives & ~no_drives; + hklm_present = TRUE; + } + RegCloseKey (key); + } + + /* If the key is present in HKLM then the one in HKCU should be ignored */ + if (!hklm_present) + { + if (RegOpenKeyEx (HKEY_CURRENT_USER, + "Software\\Microsoft\\Windows\\" + "CurrentVersion\\Policies\\Explorer", + 0, KEY_READ, &key) == ERROR_SUCCESS) + { + if (RegQueryValueEx (key, "NoDrives", NULL, &var_type, + (LPBYTE) &no_drives, &no_drives_size) == ERROR_SUCCESS) + { + viewable_drives = viewable_drives & ~no_drives; + } + RegCloseKey (key); + } + } + + return viewable_drives; +} + +/* deliver accesible (aka 'mounted') volumes */ +static GList * +get_mounts (GVolumeMonitor *volume_monitor) +{ + DWORD drives; + gchar drive[4] = "A:\\"; + GList *list = NULL; + + drives = get_viewable_logical_drives (); + + if (!drives) + g_warning ("get_viewable_logical_drives failed."); + + while (drives && drive[0] <= 'Z') + { + if (drives & 1) + { + list = g_list_prepend (list, _g_win32_mount_new (volume_monitor, drive, NULL)); + } + drives >>= 1; + drive[0]++; + } + return list; +} + +/* actually 'mounting' volumes is out of GIOs business on win32, so no volumes are delivered either */ +static GList * +get_volumes (GVolumeMonitor *volume_monitor) +{ + return NULL; +} + +/* real hardware */ +static GList * +get_connected_drives (GVolumeMonitor *volume_monitor) +{ + GList *list = NULL; + +#if 0 + HANDLE find_handle; + BOOL found; + wchar_t wc_name[MAX_PATH+1]; + + find_handle = FindFirstVolumeW (wc_name, MAX_PATH); + found = (find_handle != INVALID_HANDLE_VALUE); + while (found) + { + /* I don't know what this code is supposed to do; clearly it now + * does nothing, the returned GList is always NULL. But what was + * this code supposed to be a start of? The volume names that + * the FindFirstVolume/FindNextVolume loop iterates over returns + * device names like + * + * \Device\HarddiskVolume1 + * \Device\HarddiskVolume2 + * \Device\CdRom0 + * + * No DOS devices there, so I don't see the point with the + * QueryDosDevice call below. Probably this code is confusing volumes + * with something else that does contain the mapping from DOS devices + * to volumes. + */ + wchar_t wc_dev_name[MAX_PATH+1]; + guint trailing = wcslen (wc_name) - 1; + + /* remove trailing backslash and leading \\?\\ */ + wc_name[trailing] = L'\0'; + if (QueryDosDeviceW (&wc_name[4], wc_dev_name, MAX_PATH)) + { + gchar *name = g_utf16_to_utf8 (wc_dev_name, -1, NULL, NULL, NULL); + g_print ("%s\n", name); + g_free (name); + } + + found = FindNextVolumeW (find_handle, wc_name, MAX_PATH); + } + if (find_handle != INVALID_HANDLE_VALUE) + FindVolumeClose (find_handle); +#endif + + return list; +} + +static GVolume * +get_volume_for_uuid (GVolumeMonitor *volume_monitor, const char *uuid) +{ + return NULL; +} + +static GMount * +get_mount_for_uuid (GVolumeMonitor *volume_monitor, const char *uuid) +{ + return NULL; +} + +static gboolean +is_supported (void) +{ + return TRUE; +} + +static GMount * +get_mount_for_mount_path (const char *mount_path, + GCancellable *cancellable) +{ + GWin32Mount *mount; + + /* TODO: Set mountable volume? */ + mount = _g_win32_mount_new (NULL, mount_path, NULL); + + return G_MOUNT (mount); +} + +static void +g_win32_volume_monitor_class_init (GWin32VolumeMonitorClass *klass) +{ + GVolumeMonitorClass *monitor_class = G_VOLUME_MONITOR_CLASS (klass); + GNativeVolumeMonitorClass *native_class = G_NATIVE_VOLUME_MONITOR_CLASS (klass); + + monitor_class->get_mounts = get_mounts; + monitor_class->get_volumes = get_volumes; + monitor_class->get_connected_drives = get_connected_drives; + monitor_class->get_volume_for_uuid = get_volume_for_uuid; + monitor_class->get_mount_for_uuid = get_mount_for_uuid; + monitor_class->is_supported = is_supported; + + native_class->get_mount_for_mount_path = get_mount_for_mount_path; +} + +static void +g_win32_volume_monitor_init (GWin32VolumeMonitor *win32_monitor) +{ + /* maybe we shoud setup a callback window to listern for WM_DEVICECHANGE ? */ +#if 0 + unix_monitor->mount_monitor = g_win32_mount_monitor_new (); + + g_signal_connect (win32_monitor->mount_monitor, + "mounts-changed", G_CALLBACK (mounts_changed), + win32_monitor); + + g_signal_connect (win32_monitor->mount_monitor, + "mountpoints-changed", G_CALLBACK (mountpoints_changed), + win32_monitor); + + update_volumes (win32_monitor); + update_mounts (win32_monitor); +#endif +} diff --git a/pool/shard008/C/0129444_main.c b/pool/shard008/C/0129444_main.c new file mode 100644 index 0000000000000000000000000000000000000000..003ee177e88da78c30040a2eb765fef7e479cff1 --- /dev/null +++ b/pool/shard008/C/0129444_main.c @@ -0,0 +1,204 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +char *allocateString(const char format[], ...) +{ + va_list arguments1; + va_list arguments2; + + va_start(arguments1, format); + va_start(arguments2, format); + + int size = vsnprintf(NULL, 0, format, arguments1) + 1; + + char *output = malloc(size); + + if(output) + { + vsprintf(output, format, arguments2); + } + + va_end(arguments1); + va_end(arguments2); + + return output; +} + +char *ipv4ToString(const struct sockaddr_in *address) +{ + return allocateString("%u.%u.%u.%u", + ((char*)&address->sin_addr)[0], + ((char*)&address->sin_addr)[1], + ((char*)&address->sin_addr)[2], + ((char*)&address->sin_addr)[3] + ); +} + +char *ipv6ToString(const struct sockaddr_in6 *address) +{ + return allocateString( + "%02x%02x:%02x%02x:%02x%02x:%02x%02x:" + "%02x%02x:%02x%02x:%02x%02x:%02x%02x", + address->sin6_addr.s6_addr[0], + address->sin6_addr.s6_addr[1], + address->sin6_addr.s6_addr[2], + address->sin6_addr.s6_addr[3], + address->sin6_addr.s6_addr[4], + address->sin6_addr.s6_addr[5], + address->sin6_addr.s6_addr[6], + address->sin6_addr.s6_addr[7], + address->sin6_addr.s6_addr[8], + address->sin6_addr.s6_addr[9], + address->sin6_addr.s6_addr[10], + address->sin6_addr.s6_addr[11], + address->sin6_addr.s6_addr[12], + address->sin6_addr.s6_addr[13], + address->sin6_addr.s6_addr[14], + address->sin6_addr.s6_addr[15] + ); +} + +char *ipToString(const struct sockaddr_storage *address) +{ + if(address->ss_family == AF_INET) + { + return ipv4ToString((struct sockaddr_in*)address); + } + + if(address->ss_family == AF_INET6) + { + return ipv6ToString((struct sockaddr_in6*)address); + } + + fputs("Invalid address type.", stderr); + + return NULL; +} + +void createTable(sqlite3 *database) +{ + const char *query = "CREATE TABLE IF NOT EXISTS " + "connections(address TEXT NOT NULL, time DATETIME NOT NULL);"; + + char *error; + + if(sqlite3_exec(database, query, NULL, NULL, &error) != SQLITE_OK) + { + fprintf(stderr, "Failed to create database: %s.\n", error); + sqlite3_free(error); + } +} + +void insertAddress(sqlite3 *database, const struct sockaddr_storage *address) +{ + char *address_string = ipToString(address); + + char *query = allocateString( + "INSERT INTO connections (address, time) VALUES (\"%s\", datetime());", address_string + ); + + char *error; + + if(sqlite3_exec(database, query, NULL, NULL, &error) != SQLITE_OK) + { + fprintf(stderr, "Failed to insert row: %s.\n", error); + sqlite3_free(error); + } + + free(address_string); + free(query); +} + +int main(int argc, char *argv[]) +{ + sqlite3 *database; + int result = sqlite3_open("database.sqlite", &database); + + if(result == SQLITE_OK) + { + createTable(database); + + struct addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = AI_PASSIVE; + + struct addrinfo *address; + + if(getaddrinfo(NULL, "12345", &hints, &address) == -1) + { + + } + else + { + int sock = socket( + address->ai_family, + address->ai_socktype, + address->ai_protocol + ); + + if(sock == -1) + { + fputs("Failed to create socket.\n", stderr); + } + else + { + if(bind(sock, address->ai_addr, address->ai_addrlen) == -1) + { + fputs("Failed to bind socket to port.\n", stderr); + } + else if(listen(sock, 16) == -1) + { + fputs("Failed to listen to socket.\n", stderr); + } + else + { + while(true) + { + struct sockaddr_storage remote_address; + socklen_t remote_address_size = sizeof(remote_address); + + int remote = accept( + sock, + (struct sockaddr*)&remote_address, + &remote_address_size + ); + + if(remote == -1) + { + fputs("Failed to accept remote connection.\n", stderr); + } + else + { + char *address_string = ipToString(&remote_address); + printf("Received connection from %s\n", address_string); + insertAddress(database, &remote_address); + free(address_string); + close(remote); + } + } + } + + close(sock); + } + + freeaddrinfo(address); + } + + sqlite3_close(database); + } + else + { + const char *error = sqlite3_errmsg(database); + fprintf(stderr, "SQLite encountered an error: %s\n", error); + } + + return EXIT_SUCCESS; +} diff --git a/pool/shard008/C/0129452_board-kona-sdio.c b/pool/shard008/C/0129452_board-kona-sdio.c new file mode 100644 index 0000000000000000000000000000000000000000..25421bfc4578ff3f9aedf90e283657da6fdfd49e --- /dev/null +++ b/pool/shard008/C/0129452_board-kona-sdio.c @@ -0,0 +1,167 @@ +/* arch/arm/mach-omap2/board-kona-sdio.c + * + * Based on mach-omap2/board-palau-sdio.c + * + * Copyright (C) 2012 Samsung Electronics Co, Ltd. + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * 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. + */ + +#include +#include +#include +#include + +#include +#include + +#include "board-kona.h" +#include +#include "mux.h" +#include "omap_muxtbl.h" +#include "hsmmc.h" + +/*for sysfs to update sd detect pin's status*/ +static struct device *sd_detection_cmd_dev; + +static struct omap2_hsmmc_info kona_mmc_info[] = { + { + .mmc = 2, + .nonremovable = true, + .external_ldo = false, + .caps = MMC_CAP_8_BIT_DATA | MMC_CAP_1_8V_DDR | + MMC_CAP_UHS_DDR50, + .caps2 = MMC_CAP2_PACKED_CMD | MMC_CAP2_ADAPT_PACKED, + .ocr_mask = MMC_VDD_165_195, + .gpio_wp = -EINVAL, + .gpio_cd = -EINVAL, +#ifdef CONFIG_PM_RUNTIME + .power_saving = false, +#endif + }, + { + .mmc = 1, + .caps = MMC_CAP_8_BIT_DATA, + .gpio_wp = -EINVAL, + .gpio_cd = -EINVAL, +#ifdef CONFIG_PM_RUNTIME + .power_saving = false, +#endif + }, + { + .name = "omap_wlan", + .mmc = 5, + .caps = MMC_CAP_4_BIT_DATA, + .gpio_wp = -EINVAL, + .gpio_cd = -EINVAL, + .ocr_mask = MMC_VDD_165_195 | MMC_VDD_20_21, + .nonremovable = false, + .mmc_data = &kona_wifi_data, + }, + {} /* Terminator */ +}; + + +static ssize_t sd_detection_cmd_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + int ret = -EIO; + u8 read_reg = 0; + + ret = twl_i2c_read_u8(TWL6030_MODULE_ID0, &read_reg, + TWL6034_MMCCTRL); + + if (ret >= 0) + ret = read_reg & STS_MMC; + + if (ret) { + pr_debug("SD : card inserted.\n"); + return sprintf(buf, "Insert\n"); + } else { + pr_debug("SD : card removed.\n"); + return sprintf(buf, "Remove\n"); + } + +} +static DEVICE_ATTR(status, S_IRUGO, sd_detection_cmd_show, NULL); + + +static int kona_hsmmc_late_init(struct device *dev) +{ + int ret = 0; + struct platform_device *pdev = + container_of(dev, struct platform_device, dev); + struct omap_mmc_platform_data *pdata = dev->platform_data; + + /* Setting MMC1 Card detect IRQ */ + if (pdev->id == 0) { + ret = twl6030_mmc_card_detect_config(); + if (ret) + pr_err("(%s): failed configuring MMC1 card detect\n", + __func__); + pdata->slots[0].card_detect_irq = + TWL6030_IRQ_BASE + MMCDETECT_INTR_OFFSET; + pdata->slots[0].card_detect = twl6030_mmc_card_detect; + + if (sd_detection_cmd_dev == NULL) { + /*create sysfs file for detect pin*/ + sd_detection_cmd_dev = device_create(sec_class, + NULL, 0, NULL, "sdcard"); + if (IS_ERR(sd_detection_cmd_dev)) + pr_err("Failed to create sdcard sysfs dev\n"); + + if (device_create_file(sd_detection_cmd_dev, + &dev_attr_status) < 0) + pr_err("Fail to create sysfs " + "sdcard/status sysfs file\n"); + } + + } + + return ret; +} + +static void __init kona_hsmmc_set_late_init(struct device *dev) +{ + struct omap_mmc_platform_data *pdata; + + /* dev can be null if CONFIG_MMC_OMAP_HS is not set */ + if (!dev) { + pr_err("(%s): failed!\n", __func__); + return; + } + + pdata = dev->platform_data; + pdata->init = kona_hsmmc_late_init; +} + +static int __init kona_hsmmc_init(struct omap2_hsmmc_info *controllers) +{ + struct omap2_hsmmc_info *c; + + /* Board specific GPIO pin for External LDO control */ + for (c = controllers; c->mmc; c++) { + if ((c->mmc == 2) && (c->external_ldo == true)) + c->gpio_for_ldo = + omap_muxtbl_get_gpio_by_name("eMMC_EN"); + } + + omap2_hsmmc_init(controllers); + + for (c = controllers; c->mmc; c++) + kona_hsmmc_set_late_init(c->dev); + + return 0; +} + +void __init omap4_kona_sdio_init(void) +{ + kona_hsmmc_init(kona_mmc_info); +} diff --git a/pool/shard008/C/0129454_mdss_mdp_rotator.c b/pool/shard008/C/0129454_mdss_mdp_rotator.c new file mode 100644 index 0000000000000000000000000000000000000000..a5d072b2ae5809e63d9fbfcf400abc441719ac90 --- /dev/null +++ b/pool/shard008/C/0129454_mdss_mdp_rotator.c @@ -0,0 +1,261 @@ +/* Copyright (c) 2012, The Linux Foundation. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 and + * only version 2 as published by the Free Software Foundation. + * + * 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. + * + */ + +#define pr_fmt(fmt) "%s: " fmt, __func__ + +#include +#include +#include +#include + +#include "mdss_mdp.h" +#include "mdss_mdp_rotator.h" + +#define MAX_ROTATOR_SESSIONS 8 + +static DEFINE_MUTEX(rotator_lock); +static struct mdss_mdp_rotator_session rotator_session[MAX_ROTATOR_SESSIONS]; +static LIST_HEAD(rotator_queue); + +struct mdss_mdp_rotator_session *mdss_mdp_rotator_session_alloc(void) +{ + struct mdss_mdp_rotator_session *rot; + int i; + + mutex_lock(&rotator_lock); + for (i = 0; i < MAX_ROTATOR_SESSIONS; i++) { + rot = &rotator_session[i]; + if (rot->ref_cnt == 0) { + rot->ref_cnt++; + rot->session_id = i | MDSS_MDP_ROT_SESSION_MASK; + mutex_init(&rot->lock); + init_completion(&rot->comp); + break; + } + } + mutex_unlock(&rotator_lock); + if (i == MAX_ROTATOR_SESSIONS) { + pr_err("max rotator sessions reached\n"); + return NULL; + } + + return rot; +} + +struct mdss_mdp_rotator_session *mdss_mdp_rotator_session_get(u32 session_id) +{ + struct mdss_mdp_rotator_session *rot; + u32 ndx; + + ndx = session_id & ~MDSS_MDP_ROT_SESSION_MASK; + if (ndx < MAX_ROTATOR_SESSIONS) { + rot = &rotator_session[ndx]; + if (rot->ref_cnt && rot->session_id == session_id) + return rot; + } + return NULL; +} + +static struct mdss_mdp_pipe *mdss_mdp_rotator_pipe_alloc(void) +{ + struct mdss_mdp_mixer *mixer; + struct mdss_mdp_pipe *pipe = NULL; + int pnum; + + mixer = mdss_mdp_wb_mixer_alloc(1); + if (!mixer) + return NULL; + + switch (mixer->num) { + case MDSS_MDP_LAYERMIXER3: + pnum = MDSS_MDP_SSPP_DMA0; + break; + case MDSS_MDP_LAYERMIXER4: + pnum = MDSS_MDP_SSPP_DMA1; + break; + default: + goto done; + } + + pipe = mdss_mdp_pipe_alloc_pnum(pnum); + + if (pipe) + pipe->mixer = mixer; +done: + if (!pipe) + mdss_mdp_wb_mixer_destroy(mixer); + + return pipe; +} + +static int mdss_mdp_rotator_busy_wait(struct mdss_mdp_rotator_session *rot) +{ + mutex_lock(&rot->lock); + if (rot->busy) { + pr_debug("waiting for rot=%d to complete\n", rot->pipe->num); + wait_for_completion_interruptible(&rot->comp); + rot->busy = false; + + } + mutex_unlock(&rot->lock); + + return 0; +} + +static void mdss_mdp_rotator_callback(void *arg) +{ + struct mdss_mdp_rotator_session *rot; + + rot = (struct mdss_mdp_rotator_session *) arg; + if (rot) + complete(&rot->comp); +} + +static int mdss_mdp_rotator_kickoff(struct mdss_mdp_ctl *ctl, + struct mdss_mdp_rotator_session *rot, + struct mdss_mdp_data *dst_data) +{ + int ret; + struct mdss_mdp_writeback_arg wb_args = { + .callback_fnc = mdss_mdp_rotator_callback, + .data = dst_data, + .priv_data = rot, + }; + + mutex_lock(&rot->lock); + INIT_COMPLETION(rot->comp); + rot->busy = true; + ret = mdss_mdp_display_commit(ctl, &wb_args); + if (ret) { + rot->busy = false; + pr_err("problem with kickoff rot pipe=%d", rot->pipe->num); + } + mutex_unlock(&rot->lock); + return ret; +} + +static int mdss_mdp_rotator_pipe_dequeue(struct mdss_mdp_rotator_session *rot) +{ + if (rot->pipe) { + pr_debug("reusing existing session=%d\n", rot->pipe->num); + mdss_mdp_rotator_busy_wait(rot); + list_move_tail(&rot->head, &rotator_queue); + } else { + struct mdss_mdp_rotator_session *tmp; + + rot->params_changed++; + rot->pipe = mdss_mdp_rotator_pipe_alloc(); + if (rot->pipe) { + pr_debug("use new rotator pipe=%d\n", rot->pipe->num); + + rot->pipe->mixer_stage = MDSS_MDP_STAGE_UNUSED; + list_add_tail(&rot->head, &rotator_queue); + } else if (!list_empty(&rotator_queue)) { + tmp = list_first_entry(&rotator_queue, + struct mdss_mdp_rotator_session, + head); + + pr_debug("wait for rotator pipe=%d\n", tmp->pipe->num); + mdss_mdp_rotator_busy_wait(tmp); + rot->pipe = tmp->pipe; + tmp->pipe = NULL; + + list_del(&tmp->head); + list_add_tail(&rot->head, &rotator_queue); + } else { + pr_err("no available rotator pipes\n"); + return -EBUSY; + } + } + + return 0; +} + +int mdss_mdp_rotator_queue(struct mdss_mdp_rotator_session *rot, + struct mdss_mdp_data *src_data, + struct mdss_mdp_data *dst_data) +{ + struct mdss_mdp_pipe *rot_pipe; + struct mdss_mdp_ctl *ctl; + int ret; + + if (!rot) + return -ENODEV; + + mutex_lock(&rotator_lock); + ret = mdss_mdp_rotator_pipe_dequeue(rot); + if (ret) { + pr_err("unable to acquire rotator\n"); + goto done; + } + + rot_pipe = rot->pipe; + + pr_debug("queue rotator pnum=%d\n", rot_pipe->num); + + ctl = rot_pipe->mixer->ctl; + + if (rot->params_changed) { + rot->params_changed = 0; + rot_pipe->flags = rot->rotations; + rot_pipe->src_fmt = mdss_mdp_get_format_params(rot->format); + rot_pipe->img_width = rot->img_width; + rot_pipe->img_height = rot->img_height; + rot_pipe->src = rot->src_rect; + rot_pipe->dst = rot->src_rect; + rot_pipe->bwc_mode = rot->bwc_mode; + rot_pipe->params_changed++; + } + + ret = mdss_mdp_pipe_queue_data(rot->pipe, src_data); + if (ret) { + pr_err("unable to queue rot data\n"); + goto done; + } + + ret = mdss_mdp_rotator_kickoff(ctl, rot, dst_data); + +done: + mutex_unlock(&rotator_lock); + + if (!rot->no_wait) + mdss_mdp_rotator_busy_wait(rot); + + return ret; +} + +int mdss_mdp_rotator_finish(struct mdss_mdp_rotator_session *rot) +{ + struct mdss_mdp_pipe *rot_pipe; + + if (!rot) + return -ENODEV; + + pr_debug("finish rot id=%x\n", rot->session_id); + + mutex_lock(&rotator_lock); + rot_pipe = rot->pipe; + if (rot_pipe) { + mdss_mdp_rotator_busy_wait(rot); + list_del(&rot->head); + } + memset(rot, 0, sizeof(*rot)); + if (rot_pipe) { + struct mdss_mdp_mixer *mixer = rot_pipe->mixer; + mdss_mdp_pipe_destroy(rot_pipe); + mdss_mdp_wb_mixer_destroy(mixer); + } + mutex_unlock(&rotator_lock); + + return 0; +} diff --git a/pool/shard008/C/0129455_cpuli1.c b/pool/shard008/C/0129455_cpuli1.c new file mode 100644 index 0000000000000000000000000000000000000000..d757cb6d483b1df652a4aa660d34a47c8de2d16a --- /dev/null +++ b/pool/shard008/C/0129455_cpuli1.c @@ -0,0 +1,57 @@ +#define _GNU_SOURCE /* See feature_test_macros(7) */ +#include +#include +#include +#include +#include +#include +#include + +const int NUM_THREADS = 1; +void *thread_main( void *threadid) +{ + /* 把自己加入cgroup中(syscall(SYS_gettid)为得到线程的系统tid) */ + char cmd[128]; + long tid; + int a=0; + sprintf (cmd, "echo %ld >> /sys/fs/cgroup/cpu/zz/tasks " , syscall(SYS_gettid)); + system (cmd); +// sprintf (cmd, "echo %ld >> /sys/fs/cgroup/cpuset/zz/tasks" , syscall(SYS_gettid)); +// system (cmd); + tid = ( long )threadid; + printf ( "Hello World! It's me, thread #%ld, pid #%ld!\n" , tid, syscall(SYS_gettid)); + while (1) { + a++; + } + pthread_exit(NULL); +} +int main ( int argc, char *argv[]) +{ + int num_threads; + if (argc > 1) { + num_threads = atoi (argv[1]); + } + if (num_threads<=0 || num_threads>=100) { + num_threads = NUM_THREADS; + } + mkdir("/sys/fs/cgroup/cpu/zz",755); + /* 设置CPU利用率为20% */ + system ( "echo 20000> /sys/fs/cgroup/cpu/zz/cpu.cfs_quota_us" ); + mkdir("/sys/fs/cgroup/cpuset/zz",755); + /* 限制CPU只能使用#1核*/ + system ( "echo \"0\" > /sys/fs/cgroup/cpuset/zz/cpuset.cpus" ); + pthread_t* threads = (pthread_t*) malloc ( sizeof (pthread_t)*num_threads); + int rc; + long t; + for (t=0; t +#include +typedef struct node { + int data; + struct node *next; + }node; + node *list = NULL; + +void ins_beg() { + int x; + scanf("%d",&x); + node *p; + p = (node *)malloc(sizeof(node)); + p->data = x; + p->next = list; + list = p; +} +void ins_end() { + int x; + scanf("%d",&x); + node *p,*q; + p = list; + while(p->next != NULL) + p = p->next; + q = (node *)malloc(sizeof(node)); + q->data = x; + q->next = NULL; + p->next = q; +} + +void del_beg() { + node *p; + p = list; + int x = p->data; + printf("%d is deleted\n",x); + list = p->next; + free(p); +} +void del_end() { + node *p = list; + node *q = p->next; + while(q->next != NULL) { + p = q; + q = q->next; + } + int x = q->data; + printf("%d is deleted\n",x); + p->next = NULL; + free(q); +} + +void display() { + int c = 0; + node *p = list; + while(p != NULL) { + c++; + int y = p->data; + printf("%d ",y); + p = p->next; + } + printf("\n"); +} +int main() { + int n; + int choice; + do { + printf("1)Insert at begining\n2)Insert at end\n4)Delete at beginging\n5)Delete at end\n7)Display\n8)Exit\n"); + scanf("%d",&choice); + switch(choice) + { + case 1: + ins_beg(); + break; + case 2: + ins_end(); + break; + break; + case 4: + del_beg(); + break; + case 5: + del_end(); + break; + case 7: + display(); + break; + case 8: + exit(0); + } + }while(choice!=8); + return 0; +} diff --git a/pool/shard008/C/0129460_test_syr2.c b/pool/shard008/C/0129460_test_syr2.c new file mode 100644 index 0000000000000000000000000000000000000000..be4e4b220a76b321a837923d6342bbef6c3aeba0 --- /dev/null +++ b/pool/shard008/C/0129460_test_syr2.c @@ -0,0 +1,333 @@ +/* + + BLIS + An object-based framework for developing high-performance BLAS-like + libraries. + + Copyright (C) 2014, The University of Texas + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + - Neither the name of The University of Texas nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#include "blis.h" +#include "test_libblis.h" + + +// Static variables. +static char* op_str = "syr2"; +static char* o_types = "vvm"; // x y a +static char* p_types = "ucc"; // uploa conjx conjy +static thresh_t thresh[BLIS_NUM_FP_TYPES] = { { 1e-04, 1e-05 }, // warn, pass for s + { 1e-04, 1e-05 }, // warn, pass for c + { 1e-13, 1e-14 }, // warn, pass for d + { 1e-13, 1e-14 } }; // warn, pass for z + +// Local prototypes. +void libblis_test_syr2_deps( test_params_t* params, + test_op_t* op ); + +void libblis_test_syr2_experiment( test_params_t* params, + test_op_t* op, + iface_t iface, + num_t datatype, + char* pc_str, + char* sc_str, + unsigned int p_cur, + double* perf, + double* resid ); + +void libblis_test_syr2_impl( iface_t iface, + obj_t* alpha, + obj_t* x, + obj_t* y, + obj_t* a ); + +void libblis_test_syr2_check( obj_t* alpha, + obj_t* x, + obj_t* y, + obj_t* a, + obj_t* a_orig, + double* resid ); + + + +void libblis_test_syr2_deps( test_params_t* params, test_op_t* op ) +{ + libblis_test_randv( params, &(op->ops->randv) ); + libblis_test_randm( params, &(op->ops->randm) ); + libblis_test_normfv( params, &(op->ops->normfv) ); + libblis_test_subv( params, &(op->ops->subv) ); + libblis_test_copym( params, &(op->ops->copym) ); + libblis_test_scal2v( params, &(op->ops->scal2v) ); + libblis_test_dotv( params, &(op->ops->dotv) ); + libblis_test_gemv( params, &(op->ops->gemv) ); +} + + + +void libblis_test_syr2( test_params_t* params, test_op_t* op ) +{ + + // Return early if this test has already been done. + if ( op->test_done == TRUE ) return; + + // Return early if operation is disabled. + if ( op->op_switch == DISABLE_ALL || + op->ops->l2_over == DISABLE_ALL ) return; + + // Call dependencies first. + if ( TRUE ) libblis_test_syr2_deps( params, op ); + + // Execute the test driver for each implementation requested. + if ( op->front_seq == ENABLE ) + { + libblis_test_op_driver( params, + op, + BLIS_TEST_SEQ_FRONT_END, + op_str, + p_types, + o_types, + thresh, + libblis_test_syr2_experiment ); + } +} + + + +void libblis_test_syr2_experiment( test_params_t* params, + test_op_t* op, + iface_t iface, + num_t datatype, + char* pc_str, + char* sc_str, + unsigned int p_cur, + double* perf, + double* resid ) +{ + unsigned int n_repeats = params->n_repeats; + unsigned int i; + + double time_min = 1e9; + double time; + + dim_t m; + + uplo_t uploa; + conj_t conjx, conjy; + + obj_t alpha, x, y, a; + obj_t a_save; + + + // Map the dimension specifier to an actual dimension. + m = libblis_test_get_dim_from_prob_size( op->dim_spec[0], p_cur ); + + // Map parameter characters to BLIS constants. + bli_param_map_char_to_blis_uplo( pc_str[0], &uploa ); + bli_param_map_char_to_blis_conj( pc_str[1], &conjx ); + bli_param_map_char_to_blis_conj( pc_str[2], &conjy ); + + // Create test scalars. + bli_obj_scalar_init_detached( datatype, &alpha ); + + // Create test operands (vectors and/or matrices). + libblis_test_vobj_create( params, datatype, + sc_str[0], m, &x ); + libblis_test_vobj_create( params, datatype, + sc_str[1], m, &y ); + libblis_test_mobj_create( params, datatype, BLIS_NO_TRANSPOSE, + sc_str[2], m, m, &a ); + libblis_test_mobj_create( params, datatype, BLIS_NO_TRANSPOSE, + sc_str[2], m, m, &a_save ); + + // Set alpha. + //bli_copysc( &BLIS_MINUS_ONE, &alpha ); + bli_setsc( -1.0, 1.0, &alpha ); + + // Randomize x and y. + bli_randv( &x ); + bli_randv( &y ); + + // Set the structure and uplo properties of A. + bli_obj_set_struc( BLIS_SYMMETRIC, a ); + bli_obj_set_uplo( uploa, a ); + + // Randomize A, make it densely symmetric, and zero the unstored triangle + // to ensure the implementation is reads only from the stored region. + bli_randm( &a ); + bli_mksymm( &a ); + bli_mktrim( &a ); + + bli_obj_set_struc( BLIS_SYMMETRIC, a_save ); + bli_obj_set_uplo( uploa, a_save ); + bli_copym( &a, &a_save ); + + // Apply the remaining parameters. + bli_obj_set_conj( conjx, x ); + bli_obj_set_conj( conjy, y ); + + // Repeat the experiment n_repeats times and record results. + for ( i = 0; i < n_repeats; ++i ) + { + bli_copym( &a_save, &a ); + + time = bli_clock(); + + libblis_test_syr2_impl( iface, &alpha, &x, &y, &a ); + + time_min = bli_clock_min_diff( time_min, time ); + } + + // Estimate the performance of the best experiment repeat. + *perf = ( 2.0 * m * m ) / time_min / FLOPS_PER_UNIT_PERF; + if ( bli_obj_is_complex( a ) ) *perf *= 4.0; + + // Perform checks. + libblis_test_syr2_check( &alpha, &x, &y, &a, &a_save, resid ); + + // Zero out performance and residual if output matrix is empty. + libblis_test_check_empty_problem( &a, perf, resid ); + + // Free the test objects. + bli_obj_free( &x ); + bli_obj_free( &y ); + bli_obj_free( &a ); + bli_obj_free( &a_save ); +} + + + +void libblis_test_syr2_impl( iface_t iface, + obj_t* alpha, + obj_t* x, + obj_t* y, + obj_t* a ) +{ + switch ( iface ) + { + case BLIS_TEST_SEQ_FRONT_END: + bli_syr2( alpha, x, y, a ); + break; + + default: + libblis_test_printf_error( "Invalid interface type.\n" ); + } +} + + + +void libblis_test_syr2_check( obj_t* alpha, + obj_t* x, + obj_t* y, + obj_t* a, + obj_t* a_orig, + double* resid ) +{ + num_t dt = bli_obj_datatype( *a ); + num_t dt_real = bli_obj_datatype_proj_to_real( *a ); + + dim_t m_a = bli_obj_length( *a ); + + obj_t xt, yt; + obj_t t, v, w1, w2; + obj_t tau, rho, norm; + + double junk; + + // + // Pre-conditions: + // - x is randomized. + // - y is randomized. + // - a is randomized and symmetric. + // Note: + // - alpha should have a non-zero imaginary component in the + // complex cases in order to more fully exercise the implementation. + // + // Under these conditions, we assume that the implementation for + // + // A := A_orig + alpha * conjx(x) * conjy(y)^T + alpha * conjy(y) * conjx(x)^T + // + // is functioning correctly if + // + // normf( v - w ) + // + // is negligible, where + // + // v = A * t + // w = ( A_orig + alpha * conjx(x) * conjy(y)^T + alpha * conjy(y) * conjx(x)^T ) * t + // = A_orig * t + alpha * conjx(x) * conjy(y)^T * t + alpha * conjy(y) * conjx(x)^T * t + // = A_orig * t + alpha * conjx(x) * conjy(y)^T * t + alpha * conjy(y) * rho + // = A_orig * t + alpha * conjx(x) * conjy(y)^T * t + w1 + // = A_orig * t + alpha * conjx(x) * rho + w1 + // = A_orig * t + w2 + w1 + // + + bli_mksymm( a ); + bli_mksymm( a_orig ); + bli_obj_set_struc( BLIS_GENERAL, *a ); + bli_obj_set_struc( BLIS_GENERAL, *a_orig ); + bli_obj_set_uplo( BLIS_DENSE, *a ); + bli_obj_set_uplo( BLIS_DENSE, *a_orig ); + + bli_obj_scalar_init_detached( dt, &tau ); + bli_obj_scalar_init_detached( dt, &rho ); + bli_obj_scalar_init_detached( dt_real, &norm ); + + bli_obj_create( dt, m_a, 1, 0, 0, &t ); + bli_obj_create( dt, m_a, 1, 0, 0, &v ); + bli_obj_create( dt, m_a, 1, 0, 0, &w1 ); + bli_obj_create( dt, m_a, 1, 0, 0, &w2 ); + + bli_obj_alias_to( *x, xt ); + bli_obj_alias_to( *y, yt ); + + bli_setsc( 1.0/( double )m_a, -1.0/( double )m_a, &tau ); + bli_setv( &tau, &t ); + + bli_gemv( &BLIS_ONE, a, &t, &BLIS_ZERO, &v ); + + bli_dotv( &xt, &t, &rho ); + bli_mulsc( alpha, &rho ); + bli_scal2v( &rho, y, &w1 ); + + bli_dotv( &yt, &t, &rho ); + bli_mulsc( alpha, &rho ); + bli_scal2v( &rho, x, &w2 ); + + bli_addv( &w2, &w1 ); + + bli_gemv( &BLIS_ONE, a_orig, &t, &BLIS_ONE, &w1 ); + + bli_subv( &w1, &v ); + bli_normfv( &v, &norm ); + bli_getsc( &norm, resid, &junk ); + + bli_obj_free( &t ); + bli_obj_free( &v ); + bli_obj_free( &w1 ); + bli_obj_free( &w2 ); +} + diff --git a/pool/shard008/C/0129461_xor.c b/pool/shard008/C/0129461_xor.c new file mode 100644 index 0000000000000000000000000000000000000000..e031d5d542f80d345324c746e63d255e3b308655 --- /dev/null +++ b/pool/shard008/C/0129461_xor.c @@ -0,0 +1,49 @@ +#include "parser_internal.h" + +typedef struct { + const HParser *p1; + const HParser *p2; +} HTwoParsers; + + +static HParseResult* parse_xor(void *env, HParseState *state) { + HTwoParsers *parsers = (HTwoParsers*)env; + // cache the initial state of the input stream + HInputStream start_state = state->input_stream; + HParseResult *r1 = h_do_parse(parsers->p1, state); + HInputStream after_p1_state = state->input_stream; + // reset input stream, parse again + state->input_stream = start_state; + HParseResult *r2 = h_do_parse(parsers->p2, state); + if (NULL == r1) { + if (NULL != r2) { + return r2; + } else { + return NULL; + } + } else { + if (NULL == r2) { + state->input_stream = after_p1_state; + return r1; + } else { + return NULL; + } + } +} + +static const HParserVtable xor_vt = { + .parse = parse_xor, + .isValidRegular = h_false, + .isValidCF = h_false, // XXX should this be true if both p1 and p2 are CF? + .compile_to_rvm = h_not_regular, +}; + +HParser* h_xor(const HParser* p1, const HParser* p2) { + return h_xor__m(&system_allocator, p1, p2); +} +HParser* h_xor__m(HAllocator* mm__, const HParser* p1, const HParser* p2) { + HTwoParsers *env = h_new(HTwoParsers, 1); + env->p1 = p1; + env->p2 = p2; + return h_new_parser(mm__, &xor_vt, env); +} diff --git a/pool/shard008/C/0129467_idle.c b/pool/shard008/C/0129467_idle.c new file mode 100644 index 0000000000000000000000000000000000000000..372461bced4ce39c8a2ac9c573818a077c697ae1 --- /dev/null +++ b/pool/shard008/C/0129467_idle.c @@ -0,0 +1,181 @@ +/* + * File : idle.c + * This file is part of RT-Thread RTOS + * COPYRIGHT (C) 2006 - 2012, RT-Thread Development Team + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rt-thread.org/license/LICENSE + * + * Change Logs: + * Date Author Notes + * 2006-03-23 Bernard the first version + * 2010-11-10 Bernard add cleanup callback function in thread exit. + */ + +#include +#include + +#ifndef IDLE_THREAD_STACK_SIZE +#if defined (RT_USING_HOOK) || defined(RT_USING_HEAP) +#define IDLE_THREAD_STACK_SIZE 256 +#else +#define IDLE_THREAD_STACK_SIZE 128 +#endif +#endif + +static struct rt_thread idle; +ALIGN(RT_ALIGN_SIZE) +static rt_uint8_t rt_thread_stack[IDLE_THREAD_STACK_SIZE]; + +extern rt_list_t rt_thread_defunct; + +#ifdef RT_USING_HOOK +/** + * @addtogroup Hook + */ + +/*@{*/ + +static void (*rt_thread_idle_hook)(); + +/** + * This function will set a hook function to idle thread loop. + * + * @param hook the specified hook function + * + * @note the hook function must be simple and never be blocked or suspend. + */ +void rt_thread_idle_sethook(void (*hook)()) +{ + rt_thread_idle_hook = hook; +} + +/*@}*/ +#endif + +/** + * @ingroup Thread + * + * This function will perform system background job when system idle. + */ +void rt_thread_idle_excute(void) +{ + /* check the defunct thread list */ + if (!rt_list_isempty(&rt_thread_defunct)) + { + rt_base_t lock; + rt_thread_t thread; +#ifdef RT_USING_MODULE + rt_module_t module = RT_NULL; +#endif + RT_DEBUG_NOT_IN_INTERRUPT; + + /* disable interrupt */ + lock = rt_hw_interrupt_disable(); + + /* re-check whether list is empty */ + if (!rt_list_isempty(&rt_thread_defunct)) + { + /* get defunct thread */ + thread = rt_list_entry(rt_thread_defunct.next, struct rt_thread, tlist); +#ifdef RT_USING_MODULE + /* get thread's parent module */ + module = (rt_module_t)thread->module_id; + + /* if the thread is module's main thread */ + if (module != RT_NULL && module->module_thread == thread) + { + /* detach module's main thread */ + module->module_thread = RT_NULL; + } +#endif + /* remove defunct thread */ + rt_list_remove(&(thread->tlist)); + /* invoke thread cleanup */ + if (thread->cleanup != RT_NULL) + thread->cleanup(thread); + + /* if it's a system object, not delete it */ + if (rt_object_is_systemobject((rt_object_t)thread) == RT_TRUE) + { + /* enable interrupt */ + rt_hw_interrupt_enable(lock); + return; + } + } + else + { + /* enable interrupt */ + rt_hw_interrupt_enable(lock); + + /* may the defunct thread list is removed by others, just return */ + return; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(lock); + +#ifdef RT_USING_HEAP +#if defined(RT_USING_MODULE) && defined(RT_USING_SLAB) + /* the thread belongs to an application module */ + if (thread->flags & RT_OBJECT_FLAG_MODULE) + rt_module_free((rt_module_t)thread->module_id, thread->stack_addr); + else +#endif + /* release thread's stack */ + rt_free(thread->stack_addr); + /* delete thread object */ + rt_object_delete((rt_object_t)thread); +#endif + +#ifdef RT_USING_MODULE + if (module != RT_NULL) + { + /* if sub thread list and main thread are all empty */ + if ((module->module_thread == RT_NULL) && + rt_list_isempty(&module->module_object[RT_Object_Class_Thread].object_list) ) + { + module->nref --; + } + + /* unload module */ + if (module->nref == 0) + rt_module_unload(module); + } +#endif + } +} + +static void rt_thread_idle_entry(void *parameter) +{ + while (1) + { + #ifdef RT_USING_HOOK + if (rt_thread_idle_hook != RT_NULL) + rt_thread_idle_hook(); + #endif + + rt_thread_idle_excute(); + } +} + +/** + * @ingroup SymstemInit + * + * This function will initialize idle thread, then start it. + * + * @note this function must be invoked when system init. + */ +void rt_thread_idle_init(void) +{ + /* initialize thread */ + rt_thread_init(&idle, + "tidle", + rt_thread_idle_entry, RT_NULL, + &rt_thread_stack[0], sizeof(rt_thread_stack), + RT_THREAD_PRIORITY_MAX - 1, 32); + + /* startup */ + rt_thread_startup(&idle); +} diff --git a/pool/shard008/C/0129469_empty-Seed1-RandomFuns-Type_int-ControlStructures_8-BB1-ForBound_boundedInput-Operators_Shiftlt_Shiftrt_Lt_Gt_Le_Ge_Eq_Ne_BAnd_BXor_BOr.c b/pool/shard008/C/0129469_empty-Seed1-RandomFuns-Type_int-ControlStructures_8-BB1-ForBound_boundedInput-Operators_Shiftlt_Shiftrt_Lt_Gt_Le_Ge_Eq_Ne_BAnd_BXor_BOr.c new file mode 100644 index 0000000000000000000000000000000000000000..332d82fa9aa879881327d9e7af6affdb2ea912c8 --- /dev/null +++ b/pool/shard008/C/0129469_empty-Seed1-RandomFuns-Type_int-ControlStructures_8-BB1-ForBound_boundedInput-Operators_Shiftlt_Shiftrt_Lt_Gt_Le_Ge_Eq_Ne_BAnd_BXor_BOr.c @@ -0,0 +1,93 @@ +/* Generated by CIL v. 1.7.0 */ +/* print_CIL_Input is false */ + +struct _IO_FILE; +struct timeval; +extern void signal(int sig , void *func ) ; +extern float strtof(char const *str , char const *endptr ) ; +typedef struct _IO_FILE FILE; +extern int atoi(char const *s ) ; +extern double strtod(char const *str , char const *endptr ) ; +extern int fclose(void *stream ) ; +extern void *fopen(char const *filename , char const *mode ) ; +extern void abort() ; +extern void exit(int status ) ; +extern int raise(int sig ) ; +extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; +extern int strcmp(char const *a , char const *b ) ; +extern int rand() ; +extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; +void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ; +extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; +extern int gettimeofday(struct timeval *tv , void *tz , ...) ; +extern int printf(char const *format , ...) ; +int main(int argc , char *argv[] ) ; +void megaInit(void) ; +extern unsigned long strlen(char const *s ) ; +extern long strtol(char const *str , char const *endptr , int base ) ; +extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; +extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; +struct timeval { + long tv_sec ; + long tv_usec ; +}; +extern void *malloc(unsigned long size ) ; +extern int scanf(char const *format , ...) ; +int main(int argc , char *argv[] ) +{ + unsigned int input[1] ; + unsigned int output[1] ; + int randomFuns_i5 ; + unsigned int randomFuns_value6 ; + int randomFuns_main_i7 ; + + { + megaInit(); + if (argc != 2) { + printf("Call this program with %i arguments\n", 1); + exit(-1); + } else { + + } + randomFuns_i5 = 0; + while (randomFuns_i5 < 1) { + randomFuns_value6 = (unsigned int )strtoul(argv[randomFuns_i5 + 1], 0, 10); + input[randomFuns_i5] = randomFuns_value6; + randomFuns_i5 ++; + } + RandomFunc(input, output); + if (output[0] == 335527679U) { + printf("You win!\n"); + } else { + + } + randomFuns_main_i7 = 0; + while (randomFuns_main_i7 < 1) { + printf("%u\n", output[randomFuns_main_i7]); + randomFuns_main_i7 ++; + } +} +} +void megaInit(void) +{ + + + { + +} +} +void RandomFunc(unsigned int input[1] , unsigned int output[1] ) +{ + unsigned int state[1] ; + unsigned int local1 ; + + { + state[0UL] = (input[0UL] | 51238316UL) >> 3U; + local1 = 0UL; + while (local1 < 0U) { + state[0UL] <<= ((state[0UL] >> 3U) & 7U) | 1UL; + local1 += 2UL; + } + output[0UL] = (state[0UL] | 28054104UL) | 326507717U; +} +} diff --git a/pool/shard008/C/0129470_pyhm.c b/pool/shard008/C/0129470_pyhm.c new file mode 100644 index 0000000000000000000000000000000000000000..81312f1449c0a09e4052ba875e312ee1f980321c --- /dev/null +++ b/pool/shard008/C/0129470_pyhm.c @@ -0,0 +1,80 @@ +/** + * (c) 2002-2006 Nathan Hjelm + * v0.4.0 pyhm.c + * + * Functions for managing playlists on the iPod. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the Lesser GNU 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 Lesser GNU Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + **/ + +#include "itunesdbi.h" + +int db_pyhm_create (tree_node_t **entry, int is_visible) { + struct db_pyhm *pyhm_data; + int ret; + + if ((ret = db_node_allocate (entry, PYHM, PYHM_CELL_SIZE, PYHM_CELL_SIZE)) < 0) + return ret; + + pyhm_data = (struct db_pyhm *)(*entry)->data; + pyhm_data->is_visible = (is_visible) ? 1 : 0; + pyhm_data->creation_date = DATE_TO_APPLE(time (NULL)); + pyhm_data->flags = 0x00000001; + + return 0; +} + +void db_pyhm_set_id (tree_node_t *entry, int id) { + struct db_pyhm *pyhm_data; + + pyhm_data = (struct db_pyhm *)entry->data; + pyhm_data->playlist_id = id; +} + +int db_pyhm_get_id (tree_node_t *entry) { + struct db_pyhm *pyhm_data; + + pyhm_data = (struct db_pyhm *)entry->data; + return pyhm_data->playlist_id; +} + +int db_pyhm_dohm_attach (tree_node_t *entry, tree_node_t *dohm) { + struct db_pyhm *pyhm_data; + + pyhm_data = (struct db_pyhm *)entry->data; + pyhm_data->num_dohm++; + + db_attach_at (entry, dohm, pyhm_data->num_dohm - 1); + + return 0; +} + +int db_pyhm_dohm_detach (tree_node_t *pyhm_header, int index, tree_node_t **store) { + struct db_pyhm *pyhm_data; + + pyhm_data = (struct db_pyhm *)pyhm_header->data; + pyhm_data->num_dohm--; + + return db_detach (pyhm_header, index, store); +} + +void db_pyhm_set_podcast (tree_node_t *pyhm_header, char is_podcast) { + struct db_pyhm *pyhm_data = (struct db_pyhm *)pyhm_header->data; + + if (is_podcast) + pyhm_data->flags |= 0x00010000; + else + pyhm_data->flags &= 0xff00ffff; +} diff --git a/pool/shard008/C/0129471_packet-cisco-wids.c b/pool/shard008/C/0129471_packet-cisco-wids.c new file mode 100644 index 0000000000000000000000000000000000000000..0327cddd3f34f0ce2a3188ff266574b82a9b7b03 --- /dev/null +++ b/pool/shard008/C/0129471_packet-cisco-wids.c @@ -0,0 +1,217 @@ +/* packet-cwids.c + * Routines for dissecting wireless ids packets sent from a Cisco + * access point to the WLSE (or whatever) + * + * $Id$ + * + * Copyright 2006 Joerg Mayer (see AUTHORS file) + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * 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. + */ + +/* With current IOS, you can use Cisco wireless Bridges/APs as + * wireless sniffers and configure them to send the data to some + * central IDS: + * interface dot11Radio 0 + * station-role scanner + * monitor frames endpoint ip address 172.22.1.1 port 8999 truncate 2312 + * These frames are raw, i.e. they don't have a pcap header. + * Running wireshark at the receiving end will provide those. + */ + +/* 2do: + * - Find out more about the contents of the capture header + * - Protect the address fields etc (all columns?) + * - Create subelements and put each header and packet into it + * - fuzz-test the dissector + * - Find some heuristic to detect the packet automagically and + * convert dissector into a heuristic dissector + * - Is the TRY/CATCH stuff OK? + */ + +#include "config.h" + +#include +#include +#include +#include +#include + +static guint global_udp_port = 0; + +static int proto_cwids = -1; +static int hf_cwids_version = -1; +static int hf_cwids_unknown1 = -1; +static int hf_cwids_channel = -1; +static int hf_cwids_unknown2 = -1; +static int hf_cwids_reallength = -1; +static int hf_cwids_capturelen = -1; +static int hf_cwids_unknown3 = -1; + +static gint ett_cwids = -1; + +static dissector_handle_t ieee80211_handle; + +static void +dissect_cwids(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) +{ + tvbuff_t *wlan_tvb; + proto_tree *ti, *cwids_tree; + volatile int offset = 0; + guint16 capturelen; + void *pd_save; + + col_set_str(pinfo->cinfo, COL_PROTOCOL, "CWIDS"); + col_set_str(pinfo->cinfo, COL_INFO, "Cwids: "); + /* FIXME: col_set_fence(pinfo->cinfo, all-cols, only addr-cols?); */ + + cwids_tree = NULL; + + while(tvb_length_remaining(tvb, offset) > 0) { + ti = proto_tree_add_item(tree, proto_cwids, tvb, offset, 28, ENC_NA); + cwids_tree = proto_item_add_subtree(ti, ett_cwids); + + proto_tree_add_item(cwids_tree, hf_cwids_version, tvb, offset, 2, ENC_BIG_ENDIAN); + offset += 2; + proto_tree_add_item(cwids_tree, hf_cwids_unknown1, tvb, offset, 7, ENC_NA); + offset += 7; + proto_tree_add_item(cwids_tree, hf_cwids_channel, tvb, offset, 1, ENC_BIG_ENDIAN); + offset += 1; + proto_tree_add_item(cwids_tree, hf_cwids_unknown2, tvb, offset, 6, ENC_NA); + offset += 6; + proto_tree_add_item(cwids_tree, hf_cwids_reallength, tvb, offset, 2, ENC_BIG_ENDIAN); + offset += 2; + capturelen = tvb_get_ntohs(tvb, offset); + proto_tree_add_item(cwids_tree, hf_cwids_capturelen, tvb, offset, 2, ENC_BIG_ENDIAN); + offset += 2; + proto_tree_add_item(cwids_tree, hf_cwids_unknown3, tvb, offset, 8, ENC_NA); + offset += 8; + + wlan_tvb = tvb_new_subset(tvb, offset, capturelen, capturelen); + /* Continue after ieee80211 dissection errors */ + pd_save = pinfo->private_data; + TRY { + call_dissector(ieee80211_handle, wlan_tvb, pinfo, tree); + } CATCH2(BoundsError, ReportedBoundsError) { + + expert_add_info_format(pinfo, NULL, + PI_MALFORMED, PI_ERROR, + "Malformed or short IEEE80211 subpacket"); + + /* Restore the private_data structure in case one of the + * called dissectors modified it (and, due to the exception, + * was unable to restore it). + */ + pinfo->private_data = pd_save; + + col_append_str(pinfo->cinfo, COL_INFO, + " [Malformed or short IEEE80211 subpacket] " ); + col_set_fence(pinfo->cinfo, COL_INFO); +#if 0 + wlan_tvb = tvb_new_subset(tvb, offset, capturelen, capturelen); + /* FIXME: Why does this throw an exception? */ + proto_tree_add_text(cwids_tree, wlan_tvb, offset, capturelen, + "[Malformed or short IEEE80211 subpacket]"); +#else + tvb_new_subset(tvb, offset, capturelen, capturelen); +#endif + ; + } ENDTRY; + + offset += capturelen; + } +} + +void proto_register_cwids(void); +void proto_reg_handoff_cwids(void); + +void +proto_register_cwids(void) +{ + static hf_register_info hf[] = { + { &hf_cwids_version, + { "Capture Version", "cwids.version", FT_UINT16, BASE_DEC, NULL, + 0x0, "Version or format of record", HFILL }}, + + { &hf_cwids_unknown1, + { "Unknown1", "cwids.unknown1", FT_BYTES, BASE_NONE, NULL, + 0x0, "1st Unknown block - timestamp?", HFILL }}, + + { &hf_cwids_channel, + { "Channel", "cwids.channel", FT_UINT8, BASE_DEC, NULL, + 0x0, "Channel for this capture", HFILL }}, + + { &hf_cwids_unknown2, + { "Unknown2", "cwids.unknown2", FT_BYTES, BASE_NONE, NULL, + 0x0, "2nd Unknown block", HFILL }}, + + { &hf_cwids_reallength, + { "Original length", "cwids.reallen", FT_UINT16, BASE_DEC, NULL, + 0x0, "Original num bytes in frame", HFILL }}, + + { &hf_cwids_capturelen, + { "Capture length", "cwids.caplen", FT_UINT16, BASE_DEC, NULL, + 0x0, "Captured bytes in record", HFILL }}, + + { &hf_cwids_unknown3, + { "Unknown3", "cwids.unknown3", FT_BYTES, BASE_NONE, NULL, + 0x0, "3rd Unknown block", HFILL }}, + + }; + static gint *ett[] = { + &ett_cwids, + }; + + module_t *cwids_module; + + proto_cwids = proto_register_protocol("Cisco Wireless IDS Captures", "CWIDS", "cwids"); + proto_register_field_array(proto_cwids, hf, array_length(hf)); + proto_register_subtree_array(ett, array_length(ett)); + + cwids_module = prefs_register_protocol(proto_cwids, proto_reg_handoff_cwids); + prefs_register_uint_preference(cwids_module, "udp.port", + "CWIDS port", + "Set the destination UDP port Cisco wireless IDS messages", + 10, &global_udp_port); + +} + +void +proto_reg_handoff_cwids(void) +{ + static dissector_handle_t cwids_handle; + static guint saved_udp_port; + static gboolean initialized = FALSE; + + if (!initialized) { + cwids_handle = create_dissector_handle(dissect_cwids, proto_cwids); + dissector_add_handle("udp.port", cwids_handle); + ieee80211_handle = find_dissector("wlan"); + initialized = TRUE; + } else { + if (saved_udp_port != 0) { + dissector_delete_uint("udp.port", saved_udp_port, cwids_handle); + } + } + if (global_udp_port != 0) { + dissector_add_uint("udp.port", global_udp_port, cwids_handle); + } + saved_udp_port = global_udp_port; +} + diff --git a/pool/shard008/C/0129472_vport-netdev.c b/pool/shard008/C/0129472_vport-netdev.c new file mode 100644 index 0000000000000000000000000000000000000000..9bec22e3e9e8fa6fdbbab8989ccff7a1afb9c2d3 --- /dev/null +++ b/pool/shard008/C/0129472_vport-netdev.c @@ -0,0 +1,224 @@ +/* + * Copyright (c) 2007-2012 Nicira, Inc. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of version 2 of the GNU General Public + * License as published by the Free Software Foundation. + * + * 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 + */ + +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "datapath.h" +#include "vport.h" +#include "vport-internal_dev.h" +#include "vport-netdev.h" + +static struct vport_ops ovs_netdev_vport_ops; + +/* Must be called with rcu_read_lock. */ +static void netdev_port_receive(struct sk_buff *skb) +{ + struct vport *vport; + + vport = ovs_netdev_get_vport(skb->dev); + if (unlikely(!vport)) + goto error; + + if (unlikely(skb_warn_if_lro(skb))) + goto error; + + /* Make our own copy of the packet. Otherwise we will mangle the + * packet for anyone who came before us (e.g. tcpdump via AF_PACKET). + */ + skb = skb_share_check(skb, GFP_ATOMIC); + if (unlikely(!skb)) + return; + + if (skb->dev->type == ARPHRD_ETHER) { + skb_push(skb, ETH_HLEN); + skb_postpush_rcsum(skb, skb->data, ETH_HLEN); + } + ovs_vport_receive(vport, skb, skb_tunnel_info(skb)); + return; +error: + kfree_skb(skb); +} + +/* Called with rcu_read_lock and bottom-halves disabled. */ +static rx_handler_result_t netdev_frame_hook(struct sk_buff **pskb) +{ + struct sk_buff *skb = *pskb; + + if (unlikely(skb->pkt_type == PACKET_LOOPBACK)) + return RX_HANDLER_PASS; + + netdev_port_receive(skb); + return RX_HANDLER_CONSUMED; +} + +static struct net_device *get_dpdev(const struct datapath *dp) +{ + struct vport *local; + + local = ovs_vport_ovsl(dp, OVSP_LOCAL); + return local->dev; +} + +struct vport *ovs_netdev_link(struct vport *vport, const char *name) +{ + int err; + + vport->dev = dev_get_by_name(ovs_dp_get_net(vport->dp), name); + if (!vport->dev) { + err = -ENODEV; + goto error_free_vport; + } + + if (vport->dev->flags & IFF_LOOPBACK || + (vport->dev->type != ARPHRD_ETHER && + vport->dev->type != ARPHRD_NONE) || + ovs_is_internal_dev(vport->dev)) { + err = -EINVAL; + goto error_put; + } + + rtnl_lock(); + err = netdev_master_upper_dev_link(vport->dev, + get_dpdev(vport->dp), + NULL, NULL, NULL); + if (err) + goto error_unlock; + + err = netdev_rx_handler_register(vport->dev, netdev_frame_hook, + vport); + if (err) + goto error_master_upper_dev_unlink; + + dev_disable_lro(vport->dev); + dev_set_promiscuity(vport->dev, 1); + vport->dev->priv_flags |= IFF_OVS_DATAPATH; + rtnl_unlock(); + + return vport; + +error_master_upper_dev_unlink: + netdev_upper_dev_unlink(vport->dev, get_dpdev(vport->dp)); +error_unlock: + rtnl_unlock(); +error_put: + dev_put(vport->dev); +error_free_vport: + ovs_vport_free(vport); + return ERR_PTR(err); +} +EXPORT_SYMBOL_GPL(ovs_netdev_link); + +static struct vport *netdev_create(const struct vport_parms *parms) +{ + struct vport *vport; + + vport = ovs_vport_alloc(0, &ovs_netdev_vport_ops, parms); + if (IS_ERR(vport)) + return vport; + + return ovs_netdev_link(vport, parms->name); +} + +static void vport_netdev_free(struct rcu_head *rcu) +{ + struct vport *vport = container_of(rcu, struct vport, rcu); + + if (vport->dev) + dev_put(vport->dev); + ovs_vport_free(vport); +} + +void ovs_netdev_detach_dev(struct vport *vport) +{ + ASSERT_RTNL(); + vport->dev->priv_flags &= ~IFF_OVS_DATAPATH; + netdev_rx_handler_unregister(vport->dev); + netdev_upper_dev_unlink(vport->dev, + netdev_master_upper_dev_get(vport->dev)); + dev_set_promiscuity(vport->dev, -1); +} + +static void netdev_destroy(struct vport *vport) +{ + rtnl_lock(); + if (vport->dev->priv_flags & IFF_OVS_DATAPATH) + ovs_netdev_detach_dev(vport); + rtnl_unlock(); + + call_rcu(&vport->rcu, vport_netdev_free); +} + +void ovs_netdev_tunnel_destroy(struct vport *vport) +{ + rtnl_lock(); + if (vport->dev->priv_flags & IFF_OVS_DATAPATH) + ovs_netdev_detach_dev(vport); + + /* We can be invoked by both explicit vport deletion and + * underlying netdev deregistration; delete the link only + * if it's not already shutting down. + */ + if (vport->dev->reg_state == NETREG_REGISTERED) + rtnl_delete_link(vport->dev); + dev_put(vport->dev); + vport->dev = NULL; + rtnl_unlock(); + + call_rcu(&vport->rcu, vport_netdev_free); +} +EXPORT_SYMBOL_GPL(ovs_netdev_tunnel_destroy); + +/* Returns null if this device is not attached to a datapath. */ +struct vport *ovs_netdev_get_vport(struct net_device *dev) +{ + if (likely(dev->priv_flags & IFF_OVS_DATAPATH)) + return (struct vport *) + rcu_dereference_rtnl(dev->rx_handler_data); + else + return NULL; +} + +static struct vport_ops ovs_netdev_vport_ops = { + .type = OVS_VPORT_TYPE_NETDEV, + .create = netdev_create, + .destroy = netdev_destroy, + .send = dev_queue_xmit, +}; + +int __init ovs_netdev_init(void) +{ + return ovs_vport_ops_register(&ovs_netdev_vport_ops); +} + +void ovs_netdev_exit(void) +{ + ovs_vport_ops_unregister(&ovs_netdev_vport_ops); +} diff --git a/pool/shard008/C/0129475_opcodes.c b/pool/shard008/C/0129475_opcodes.c new file mode 100644 index 0000000000000000000000000000000000000000..99a32c3c37f9efab18957e3231d026fdd82a8948 --- /dev/null +++ b/pool/shard008/C/0129475_opcodes.c @@ -0,0 +1,47 @@ +#include "opcodes.h" +#include + +OpcodeType getOpcode (InstructionType instr) { + int shift = ISIZE + OP1SIZE + OP2SIZE + OP3SIZE; + OpcodeType opcode = (OpcodeType) (instr >> shift); + return opcode; +} + +void setOpcode (InstructionType *instr, char *instrWord) { + InstructionType newInstr; + int shift = ISIZE + OP1SIZE + OP2SIZE + OP3SIZE; + OpcodeType opcode = INVALID; + + if (strcmp(instrWord, "ADD\0") == 0) { + opcode = ADD; + } + else if (strcmp(instrWord, "SUB\0") == 0) { + opcode = SUB; + } + else if (strcmp(instrWord, "MUL\0") == 0) { + opcode = MUL; + } + else if (strcmp(instrWord, "LD\0") == 0) { + opcode = LD; + } + else if (strcmp(instrWord, "SD\0") == 0) { + opcode = SD; + } + else if (strcmp(instrWord, "JMP\0") == 0) { + opcode = JMP; + } + else if (strcmp(instrWord, "BEQZ\0") == 0) { + opcode = BEQZ; + } + else if (strcmp(instrWord, "HLT\0") == 0) { + opcode = HLT; + } + else { + printf("Fatal error: Invalid instruction encountered: %s\n", instrWord); + exit(0); + } + + newInstr = opcode << shift; + newInstr += ((*instr) << CSIZE) >> CSIZE; + *instr = newInstr; +} diff --git a/pool/shard008/C/0129477_http-post-simple.c b/pool/shard008/C/0129477_http-post-simple.c new file mode 100644 index 0000000000000000000000000000000000000000..afff3e169c3f16fc2179f059125dad99310e58a3 --- /dev/null +++ b/pool/shard008/C/0129477_http-post-simple.c @@ -0,0 +1,97 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SA struct sockaddr +#define MAXLINE 4096 +#define MAXSUB 300 + + +#define LISTENQ 1024 + +extern int h_errno; + + +ssize_t process_http(int sockfd, char *host, char *page, char *poststr) +{ + char sendline[MAXLINE + 1], recvline[MAXLINE + 1]; + ssize_t n; + printf("Longitud %lu\n", strlen(poststr)); + snprintf(sendline, MAXSUB, + "POST %s HTTP/1.1\r\n" + "Host: %s\r\n" + "Connection: Close" + "Content-type: application/x-www-form-urlencoded\r\n" + "Content-length: %lu\r\n\r\n" + "%s", page, host, strlen(poststr), poststr); + + write(sockfd, sendline, strlen(sendline)); + while ((n = read(sockfd, recvline, MAXLINE)) > 0) { + recvline[n] = '\0'; + printf("%s", recvline); // <-- this + } + return n; + +} + + + + + +int main(void) +{ + + + + int sockfd; + struct sockaddr_in servaddr; + + char **pptr; + //********** You can change. Puy any values here ******* + char *hname = "telit.jspblm.com"; + char *page = "/telit-post-request/"; + //char *poststr = "a=1&b=2"; // a=A;C&b=B + char *poststr = "a=10990&b=150408&c=115549&d=115554&e=59703751&f=0&g=0&h=3&i=0&j=>&k=8950203015001199331"; + //******************************************************* + + char str[50]; + struct hostent *hptr; + if ((hptr = gethostbyname(hname)) == NULL) { + fprintf(stderr, " Server down error for host: %s: %s", + hname, hstrerror(h_errno)); + exit(1); + } + printf("hostname: %s \n", hptr->h_name); + if (hptr->h_addrtype == AF_INET + && (pptr = hptr->h_addr_list) != NULL) { + printf("address: %s\n", + inet_ntop(hptr->h_addrtype, *pptr, str, + sizeof(str))); + } else { + fprintf(stderr, "Error call inet_ntop \n"); + } + + sockfd = socket(AF_INET, SOCK_STREAM, 0); + bzero(&servaddr, sizeof(servaddr)); + servaddr.sin_family = AF_INET; + servaddr.sin_port = htons(80); + inet_pton(AF_INET, str, &servaddr.sin_addr); + + connect(sockfd, (SA *) & servaddr, sizeof(servaddr)); + process_http(sockfd, hname, page, poststr); + close(sockfd); + printf("END\n"); + exit(0); + + +} \ No newline at end of file diff --git a/pool/shard008/C/0129478_CWE121_Stack_Based_Buffer_Overflow__src_char_alloca_cpy_63b.c b/pool/shard008/C/0129478_CWE121_Stack_Based_Buffer_Overflow__src_char_alloca_cpy_63b.c new file mode 100644 index 0000000000000000000000000000000000000000..54f0211f8f2347b3aa1e1eb8ae8fc74527d29fcf --- /dev/null +++ b/pool/shard008/C/0129478_CWE121_Stack_Based_Buffer_Overflow__src_char_alloca_cpy_63b.c @@ -0,0 +1,50 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE121_Stack_Based_Buffer_Overflow__src_char_alloca_cpy_63b.c +Label Definition File: CWE121_Stack_Based_Buffer_Overflow__src.label.xml +Template File: sources-sink-63b.tmpl.c +*/ +/* + * @description + * CWE: 121 Stack Based Buffer Overflow + * BadSource: Initialize data as a large string + * GoodSource: Initialize data as a small string + * Sinks: cpy + * BadSink : Copy data to string using strcpy + * Flow Variant: 63 Data flow: pointer to data passed from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +void CWE121_Stack_Based_Buffer_Overflow__src_char_alloca_cpy_63b_badSink(char * * dataPtr) +{ + char * data = *dataPtr; + { + char dest[50] = ""; + /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */ + strcpy(dest, data); + printLine(data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE121_Stack_Based_Buffer_Overflow__src_char_alloca_cpy_63b_goodG2BSink(char * * dataPtr) +{ + char * data = *dataPtr; + { + char dest[50] = ""; + /* POTENTIAL FLAW: Possible buffer overflow if data is larger than dest */ + strcpy(dest, data); + printLine(data); + } +} + +#endif /* OMITGOOD */ diff --git a/pool/shard008/C/0129481_ima-setup.c b/pool/shard008/C/0129481_ima-setup.c new file mode 100644 index 0000000000000000000000000000000000000000..3416802bcb4d69acc7adad9aa03e6737008646e3 --- /dev/null +++ b/pool/shard008/C/0129481_ima-setup.c @@ -0,0 +1,105 @@ +/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ + +/*** + This file is part of systemd. + + Copyright 2010 Lennart Poettering + Copyright (C) 2012 Roberto Sassu - Politecnico di Torino, Italy + TORSEC group -- http://security.polito.it + + systemd 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. + + systemd 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 systemd; If not, see . +***/ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ima-setup.h" +#include "mount-setup.h" +#include "macro.h" +#include "util.h" +#include "log.h" +#include "label.h" + +#define IMA_SECFS_DIR "/sys/kernel/security/ima" +#define IMA_SECFS_POLICY IMA_SECFS_DIR "/policy" +#define IMA_POLICY_PATH "/etc/ima/ima-policy" + +int ima_setup(void) { + +#ifdef HAVE_IMA + struct stat st; + ssize_t policy_size = 0, written = 0; + char *policy; + _cleanup_close_ int policyfd = -1, imafd = -1; + int result = 0; + + if (stat(IMA_POLICY_PATH, &st) < 0) + return 0; + + policy_size = st.st_size; + if (stat(IMA_SECFS_DIR, &st) < 0) { + log_debug("IMA support is disabled in the kernel, ignoring."); + return 0; + } + + if (stat(IMA_SECFS_POLICY, &st) < 0) { + log_error("Another IMA custom policy has already been loaded, ignoring."); + return 0; + } + + policyfd = open(IMA_POLICY_PATH, O_RDONLY|O_CLOEXEC); + if (policyfd < 0) { + log_error_errno(errno, "Failed to open the IMA custom policy file %s (%m), ignoring.", + IMA_POLICY_PATH); + return 0; + } + + imafd = open(IMA_SECFS_POLICY, O_WRONLY|O_CLOEXEC); + if (imafd < 0) { + log_error_errno(errno, "Failed to open the IMA kernel interface %s (%m), ignoring.", + IMA_SECFS_POLICY); + goto out; + } + + policy = mmap(NULL, policy_size, PROT_READ, MAP_PRIVATE, policyfd, 0); + if (policy == MAP_FAILED) { + log_error_errno(errno, "mmap() failed (%m), freezing"); + result = -errno; + goto out; + } + + written = loop_write(imafd, policy, (size_t)policy_size, false); + if (written != policy_size) { + log_error_errno(errno, "Failed to load the IMA custom policy file %s (%m), ignoring.", + IMA_POLICY_PATH); + goto out_mmap; + } + + log_info("Successfully loaded the IMA custom policy %s.", + IMA_POLICY_PATH); +out_mmap: + munmap(policy, policy_size); +out: + if (result) + return result; +#endif /* HAVE_IMA */ + + return 0; +} diff --git a/pool/shard008/C/0129483_mach-ap96.c b/pool/shard008/C/0129483_mach-ap96.c new file mode 100644 index 0000000000000000000000000000000000000000..5882af29f960b81dd88734f70768cf770895eb61 --- /dev/null +++ b/pool/shard008/C/0129483_mach-ap96.c @@ -0,0 +1,180 @@ +/* + * Atheros AP96 board support + * + * Copyright (C) 2009 Marco Porsch + * Copyright (C) 2009-2010 Gabor Juhos + * Copyright (C) 2010 Atheros Communications + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 as published + * by the Free Software Foundation. + */ + +#include +#include +#include +#include + +#include + +#include "machtype.h" +#include "devices.h" +#include "dev-m25p80.h" +#include "dev-ap94-pci.h" +#include "dev-gpio-buttons.h" +#include "dev-leds-gpio.h" +#include "dev-usb.h" + +#define AP96_GPIO_LED_12_GREEN 0 +#define AP96_GPIO_LED_3_GREEN 1 +#define AP96_GPIO_LED_2_GREEN 2 +#define AP96_GPIO_LED_WPS_GREEN 4 +#define AP96_GPIO_LED_5_GREEN 5 +#define AP96_GPIO_LED_4_ORANGE 6 + +/* Reset button - next to the power connector */ +#define AP96_GPIO_BTN_RESET 3 +/* WPS button - next to a led on right */ +#define AP96_GPIO_BTN_WPS 8 + +#define AP96_KEYS_POLL_INTERVAL 20 /* msecs */ +#define AP96_KEYS_DEBOUNCE_INTERVAL (3 * AP96_KEYS_POLL_INTERVAL) + +#define AP96_WMAC0_MAC_OFFSET 0x120c +#define AP96_WMAC1_MAC_OFFSET 0x520c +#define AP96_CALDATA0_OFFSET 0x1000 +#define AP96_CALDATA1_OFFSET 0x5000 + +#ifdef CONFIG_MTD_PARTITIONS +static struct mtd_partition ap96_partitions[] = { + { + .name = "uboot", + .offset = 0, + .size = 0x030000, + .mask_flags = MTD_WRITEABLE, + }, { + .name = "env", + .offset = 0x030000, + .size = 0x010000, + .mask_flags = MTD_WRITEABLE, + }, { + .name = "rootfs", + .offset = 0x040000, + .size = 0x600000, + }, { + .name = "uImage", + .offset = 0x640000, + .size = 0x1b0000, + }, { + .name = "caldata", + .offset = 0x7f0000, + .size = 0x010000, + .mask_flags = MTD_WRITEABLE, + } +}; +#endif /* CONFIG_MTD_PARTITIONS */ + +static struct flash_platform_data ap96_flash_data = { +#ifdef CONFIG_MTD_PARTITIONS + .parts = ap96_partitions, + .nr_parts = ARRAY_SIZE(ap96_partitions), +#endif +}; + +/* + * AP96 has 12 unlabeled leds in the front; these are numbered from 1 to 12 + * below (from left to right on the board). Led 1 seems to be on whenever the + * board is powered. Led 11 shows LAN link activity actity. Led 3 is orange; + * others are green. + * + * In addition, there is one led next to a button on the right side for WPS. + */ +static struct gpio_led ap96_leds_gpio[] __initdata = { + { + .name = "ap96:green:led2", + .gpio = AP96_GPIO_LED_2_GREEN, + .active_low = 1, + }, { + .name = "ap96:green:led3", + .gpio = AP96_GPIO_LED_3_GREEN, + .active_low = 1, + }, { + .name = "ap96:orange:led4", + .gpio = AP96_GPIO_LED_4_ORANGE, + .active_low = 1, + }, { + .name = "ap96:green:led5", + .gpio = AP96_GPIO_LED_5_GREEN, + .active_low = 1, + }, { + .name = "ap96:green:led12", + .gpio = AP96_GPIO_LED_12_GREEN, + .active_low = 1, + }, { /* next to a button on right */ + .name = "ap96:green:wps", + .gpio = AP96_GPIO_LED_WPS_GREEN, + .active_low = 1, + } +}; + +static struct gpio_keys_button ap96_gpio_keys[] __initdata = { + { + .desc = "reset", + .type = EV_KEY, + .code = KEY_RESTART, + .debounce_interval = AP96_KEYS_DEBOUNCE_INTERVAL, + .gpio = AP96_GPIO_BTN_RESET, + .active_low = 1, + }, { + .desc = "wps", + .type = EV_KEY, + .code = KEY_WPS_BUTTON, + .debounce_interval = AP96_KEYS_DEBOUNCE_INTERVAL, + .gpio = AP96_GPIO_BTN_WPS, + .active_low = 1, + } +}; + +#define AP96_WAN_PHYMASK 0x10 +#define AP96_LAN_PHYMASK 0x0f + +static void __init ap96_setup(void) +{ + u8 *art = (u8 *) KSEG1ADDR(0x1fff0000); + + ar71xx_add_device_mdio(0, ~(AP96_WAN_PHYMASK | AP96_LAN_PHYMASK)); + + ar71xx_init_mac(ar71xx_eth0_data.mac_addr, art, 0); + ar71xx_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_RGMII; + ar71xx_eth0_data.phy_mask = AP96_LAN_PHYMASK; + ar71xx_eth0_data.speed = SPEED_1000; + ar71xx_eth0_data.duplex = DUPLEX_FULL; + + ar71xx_add_device_eth(0); + + ar71xx_init_mac(ar71xx_eth1_data.mac_addr, art, 1); + ar71xx_eth1_data.phy_if_mode = PHY_INTERFACE_MODE_RGMII; + ar71xx_eth1_data.phy_mask = AP96_WAN_PHYMASK; + + ar71xx_eth1_pll_data.pll_1000 = 0x1f000000; + + ar71xx_add_device_eth(1); + + ar71xx_add_device_usb(); + + ar71xx_add_device_m25p80(&ap96_flash_data); + + ar71xx_add_device_leds_gpio(-1, ARRAY_SIZE(ap96_leds_gpio), + ap96_leds_gpio); + + ar71xx_register_gpio_keys_polled(-1, AP96_KEYS_POLL_INTERVAL, + ARRAY_SIZE(ap96_gpio_keys), + ap96_gpio_keys); + + ap94_pci_init(art + AP96_CALDATA0_OFFSET, + art + AP96_WMAC0_MAC_OFFSET, + art + AP96_CALDATA1_OFFSET, + art + AP96_WMAC1_MAC_OFFSET); +} + +MIPS_MACHINE(AR71XX_MACH_AP96, "AP96", "Atheros AP96", ap96_setup); diff --git a/pool/shard008/C/0129494_prog103.c b/pool/shard008/C/0129494_prog103.c new file mode 100644 index 0000000000000000000000000000000000000000..bb8e78b5005cefe2350cfb54541d3d372e13630d --- /dev/null +++ b/pool/shard008/C/0129494_prog103.c @@ -0,0 +1,30 @@ +// 连接字符串,使用'\0' +#include + +int main(void){ + void concat(char result[], const char str1[], const char str2[]); + const char s1[] = {"Test "}; + const char s2[] = {"works."}; + char s3[20]; + + concat(s3, s1, s2); + + printf("%s\n", s3); + return 0; +} + +// 连接两个字符串的函数 +void concat(char result[], const char str1[], const char str2[]){ + int i, j; + + // 复制str1到result + for(i = 0; str1[i] != '\0'; ++i) + result[i] = str1[i]; + + // 复制str2到result + for(j = 0; str2[j] != '\0'; ++j) + result[i + j] = str2[j]; + + // 使用null字符作为连接字符串的结尾 + result[i + j] = '\0'; +} diff --git a/pool/shard008/C/0129496_context.c b/pool/shard008/C/0129496_context.c new file mode 100644 index 0000000000000000000000000000000000000000..aada9df9739ddc508511db62a319932fb1261173 --- /dev/null +++ b/pool/shard008/C/0129496_context.c @@ -0,0 +1,228 @@ +/* + * common OpenGL routines + * + * copyleft (C) 2005-2010 Reimar Döffinger + * Special thanks go to the xine team and Matthias Hopf, whose video_out_opengl.c + * gave me lots of good ideas. + * + * This file is part of mpv. + * + * mpv 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. + * + * mpv 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 mpv. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "context.h" +#include "common/common.h" +#include "options/options.h" +#include "options/m_option.h" + +extern const struct mpgl_driver mpgl_driver_x11; +extern const struct mpgl_driver mpgl_driver_x11egl; +extern const struct mpgl_driver mpgl_driver_x11_probe; +extern const struct mpgl_driver mpgl_driver_drm_egl; +extern const struct mpgl_driver mpgl_driver_cocoa; +extern const struct mpgl_driver mpgl_driver_wayland; +extern const struct mpgl_driver mpgl_driver_w32; +extern const struct mpgl_driver mpgl_driver_angle; +extern const struct mpgl_driver mpgl_driver_dxinterop; +extern const struct mpgl_driver mpgl_driver_rpi; + +static const struct mpgl_driver *const backends[] = { +#if HAVE_RPI + &mpgl_driver_rpi, +#endif +#if HAVE_GL_COCOA + &mpgl_driver_cocoa, +#endif +#if HAVE_EGL_ANGLE + &mpgl_driver_angle, +#endif +#if HAVE_GL_WIN32 + &mpgl_driver_w32, +#endif +#if HAVE_GL_DXINTEROP + &mpgl_driver_dxinterop, +#endif +#if HAVE_GL_WAYLAND + &mpgl_driver_wayland, +#endif +#if HAVE_GL_X11 + &mpgl_driver_x11_probe, +#endif +#if HAVE_EGL_X11 + &mpgl_driver_x11egl, +#endif +#if HAVE_GL_X11 + &mpgl_driver_x11, +#endif +#if HAVE_EGL_DRM + &mpgl_driver_drm_egl, +#endif +}; + +int mpgl_find_backend(const char *name) +{ + if (name == NULL || strcmp(name, "auto") == 0) + return -1; + for (int n = 0; n < MP_ARRAY_SIZE(backends); n++) { + if (strcmp(backends[n]->name, name) == 0) + return n; + } + return -2; +} + +int mpgl_validate_backend_opt(struct mp_log *log, const struct m_option *opt, + struct bstr name, struct bstr param) +{ + if (bstr_equals0(param, "help")) { + mp_info(log, "OpenGL windowing backends:\n"); + mp_info(log, " auto (autodetect)\n"); + for (int n = 0; n < MP_ARRAY_SIZE(backends); n++) + mp_info(log, " %s\n", backends[n]->name); + return M_OPT_EXIT - 1; + } + char s[20]; + snprintf(s, sizeof(s), "%.*s", BSTR_P(param)); + return mpgl_find_backend(s) >= -1 ? 1 : M_OPT_INVALID; +} + +#if HAVE_C11_TLS +#define MP_TLS _Thread_local +#elif defined(__GNU__) +#define MP_TLS __thread +#endif + +#ifdef MP_TLS +static MP_TLS MPGLContext *current_context; + +static void * GLAPIENTRY get_native_display(const char *name) +{ + if (current_context && current_context->native_display_type && + name && strcmp(current_context->native_display_type, name) == 0) + return current_context->native_display; + return NULL; +} + +static void set_current_context(MPGLContext *context) +{ + current_context = context; + if (context && !context->gl->MPGetNativeDisplay) + context->gl->MPGetNativeDisplay = get_native_display; +} +#else +static void set_current_context(MPGLContext *context) +{ +} +#endif + +static MPGLContext *init_backend(struct vo *vo, const struct mpgl_driver *driver, + bool probing, int vo_flags) +{ + MPGLContext *ctx = talloc_ptrtype(NULL, ctx); + *ctx = (MPGLContext) { + .gl = talloc_zero(ctx, GL), + .vo = vo, + .driver = driver, + }; + bool old_probing = vo->probing; + vo->probing = probing; // hack; kill it once backends are separate + MP_VERBOSE(vo, "Initializing OpenGL backend '%s'\n", ctx->driver->name); + ctx->priv = talloc_zero_size(ctx, ctx->driver->priv_size); + if (ctx->driver->init(ctx, vo_flags) < 0) { + vo->probing = old_probing; + talloc_free(ctx); + return NULL; + } + vo->probing = old_probing; + + if (!ctx->gl->version && !ctx->gl->es) + goto cleanup; + + if (probing && ctx->gl->es && (vo_flags & VOFLAG_NO_GLES)) { + MP_VERBOSE(ctx->vo, "Skipping GLES backend.\n"); + goto cleanup; + } + + if (ctx->gl->mpgl_caps & MPGL_CAP_SW) { + MP_WARN(ctx->vo, "Suspected software renderer or indirect context.\n"); + if (vo->probing && !(vo_flags & VOFLAG_SW)) + goto cleanup; + } + + ctx->gl->debug_context = !!(vo_flags & VOFLAG_GL_DEBUG); + + set_current_context(ctx); + + return ctx; + +cleanup: + mpgl_uninit(ctx); + return NULL; +} + +// Create a VO window and create a GL context on it. +// vo_flags: passed to the backend's create window function +MPGLContext *mpgl_init(struct vo *vo, const char *backend_name, int vo_flags) +{ + MPGLContext *ctx = NULL; + int index = mpgl_find_backend(backend_name); + if (index == -1) { + for (int n = 0; n < MP_ARRAY_SIZE(backends); n++) { + ctx = init_backend(vo, backends[n], true, vo_flags); + if (ctx) + break; + } + // VO forced, but no backend is ok => force the first that works at all + if (!ctx && !vo->probing) { + for (int n = 0; n < MP_ARRAY_SIZE(backends); n++) { + ctx = init_backend(vo, backends[n], false, vo_flags); + if (ctx) + break; + } + } + } else if (index >= 0) { + ctx = init_backend(vo, backends[index], false, vo_flags); + } + return ctx; +} + +int mpgl_reconfig_window(struct MPGLContext *ctx) +{ + return ctx->driver->reconfig(ctx); +} + +int mpgl_control(struct MPGLContext *ctx, int *events, int request, void *arg) +{ + return ctx->driver->control(ctx, events, request, arg); +} + +void mpgl_swap_buffers(struct MPGLContext *ctx) +{ + ctx->driver->swap_buffers(ctx); +} + +void mpgl_uninit(MPGLContext *ctx) +{ + set_current_context(NULL); + if (ctx) + ctx->driver->uninit(ctx); + talloc_free(ctx); +} diff --git a/pool/shard008/C/0129497_2.c b/pool/shard008/C/0129497_2.c new file mode 100644 index 0000000000000000000000000000000000000000..2f0f1a61a185993a89135c4958c6bc5e3c171c10 --- /dev/null +++ b/pool/shard008/C/0129497_2.c @@ -0,0 +1,17 @@ +#include +#include +#include + +void swap(int *a, int *b){ + int temp = *a; + *a = *b; + *b = temp; +} + +int main(int argc, const char *argv[]) +{ + int a = 10; + int b = 5; + swap(&a, &b); + return 0; +} diff --git a/pool/shard008/C/0129498_iter5.c b/pool/shard008/C/0129498_iter5.c new file mode 100644 index 0000000000000000000000000000000000000000..7e4c91690ab68801998f444c756e891492baaa44 --- /dev/null +++ b/pool/shard008/C/0129498_iter5.c @@ -0,0 +1,104 @@ +/* Copyright 2017-2019. Martin Uecker. + * All rights reserved. Use of this source code is governed by + * a BSD-style license which can be found in the LICENSE file. + */ + +#include + +#include "num/ops.h" +#include "num/multind.h" +#include "num/flpmath.h" +#include "num/iovec.h" + +#include "nlops/nlop.h" + +#include "misc/misc.h" +#include "misc/types.h" + +#include "iter/italgos.h" +#include "iter/iter3.h" +#include "iter/vec.h" + +#include "iter5.h" + + + +struct iter5_altmin_s { + + INTERFACE(iter_op_data); + + struct nlop_s* nlop; + + struct iter3_irgnm_conf* conf; + + long i; // argument to minimize +}; + +DEF_TYPEID(iter5_altmin_s); + + +static void altmin_nlop(iter_op_data* _o, int N, float* args[N], unsigned long der_out, unsigned long der_in) +{ + const auto data = CAST_DOWN(iter5_altmin_s, _o); + + assert((unsigned int)N == operator_nr_args(data->nlop->op)); + + nlop_generic_apply_select_derivative_unchecked(data->nlop, N, (void*)args, der_out, der_in); +} + +static void altmin_normal(iter_op_data* _o, float* dst, const float* src) +{ + const auto data = CAST_DOWN(iter5_altmin_s, _o); + const struct linop_s* der = nlop_get_derivative(data->nlop, 0, data->i); + + linop_normal_unchecked(der, (complex float*)dst, (const complex float*)src); +} + +static void altmin_inverse(iter_op_data* _o, float alpha, float* dst, const float* src) +{ + const auto data = CAST_DOWN(iter5_altmin_s, _o); + + const struct iovec_s* idest = nlop_generic_domain(data->nlop, data->i); + + long size = 2 * md_calc_size(idest->N, idest->dims); + + float* AHy = md_alloc_sameplace(1, MD_DIMS(size), FL_SIZE, src); + + linop_adjoint_unchecked(nlop_get_derivative(data->nlop, 0, data->i), (complex float*)AHy, (const complex float*)src); + + float eps = data->conf->cgtol * md_norm(idest->N, idest->dims, AHy); + + conjgrad(data->conf->cgiter, alpha, eps, size, select_vecops(src), + (struct iter_op_s){ altmin_normal, _o }, dst, AHy, NULL); + + md_free(AHy); +} + + + +void iter5_altmin(iter3_conf* _conf, + struct nlop_s* nlop, + long NI, float* dst[NI], + long M, const float* src, + struct iter_nlop_s cb) +{ + auto conf = CAST_DOWN(iter3_irgnm_conf, _conf); + struct iter5_altmin_s data = { { &TYPEID(iter5_altmin_s) }, nlop, conf, -1 }; + + struct iter_op_p_s min_ops[NI]; + struct iter5_altmin_s min_data[NI]; + + for(long i = 0; i < NI; ++i) { + + min_data[i] = (struct iter5_altmin_s){ { &TYPEID(iter5_altmin_s) }, nlop, conf, i }; + min_ops[i] = (struct iter_op_p_s){ altmin_inverse, CAST_UP(&min_data[i]) }; + } + + altmin(conf->iter, conf->alpha, conf->redu, + M, select_vecops(src), + NI, (struct iter_nlop_s){ altmin_nlop, CAST_UP(&data) }, + min_ops, dst, src, cb); +} + + + diff --git a/pool/shard008/C/0129500_nnspatt.c b/pool/shard008/C/0129500_nnspatt.c new file mode 100644 index 0000000000000000000000000000000000000000..725dc0768c6c210c15c574d98fc2350a4e78d3d9 --- /dev/null +++ b/pool/shard008/C/0129500_nnspatt.c @@ -0,0 +1,182 @@ +// (c) Michael Buro 1992-2002, licensed under the GNU Public License, version 2 + +#include "nnspatt.h" + +SPattern::SPattern() { tab = 0; trans_num = 0; } + +void SPattern::init(SPatternInfo &spinf) +{ + int i, j; + + name = spinf.name; + + cout << "SPattern " << name << endl; + + sp.hash_read(spinf.conf_file); + + // compute square lists + + trans_num = sp.dsymm_n; + + cout << "distinct patterns:" << endl; + + FOR (i, sp.dsymm_n) { + + cout << i << " 1: " << flush; + + for (j=0; sp.sq_list1[j]; j++) { + sq_lists1[i][j] = Trans[sp.dsymm[i]](sp.sq_list1[j]); + KoorAus(sq_lists1[i][j]); fflush(stdout); + cout << " "; + } + + sq_lists1[i][j] = 0; + + cout << " 2: " << flush; + + for (j=0; sp.sq_list2[j]; j++) { + sq_lists2[i][j] = Trans[sp.dsymm[i]](sp.sq_list2[j]); + KoorAus(sq_lists2[i][j]); fflush(stdout); + cout << " "; + } + + sq_lists2[i][j] = 0; + + cout << endl; + + } + + // allocate table + + cout << " new entry[" << sp.var_num << "]" << endl; + + tab = new Entry[sp.var_num]; + if (!tab) Error("SPattern::init: no memory"); + + cout << " entries=" << sizeof(Entry[sp.var_num]) << " esti=" << sp.var_num * sizeof(Estimate[Entry::INTERVAL_NUM]) << endl; + + FOR (i, sp.var_num) tab[i].alloc_esti(); + +} + + +void SPattern::conf_write(FILE *fp, int l, int n) +{ + Error("SPattern::conf_write not implemented yet"); + +#if 0 + + int i, r, cont[MAX_LEN]; + + FOR (i, l) { + r = n % 3; + if (r == 0) cont[i] = WHITE; + else if (r == 1) cont[i] = LEER; + else cont[i] = BLACK; + n /= 3; + } + + FOR (i, l) WriteDisc(fp, cont[l-1-i]); + +#endif + +} + + +void SPattern::asc_write(FILE *fp) +{ + Error("SPattern::asc_write not implemented yet"); + +#if 0 + int i, k; + + FOR (k, Pot3[len]) { + + Pattern::conf_write(fp, len, k); + + if (one_phase) { + + fprintf(fp, " %+6.3f", tab[k].p_map->get_y(0)); + + } else { + + FOR (i, Entry::INTERVAL_NUM) + fprintf(fp, " %+6.3f", tab[k].p_map->get_y(i)); + + } + + fprintf(fp, "\n"); + } +#endif + +} + + +void SPattern::bin_write(FILE *fp) +{ + int k, l; + + fputc(0x55, fp); // magic + fputc(0xaa, fp); + fputc(0x00, fp); + fputc((sp.var_num+sp.check_sum) % 253, fp); // source checksum + + fputc(Entry::INTERVAL_NUM, fp); + fputc(Entry::DISC_MIN, fp); + fputc(Entry::INTERVAL_LEN, fp); + + FOR (l, Entry::INTERVAL_NUM) + FOR (k, sp.var_num) + tab[k].bin_write(fp, l); +} + + +bool SPattern::bin_read(FILE *fp) +{ + int k, l; + + if (fgetc(fp) != 0x55) return true; + if (fgetc(fp) != 0xaa) return true; + if (fgetc(fp) != 0x00) return true; + if (fgetc(fp) != (((sp.var_num+sp.check_sum) % 253) & 0xff)) ; // !!! return true; + + if (fgetc(fp) != Entry::INTERVAL_NUM) return true; + if (fgetc(fp) != Entry::DISC_MIN) return true; + if (fgetc(fp) != Entry::INTERVAL_LEN) return true; + + FOR (l, Entry::INTERVAL_NUM) + FOR (k, sp.var_num) + tab[k].bin_read(fp, l); + + return false; +} + + +bool SPattern::bin_write_freq(FILE *fp, int n) +{ + Error("Spattern::bin_write_freq not implemented"); +#if 0 + + int k, l; + + if (n <= 0) Error("n <= 0"); + if (one_phase) Error("one phase not implemented"); + + fputc(len, fp); + fputc(Entry::INTERVAL_NUM, fp); + fputc(Entry::DISC_MIN, fp); + fputc(Entry::INTERVAL_LEN, fp); + + FOR (l, Entry::INTERVAL_NUM) + FOR (k, Pot3[len]) { + int val = (tab[k].p_map->get_n(l) < n) * 512; + fputc(val & 255, fp); + fputc(val >> 8, fp); + } + +#endif + + return false; + +} + diff --git a/pool/shard008/C/0129502_mt6573_pm_api.c b/pool/shard008/C/0129502_mt6573_pm_api.c new file mode 100644 index 0000000000000000000000000000000000000000..ca2189db697fdb2640f1fa1bbefba5fe1835f3c3 --- /dev/null +++ b/pool/shard008/C/0129502_mt6573_pm_api.c @@ -0,0 +1,295 @@ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mach/mt6573_reg_base.h" +#include "mach/irqs.h" +#include "mach/mt6573_eint.h" +#include "mach/dma.h" +#include "mach/sync_write.h" +#include "mach/mt6573_pll.h" +#include "mach/mt6573_typedefs.h" +#include "mach/mtkpm.h" +#include "mach/mt6573_ost_sm.h" +#include "mach/mt6573_gpio.h" +#include "pmu6573_hw.h" +#include "pmu6573_sw.h" +#include "upmu_common_sw.h" +#include "auddrv_register.h" +#include "cust_leds.h" + +UINT32 gChipVer ; +UINT32 CM_DBG_FLAG = 0x0; //DBG_PMAPI_CG | DBG_PMAPI_SUB | DBG_PMAPI_CG_LIS; + +ROOTBUS_HW g_MT6573_BusHW ; + +BOOL bCanEnDVFS = FALSE ; +BOOL bBUCK_ADJUST = FALSE ; +BOOL bEnDVFSLog = FALSE; + + +#if 0 + +void hwLowPowerPLLSwitch(void) +{ + UINT32 delay; + printk("dump code to internal SRAM\n\r"); + MT6573_EMI_switch(); + + /* Configuring the Mixedsys clock control and overrides for low power Audio mode (option 1) */ + /* Fire up the AUXPLL, running at 208MHz */ + //*AUX_PLL_CON0 = *AUX_PLL_CON0 | 0x0001; + DRV_SetReg32(AUXPLL_CON0_REG,0x0001); + + /* Waiting for AUXPLL Lock */ + while (((DRV_Reg32(AUXPLL_CON0_REG) & 0x8000) >> 15) == 0); + + // =========================================================== + // Below are OVERRIDE MUX in PLL BLOCK + // =========================================================== + /* TINFO="RG_OVRD_SYS_CLK : Select AUXPLL (26MHz) as Sysclk source" */ + /* TINFO="RG_OVRD_BUS_CLK : Select AUXPLL (104MHz) as Bus clock source" */ + /* TINFO="RG_OVRD_AUDIO_CLK: Select AUXPLL (26MHz) as Audio clock source" */ + //*PLL_CON2 = *PLL_CON2 | 0x3200; /* bit 13,12, bit 9 */ + DRV_SetReg32(PLL_CON2_REG,0x3200); + + // =========================================================== + // BELOW ARE MUX in CLKSW + // =========================================================== + /* TINFO="EMI_PLLSEL: Select AUXPLL (208M) as EMI clock source" */ + //*PLL_CON4 = (*PLL_CON4 & 0xFF0F) | 0x0020; + //DRV_WriteReg32(PLL_CON4_REG, ((DRV_Reg32(PLL_CON4_REG)& 0xFF0F)|0x0020) ); + + /* TINFO="APMCU_PLLSEL: Select AUXPLL (208M) as AP MCU clock source" */ + //*PLL_CON5 = (*PLL_CON5 & 0x0FFF) | 0x2000; + DRV_WriteReg32(PLL_CON5_REG, ((DRV_Reg32(PLL_CON5_REG)& 0x0FFF)|0x2000) ); + + // -- Not needed since OVRD used ? + // /* TINFO="SYS_PLLSEL: Select AUXPLL (26M) as SYSCLK clock source" */ + //*PLL_CON6 = *PLL_CON6 | 0x0010; + //DRV_SetReg32(PLL_CON6_REG,0x0010); + + + /*Step 0?: Backup DQSV*/ + /*Step 1: Disable Dummy Read*/ + *EMI_DRCT &= ~0x1; + /*Step 2: Block all emi transaction*/ + *EMI_CONM = 0x003F; + /*Step 3.0: */ + *EMI_DQSE &= ~(1<<28); //Clear + /*Step 3: Enter SDRAM self refresh mode and polling status*/ + *EMI_CONN |= (1<<5); + while( ( *EMI_CONN & (1<<7) ) == 0 ) + ; + /*Step 4: Wait for EMI idle bit assert*/ + while( ( *EMI_CONN & (1<<10) ) == 0 ) + ; + /*Step 5: Disable DQS strobe auto tracking*/ + *EMI_DQSE &= 0x7FFF0000; + + /*Step 6: Set DQSA~DQSD*/ + /*Step 7: Change EMI Setting*/ + //_set_emi_register_by_emi_clock_index( FALSE, Prof.emi_idx ); +#if 0 + + /*Step 8: Switch Clock*/ + *ARM_FSEL = _divisor_to_regval( SAL_CLK_ARM_DIVISIOR[Prof.arm_idx] ); + *DSP_FSEL = _divisor_to_regval( SAL_CLK_DSP_DIVISIOR[Prof.dsp_idx] ); + *EMI_FSEL = _divisor_to_regval( SAL_CLK_EMI_DIVISIOR[Prof.emi_idx] ); + + *FBUS_FSEL = _multiplier_to_regval( SAL_CLK_FBUS_MULTIPLIER[Prof.fbus_idx] ); + *SBUS_FSEL = _multiplier_to_regval( SAL_CLK_SBUS_MULTIPLIER[Prof.sbus_idx] ); +#endif + + /*Step 8: Switch Clock*/ + /* TINFO="EMI_PLLSEL: Select AUXPLL (208M) as EMI clock source" */ + //*PLL_CON4 = (*PLL_CON4 & 0xFF0F) | 0x0020; + DRV_WriteReg32(PLL_CON4_REG, ((DRV_Reg32(PLL_CON4_REG)& 0xFF0F)|0x0020) ); + + for( delay = 0; delay <= 0xFFFF; delay++ ) + ; + + /*Step 9: Unmask EMI access for all master*/ + *EMI_CONM = 0x0000; + + /*Step 10.0: IF Set, BUS will hang when access EMI*/ + //*EMI_DQSE |= (1<<28); + + /*Step 10: Exit SDRAM self refresh mode and polling status*/ + *EMI_CONN &= ~(1<<5); + while( ( *EMI_CONN & (1<<7) ) == 1 ) + ; + + /*Step 11: Enable dummy Read*/ + *EMI_DRCT |= 0x1; +} +#endif + +void mt6573_load_spare_settings(void) +{ + u16 spar0; + spar0 = 0; + if (spar0 & SPARE_SECRET_KEY) + { + if(spar0 & SPARE_E1_PATCH) + gChipVer = CHIP_VER_E2; + + if(spar0 & SPARE_DVFS_EN) + bCanEnDVFS = TRUE; + else + bCanEnDVFS = FALSE; + + if(spar0 & SPARE_VAPROC_ADJUST_EN) + bBUCK_ADJUST = TRUE; + else + bBUCK_ADJUST = FALSE; + + if(spar0 & SPARE_DVFS_LOG) + bEnDVFSLog = TRUE; + else + bEnDVFSLog = FALSE; + } +} + +void mt6573_CG_init(void) +{ + UINT32 u4Val; + struct cust_mt65xx_led *cust_led_list = get_cust_led_list(); + + set_clock_listen(TRUE); + DRV_SetReg32(APMCU_CG_CLR0, 0xffffffff); + //DRV_SetReg32(APMCU_CG_SET0, 0x2fff);//ungate UART4 + DRV_SetReg32(APMCU_CG_SET0, 0x2dff);//ungate UART1 and UART4 + + DRV_SetReg32(APMCU_CG_CLR1, 0xfffffff9);//unclear SIMIF0, SIMIF1 + if(cust_led_list[MT65XX_LED_TYPE_LCD].mode == MT65XX_LED_MODE_PWM) + { + DRV_SetReg32(APMCU_CG_SET1, 0x1f49);//ungate SIMIF0,SIMIF1,APDMA,NFI, PWM + } + else + { + DRV_SetReg32(APMCU_CG_SET1, 0x1f69);//ungate SIMIF0,SIMIF1,APDMA,NFI + } + + DRV_SetReg32(MMSYS1_CG_CLR0, 0xffffffff); + DRV_SetReg32(MMSYS1_CG_SET0, 0xfe7ffffe);//ungate LCD, DPI, GMC1 + + DRV_SetReg32(MMSYS1_CG_CLR1, 0xffffffff); + DRV_SetReg32(MMSYS1_CG_SET1, 0xff);//ungate GMC1E, GMC1SLV + + MTCMOS_En(MM2_SUBSYS); + DRV_SetReg32(MMSYS2_CG_CLR0, 0xffffffff); + DRV_SetReg32(MMSYS2_CG_SET0, 0x3e); + + MTCMOS_En(AUDIO_SUBSYS); + u4Val = DRV_Reg32(AUDIO_TOP_CON0_REG); + u4Val |= 0x74; + DRV_SetReg32(AUDIO_TOP_CON0_REG, u4Val); + +} + +void mt6573_chip_dep_init(void) +{ + dcm_disable_state(DEEP_IDLE_STATE); + + /* ALL MMSYS clock is couple with Bus clock, we cannot enable DCM at E1 */ + if (gChipVer == CHIP_VER_E1 ) + { + /*VA25 MODE_SEL, disable low power mode for VA25*/ + DRV_SetReg32((VA25_CON0+0x4),(0x1<<4)); + DRV_ClrReg32((VA25_CON0+0x4),(0x1<<3)); + /*VA12 MODE_SEL*/ + DRV_SetReg32((VA12_CON0),(0x1<<1)); + /*VA12 Force On*/ + DRV_SetReg32((VA12_CON0),(0x1<<0)); + /*MPLL force on */ + DRV_SetReg32(MPLL_CON1_REG, (0x1<<8)); + /*APLL force on */ + DRV_SetReg32(AMPLL_CON1_REG, (0x1<<8)); + /*DPLL force on */ + DRV_SetReg32(DPLL_CON1_REG, (0x1<<8)); + /*EPLL force on */ + DRV_SetReg32(EPLL_CON1_REG, (0x1<<8)); + /*3GPLL force on */ + DRV_SetReg32(WPLL_CON0_REG, (0x1<<8)); + /*2GPLL force on */ + DRV_SetReg32(GPLL_CON0_REG, (0x1<<8)); + + dcm_enable_state(SLOW_IDLE_STATE); + dcm_enable_state(LITTLE_IDLE_STATE); + /* The bus gating register for subsystem. This option will enables clock gating automatically + when the bus fabric is detected in idle mode. Together, HW will mask the handshake signals from AXI masters*/ + DRV_SetReg32(BUS_GATING_EN,0xDF); + + } + else /*Let Topsm turn off it */ + { + /*VA25 MODE_SEL, disable low power mode for VA25*/ + //DRV_SetReg32((VA25_CON0+0x4),(0x1<<4)); + //DRV_ClrReg32((VA25_CON0+0x4),(0x1<<3)); + + DRV_ClrReg32(MPLL_CON1_REG, (0x1<<8)); + DRV_ClrReg32(AMPLL_CON1_REG, (0x1<<8)); + DRV_ClrReg32(DPLL_CON1_REG, (0x1<<8)); + DRV_ClrReg32(EPLL_CON1_REG, (0x1<<8)); + DRV_ClrReg32(WPLL_CON0_REG, (0x1<<8)); + DRV_ClrReg32(GPLL_CON0_REG, (0x1<<8)); + + dcm_enable_state(SLOW_IDLE_STATE); + dcm_enable_state(DEEP_IDLE_STATE); + dcm_enable_state(LITTLE_IDLE_STATE); + /* The bus gating register for subsystem. This option will enables clock gating automatically + when the bus fabric is detected in idle mode. Together, HW will mask the handshake signals from AXI masters*/ + DRV_SetReg32(BUS_GATING_EN,0xFF); + + } +} + +void mt6573_dcm_init(void) +{ + /* HW DCM init*/ + MT6573_INIT_IDLE_THREAD(); + /* The Clock CG enable of AXI bus. This option will enables clock gating automatically + when there is no traffic in the bus fabric. Together, HW will mask the handshake signals from AXI masters.*/ + DRV_SetReg32(APPER_SLP_CON,0x3); + /* The Clock CG enable of AXI bus. This option will enables clock gating automatically + when there is no traffic in the bus fabric (bus_f122). Together, HW will mask the handshake signals from AXI masters.*/ + DRV_SetReg32(AP_SLPPRT_BUS,(1<<8) ); + +} + +void mt6573_power_management_init(void) +{ + /* Check Chip Version */ + gChipVer = DRV_Reg32(APHW_VER); + printk("[%s]: gChipVer = 0x%x\r\n",__FUNCTION__, gChipVer); + /* Load DVFS, DCM Setting from Spare*/ + mt6573_load_spare_settings(); + /* Clock Gating init, gated un-necessary power*/ + mt6573_CG_init(); + /* Set specific chip setting*/ + mt6573_chip_dep_init(); + /* Power mamagement log init*/ + mt6573_log_init(); + /* DCM init*/ + mt6573_dcm_init(); + /* Thermal protect Init*/ + hwThermalProtectInit(); + /* Sleep Controller init*/ + slp_mod_init(); +} + + + + diff --git a/pool/shard008/C/0129503_error.c b/pool/shard008/C/0129503_error.c new file mode 100644 index 0000000000000000000000000000000000000000..42c4f6d8723622e80c0237eab8c0e79e61e1eb21 --- /dev/null +++ b/pool/shard008/C/0129503_error.c @@ -0,0 +1,66 @@ +/* +** error.c for PSU_2016_navy in /home/bender/Repo/PSU_2016_navy/srcs/core/ +** +** Made by John Doe +** Login +** +** Started on Fri Feb 10 09:19:37 2017 John Doe +** Last update Fri Feb 10 09:19:46 2017 John Doe +*/ + +#include +#include +#include + +#include "errors.h" +#include "base.h" + +int p_exit(const char *str, int exitval) +{ + write(2, str, len(str)); + _exit (exitval); +} +int errors(const char *errmsg, int exitval) +{ + write(2, errmsg, len(errmsg)); + _exit (exitval); +} + +const char *removetrailingspace(const char *str) +{ + if (str[0] == ' ' || str[0] == '\t') + { + while (*str == ' ' || *str == '\t') + str++; + return (str); + } + return (str); +} + +char *clean_args(const char *str) +{ + char *clean = NULL; + int i; + + i = 0; + if (str == NULL) + return (NULL); + str = removetrailingspace(str); + clean = my_malloc(clean, len(str) + 1); + while (str[i] != '\0') + if ((str[i] == ' ' || str[i] =='\t') && (str[i + 1] != ' ' && str[i + 1] \ + != '\t')) + { + clean[i] = str[i]; + i = i + 1; + } + else if (str[i] != ' ' && str[i] != '\t') + { + clean[i] = str[i]; + i = i + 1; + } + else if (str[i] == ' ' || str[i] == '\t') + str++; + clean[i] = '\0'; + return (clean); +} diff --git a/pool/shard008/C/0129506_test_6_2.c b/pool/shard008/C/0129506_test_6_2.c new file mode 100644 index 0000000000000000000000000000000000000000..3a7b0cd1e21dca433c1c3433adadc1397bdd9aeb --- /dev/null +++ b/pool/shard008/C/0129506_test_6_2.c @@ -0,0 +1,52 @@ +/******************************************************************************/ +/* */ +/* Copyright (c) 2009 FUJITSU LIMITED */ +/* */ +/* 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 */ +/* */ +/* Author: Li Zefan */ +/* */ +/******************************************************************************/ + +#define _GNU_SOURCE + +#include +#include +#include +#include "test.h" + +#define DEFAULT_USEC 30000 + +int foo(void __attribute__((unused)) *arg) +{ + return 0; +} + +int main(int argc, char **argv) +{ + int usec; + + if (argc == 2) + usec = atoi(argv[1]); + else + usec = DEFAULT_USEC; + + while (1) { + usleep(usec); + ltp_clone_quick(CLONE_NEWNS, foo, NULL); + } + + tst_exit(); +} diff --git a/pool/shard008/C/0129507_showpal.c b/pool/shard008/C/0129507_showpal.c new file mode 100644 index 0000000000000000000000000000000000000000..4c47a7d14c2b997b2c23aac343b09df701afb672 --- /dev/null +++ b/pool/shard008/C/0129507_showpal.c @@ -0,0 +1,77 @@ +#include +#include + +#define WINDOW_WIDTH 640 +#define WINDOW_HEIGHT 640 +#define NUMROW 16 +#define NUMCOL 16 +#define RECT_WIDTH 40 +#define RECT_HEIGHT 40 + +//the following line depends on your compiler +typedef unsigned char u8; +typedef unsigned int u32; + +typedef struct{ + u8 r,g,b; +}rgb6; + +//the palette is the simplest format:the whole file consists of an array of 256 colors.for every byte,only the lowest 6 bits are effective. +#define NUM_COLORS_IN_PAL 256 +typedef rgb6 pal[NUM_COLORS_IN_PAL]; + +pal pale; + +//high r-g-b low +u32 rgb6_to_u32(rgb6 *s){ + u32 t; + + t=(s->r<<18)|((s->r&0x3)<<16); + t|=(s->g<<10)|((s->g&0x3)<<8); + t|=(s->b<<2)|(s->b&0x3); + return t; +} + +void drawpix(SDL_Surface *surface,int x,int y,u32 pix){ + ((u32*)(surface->pixels))[(surface->w)*y+x]=pix; +} + +void drawrect(SDL_Surface *surface,int x,int y,int width,int height,u32 color){ + int i,j; + + for(i=y;i + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License version 2.1 as published by the Free Software Foundation. + + 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. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include +#include + +#include "../lib/grn-assertions.h" +#include "grn_store.h" + +#include + +void test_vector_empty_load(void); + +static gchar *tmp_directory; + +static grn_ctx *context; +static grn_ja *ja; +static grn_obj *vector; + +void +cut_startup(void) +{ + tmp_directory = g_build_filename(grn_test_get_tmp_dir(), + "store-ja", + NULL); +} + +void +cut_shutdown(void) +{ + g_free(tmp_directory); +} + +static void +remove_tmp_directory(void) +{ + cut_remove_path(tmp_directory, NULL); +} + +void +cut_setup(void) +{ + remove_tmp_directory(); + g_mkdir_with_parents(tmp_directory, 0700); + + context = g_new0(grn_ctx, 1); + grn_ctx_init(context, 0); + ja = grn_ja_create(context, NULL, 65536, 0); + vector = grn_obj_open(context, GRN_BULK, GRN_OBJ_VECTOR, GRN_DB_VOID); +} + +void +cut_teardown(void) +{ + if (vector) { + grn_obj_unlink(context, vector); + } + + if (ja) { + grn_ja_close(context, ja); + } + + if (context) { + grn_ctx_fin(context); + g_free(context); + } + + remove_tmp_directory(); +} + +void +test_vector_empty_load(void) +{ + void *ptr; + uint32_t len; + grn_io_win iw; + + cut_assert_equal_int(0, grn_ja_size(context, ja, 1)); + ptr = grn_ja_ref(context, ja, 1, &iw, &len); + grn_ja_unref(context, &iw); + cut_assert_null(ptr); + cut_assert_equal_uint(0, len); + + grn_test_assert(grn_ja_putv(context, ja, 1, vector, GRN_OBJ_SET)); + + cut_assert_equal_int(1, grn_ja_size(context, ja, 1)); + ptr = grn_ja_ref(context, ja, 1, &iw, &len); + grn_ja_unref(context, &iw); + cut_assert_not_null(ptr); + cut_assert_equal_uint(1, len); +} diff --git a/pool/shard008/C/0129512_dpoequ.c b/pool/shard008/C/0129512_dpoequ.c new file mode 100644 index 0000000000000000000000000000000000000000..ebe70f9809977a2392a51696cd4367a738269975 --- /dev/null +++ b/pool/shard008/C/0129512_dpoequ.c @@ -0,0 +1,152 @@ +#include "blaswrap.h" +#include "f2c.h" + +/* Subroutine */ int dpoequ_(integer *n, doublereal *a, integer *lda, + doublereal *s, doublereal *scond, doublereal *amax, integer *info) +{ +/* -- LAPACK routine (version 3.0) -- + Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., + Courant Institute, Argonne National Lab, and Rice University + March 31, 1993 + + + Purpose + ======= + + DPOEQU computes row and column scalings intended to equilibrate a + symmetric positive definite matrix A and reduce its condition number + (with respect to the two-norm). S contains the scale factors, + S(i) = 1/sqrt(A(i,i)), chosen so that the scaled matrix B with + elements B(i,j) = S(i)*A(i,j)*S(j) has ones on the diagonal. This + choice of S puts the condition number of B within a factor N of the + smallest possible condition number over all possible diagonal + scalings. + + Arguments + ========= + + N (input) INTEGER + The order of the matrix A. N >= 0. + + A (input) DOUBLE PRECISION array, dimension (LDA,N) + The N-by-N symmetric positive definite matrix whose scaling + factors are to be computed. Only the diagonal elements of A + are referenced. + + LDA (input) INTEGER + The leading dimension of the array A. LDA >= max(1,N). + + S (output) DOUBLE PRECISION array, dimension (N) + If INFO = 0, S contains the scale factors for A. + + SCOND (output) DOUBLE PRECISION + If INFO = 0, S contains the ratio of the smallest S(i) to + the largest S(i). If SCOND >= 0.1 and AMAX is neither too + large nor too small, it is not worth scaling by S. + + AMAX (output) DOUBLE PRECISION + Absolute value of largest matrix element. If AMAX is very + close to overflow or very close to underflow, the matrix + should be scaled. + + INFO (output) INTEGER + = 0: successful exit + < 0: if INFO = -i, the i-th argument had an illegal value + > 0: if INFO = i, the i-th diagonal element is nonpositive. + + ===================================================================== + + + Test the input parameters. + + Parameter adjustments */ + /* System generated locals */ + integer a_dim1, a_offset, i__1; + doublereal d__1, d__2; + /* Builtin functions */ + double sqrt(doublereal); + /* Local variables */ + static doublereal smin; + static integer i__; + extern /* Subroutine */ int xerbla_(char *, integer *); +#define a_ref(a_1,a_2) a[(a_2)*a_dim1 + a_1] + + a_dim1 = *lda; + a_offset = 1 + a_dim1 * 1; + a -= a_offset; + --s; + + /* Function Body */ + *info = 0; + if (*n < 0) { + *info = -1; + } else if (*lda < max(1,*n)) { + *info = -3; + } + if (*info != 0) { + i__1 = -(*info); + xerbla_("DPOEQU", &i__1); + return 0; + } + +/* Quick return if possible */ + + if (*n == 0) { + *scond = 1.; + *amax = 0.; + return 0; + } + +/* Find the minimum and maximum diagonal elements. */ + + s[1] = a_ref(1, 1); + smin = s[1]; + *amax = s[1]; + i__1 = *n; + for (i__ = 2; i__ <= i__1; ++i__) { + s[i__] = a_ref(i__, i__); +/* Computing MIN */ + d__1 = smin, d__2 = s[i__]; + smin = min(d__1,d__2); +/* Computing MAX */ + d__1 = *amax, d__2 = s[i__]; + *amax = max(d__1,d__2); +/* L10: */ + } + + if (smin <= 0.) { + +/* Find the first non-positive diagonal element and return. */ + + i__1 = *n; + for (i__ = 1; i__ <= i__1; ++i__) { + if (s[i__] <= 0.) { + *info = i__; + return 0; + } +/* L20: */ + } + } else { + +/* Set the scale factors to the reciprocals + of the diagonal elements. */ + + i__1 = *n; + for (i__ = 1; i__ <= i__1; ++i__) { + s[i__] = 1. / sqrt(s[i__]); +/* L30: */ + } + +/* Compute SCOND = min(S(I)) / max(S(I)) */ + + *scond = sqrt(smin) / sqrt(*amax); + } + return 0; + +/* End of DPOEQU */ + +} /* dpoequ_ */ + +#undef a_ref + + diff --git a/pool/shard008/C/0129515_mali_platform.c b/pool/shard008/C/0129515_mali_platform.c new file mode 100644 index 0000000000000000000000000000000000000000..481e6e76c5497fcea00be1e5fd7f4d1149e2db11 --- /dev/null +++ b/pool/shard008/C/0129515_mali_platform.c @@ -0,0 +1,190 @@ +/* + * Copyright (C) ST-Ericsson SA 2011 + * + * Mali related Ux500 platform initialization + * + * Author: Marta Lofstedt for + * ST-Ericsson. + * License terms: GNU General Public License (GPL) version 2. + */ + +/** + * @file mali_platform.c + * Platform specific Mali driver functions for ST-Ericsson's Ux500 platforms + */ +#include "mali_kernel_common.h" +#include "mali_osk.h" +#include "mali_platform.h" + +#include +#include +#include +#include +#include + +#include + +#define MALI_HIGH_TO_LOW_LEVEL_UTILIZATION_LIMIT 64 +#define MALI_LOW_TO_HIGH_LEVEL_UTILIZATION_LIMIT 192 + +static int is_running; +static struct regulator *regulator; +static struct clk *clk_sga; +static u32 last_utilization; +static struct work_struct mali_utilization_work; +static struct workqueue_struct *mali_utilization_workqueue; + +/* Rationale behind the values for: +* MALI_HIGH_LEVEL_UTILIZATION_LIMIT and MALI_LOW_LEVEL_UTILIZATION_LIMIT +* When operating at half clock frequency a faster clock is requested when +* reaching 75% utilization. When operating at full clock frequency a slower +* clock is requested when reaching 25% utilization. There is a margin of 25% +* at the high range of the slow clock to avoid complete saturation of the +* hardware and there is some overlap to avoid an oscillating situation where +* the clock goes back and forth from high to low. +* +* Utilization on full speed clock +* 0 64 128 192 255 +* |---------------|---------------|---------------|---------------| +* XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX +* | ^ +* V | +* XXXXXXXXXXXXXXXXXXXXXXXXX +* 0 64 128 192 255 +* |-------|-------|-------|-------| +* Utilization on half speed clock +*/ +void mali_utilization_function(struct work_struct *ptr) +{ + /*By default, platform start with 50% APE OPP and 25% DDR OPP*/ + static u32 has_requested_low = 1; + + if (last_utilization > MALI_LOW_TO_HIGH_LEVEL_UTILIZATION_LIMIT) { + if (has_requested_low) { + MALI_DEBUG_PRINT(5, ("MALI GPU utilization: %u SIGNAL_HIGH\n", last_utilization)); + /*Request 100% APE_OPP.*/ + if (prcmu_qos_add_requirement(PRCMU_QOS_APE_OPP, "mali", 100)) { + MALI_DEBUG_PRINT(2, ("MALI 100% APE_OPP failed\n")); + return; + } + /* + * Since the utilization values will be reported higher + * if DDR_OPP is lowered, we also request 100% DDR_OPP. + */ + if (prcmu_qos_add_requirement(PRCMU_QOS_DDR_OPP, "mali", 100)) { + MALI_DEBUG_PRINT(2, ("MALI 100% DDR_OPP failed\n")); + return; + } + has_requested_low = 0; + } + } else { + if (last_utilization < MALI_HIGH_TO_LOW_LEVEL_UTILIZATION_LIMIT) { + if (!has_requested_low) { + /*Remove APE_OPP and DDR_OPP requests*/ + prcmu_qos_remove_requirement(PRCMU_QOS_APE_OPP, "mali"); + prcmu_qos_remove_requirement(PRCMU_QOS_DDR_OPP, "mali"); + MALI_DEBUG_PRINT(5, ("MALI GPU utilization: %u SIGNAL_LOW\n", last_utilization)); + has_requested_low = 1; + } + } + } + MALI_DEBUG_PRINT(5, ("MALI GPU utilization: %u\n", last_utilization)); +} + +_mali_osk_errcode_t mali_platform_init(_mali_osk_resource_t *resource) +{ + is_running = 0; + last_utilization = 0; + + mali_utilization_workqueue = create_singlethread_workqueue("mali_utilization_workqueue"); + if (NULL == mali_utilization_workqueue) { + MALI_DEBUG_PRINT(2, ("%s: Failed to setup workqueue %s\n", __func__, "v-mali")); + goto error; + } + INIT_WORK(&mali_utilization_work, mali_utilization_function); + + regulator = regulator_get(NULL, "v-mali"); + if (IS_ERR(regulator)) { + MALI_DEBUG_PRINT(2, ("%s: Failed to get regulator %s\n", __func__, "v-mali")); + goto error; + } + + clk_sga = clk_get_sys("mali", NULL); + if (IS_ERR(clk_sga)) { + regulator_put(regulator); + MALI_DEBUG_PRINT(2, ("%s: Failed to get clock %s\n", __func__, "mali")); + goto error; + } + + MALI_SUCCESS; +error: + MALI_DEBUG_PRINT(1, ("SGA initialization failed.\n")); + MALI_ERROR(_MALI_OSK_ERR_FAULT); +} + +_mali_osk_errcode_t mali_platform_deinit(_mali_osk_resource_type_t *type) +{ + destroy_workqueue(mali_utilization_workqueue); + regulator_put(regulator); + clk_put(clk_sga); + MALI_DEBUG_PRINT(2, ("SGA terminated.\n")); + MALI_SUCCESS; +} + +_mali_osk_errcode_t mali_platform_powerdown(u32 cores) +{ + if (is_running) { + clk_disable(clk_sga); + if (regulator) { + int ret = regulator_disable(regulator); + if (ret < 0) { + MALI_DEBUG_PRINT(2, ("%s: Failed to disable regulator %s\n", __func__, "v-mali")); + is_running = 0; + MALI_ERROR(_MALI_OSK_ERR_FAULT); + } + } + is_running = 0; + } + MALI_DEBUG_PRINT(4, ("mali_platform_powerdown is_running: %u cores: %u\n", is_running, cores)); + MALI_SUCCESS; +} + +_mali_osk_errcode_t mali_platform_powerup(u32 cores) +{ + if (!is_running) { + int ret = regulator_enable(regulator); + if (ret < 0) { + MALI_DEBUG_PRINT(2, ("%s: Failed to enable regulator %s\n", __func__, "v-mali")); + goto error; + } + + ret = clk_enable(clk_sga); + if (ret < 0) { + regulator_disable(regulator); + MALI_DEBUG_PRINT(2, ("%s: Failed to enable clock %s\n", __func__, "mali")); + goto error; + } + is_running = 1; + } + MALI_DEBUG_PRINT(4, ("mali_platform_powerup is_running:%u cores: %u\n", is_running, cores)); + MALI_SUCCESS; +error: + MALI_DEBUG_PRINT(1, ("Failed to power up.\n")); + MALI_ERROR(_MALI_OSK_ERR_FAULT); +} + +void mali_gpu_utilization_handler(u32 utilization) +{ + last_utilization = utilization; + /* + * We should not cancel the potentially not yet run old work + * in favor of a new work. + * Since the utilization value will change, + * the mali_utilization_function will evaluate based on + * what is the utilization now and not on what it was + * when it was scheduled. + */ + queue_work(mali_utilization_workqueue, &mali_utilization_work); +} + + diff --git a/pool/shard008/C/0129523_net_mcast_recv.c b/pool/shard008/C/0129523_net_mcast_recv.c new file mode 100644 index 0000000000000000000000000000000000000000..7f88f53d022beea5b9acd242aa8cb4c73ceed785 --- /dev/null +++ b/pool/shard008/C/0129523_net_mcast_recv.c @@ -0,0 +1,72 @@ +#include "muggle/c/muggle_c.h" + +int main(int argc, char *argv[]) +{ + if (muggle_log_simple_init(MUGGLE_LOG_LEVEL_INFO, MUGGLE_LOG_LEVEL_INFO) != 0) + { + MUGGLE_LOG_ERROR("failed initalize log"); + exit(EXIT_FAILURE); + } + + if (muggle_socket_lib_init() != 0) + { + MUGGLE_LOG_ERROR("failed initalize socket library"); + exit(EXIT_FAILURE); + } + + if (argc < 3) + { + MUGGLE_LOG_ERROR("usage: %s [net-iface] [mcast-source-group]", argv[0]); + exit(EXIT_FAILURE); + } + + const char *grp_host = argv[1]; + const char *grp_serv = argv[2]; + const char *iface = NULL; + const char *src_grp = NULL; + if (argc > 3) + { + iface = argv[3]; + } + if (argc > 4) + { + src_grp = argv[4]; + } + + MUGGLE_LOG_INFO("join multicast group"); + muggle_socket_t fd = muggle_mcast_join(grp_host, grp_serv, iface, src_grp, NULL); + if (fd == MUGGLE_INVALID_SOCKET) + { + MUGGLE_LOG_ERROR("failed multicast join %s:%s", grp_host, grp_serv); + exit(EXIT_FAILURE); + } + + int n; + char straddr[MUGGLE_SOCKET_ADDR_STRLEN]; + char buf[65536]; + struct sockaddr_storage addr; + muggle_socklen_t addrlen; + while (1) + { + addrlen = sizeof(addr); + n = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr*)&addr, &addrlen); + + if (muggle_socket_ntop((struct sockaddr*)&addr, straddr, MUGGLE_SOCKET_ADDR_STRLEN, 0) == NULL) + { + snprintf(straddr, MUGGLE_SOCKET_ADDR_STRLEN, "unknown:unknown"); + } + MUGGLE_LOG_INFO("recv %d bytes from %s", n, straddr); + + if (n > 10) + { + MUGGLE_LOG_INFO("leave multicast group"); + if (muggle_mcast_leave(fd, grp_host, grp_serv, iface, src_grp) != 0) + { + MUGGLE_LOG_ERROR("failed leave multicast group"); + } + muggle_socket_close(fd); + } + } + + return 0; +} diff --git a/pool/shard008/C/0129524_uncompr.c b/pool/shard008/C/0129524_uncompr.c new file mode 100644 index 0000000000000000000000000000000000000000..66a1b5e78080b062c52dc5bb579ba60b51625d9f --- /dev/null +++ b/pool/shard008/C/0129524_uncompr.c @@ -0,0 +1,61 @@ +/* uncompr.c -- decompress a memory buffer + * Copyright (C) 1995-2003 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id: uncompr.c,v 1.2 2006/02/21 05:55:31 bean Exp $ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +/* =========================================================================== + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be large enough to hold the + entire uncompressed data. (The size of the uncompressed data must have + been saved previously by the compressor and transmitted to the decompressor + by some mechanism outside the scope of this compression library.) + Upon exit, destLen is the actual size of the compressed buffer. + This function can be used to decompress a whole file at once if the + input file is mmap'ed. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted. +*/ +int ZEXPORT uncompress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + z_stream stream; + int err; + + stream.next_in = (Bytef*)source; + stream.avail_in = (uInt)sourceLen; + /* Check for source > 64K on 16-bit machine: */ + if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; + + stream.next_out = dest; + stream.avail_out = (uInt)*destLen; + if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + + err = inflateInit(&stream); + if (err != Z_OK) return err; + + err = inflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + inflateEnd(&stream); + if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) + return Z_DATA_ERROR; + return err; + } + *destLen = stream.total_out; + + err = inflateEnd(&stream); + return err; +} diff --git a/pool/shard008/C/0129528_test-support.c b/pool/shard008/C/0129528_test-support.c new file mode 100644 index 0000000000000000000000000000000000000000..031291383da90e51d1e00c1f537c3837859f8013 --- /dev/null +++ b/pool/shard008/C/0129528_test-support.c @@ -0,0 +1,198 @@ +/* Copyright (C) 2011 Omnibond, LLC + Client testing - support routines */ + +#include +#include +#include +#include + +#include "test-support.h" +#include "timer.h" + +const char *ops[] = {"=", "<>", "<", ">", "=<", ">="}; + +/* allocate and concatenate a string */ +char *quickcat(const char *str1, const char *str2) +{ + char *str; + + str = (char *) malloc(strlen(str1) + strlen(str2) + 1); + + sprintf(str, "%s%s", str1, str2); + + return str; +} + +/* generate a random dir name... caller must free */ +char *randdir(const char *root) +{ + char *slashdir, name[16], *dir; + + if (!root) + return NULL; + + /* append trailing slash */ + if (strlen(root) > 0 && root[strlen(root)-1] != SLASH_CHAR) + slashdir = quickcat(root, SLASH_STR); + else + slashdir = _strdup(root); + + /* generate random dir name */ + sprintf(name, "dir%05d", rand()); + + dir = quickcat(slashdir, name); + + free(slashdir); + + return dir; +} + +/* generate a random file name... caller must free */ +char *randfile(const char *root) +{ + char *slashdir, name[16], *file; + + if (!root) + return NULL; + + /* append trailing slash */ + if (strlen(root) > 0 && root[strlen(root)-1] != SLASH_CHAR) + slashdir = quickcat(root, SLASH_STR); + else + slashdir = _strdup(root); + + /* generate random dir name */ + sprintf(name, "f%05d.tst", rand()); + + file = quickcat(slashdir, name); + + free(slashdir); + + return file; +} + +/* create a 0-byte file */ +int quick_create(char *file_name) +{ + FILE *f; + + f = fopen(file_name, "w"); + if (f) + { + fclose(f); + return 0; + } + + return errno; +} + +void report_error(global_options *options, + const char *msg) +{ + /* report to console and/or file */ + if (options->report_flags & REPORT_CONSOLE) + printf("%s\n", msg); + + if (options->report_flags & REPORT_FILE) + { + fprintf(options->freport, "%s\n", msg); + fflush(options->freport); + } + +} + +void report_result(global_options *options, + const char *test_name, + const char *sub_test, + int expected_result, + int expected_code, + int code_operation, + int actual_code) +{ + int comp, ret; + char *ok_str, *line; + size_t line_size = 0; + + /* determine result of test */ + switch (code_operation) + { + case OPER_EQUAL: + comp = actual_code == expected_code; + break; + case OPER_NOTEQUAL: + comp = actual_code != expected_code; + break; + case OPER_LESS: + comp = actual_code < expected_code; + break; + case OPER_GREATER: + comp = actual_code > expected_code; + break; + case OPER_LESSOREQUAL: + comp = actual_code <= expected_code; + break; + case OPER_GREATEROREQUAL: + comp = actual_code >= expected_code; + } + + ok_str = comp ? "OK" : "NOT_OK"; + + /* determine size of line buffer */ + line_size += strlen(test_name); + line_size += 14; /* EXPECT_SUCCESS */ + line_size += 11; /* max decimal size -- actual_code */ + line_size += 8; /* expected */ + line_size += 2; /* operator */ + line_size += 11; /* expected_code */ + line_size += 3; /* got */ + line_size += 6; /* NOT_OK */ + line_size += 9; /* spaces & null */ + + line = (char *) malloc(line_size); + + /* print to buffer */ + ret = _snprintf(line, line_size, "%s %s %s expected %s %d got %d %s", + test_name, + sub_test, + (expected_result == RESULT_SUCCESS) ? "EXPECT_SUCCESS" : "EXPECT_FAILURE", + ops[code_operation], expected_code, actual_code, + ok_str); + if (ret < 0) + sprintf(line, "LINE BUFFER OVERFLOW"); + + /* report to console and/or file */ + if (options->report_flags & REPORT_CONSOLE) + printf("%s\n", line); + + if (options->report_flags & REPORT_FILE) + { + fprintf(options->freport, "%s\n", line); + fflush(options->freport); + } + + free(line); +} + +void report_perf(global_options *options, + const char *test_name, + const char *sub_test, + double value, + char *format) +{ + char valstr[32]; + + /* get the string for the value in the specified format */ + sprintf(valstr, format, value); + + /* report to console and/or file */ + if (options->report_flags & REPORT_CONSOLE) + printf("%s %s PERF %s\n", test_name, sub_test, valstr); + + if (options->report_flags & REPORT_FILE) + { + fprintf(options->freport, "%s %s PERF %s\n", test_name, sub_test, valstr); + fflush(options->freport); + } + +} + \ No newline at end of file diff --git a/pool/shard008/C/0129538_mips_cmgcr.c b/pool/shard008/C/0129538_mips_cmgcr.c new file mode 100644 index 0000000000000000000000000000000000000000..3c8b37f700f7d8db4be415d86f0ee5784df071b3 --- /dev/null +++ b/pool/shard008/C/0129538_mips_cmgcr.c @@ -0,0 +1,255 @@ +/* + * This file is subject to the terms and conditions of the GNU General Public + * License. See the file "COPYING" in the main directory of this archive + * for more details. + * + * Copyright (C) 2012 MIPS Technologies, Inc. All rights reserved. + * Authors: Sanjay Lal + * + * Copyright (C) 2015 Imagination Technologies + */ + +#include "qemu/osdep.h" +#include "qemu/log.h" +#include "qemu/module.h" +#include "hw/sysbus.h" +#include "migration/vmstate.h" +#include "hw/misc/mips_cmgcr.h" +#include "hw/misc/mips_cpc.h" +#include "hw/qdev-properties.h" +#include "hw/intc/mips_gic.h" + +static inline bool is_cpc_connected(MIPSGCRState *s) +{ + return s->cpc_mr != NULL; +} + +static inline bool is_gic_connected(MIPSGCRState *s) +{ + return s->gic_mr != NULL; +} + +static inline void update_gcr_base(MIPSGCRState *gcr, uint64_t val) +{ + CPUState *cpu; + MIPSCPU *mips_cpu; + + gcr->gcr_base = val & GCR_BASE_GCRBASE_MSK; + memory_region_set_address(&gcr->iomem, gcr->gcr_base); + + CPU_FOREACH(cpu) { + mips_cpu = MIPS_CPU(cpu); + mips_cpu->env.CP0_CMGCRBase = gcr->gcr_base >> 4; + } +} + +static inline void update_cpc_base(MIPSGCRState *gcr, uint64_t val) +{ + if (is_cpc_connected(gcr)) { + gcr->cpc_base = val & GCR_CPC_BASE_MSK; + memory_region_transaction_begin(); + memory_region_set_address(gcr->cpc_mr, + gcr->cpc_base & GCR_CPC_BASE_CPCBASE_MSK); + memory_region_set_enabled(gcr->cpc_mr, + gcr->cpc_base & GCR_CPC_BASE_CPCEN_MSK); + memory_region_transaction_commit(); + } +} + +static inline void update_gic_base(MIPSGCRState *gcr, uint64_t val) +{ + if (is_gic_connected(gcr)) { + gcr->gic_base = val & GCR_GIC_BASE_MSK; + memory_region_transaction_begin(); + memory_region_set_address(gcr->gic_mr, + gcr->gic_base & GCR_GIC_BASE_GICBASE_MSK); + memory_region_set_enabled(gcr->gic_mr, + gcr->gic_base & GCR_GIC_BASE_GICEN_MSK); + memory_region_transaction_commit(); + } +} + +/* Read GCR registers */ +static uint64_t gcr_read(void *opaque, hwaddr addr, unsigned size) +{ + MIPSGCRState *gcr = (MIPSGCRState *) opaque; + MIPSGCRVPState *current_vps = &gcr->vps[current_cpu->cpu_index]; + MIPSGCRVPState *other_vps = &gcr->vps[current_vps->other]; + + switch (addr) { + /* Global Control Block Register */ + case GCR_CONFIG_OFS: + /* Set PCORES to 0 */ + return 0; + case GCR_BASE_OFS: + return gcr->gcr_base; + case GCR_REV_OFS: + return gcr->gcr_rev; + case GCR_GIC_BASE_OFS: + return gcr->gic_base; + case GCR_CPC_BASE_OFS: + return gcr->cpc_base; + case GCR_GIC_STATUS_OFS: + return is_gic_connected(gcr); + case GCR_CPC_STATUS_OFS: + return is_cpc_connected(gcr); + case GCR_L2_CONFIG_OFS: + /* L2 BYPASS */ + return GCR_L2_CONFIG_BYPASS_MSK; + /* Core-Local and Core-Other Control Blocks */ + case MIPS_CLCB_OFS + GCR_CL_CONFIG_OFS: + case MIPS_COCB_OFS + GCR_CL_CONFIG_OFS: + /* Set PVP to # of VPs - 1 */ + return gcr->num_vps - 1; + case MIPS_CLCB_OFS + GCR_CL_RESETBASE_OFS: + return current_vps->reset_base; + case MIPS_COCB_OFS + GCR_CL_RESETBASE_OFS: + return other_vps->reset_base; + case MIPS_CLCB_OFS + GCR_CL_OTHER_OFS: + return current_vps->other; + case MIPS_COCB_OFS + GCR_CL_OTHER_OFS: + return other_vps->other; + default: + qemu_log_mask(LOG_UNIMP, "Read %d bytes at GCR offset 0x%" HWADDR_PRIx + "\n", size, addr); + return 0; + } + return 0; +} + +static inline target_ulong get_exception_base(MIPSGCRVPState *vps) +{ + /* TODO: BEV_BASE and SELECT_BEV */ + return (int32_t)(vps->reset_base & GCR_CL_RESET_BASE_RESETBASE_MSK); +} + +/* Write GCR registers */ +static void gcr_write(void *opaque, hwaddr addr, uint64_t data, unsigned size) +{ + MIPSGCRState *gcr = (MIPSGCRState *)opaque; + MIPSGCRVPState *current_vps = &gcr->vps[current_cpu->cpu_index]; + MIPSGCRVPState *other_vps = &gcr->vps[current_vps->other]; + + switch (addr) { + case GCR_BASE_OFS: + update_gcr_base(gcr, data); + break; + case GCR_GIC_BASE_OFS: + update_gic_base(gcr, data); + break; + case GCR_CPC_BASE_OFS: + update_cpc_base(gcr, data); + break; + case MIPS_CLCB_OFS + GCR_CL_RESETBASE_OFS: + current_vps->reset_base = data & GCR_CL_RESET_BASE_MSK; + cpu_set_exception_base(current_cpu->cpu_index, + get_exception_base(current_vps)); + break; + case MIPS_COCB_OFS + GCR_CL_RESETBASE_OFS: + other_vps->reset_base = data & GCR_CL_RESET_BASE_MSK; + cpu_set_exception_base(current_vps->other, + get_exception_base(other_vps)); + break; + case MIPS_CLCB_OFS + GCR_CL_OTHER_OFS: + if ((data & GCR_CL_OTHER_MSK) < gcr->num_vps) { + current_vps->other = data & GCR_CL_OTHER_MSK; + } + break; + case MIPS_COCB_OFS + GCR_CL_OTHER_OFS: + if ((data & GCR_CL_OTHER_MSK) < gcr->num_vps) { + other_vps->other = data & GCR_CL_OTHER_MSK; + } + break; + default: + qemu_log_mask(LOG_UNIMP, "Write %d bytes at GCR offset 0x%" HWADDR_PRIx + " 0x%" PRIx64 "\n", size, addr, data); + break; + } +} + +static const MemoryRegionOps gcr_ops = { + .read = gcr_read, + .write = gcr_write, + .endianness = DEVICE_NATIVE_ENDIAN, + .impl = { + .max_access_size = 8, + }, +}; + +static void mips_gcr_init(Object *obj) +{ + SysBusDevice *sbd = SYS_BUS_DEVICE(obj); + MIPSGCRState *s = MIPS_GCR(obj); + + memory_region_init_io(&s->iomem, OBJECT(s), &gcr_ops, s, + "mips-gcr", GCR_ADDRSPACE_SZ); + sysbus_init_mmio(sbd, &s->iomem); +} + +static void mips_gcr_reset(DeviceState *dev) +{ + MIPSGCRState *s = MIPS_GCR(dev); + int i; + + update_gic_base(s, 0); + update_cpc_base(s, 0); + + for (i = 0; i < s->num_vps; i++) { + s->vps[i].other = 0; + s->vps[i].reset_base = 0xBFC00000 & GCR_CL_RESET_BASE_MSK; + cpu_set_exception_base(i, get_exception_base(&s->vps[i])); + } +} + +static const VMStateDescription vmstate_mips_gcr = { + .name = "mips-gcr", + .version_id = 0, + .minimum_version_id = 0, + .fields = (VMStateField[]) { + VMSTATE_UINT64(cpc_base, MIPSGCRState), + VMSTATE_END_OF_LIST() + }, +}; + +static Property mips_gcr_properties[] = { + DEFINE_PROP_INT32("num-vp", MIPSGCRState, num_vps, 1), + DEFINE_PROP_INT32("gcr-rev", MIPSGCRState, gcr_rev, 0x800), + DEFINE_PROP_UINT64("gcr-base", MIPSGCRState, gcr_base, GCR_BASE_ADDR), + DEFINE_PROP_LINK("gic", MIPSGCRState, gic_mr, TYPE_MEMORY_REGION, + MemoryRegion *), + DEFINE_PROP_LINK("cpc", MIPSGCRState, cpc_mr, TYPE_MEMORY_REGION, + MemoryRegion *), + DEFINE_PROP_END_OF_LIST(), +}; + +static void mips_gcr_realize(DeviceState *dev, Error **errp) +{ + MIPSGCRState *s = MIPS_GCR(dev); + + /* Create local set of registers for each VP */ + s->vps = g_new(MIPSGCRVPState, s->num_vps); +} + +static void mips_gcr_class_init(ObjectClass *klass, void *data) +{ + DeviceClass *dc = DEVICE_CLASS(klass); + device_class_set_props(dc, mips_gcr_properties); + dc->vmsd = &vmstate_mips_gcr; + dc->reset = mips_gcr_reset; + dc->realize = mips_gcr_realize; +} + +static const TypeInfo mips_gcr_info = { + .name = TYPE_MIPS_GCR, + .parent = TYPE_SYS_BUS_DEVICE, + .instance_size = sizeof(MIPSGCRState), + .instance_init = mips_gcr_init, + .class_init = mips_gcr_class_init, +}; + +static void mips_gcr_register_types(void) +{ + type_register_static(&mips_gcr_info); +} + +type_init(mips_gcr_register_types) diff --git a/pool/shard008/C/0129543_check_write.c b/pool/shard008/C/0129543_check_write.c new file mode 100644 index 0000000000000000000000000000000000000000..2315217a55fec571239971b9e5d04d9d194a7abd --- /dev/null +++ b/pool/shard008/C/0129543_check_write.c @@ -0,0 +1,68 @@ +#include +#include +#include +#include + +#include + +START_TEST (test_harp_write_configs) { + harp_list_t *configs = harp_read_configs(FIXTURESDIR "/full.conf", NULL); + + char *tpl = "/tmp/harp.test.XXXXXXXXXX"; + char *temp_path = (char*)malloc(strlen(tpl) + 1); + strncpy(temp_path, tpl, strlen(tpl) + 1); + if(mktemp(temp_path) == NULL) { + perror("mktemp"); + ck_abort(); + } + + int rc = harp_write_configs(configs, temp_path); + ck_assert_int_eq(rc, 0); + + FILE *f1 = fopen(FIXTURESDIR "/full.conf", "r"); + if(f1 == NULL) { + perror("fopen"); + ck_abort(); + } + + FILE *f2 = fopen(temp_path, "r"); + if(f2 == NULL) { + perror("fopen"); + ck_abort(); + } + + char buf1[300], buf2[300]; + + size_t count1 = fread(&buf1, 1, 299, f1); + size_t count2 = fread(&buf2, 1, 299, f2); + + buf1[299] = '\0'; + buf2[299] = '\0'; + + ck_assert_int_ne(count1, 0); + ck_assert_int_ne(count2, 0); + + ck_assert_str_eq(buf1, buf2); + + fclose(f1); + fclose(f2); + + harp_free_list(configs, (harp_free_function_t*)&harp_free_config); + free(temp_path); +} +END_TEST + +/* + * Suite + */ + +Suite *harp_config_write_suite() { + Suite *suite = suite_create("Write config"); + + TCase *tc_all = tcase_create("Write"); + tcase_add_test(tc_all, test_harp_write_configs); + + suite_add_tcase(suite, tc_all); + + return suite; +} diff --git a/pool/shard008/C/0129547_impersonate_macaddress.c b/pool/shard008/C/0129547_impersonate_macaddress.c new file mode 100644 index 0000000000000000000000000000000000000000..7672d7930dc16e55a50502e07b506953d07267c2 --- /dev/null +++ b/pool/shard008/C/0129547_impersonate_macaddress.c @@ -0,0 +1,47 @@ +/* + * COPYRIGHT (C) 2015 Yann Sionneau + */ + +#define _GNU_SOURCE + +#include +#include +#include +#include +#include +#include +#include +#include + +#define ETHER_ADDR_LEN 6 + +int ioctl(int d, unsigned long request, ...) +{ + va_list myargs; + struct ifreq *ifr; + int ret; + int i; + char mac_addr_buff[ETHER_ADDR_LEN]; + char *mac_addr; + + va_start(myargs, request); + mac_addr = getenv("MACADDR"); + sscanf(mac_addr, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &mac_addr_buff[0], + &mac_addr_buff[1], &mac_addr_buff[2], &mac_addr_buff[3], + &mac_addr_buff[4], &mac_addr_buff[5]); + + if(request == SIOCGIFHWADDR) { + ifr = va_arg(myargs, struct ifreq *); + ifr->ifr_hwaddr.sa_family = ARPHRD_ETHER; + for(i = 0; i < ETHER_ADDR_LEN; i++) + ifr->ifr_hwaddr.sa_data[i] = mac_addr_buff[i]; + va_end(myargs); + return 0; + } else { + int (*real_ioctl)(int, unsigned long, ...); + real_ioctl = dlsym(RTLD_NEXT, "ioctl"); + ret = real_ioctl(d, request, myargs); + va_end(myargs); + return ret; + } +} diff --git a/pool/shard008/C/0129552_os_functions.c b/pool/shard008/C/0129552_os_functions.c new file mode 100644 index 0000000000000000000000000000000000000000..86d52b23f533a0ee9431f9a6f267521359c8e56e --- /dev/null +++ b/pool/shard008/C/0129552_os_functions.c @@ -0,0 +1,134 @@ + +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * 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. + * + * $Id$ + */ + +#include "libjc.h" + +/* + +This file contains O/S dependent (but architecture independent) functions. +The following functions must be defined here: + + int + _jc_num_cpus(_jc_env *env) + + This function should return the number of CPU's. It is used + to implement the Runtime.availableProcessors() method. + + */ + +/************************************************************************ + * FreeBSD * + ************************************************************************/ + +#if defined(__FreeBSD__) + +#include + +int +_jc_num_cpus(_jc_env *env) +{ + static const char *const node = "hw.ncpu"; + _jc_jvm *const vm = env->vm; + int num; + + if (sysctlbyname(node, NULL, 0, &num, sizeof(num)) == -1) { + _jc_eprintf(vm, "sysctl(%s): %s", node, strerror(errno)); + return 1; + } + return num; +} + +/************************************************************************ + * OS X * + ************************************************************************/ + +/** @todo is this really the right way to detect OS X? */ +#elif defined(__APPLE__) + +#include + +int +_jc_num_cpus(_jc_env *env) +{ + static const char *const node = "hw.ncpu"; + _jc_jvm *const vm = env->vm; + int num; + + if (sysctlbyname(node, NULL, 0, &num, sizeof(num)) == -1) { + _jc_eprintf(vm, "sysctl(%s): %s", node, strerror(errno)); + return 1; + } + return num; +} + +/************************************************************************ + * Linux * + ************************************************************************/ + +#elif defined(__linux__) + +int +_jc_num_cpus(_jc_env *env) +{ + _jc_jvm *const vm = env->vm; + static const char *const file = "/proc/cpuinfo"; + char buf[64]; + size_t len; + FILE *fp; + int num; + int ch; + + if ((fp = fopen("/proc/cpuinfo", "r")) == NULL) { + _jc_eprintf(vm, "%s: %s", file, strerror(errno)); + return 1; + } + for (num = 0; fgets(buf, sizeof(buf), fp) != NULL; ) { + len = strlen(buf); + if (len > 0 && buf[len - 1] != '\n') + while ((ch = getc(fp)) != '\n' && ch != EOF); + if (strncmp(buf, "processor", 9) == 0) + num++; + } + fclose(fp); + return num; +} + +#elif defined(__CYGWIN__) + +/************************************************************************ + * CYGWIN * + ************************************************************************/ + +#include + +int +_jc_num_cpus(_jc_env *env) +{ + return (int)sysconf(_SC_NPROCESSORS_ONLN); +} + +/************************************************************************ + * Others * + ************************************************************************/ + +#else +#error "Unsupported operating system" +#endif + diff --git a/pool/shard008/C/0129556_UART.c b/pool/shard008/C/0129556_UART.c new file mode 100644 index 0000000000000000000000000000000000000000..b69aa1bc576e390328eba7044cbc1c8ef474e429 --- /dev/null +++ b/pool/shard008/C/0129556_UART.c @@ -0,0 +1,84 @@ +#define FCK 8000000ULL +#define FCY 4000000ULL + +#include +#include + + +//Initializes UART1 module for communication with GPS +void UART1_init(unsigned long baud){ + + U1BRG = ((FCY / baud) / 16)-1; //Baud rate calculation + U1MODEbits.UARTEN = 0; //Disable module + U1MODE = 0; //8-bit data,no parity, one stop bit + U1STA = 0; //Reset status register + IEC0bits.U1RXIE = 0; //disable receive interrupt + IFS0bits.U1RXIF = 0; //clear interrupt flag + IPC2bits.U1RXIP = 6; //set interrupt priority + U1MODEbits.UARTEN = 1; //Enable module + U1STAbits.UTXEN = 1; //Enable transmission +} + +//Initializes UART2 module for communication with RPi +void UART2_init(unsigned long baud){ + + U2BRG = ((FCY / baud) / 16)-1; //Baud rate calculation + U2MODEbits.UARTEN = 0; //Disable module + U2MODE = 0; //8-bit data,no parity, one stop bit + U2STA = 0; //Reset status register + IEC1bits.U2RXIE = 0; //disable receive interrupt + IFS1bits.U2RXIF = 0; //clear interrupt flag + IPC7bits.U2RXIP = 5; //set interrupt priority + U2MODEbits.UARTEN = 1; //Enable module + U2STAbits.UTXEN = 1; //Enable transmission +} + +//Sends one byte via UART1 module +void UART1_PutChar(char ch){ + + while(U1STAbits.UTXBF != 0); + U1TXREG = ch; +} + +//Sends one byte via UART2 module +void UART2_PutChar(char ch){ + + while(U2STAbits.UTXBF == 1); + U2TXREG = ch; +} + +//Receives one byte via UART1 module +char UART1_GetChar(void){ + + char temp; + if(U1STAbits.OERR == 1){ + U1STAbits.OERR = 0; + } + while(U1STAbits.URXDA == 0); + temp = U1RXREG; + return temp; +} + +//Receives one byte via UART2 module +char UART2_GetChar(void){ + + char temp; + if(U2STAbits.OERR == 1){ + U2STAbits.OERR = 0; + } + while(U2STAbits.URXDA == 0); + temp = U2RXREG; + return temp; +} + +//Sends array ending in '\n' via UART2 module +void sendArray(char *str){ + + char i; + + do{ + UART2_PutChar(*str); + i = *str; + str++; + }while(i != '\n'); +} diff --git a/pool/shard008/C/0129560_03_order_of_periodic.c b/pool/shard008/C/0129560_03_order_of_periodic.c new file mode 100644 index 0000000000000000000000000000000000000000..4e3c8ba424d376991818357d5a9549bd128ed0f3 --- /dev/null +++ b/pool/shard008/C/0129560_03_order_of_periodic.c @@ -0,0 +1,50 @@ +/* + * Test 03 + * Tests that the RTOS correctly schedules periodic tasks. + */ + +#include "trace.h" +#include "kernel.h" +#include "03_order_of_periodic.h" + +#include + +int count = 0; + +void test_results() { + char * trace = get_trace(); + char * correct_trace = "(1,1),(2,2),(3,3),(4,4),(5,5),(6,"; + if (strcmp(correct_trace, trace) == 0) { + OS_Abort(TEST_PASS); + } else { + OS_Abort(TEST_FAIL); + } +} + +void task(void) { + int arg = 0; + arg = Task_GetArg(); + + for (;;) { + add_to_trace(arg, ENTER); + + if (arg == 6) { + Disable_Interrupt(); + test_results(); + } + + add_to_trace(arg, EXIT); + + Task_Next(); + } +} + +void main_a() { + Task_Create_Period(task, 1, 8, 1, 1); + Task_Create_Period(task, 2, 8, 1, 2); + Task_Create_Period(task, 3, 8, 1, 3); + Task_Create_Period(task, 4, 8, 1, 4); + Task_Create_Period(task, 5, 8, 1, 5); + Task_Create_Period(task, 6, 8, 1, 6); + Task_Create_Period(task, 7, 8, 1, 7); +} \ No newline at end of file diff --git a/pool/shard008/C/0129562_jibmodpw.c b/pool/shard008/C/0129562_jibmodpw.c new file mode 100644 index 0000000000000000000000000000000000000000..9b08b5265efe1207d947d17227b47617b7498ca2 --- /dev/null +++ b/pool/shard008/C/0129562_jibmodpw.c @@ -0,0 +1,268 @@ +//--------------------------------------------------------------------------- +// Copyright (C) 2001 Dallas Semiconductor Corporation, All Rights Reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the "Software"), +// to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +// IN NO EVENT SHALL DALLAS SEMICONDUCTOR BE LIABLE FOR ANY CLAIM, DAMAGES +// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// +// Except as contained in this notice, the name of Dallas Semiconductor +// shall not be used except as stated in the Dallas Semiconductor +// Branding Policy. +//-------------------------------------------------------------------------- +// +// jibmodpw.c - test teh a JiBLet TestModPow on a Java Powered iButton +// +// version 3.00 Beta +// + +#include "jib96.h" +#include +#include + +#define MAXDEVICES 10 +#define LOAD_UNLOAD_TIME 500 +#define EXECUTE_TIME 1500 + +// external functions +extern SMALLINT owAcquire(int,char *); +extern void owRelease(int); +extern SMALLINT FindDevices(int,uchar FamilySN[][8],SMALLINT,int); +extern void PrintSerialNum(uchar*); +extern SMALLINT owOverdriveAccess(int); +extern void owSerialNum(int,uchar *,SMALLINT); +extern int key_abort(void); + +// local prototypes +uchar *getRandData(uchar p_Len, uchar *p_lpData); +uchar CycleTest(int portnum, uchar *dev); + +// globals +int g_NumCompletions = 0, + g_NumFailures = 0; + +//-------------------------------------------------------------------------- +// Main for the Jib test +// +int main(int argc, char **argv) +{ + int i, portnum=0, NumDevices; + uchar FamilySN[MAXDEVICES][8]; + + // check for required port name + if (argc != 2) + { + printf("1-Wire Net name required on command line!\n" + " (example: \"COM1\" (Win32 DS2480),\"/dev/cua0\" " + "(Linux DS2480),\"1\" (Win32 TMEX)\n"); + exit(1); + } + + // attempt to acquire the 1-Wire Net + if ((portnum = owAcquireEx(argv[1])) < 0) + { + OWERROR_DUMP(stdout); + exit(1); + } + + // success + printf("Port opened: %s\n",argv[1]); + + // initialize the random number generator + srand((unsigned)time(NULL)); + + // Find the device(s) + NumDevices = FindDevices(portnum, &FamilySN[0], 0x16, MAXDEVICES); + + if (NumDevices>0) + { + printf("\n"); + printf("JiB(s) Found: \n"); + for (i = 0; i < NumDevices; i++) + { + PrintSerialNum(FamilySN[i]); + printf("\n"); + } + printf("\n\n"); + + do + { + // loop through the devices and do a test on each + for (i = 0; i < NumDevices; i++) + CycleTest(portnum, FamilySN[i]); + } + while (!key_abort()); + } + else + printf("No JiB's Found!\n"); + + // release the 1-Wire Net + owRelease(portnum); + printf("Closing port %s.\n", argv[1]); + exit(0); + return 0; +} + +//-------------------------------------------------------------------------- +// Get random numbers +// +uchar *getRandData(uchar p_Len, uchar *p_lpData) +{ + int i; + p_lpData[0] = p_Len; + + for(i = 1; i <= p_Len; i++) + p_lpData[i] = (uchar)rand(); + + p_lpData[1] |= 0x80; + return p_lpData; +} + +//-------------------------------------------------------------------------- +// This is a simple function to verify the coprocessor functions using +// the JiBlet TestModExp.jib. +// NOTE: TestModExp must be loaded and selected before executing this function. +// +uchar CycleTest(int portnum, uchar *dev) +{ + + LPRESPONSEAPDU l_lpResponseAPDU; + uchar l_RefBuffer[256]; + uchar l_Message[129], + l_Modulus[129], + l_Exponent[129]; + uchar l_i; + + // select the device and put in overdrive + printf("\nDevice: "); + PrintSerialNum(dev); + printf("\n"); + + owSerialNum(portnum,dev,0); + if (!owOverdriveAccess(portnum)) + printf("ERROR, could not get device in overdrive!\n"); + + // read the firmware string // + l_lpResponseAPDU = GetFirmwareVersionString(portnum); + + if(l_lpResponseAPDU) + { + if(l_lpResponseAPDU->SW == (ushort)0x9000) + { + // trim out the length byte // + memcpy(l_RefBuffer,l_lpResponseAPDU->Data+1,l_lpResponseAPDU->Len-1); + + // zero terminate the string // + l_RefBuffer[l_lpResponseAPDU->Len-1] = 0; + printf("Firmware: %s\n",l_RefBuffer); + } + else + printf("GetFirmwareVersionString Error: SW = %04.4X",l_lpResponseAPDU->SW); + } + + printf("Loading Message\n"); + l_lpResponseAPDU = Process(portnum, 0x80, 0x00, 0, 0, 128, getRandData(127,l_Message), LOAD_UNLOAD_TIME); + + if(l_lpResponseAPDU->SW != (ushort)0x9000) + { + printf("Load Message failed with SW = %04x\n",l_lpResponseAPDU->SW); + return FALSE; + } + + printf("Loading Exponent\n"); + l_lpResponseAPDU = Process(portnum, 0x80, 0x01, 0, 0, 128, getRandData(127,l_Exponent), LOAD_UNLOAD_TIME); + + if(l_lpResponseAPDU->SW != (ushort)0x9000) + { + printf("Load Exponent failed with SW = %04x\n",l_lpResponseAPDU->SW); + return FALSE; + } + + // make the modulus 1 byte larger than the exponent and message to insure that it is larger + // without actually doing a "big number" compare (a quick cheat). + printf("Loading Modulus\n"); + l_lpResponseAPDU = Process(portnum, 0x80, 0x02, 0, 0, 129, getRandData(128,l_Modulus), LOAD_UNLOAD_TIME); + + if(l_lpResponseAPDU->SW != (ushort)0x9000) + { + printf("Load Modulus failed with SW = %04x\n",l_lpResponseAPDU->SW); + return FALSE; + } + + printf("Performing Exponentiation\n"); + l_lpResponseAPDU = Process(portnum, 0x80, 0x03, 0, 0, 0, NULL, EXECUTE_TIME); + + if(l_lpResponseAPDU->SW != (ushort)0x9000) + { + printf("Exponentiation failed with SW = %04x\n",l_lpResponseAPDU->SW); + return FALSE; + } + + printf("Performing Read\n"); + l_lpResponseAPDU = Process(portnum, 0x80, 0x04, 0, 0, 0, NULL, LOAD_UNLOAD_TIME); + + if(l_lpResponseAPDU->SW != (ushort)0x9000) + { + printf("Read failed with SW = %04x\n",l_lpResponseAPDU->SW); + return FALSE; + } + + memcpy(l_RefBuffer,l_lpResponseAPDU->Data,l_lpResponseAPDU->Len); + + printf("Performing Verification\n"); + l_lpResponseAPDU = Process(portnum, 0x80, 0x03, 0, 0, 0, NULL, EXECUTE_TIME); + + if(l_lpResponseAPDU->SW != (ushort)0x9000) + { + printf("Verification failed with SW = %04x\n",l_lpResponseAPDU->SW); + return FALSE; + } + + printf("Performing Verification Read\n"); + l_lpResponseAPDU = Process(portnum, 0x80, 0x04, 0, 0, 0, NULL, LOAD_UNLOAD_TIME); + + if(l_lpResponseAPDU->SW != (ushort)0x9000) + { + printf("Read failed with SW = %04x\n",l_lpResponseAPDU->SW); + return FALSE; + } + + printf("Result: "); + + for(l_i = 0; l_i < l_lpResponseAPDU->Len; l_i++) + { + if(!(l_i%16)) + printf("\n"); + + printf("%02X ",l_lpResponseAPDU->Data[l_i]); + } + + printf("\n"); + g_NumCompletions++; + + if(!memcmp(l_RefBuffer,l_lpResponseAPDU->Data,l_lpResponseAPDU->Len)) + { + printf("Buffer matches reference\nCompleted Iterations: %d, Failures: %d, Percent Failures: %2.2f\n", + g_NumCompletions,g_NumFailures,(double)g_NumFailures/g_NumCompletions*100); + } + else + { + printf("Buffer does NOT match reference\nIterations: %d, Failures: %d\n",g_NumCompletions,++g_NumFailures); + } + + return TRUE; +} + diff --git a/pool/shard008/C/0129563_zgerqf.c b/pool/shard008/C/0129563_zgerqf.c new file mode 100644 index 0000000000000000000000000000000000000000..e498c49753633503dd65ab1728e23b5db3381841 --- /dev/null +++ b/pool/shard008/C/0129563_zgerqf.c @@ -0,0 +1,263 @@ +#include "f2c.h" +#include "blaswrap.h" + +/* Table of constant values */ + +static integer c__1 = 1; +static integer c_n1 = -1; +static integer c__3 = 3; +static integer c__2 = 2; + +/* Subroutine */ int zgerqf_(integer *m, integer *n, doublecomplex *a, + integer *lda, doublecomplex *tau, doublecomplex *work, integer *lwork, + integer *info) +{ + /* System generated locals */ + integer a_dim1, a_offset, i__1, i__2, i__3, i__4; + + /* Local variables */ + integer i__, k, ib, nb, ki, kk, mu, nu, nx, iws, nbmin, iinfo; + extern /* Subroutine */ int zgerq2_(integer *, integer *, doublecomplex *, + integer *, doublecomplex *, doublecomplex *, integer *), xerbla_( + char *, integer *); + extern integer ilaenv_(integer *, char *, char *, integer *, integer *, + integer *, integer *); + extern /* Subroutine */ int zlarfb_(char *, char *, char *, char *, + integer *, integer *, integer *, doublecomplex *, integer *, + doublecomplex *, integer *, doublecomplex *, integer *, + doublecomplex *, integer *); + integer ldwork; + extern /* Subroutine */ int zlarft_(char *, char *, integer *, integer *, + doublecomplex *, integer *, doublecomplex *, doublecomplex *, + integer *); + integer lwkopt; + logical lquery; + + +/* -- LAPACK routine (version 3.1) -- */ +/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ +/* November 2006 */ + +/* .. Scalar Arguments .. */ +/* .. */ +/* .. Array Arguments .. */ +/* .. */ + +/* Purpose */ +/* ======= */ + +/* ZGERQF computes an RQ factorization of a complex M-by-N matrix A: */ +/* A = R * Q. */ + +/* Arguments */ +/* ========= */ + +/* M (input) INTEGER */ +/* The number of rows of the matrix A. M >= 0. */ + +/* N (input) INTEGER */ +/* The number of columns of the matrix A. N >= 0. */ + +/* A (input/output) COMPLEX*16 array, dimension (LDA,N) */ +/* On entry, the M-by-N matrix A. */ +/* On exit, */ +/* if m <= n, the upper triangle of the subarray */ +/* A(1:m,n-m+1:n) contains the M-by-M upper triangular matrix R; */ +/* if m >= n, the elements on and above the (m-n)-th subdiagonal */ +/* contain the M-by-N upper trapezoidal matrix R; */ +/* the remaining elements, with the array TAU, represent the */ +/* unitary matrix Q as a product of min(m,n) elementary */ +/* reflectors (see Further Details). */ + +/* LDA (input) INTEGER */ +/* The leading dimension of the array A. LDA >= max(1,M). */ + +/* TAU (output) COMPLEX*16 array, dimension (min(M,N)) */ +/* The scalar factors of the elementary reflectors (see Further */ +/* Details). */ + +/* WORK (workspace/output) COMPLEX*16 array, dimension (MAX(1,LWORK)) */ +/* On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */ + +/* LWORK (input) INTEGER */ +/* The dimension of the array WORK. LWORK >= max(1,M). */ +/* For optimum performance LWORK >= M*NB, where NB is */ +/* the optimal blocksize. */ + +/* If LWORK = -1, then a workspace query is assumed; the routine */ +/* only calculates the optimal size of the WORK array, returns */ +/* this value as the first entry of the WORK array, and no error */ +/* message related to LWORK is issued by XERBLA. */ + +/* INFO (output) INTEGER */ +/* = 0: successful exit */ +/* < 0: if INFO = -i, the i-th argument had an illegal value */ + +/* Further Details */ +/* =============== */ + +/* The matrix Q is represented as a product of elementary reflectors */ + +/* Q = H(1)' H(2)' . . . H(k)', where k = min(m,n). */ + +/* Each H(i) has the form */ + +/* H(i) = I - tau * v * v' */ + +/* where tau is a complex scalar, and v is a complex vector with */ +/* v(n-k+i+1:n) = 0 and v(n-k+i) = 1; conjg(v(1:n-k+i-1)) is stored on */ +/* exit in A(m-k+i,1:n-k+i-1), and tau in TAU(i). */ + +/* ===================================================================== */ + +/* .. Local Scalars .. */ +/* .. */ +/* .. External Subroutines .. */ +/* .. */ +/* .. Intrinsic Functions .. */ +/* .. */ +/* .. External Functions .. */ +/* .. */ +/* .. Executable Statements .. */ + +/* Test the input arguments */ + + /* Parameter adjustments */ + a_dim1 = *lda; + a_offset = 1 + a_dim1; + a -= a_offset; + --tau; + --work; + + /* Function Body */ + *info = 0; + lquery = *lwork == -1; + if (*m < 0) { + *info = -1; + } else if (*n < 0) { + *info = -2; + } else if (*lda < max(1,*m)) { + *info = -4; + } + + if (*info == 0) { + k = min(*m,*n); + if (k == 0) { + lwkopt = 1; + } else { + nb = ilaenv_(&c__1, "ZGERQF", " ", m, n, &c_n1, &c_n1); + lwkopt = *m * nb; + } + work[1].r = (doublereal) lwkopt, work[1].i = 0.; + + if (*lwork < max(1,*m) && ! lquery) { + *info = -7; + } + } + + if (*info != 0) { + i__1 = -(*info); + xerbla_("ZGERQF", &i__1); + return 0; + } else if (lquery) { + return 0; + } + +/* Quick return if possible */ + + if (k == 0) { + return 0; + } + + nbmin = 2; + nx = 1; + iws = *m; + if (nb > 1 && nb < k) { + +/* Determine when to cross over from blocked to unblocked code. */ + +/* Computing MAX */ + i__1 = 0, i__2 = ilaenv_(&c__3, "ZGERQF", " ", m, n, &c_n1, &c_n1); + nx = max(i__1,i__2); + if (nx < k) { + +/* Determine if workspace is large enough for blocked code. */ + + ldwork = *m; + iws = ldwork * nb; + if (*lwork < iws) { + +/* Not enough workspace to use optimal NB: reduce NB and */ +/* determine the minimum value of NB. */ + + nb = *lwork / ldwork; +/* Computing MAX */ + i__1 = 2, i__2 = ilaenv_(&c__2, "ZGERQF", " ", m, n, &c_n1, & + c_n1); + nbmin = max(i__1,i__2); + } + } + } + + if (nb >= nbmin && nb < k && nx < k) { + +/* Use blocked code initially. */ +/* The last kk rows are handled by the block method. */ + + ki = (k - nx - 1) / nb * nb; +/* Computing MIN */ + i__1 = k, i__2 = ki + nb; + kk = min(i__1,i__2); + + i__1 = k - kk + 1; + i__2 = -nb; + for (i__ = k - kk + ki + 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ + += i__2) { +/* Computing MIN */ + i__3 = k - i__ + 1; + ib = min(i__3,nb); + +/* Compute the RQ factorization of the current block */ +/* A(m-k+i:m-k+i+ib-1,1:n-k+i+ib-1) */ + + i__3 = *n - k + i__ + ib - 1; + zgerq2_(&ib, &i__3, &a[*m - k + i__ + a_dim1], lda, &tau[i__], & + work[1], &iinfo); + if (*m - k + i__ > 1) { + +/* Form the triangular factor of the block reflector */ +/* H = H(i+ib-1) . . . H(i+1) H(i) */ + + i__3 = *n - k + i__ + ib - 1; + zlarft_("Backward", "Rowwise", &i__3, &ib, &a[*m - k + i__ + + a_dim1], lda, &tau[i__], &work[1], &ldwork); + +/* Apply H to A(1:m-k+i-1,1:n-k+i+ib-1) from the right */ + + i__3 = *m - k + i__ - 1; + i__4 = *n - k + i__ + ib - 1; + zlarfb_("Right", "No transpose", "Backward", "Rowwise", &i__3, + &i__4, &ib, &a[*m - k + i__ + a_dim1], lda, &work[1], + &ldwork, &a[a_offset], lda, &work[ib + 1], &ldwork); + } +/* L10: */ + } + mu = *m - k + i__ + nb - 1; + nu = *n - k + i__ + nb - 1; + } else { + mu = *m; + nu = *n; + } + +/* Use unblocked code to factor the last or only block */ + + if (mu > 0 && nu > 0) { + zgerq2_(&mu, &nu, &a[a_offset], lda, &tau[1], &work[1], &iinfo); + } + + work[1].r = (doublereal) iws, work[1].i = 0.; + return 0; + +/* End of ZGERQF */ + +} /* zgerqf_ */ diff --git a/pool/shard008/C/0129564_altstack.c b/pool/shard008/C/0129564_altstack.c new file mode 100644 index 0000000000000000000000000000000000000000..4e2f71e60d1926468724219b11861d7b2e00c502 --- /dev/null +++ b/pool/shard008/C/0129564_altstack.c @@ -0,0 +1,132 @@ +/*BEGIN_LEGAL +#BEGIN_LEGAL +##BEGIN_LEGAL +##INTEL CONFIDENTIAL +##Copyright 2002-2005 Intel Corporation All Rights Reserved. +## +##The source code contained or described herein and all documents +##related to the source code (Material) are owned by Intel Corporation +##or its suppliers or licensors. Title to the Material remains with +##Intel Corporation or its suppliers and licensors. The Material may +##contain trade secrets and proprietary and confidential information of +##Intel Corporation and its suppliers and licensors, and is protected by +##worldwide copyright and trade secret laws and treaty provisions. No +##part of the Material may be used, copied, reproduced, modified, +##published, uploaded, posted, transmitted, distributed, or disclosed in +##any way without Intels prior express written permission. No license +##under any patent, copyright, trade secret or other intellectual +##property right is granted to or conferred upon you by disclosure or +##delivery of the Materials, either expressly, by implication, +##inducement, estoppel or otherwise. Any license under such intellectual +##property rights must be express and approved by Intel in writing. +## +##Unless otherwise agreed by Intel in writing, you may not remove or +##alter this notice or any other notice embedded in Materials by Intel +##or Intels suppliers or licensors in any way. +##END_LEGAL +#INTEL CONFIDENTIAL +#Copyright 2002-2005 Intel Corporation All Rights Reserved. +# +#The source code contained or described herein and all documents +#related to the source code (Material) are owned by Intel Corporation +#or its suppliers or licensors. Title to the Material remains with +#Intel Corporation or its suppliers and licensors. The Material may +#contain trade secrets and proprietary and confidential information of +#Intel Corporation and its suppliers and licensors, and is protected by +#worldwide copyright and trade secret laws and treaty provisions. No +#part of the Material may be used, copied, reproduced, modified, +#published, uploaded, posted, transmitted, distributed, or disclosed in +#any way without Intels prior express written permission. No license +#under any patent, copyright, trade secret or other intellectual +#property right is granted to or conferred upon you by disclosure or +#delivery of the Materials, either expressly, by implication, +#inducement, estoppel or otherwise. Any license under such intellectual +#property rights must be express and approved by Intel in writing. +# +#Unless otherwise agreed by Intel in writing, you may not remove or +#alter this notice or any other notice embedded in Materials by Intel +#or Intels suppliers or licensors in any way. +#END_LEGAL +Intel Open Source License + +Copyright (c) 2002-2005 Intel Corporation +All rights reserved. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. Redistributions +in binary form must reproduce the above copyright notice, this list of +conditions and the following disclaimer in the documentation and/or +other materials provided with the distribution. Neither the name of +the Intel Corporation nor the names of its contributors may be used to +endorse or promote products derived from this software without +specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR +ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +END_LEGAL */ +/* + * This test verifies that the application can set up an alternate stack for + * its signal handler. + */ + +#include +#include +#include + +char Stack[SIGSTKSZ]; + +static void Handle(int); + + +int main() +{ + struct sigaction act; + stack_t ss; + + ss.ss_sp = Stack; + ss.ss_size = sizeof(Stack); + ss.ss_flags = 0; + if (sigaltstack(&ss, 0) != 0) + { + fprintf(stderr, "Unable to set alternate stack\n"); + return 1; + } + printf("Alternate stack is %p - %p\n", Stack, &Stack[SIGSTKSZ]); + + act.sa_handler = Handle; + act.sa_flags = SA_ONSTACK; + sigemptyset(&act.sa_mask); + if (sigaction(SIGUSR1, &act, 0) != 0) + { + fprintf(stderr, "Unable to set up USR1 handler\n"); + return 1; + } + + raise(SIGUSR1); + return 0; +} + + +static void Handle(int sig) +{ + char *sp = (char *)&sig; + + printf("Got signal %d with SP=%p\n", sig, sp); + if (sp < Stack || sp > &Stack[SIGSTKSZ]) + { + fprintf(stderr, "Handler not running on alternate stack\n"); + exit(1); + } +} diff --git a/pool/shard008/C/0129565_receive.c b/pool/shard008/C/0129565_receive.c new file mode 100644 index 0000000000000000000000000000000000000000..6a17d59b5f3d1d7e7f3283dae49fb3f9b429a960 --- /dev/null +++ b/pool/shard008/C/0129565_receive.c @@ -0,0 +1,252 @@ +/* + *$Id: receive.c,v 1.50 2004/08/24 08:45:10 janakj Exp $ + * + * Copyright (C) 2001-2003 FhG Fokus + * + * This file is part of ser, a free SIP server. + * + * ser 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 + * + * For a license to use the ser software under conditions + * other than those described here, or to purchase support for this + * software, please contact iptel.org by e-mail at the following addresses: + * info@iptel.org + * + * ser 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * History: + * --------- + * 2003-02-28 scratchpad compatibility abandoned (jiri) + * 2003-01-29 transport-independent message zero-termination in + * receive_msg (jiri) + * 2003-02-07 undoed jiri's zero term. changes (they break tcp) (andrei) + * 2003-02-10 moved zero-term in the calling functions (udp_receive & + * tcp_read_req) + * 2003-08-13 fixed exec_pre_cb returning 0 (backported from stable) (andrei) + * 2004-02-06 added user preferences support - destroy_avps() (bogdan) + * 2004-04-30 exec_pre_cb is called after basic sanity checks (at least one + * via present & parsed ok) (andrei) + * 2004-08-23 avp core changed - destroy_avp-> reset_avps (bogdan) + */ + + +#include +#include +#include + +#include "receive.h" +#include "globals.h" +#include "dprint.h" +#include "route.h" +#include "parser/msg_parser.h" +#include "forward.h" +#include "action.h" +#include "mem/mem.h" +#include "stats.h" +#include "ip_addr.h" +#include "script_cb.h" +#include "dset.h" +#include "usr_avp.h" + + +#include "tcp_server.h" /* for tcpconn_add_alias */ + + +#ifdef DEBUG_DMALLOC +#include +#endif + +unsigned int msg_no=0; +/* address preset vars */ +str default_global_address={0,0}; +str default_global_port={0,0}; +str default_via_address={0,0}; +str default_via_port={0,0}; + + + +/* WARNING: buf must be 0 terminated (buf[len]=0) or some things might + * break (e.g.: modules/textops) + */ +int receive_msg(char* buf, unsigned int len, struct receive_info* rcv_info) +{ + struct sip_msg* msg; + int ret; +#ifdef STATS + int skipped = 1; + struct timeval tvb, tve; + struct timezone tz; + unsigned int diff; +#endif + + msg=pkg_malloc(sizeof(struct sip_msg)); + if (msg==0) { + LOG(L_ERR, "ERROR: receive_msg: no mem for sip_msg\n"); + goto error00; + } + msg_no++; + /* number of vias parsed -- good for diagnostic info in replies */ + via_cnt=0; + + memset(msg,0, sizeof(struct sip_msg)); /* init everything to 0 */ + /* fill in msg */ + msg->buf=buf; + msg->len=len; + /* zero termination (termination of orig message bellow not that + useful as most of the work is done with scratch-pad; -jiri */ + /* buf[len]=0; */ /* WARNING: zero term removed! */ + msg->rcv=*rcv_info; + msg->id=msg_no; + msg->set_global_address=default_global_address; + msg->set_global_port=default_global_port; + + if (parse_msg(buf,len, msg)!=0){ + LOG(L_ERR, "ERROR: receive_msg: parse_msg failed\n"); + goto error02; + } + DBG("After parse_msg...\n"); + + + /* ... clear branches from previous message */ + clear_branches(); + + if (msg->first_line.type==SIP_REQUEST){ + /* sanity checks */ + if ((msg->via1==0) || (msg->via1->error!=PARSE_OK)){ + /* no via, send back error ? */ + LOG(L_ERR, "ERROR: receive_msg: no via found in request\n"); + goto error; + } + /* check if necessary to add receive?->moved to forward_req */ + /* check for the alias stuff */ +#ifdef USE_TCP + if (msg->via1->alias && tcp_accept_aliases && + (((rcv_info->proto==PROTO_TCP) && !tcp_disable) +#ifdef USE_TLS + || ((rcv_info->proto==PROTO_TLS) && !tls_disable) +#endif + ) + ){ + if (tcpconn_add_alias(rcv_info->proto_reserved1, msg->via1->port, + rcv_info->proto)!=0){ + LOG(L_ERR, " ERROR: receive_msg: tcp alias failed\n"); + /* continue */ + } + } +#endif + + DBG("preparing to run routing scripts...\n"); +#ifdef STATS + gettimeofday( & tvb, &tz ); +#endif + /* execute pre-script callbacks, if any; -jiri */ + /* if some of the callbacks said not to continue with + script processing, don't do so + if we are here basic sanity checks are already done + (like presence of at least one via), so you can count + on via1 being parsed in a pre-script callback --andrei + */ + ret=exec_pre_cb(msg); + if (ret<=0){ + if (ret<0) goto error; + else goto end; /* drop the message -- no error -- andrei */ + } + /* exec the routing script */ + if (run_actions(rlist[0], msg)<0) { + LOG(L_WARN, "WARNING: receive_msg: " + "error while trying script\n"); + goto error; + } + +#ifdef STATS + gettimeofday( & tve, &tz ); + diff = (tve.tv_sec-tvb.tv_sec)*1000000+(tve.tv_usec-tvb.tv_usec); + stats->processed_requests++; + stats->acc_req_time += diff; + DBG("successfully ran routing scripts...(%d usec)\n", diff); + STATS_RX_REQUEST( msg->first_line.u.request.method_value ); +#endif + }else if (msg->first_line.type==SIP_REPLY){ + /* sanity checks */ + if ((msg->via1==0) || (msg->via1->error!=PARSE_OK)){ + /* no via, send back error ? */ + LOG(L_ERR, "ERROR: receive_msg: no via found in reply\n"); + goto error; + } +#if 0 + if ((msg->via2==0) || (msg->via2->error!=PARSE_OK)){ + /* no second via => error? */ + LOG(L_ERR, "ERROR: receive_msg: no 2nd via found in reply\n"); + goto error; + } + /* check if via1 == us */ +#endif + +#ifdef STATS + gettimeofday( & tvb, &tz ); + STATS_RX_RESPONSE ( msg->first_line.u.reply.statuscode / 100 ); +#endif + + /* execute pre-script callbacks, if any; -jiri */ + /* if some of the callbacks said not to continue with + script processing, don't do so + if we are here basic sanity checks are already done + (like presence of at least one via), so you can count + on via1 being parsed in a pre-script callback --andrei + */ + ret=exec_pre_cb(msg); + if (ret<=0){ + if (ret<0) goto error; + else goto end; /* drop the message -- no error -- andrei */ + } + + /* send the msg */ + forward_reply(msg); + +#ifdef STATS + gettimeofday( & tve, &tz ); + diff = (tve.tv_sec-tvb.tv_sec)*1000000+(tve.tv_usec-tvb.tv_usec); + stats->processed_responses++; + stats->acc_res_time+=diff; + DBG("successfully ran reply processing...(%d usec)\n", diff); +#endif + } +end: +#ifdef STATS + skipped = 0; +#endif + /* execute post-script callbacks, if any; -jiri */ + exec_post_cb(msg); + /* free possible loaded avps -bogdan */ + reset_avps(); + DBG("receive_msg: cleaning up\n"); + free_sip_msg(msg); + pkg_free(msg); +#ifdef STATS + if (skipped) STATS_RX_DROPS; +#endif + return 0; +error: + DBG("error:...\n"); + /* execute post-script callbacks, if any; -jiri */ + exec_post_cb(msg); + /* free possible loaded avps -bogdan */ + reset_avps(); +error02: + free_sip_msg(msg); + pkg_free(msg); +error00: + STATS_RX_DROPS; + return -1; +} + diff --git a/pool/shard008/C/0129567_character_tokenizer.c b/pool/shard008/C/0129567_character_tokenizer.c new file mode 100644 index 0000000000000000000000000000000000000000..1ceb391095c007c459394c7d1bd893eac07bbdda --- /dev/null +++ b/pool/shard008/C/0129567_character_tokenizer.c @@ -0,0 +1,171 @@ +// +// character_tokenizer.c +// +// Created by Hai Feng Kao on 4/6/13. +// All rights reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +// Implementation of the "simple" full-text-search tokenizer. + +#include "sqlite3.h" +#include //for tolower +#include //for memset +#import "character_tokenizer.h" + +typedef struct character_tokenizer { + sqlite3_tokenizer base; +} character_tokenizer; + +typedef struct character_tokenizer_cursor { + sqlite3_tokenizer_cursor base; + const char *pInput; // input we are tokenizing + int nBytes; // size of the input + int iPosition; // current position in pInput + int iToken; // index of next token to be returned + char *pToken; // storage for current token +} character_tokenizer_cursor; + +static int characterCreate( + int argc, const char * const *argv, + sqlite3_tokenizer **ppTokenizer + ){ + character_tokenizer *t; + t = (character_tokenizer *) sqlite3_malloc(sizeof(*t)); + if( t == NULL + ) return SQLITE_NOMEM; + memset(t, 0, sizeof(*t)); + + *ppTokenizer = &t->base; + return SQLITE_OK; +} + +static int characterDestroy(sqlite3_tokenizer *pTokenizer){ + sqlite3_free(pTokenizer); + return SQLITE_OK; +} + +static int characterOpen( + sqlite3_tokenizer *pTokenizer, /* The tokenizer */ + const char *pInput, int nBytes, /* String to be tokenized */ + sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */ + ){ + character_tokenizer_cursor *c; + if(pInput == 0){ + nBytes = 0; + }else if(nBytes < 0){ + nBytes = (int)strlen(pInput); + } + c = (character_tokenizer_cursor *) sqlite3_malloc(sizeof(*c)); + if(c == NULL){ + return SQLITE_NOMEM; + } + c->iToken = c->iPosition = 0; + c->pToken = NULL; + c->nBytes = nBytes; + c->pInput = pInput; + *ppCursor = &c->base; + return SQLITE_OK; +} + +static int characterClose(sqlite3_tokenizer_cursor *pCursor){ + character_tokenizer_cursor *c = (character_tokenizer_cursor *) pCursor; + + if(c->pToken != NULL){ + sqlite3_free(c->pToken); + c->pToken = NULL; + } + + sqlite3_free(c); + return SQLITE_OK; +} + +static int characterNext( + sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by cusOpen */ + const char **ppToken, /* OUT: *ppToken is the token text */ + int *pnBytes, /* OUT: Number of bytes in token */ + int *piStartOffset, /* OUT: Starting offset of token */ + int *piEndOffset, /* OUT: Ending offset of token */ + int *piPosition /* OUT: Position integer of token */ + ){ + character_tokenizer_cursor *c = (character_tokenizer_cursor *) pCursor; + if(c->pToken != NULL){ + sqlite3_free(c->pToken); + c->pToken = NULL; + } + + if (c->iPosition >= c->nBytes) { + return SQLITE_DONE; + } + + int length = 1; // the size of current character, which can be at most 4 bytes + + const char* token = &(c->pInput[c->iPosition]); + *piStartOffset = c->iPosition; + + // find the beginning of next utf8 character + c->iPosition++; + while (c->iPosition < c->nBytes) { + char byte = c->pInput[c->iPosition]; + if (((byte & 0x80) == 0) || ((byte & 0xc0) == 0xc0)) { + // we have reached the first byte of next utf8 character + break; + } + length++; + c->iPosition++; + } + + c->pToken = (char *)sqlite3_malloc(length+1); + if(c->pToken == NULL){ + return SQLITE_NOMEM; + } + + c->pToken[length] = 0; + memcpy(c->pToken, token, length); + int i; + for (i = 0; i < length; ++i) { + unsigned char byte = c->pToken[i]; + + if (byte < 0x80) { + // ascii character, make it case-insensitive + c->pToken[i] = tolower(byte); + } + } + + *ppToken = c->pToken; + *pnBytes = length; + + *piEndOffset = *piStartOffset+length; + *piPosition = c->iToken++; + return SQLITE_OK; +} + +static const sqlite3_tokenizer_module characterTokenizerModule = { + 0, + characterCreate, + characterDestroy, + characterOpen, + characterClose, + characterNext, +}; + +void get_character_tokenizer_module(const sqlite3_tokenizer_module **ppModule){ + *ppModule = &characterTokenizerModule; +} + diff --git a/pool/shard008/C/0129570_getfocus.c b/pool/shard008/C/0129570_getfocus.c new file mode 100644 index 0000000000000000000000000000000000000000..245b5f1b43f03d199ef29f816683a35e79f12290 --- /dev/null +++ b/pool/shard008/C/0129570_getfocus.c @@ -0,0 +1,148 @@ +/************************************************************ + +Copyright 1989, 1998 The Open Group + +Permission to use, copy, modify, distribute, and sell this software and its +documentation for any purpose is hereby granted without fee, provided that +the above copyright notice appear in all copies and that both that +copyright notice and this permission notice appear in supporting +documentation. + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN +AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Except as contained in this notice, the name of The Open Group shall not be +used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization from The Open Group. + +Copyright 1989 by Hewlett-Packard Company, Palo Alto, California. + + All Rights Reserved + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Hewlett-Packard not be +used in advertising or publicity pertaining to distribution of the +software without specific, written prior permission. + +HEWLETT-PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING +ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL +HEWLETT-PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR +ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS +SOFTWARE. + +********************************************************/ + +/*********************************************************************** + * + * Extension function to get the focus for an extension device. + * + */ + +#define NEED_EVENTS +#define NEED_REPLIES +#ifdef HAVE_DIX_CONFIG_H +#include +#endif + +#include /* for inputstr.h */ +#include /* Request macro */ +#include "windowstr.h" /* focus struct */ +#include "inputstr.h" /* DeviceIntPtr */ +#include +#include +#include "extnsionst.h" +#include "extinit.h" /* LookupDeviceIntRec */ +#include "exglobals.h" + +#include "getfocus.h" + +/*********************************************************************** + * + * This procedure gets the focus for a device. + * + */ + +int +SProcXGetDeviceFocus(ClientPtr client) +{ + char n; + + REQUEST(xGetDeviceFocusReq); + swaps(&stuff->length, n); + return (ProcXGetDeviceFocus(client)); +} + +/*********************************************************************** + * + * This procedure gets the focus for a device. + * + */ + +int +ProcXGetDeviceFocus(ClientPtr client) +{ + DeviceIntPtr dev; + FocusClassPtr focus; + xGetDeviceFocusReply rep; + + REQUEST(xGetDeviceFocusReq); + REQUEST_SIZE_MATCH(xGetDeviceFocusReq); + + dev = LookupDeviceIntRec(stuff->deviceid); + if (dev == NULL || !dev->focus) { + SendErrorToClient(client, IReqCode, X_GetDeviceFocus, 0, BadDevice); + return Success; + } + + rep.repType = X_Reply; + rep.RepType = X_GetDeviceFocus; + rep.length = 0; + rep.sequenceNumber = client->sequence; + + focus = dev->focus; + + if (focus->win == NoneWin) + rep.focus = None; + else if (focus->win == PointerRootWin) + rep.focus = PointerRoot; + else if (focus->win == FollowKeyboardWin) + rep.focus = FollowKeyboard; + else + rep.focus = focus->win->drawable.id; + + rep.time = focus->time.milliseconds; + rep.revertTo = focus->revert; + WriteReplyToClient(client, sizeof(xGetDeviceFocusReply), &rep); + return Success; +} + +/*********************************************************************** + * + * This procedure writes the reply for the GetDeviceFocus function, + * if the client and server have a different byte ordering. + * + */ + +void +SRepXGetDeviceFocus(ClientPtr client, int size, xGetDeviceFocusReply * rep) +{ + char n; + + swaps(&rep->sequenceNumber, n); + swapl(&rep->length, n); + swapl(&rep->focus, n); + swapl(&rep->time, n); + WriteToClient(client, size, (char *)rep); +} diff --git a/pool/shard008/C/0129576_sign.c b/pool/shard008/C/0129576_sign.c new file mode 100644 index 0000000000000000000000000000000000000000..dd20cff3dff3f6d3403bae2d726a6f22b16bb910 --- /dev/null +++ b/pool/shard008/C/0129576_sign.c @@ -0,0 +1,63 @@ +#include "crypto_sign.h" + +#include +#include + +#include "gui_config.h" +#include "gui.h" + +#include "gui_sig.h" +#include "hash_utils.h" + +int +crypto_sign_keypair(unsigned char *pk, unsigned char *sk) +{ + gui_genkey( pk, (gui_key *) sk); + + pk[_SALT_PUB_KEY_LEN-1] = _SALT_BYTE; + sk[_SALT_SEC_KEY_LEN-1] = _SALT_BYTE; + + return 0; +} + + +int +crypto_sign(unsigned char *sm, unsigned long long *smlen, const unsigned char *m, unsigned long long mlen, const unsigned char *sk) +{ + unsigned char digest[_HASH_LEN]; + + sha2_chain_msg( digest , _HASH_LEN , m , mlen ); + + memmove( sm , m , mlen ); + smlen[0] = mlen + _SALT_SIGNATURE_BYTE; + + unsigned r = gui_sign_salt( sm + mlen , sk , digest ); + + if( r ) return 0; + return -1; +} + + + + + + +int +crypto_sign_open(unsigned char *m, unsigned long long *mlen,const unsigned char *sm, unsigned long long smlen,const unsigned char *pk) +{ + unsigned char pkcopy[crypto_sign_PUBLICKEYBYTES]; + memcpy(pkcopy,pk,crypto_sign_PUBLICKEYBYTES); + + if( _SALT_SIGNATURE_BYTE > smlen ) return -1; + memmove( m , sm , smlen-_SALT_SIGNATURE_BYTE ); + mlen[0] = smlen-_SALT_SIGNATURE_BYTE; + + unsigned char digest[_HASH_LEN]; + sha2_chain_msg( digest , _HASH_LEN , m , *mlen ); + + unsigned r = gui_verify_salt( pkcopy , sm + mlen[0] , digest ); + + if( r ) return 0; + return -1; +} + diff --git a/pool/shard008/C/0129582_main.c b/pool/shard008/C/0129582_main.c new file mode 100644 index 0000000000000000000000000000000000000000..a88624298b810c18322fbce1bf1fcd01cfbbc09f --- /dev/null +++ b/pool/shard008/C/0129582_main.c @@ -0,0 +1,40 @@ + +#include "queue.h" +#include + +#define DATA_TYPE char + +int main (int argc, char *argv[]){ + + unsigned i; + queue_t s; + DATA_TYPE *a = "Hi_my_friend" ; + DATA_TYPE *c = "Other" ; + DATA_TYPE b; + + queue_init(&s, sizeof(DATA_TYPE)); + + //Force resize + for (i = 0; i < 7; ++i){ + queue_push_back(&s, &(a[i])); + } + + queue_pop_front(&s, NULL); + queue_pop_front(&s, NULL); + + + //Force resize + for (i = 0; i < 3; ++i){ //"i myMi" H=0, T=5 + queue_push_back(&s, &(c[i])); + } + + while (!queue_empty(&s)){ + queue_pop_front(&s, &b); + printf("%c, %u\n", b, queue_size(&s)); + } + + + queue_destroy(&s); + + return 0; +} diff --git a/pool/shard008/C/0129584_ex5.c b/pool/shard008/C/0129584_ex5.c new file mode 100644 index 0000000000000000000000000000000000000000..5852ea63a72672870499b067f20eca42b7806563 --- /dev/null +++ b/pool/shard008/C/0129584_ex5.c @@ -0,0 +1,35 @@ +/*5. (a) Escreva uma função que recebe um inteiro positivo m e devolve 1 se m é primo, 0 em caso contrário. +(b) Escreva um programa que leia um inteiro não-negativo n e imprima a soma dos n primeiros números primos. */ +#include +int primo(int n) +{ + int i, cont=0; + for(i=1;i<=n;i++) + { + if(n%i==0) + cont++; + } + if(cont==2) + return 1; + else + return 0; +} +int main() +{ + int i, j, n, soma=0; + do + { + printf("entre com n: "); + scanf("%d", &n); + }while(n<0) + for(i=0;i<=n;i++) + { + j = primo(i); + if(j==1) + { + printf(" %d ", i); + soma += i; + } + } + printf("\nsoma dos primeiros primos: %d\n", soma); +} \ No newline at end of file diff --git a/pool/shard008/C/0129586_pr64818.c b/pool/shard008/C/0129586_pr64818.c new file mode 100644 index 0000000000000000000000000000000000000000..bddd8462c698adb15c50913b6ceffadc6f64a876 --- /dev/null +++ b/pool/shard008/C/0129586_pr64818.c @@ -0,0 +1,30 @@ +/* { dg-do compile } */ +/* { dg-options "-O1" } */ + +char temp[16]; +extern int foo1 (void); + +void foo (void) +{ + int i; + int len; + + while (1) + { + len = foo1 (); + register int a asm ("r0") = 5; + register char *b asm ("r1") = temp; + register int c asm ("r2") = len; + asm volatile ("mov %[r0], %[r0]\n mov %[r1], %[r1]\n mov %[r2], %[r2]\n" + : "+m"(*b) + : [r0]"r"(a), [r1]"r"(b), [r2]"r"(c)); + + for (i = 0; i < len; i++) + { + if (temp[i] == 10) + return; + } + } +} + +/* { dg-final { scan-assembler "\[\\t \]+mov\ r1,\ r1" } } */ diff --git a/pool/shard008/C/0129589_ua_session_manager.c b/pool/shard008/C/0129589_ua_session_manager.c new file mode 100644 index 0000000000000000000000000000000000000000..dd21da489e8275b3f7d30caf7f7a9c3097d93ed4 --- /dev/null +++ b/pool/shard008/C/0129589_ua_session_manager.c @@ -0,0 +1,188 @@ +/* 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/. + * + * Copyright 2014-2017 (c) Fraunhofer IOSB (Author: Julius Pfrommer) + * Copyright 2014, 2017 (c) Florian Palm + * Copyright 2015 (c) Sten Grüner + * Copyright 2015 (c) Oleksiy Vasylyev + * Copyright 2017 (c) Stefan Profanter, fortiss GmbH + */ + +#include "ua_session_manager.h" +#include "ua_server_internal.h" +#include "ua_subscription.h" + +UA_StatusCode +UA_SessionManager_init(UA_SessionManager *sm, UA_Server *server) { + LIST_INIT(&sm->sessions); + sm->currentSessionCount = 0; + sm->server = server; + return UA_STATUSCODE_GOOD; +} + +/* Delayed callback to free the session memory */ +static void +removeSessionCallback(UA_Server *server, session_list_entry *entry) { + UA_Session_deleteMembersCleanup(&entry->session, server); +} + +static void +removeSession(UA_SessionManager *sm, session_list_entry *sentry) { + /* Remove the Subscriptions */ +#ifdef UA_ENABLE_SUBSCRIPTIONS + UA_Subscription *sub, *tempsub; + LIST_FOREACH_SAFE(sub, &sentry->session.serverSubscriptions, listEntry, tempsub) { + UA_Session_deleteSubscription(sm->server, &sentry->session, sub->subscriptionId); + } + + UA_PublishResponseEntry *entry; + while((entry = UA_Session_dequeuePublishReq(&sentry->session))) { + UA_PublishResponse_deleteMembers(&entry->response); + UA_free(entry); + } +#endif + + /* Detach the Session from the SecureChannel */ + UA_Session_detachFromSecureChannel(&sentry->session); + + /* Deactivate the session */ + sentry->session.activated = false; + + /* Detach the session from the session manager and make the capacity + * available */ + LIST_REMOVE(sentry, pointers); + UA_atomic_subUInt32(&sm->currentSessionCount, 1); + + /* Add a delayed callback to remove the session when the currently + * scheduled jobs have completed */ + sentry->cleanupCallback.callback = (UA_ApplicationCallback)removeSessionCallback; + sentry->cleanupCallback.application = sm->server; + sentry->cleanupCallback.data = sentry; + UA_WorkQueue_enqueueDelayed(&sm->server->workQueue, &sentry->cleanupCallback); +} + +void UA_SessionManager_deleteMembers(UA_SessionManager *sm) { + session_list_entry *current, *temp; + LIST_FOREACH_SAFE(current, &sm->sessions, pointers, temp) { + removeSession(sm, current); + } +} + +void +UA_SessionManager_cleanupTimedOut(UA_SessionManager *sm, + UA_DateTime nowMonotonic) { + session_list_entry *sentry, *temp; + LIST_FOREACH_SAFE(sentry, &sm->sessions, pointers, temp) { + /* Session has timed out? */ + if(sentry->session.validTill >= nowMonotonic) + continue; + UA_LOG_INFO_SESSION(&sm->server->config.logger, &sentry->session, + "Session has timed out"); + sm->server->config.accessControl.closeSession(sm->server, + &sm->server->config.accessControl, + &sentry->session.sessionId, + sentry->session.sessionHandle); + removeSession(sm, sentry); + } +} + +UA_Session * +UA_SessionManager_getSessionByToken(UA_SessionManager *sm, const UA_NodeId *token) { + session_list_entry *current = NULL; + LIST_FOREACH(current, &sm->sessions, pointers) { + /* Token does not match */ + if(!UA_NodeId_equal(¤t->session.header.authenticationToken, token)) + continue; + + /* Session has timed out */ + if(UA_DateTime_nowMonotonic() > current->session.validTill) { + UA_LOG_INFO_SESSION(&sm->server->config.logger, ¤t->session, + "Client tries to use a session that has timed out"); + return NULL; + } + + /* Ok, return */ + return ¤t->session; + } + + /* Session not found */ + UA_String nodeIdStr = UA_STRING_NULL; + UA_NodeId_toString(token, &nodeIdStr); + UA_LOG_INFO(&sm->server->config.logger, UA_LOGCATEGORY_SESSION, + "Try to use Session with token %.*s but is not found", + (int)nodeIdStr.length, nodeIdStr.data); + UA_String_deleteMembers(&nodeIdStr); + return NULL; +} + +UA_Session * +UA_SessionManager_getSessionById(UA_SessionManager *sm, const UA_NodeId *sessionId) { + session_list_entry *current = NULL; + LIST_FOREACH(current, &sm->sessions, pointers) { + /* Token does not match */ + if(!UA_NodeId_equal(¤t->session.sessionId, sessionId)) + continue; + + /* Session has timed out */ + if(UA_DateTime_nowMonotonic() > current->session.validTill) { + UA_LOG_INFO_SESSION(&sm->server->config.logger, ¤t->session, + "Client tries to use a session that has timed out"); + return NULL; + } + + /* Ok, return */ + return ¤t->session; + } + + /* Session not found */ + UA_String sessionIdStr = UA_STRING_NULL; + UA_NodeId_toString(sessionId, &sessionIdStr); + UA_LOG_INFO(&sm->server->config.logger, UA_LOGCATEGORY_SESSION, + "Try to use Session with identifier %.*s but is not found", + (int)sessionIdStr.length, sessionIdStr.data); + UA_String_deleteMembers(&sessionIdStr); + return NULL; +} + +/* Creates and adds a session. But it is not yet attached to a secure channel. */ +UA_StatusCode +UA_SessionManager_createSession(UA_SessionManager *sm, UA_SecureChannel *channel, + const UA_CreateSessionRequest *request, UA_Session **session) { + if(sm->currentSessionCount >= sm->server->config.maxSessions) + return UA_STATUSCODE_BADTOOMANYSESSIONS; + + session_list_entry *newentry = (session_list_entry *)UA_malloc(sizeof(session_list_entry)); + if(!newentry) + return UA_STATUSCODE_BADOUTOFMEMORY; + + UA_atomic_addUInt32(&sm->currentSessionCount, 1); + UA_Session_init(&newentry->session); + newentry->session.sessionId = UA_NODEID_GUID(1, UA_Guid_random()); + newentry->session.header.authenticationToken = UA_NODEID_GUID(1, UA_Guid_random()); + + if(request->requestedSessionTimeout <= sm->server->config.maxSessionTimeout && + request->requestedSessionTimeout > 0) + newentry->session.timeout = request->requestedSessionTimeout; + else + newentry->session.timeout = sm->server->config.maxSessionTimeout; + + UA_Session_updateLifetime(&newentry->session); + LIST_INSERT_HEAD(&sm->sessions, newentry, pointers); + *session = &newentry->session; + return UA_STATUSCODE_GOOD; +} + +UA_StatusCode +UA_SessionManager_removeSession(UA_SessionManager *sm, const UA_NodeId *token) { + session_list_entry *current; + LIST_FOREACH(current, &sm->sessions, pointers) { + if(UA_NodeId_equal(¤t->session.header.authenticationToken, token)) + break; + } + if(!current) + return UA_STATUSCODE_BADSESSIONIDINVALID; + + removeSession(sm, current); + return UA_STATUSCODE_GOOD; +} diff --git a/pool/shard008/C/0129596_t-compose_horner.c b/pool/shard008/C/0129596_t-compose_horner.c new file mode 100644 index 0000000000000000000000000000000000000000..aae50b7015b2926843cc5f472f705756a4970fe6 --- /dev/null +++ b/pool/shard008/C/0129596_t-compose_horner.c @@ -0,0 +1,100 @@ +/* + Copyright (C) 2012 Fredrik Johansson + + This file is part of Arb. + + Arb is free software: you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License (LGPL) as published + by the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. See . +*/ + +#include "acb_poly.h" + + +int main() +{ + slong iter; + flint_rand_t state; + + flint_printf("compose_horner...."); + fflush(stdout); + + flint_randinit(state); + + for (iter = 0; iter < 3000 * arb_test_multiplier(); iter++) + { + slong qbits1, qbits2, rbits1, rbits2, rbits3; + fmpq_poly_t A, B, C; + acb_poly_t a, b, c, d; + + qbits1 = 2 + n_randint(state, 200); + qbits2 = 2 + n_randint(state, 200); + rbits1 = 2 + n_randint(state, 200); + rbits2 = 2 + n_randint(state, 200); + rbits3 = 2 + n_randint(state, 200); + + fmpq_poly_init(A); + fmpq_poly_init(B); + fmpq_poly_init(C); + + acb_poly_init(a); + acb_poly_init(b); + acb_poly_init(c); + acb_poly_init(d); + + fmpq_poly_randtest(A, state, 1 + n_randint(state, 20), qbits1); + fmpq_poly_randtest(B, state, 1 + n_randint(state, 10), qbits2); + fmpq_poly_compose(C, A, B); + + acb_poly_set_fmpq_poly(a, A, rbits1); + acb_poly_set_fmpq_poly(b, B, rbits2); + acb_poly_compose_horner(c, a, b, rbits3); + + if (!acb_poly_contains_fmpq_poly(c, C)) + { + flint_printf("FAIL\n\n"); + flint_printf("bits3 = %wd\n", rbits3); + + flint_printf("A = "); fmpq_poly_print(A); flint_printf("\n\n"); + flint_printf("B = "); fmpq_poly_print(B); flint_printf("\n\n"); + flint_printf("C = "); fmpq_poly_print(C); flint_printf("\n\n"); + + flint_printf("a = "); acb_poly_printd(a, 15); flint_printf("\n\n"); + flint_printf("b = "); acb_poly_printd(b, 15); flint_printf("\n\n"); + flint_printf("c = "); acb_poly_printd(c, 15); flint_printf("\n\n"); + + flint_abort(); + } + + acb_poly_set(d, a); + acb_poly_compose_horner(d, d, b, rbits3); + if (!acb_poly_equal(d, c)) + { + flint_printf("FAIL (aliasing 1)\n\n"); + flint_abort(); + } + + acb_poly_set(d, b); + acb_poly_compose_horner(d, a, d, rbits3); + if (!acb_poly_equal(d, c)) + { + flint_printf("FAIL (aliasing 2)\n\n"); + flint_abort(); + } + + fmpq_poly_clear(A); + fmpq_poly_clear(B); + fmpq_poly_clear(C); + + acb_poly_clear(a); + acb_poly_clear(b); + acb_poly_clear(c); + acb_poly_clear(d); + } + + flint_randclear(state); + flint_cleanup(); + flint_printf("PASS\n"); + return EXIT_SUCCESS; +} diff --git a/pool/shard008/C/0129599_uncompr.c b/pool/shard008/C/0129599_uncompr.c new file mode 100644 index 0000000000000000000000000000000000000000..f0ac30513c61c9859cc73c06dd8c0ea8efc8e448 --- /dev/null +++ b/pool/shard008/C/0129599_uncompr.c @@ -0,0 +1,61 @@ +/* uncompr.c -- decompress a memory buffer + * Copyright (C) 1995-2003 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id: uncompr.c,v 1.1.1.1 2005-10-29 18:01:49 dpt Exp $ */ + +#define ZLIB_INTERNAL +#include "zlib.h" + +/* =========================================================================== + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total + size of the destination buffer, which must be large enough to hold the + entire uncompressed data. (The size of the uncompressed data must have + been saved previously by the compressor and transmitted to the decompressor + by some mechanism outside the scope of this compression library.) + Upon exit, destLen is the actual size of the compressed buffer. + This function can be used to decompress a whole file at once if the + input file is mmap'ed. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted. +*/ +int ZEXPORT uncompress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + z_stream stream; + int err; + + stream.next_in = (Bytef*)source; + stream.avail_in = (uInt)sourceLen; + /* Check for source > 64K on 16-bit machine: */ + if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; + + stream.next_out = dest; + stream.avail_out = (uInt)*destLen; + if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + + err = inflateInit(&stream); + if (err != Z_OK) return err; + + err = inflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + inflateEnd(&stream); + if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) + return Z_DATA_ERROR; + return err; + } + *destLen = stream.total_out; + + err = inflateEnd(&stream); + return err; +} diff --git a/pool/shard008/C/0129600_imx-mc13783.c b/pool/shard008/C/0129600_imx-mc13783.c new file mode 100644 index 0000000000000000000000000000000000000000..4ae30f21fdb5385c003553e31c60bcaaa60d23cb --- /dev/null +++ b/pool/shard008/C/0129600_imx-mc13783.c @@ -0,0 +1,173 @@ +/* + * imx-mc13783.c -- SoC audio for imx based boards with mc13783 codec + * + * Copyright 2012 Philippe Retornaz, + * + * Heavly based on phycore-mc13783: + * Copyright 2009 Sascha Hauer, Pengutronix + * + * 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. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../codecs/mc13783.h" +#include "imx-ssi.h" +#include "imx-audmux.h" + +#define FMT_SSI (SND_SOC_DAIFMT_DSP_A | SND_SOC_DAIFMT_NB_NF | \ + SND_SOC_DAIFMT_CBM_CFM) + +static int imx_mc13783_hifi_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct snd_soc_dai *cpu_dai = rtd->cpu_dai; + struct snd_soc_dai *codec_dai = rtd->codec_dai; + int ret; + + ret = snd_soc_dai_set_tdm_slot(codec_dai, 0xfffffffc, 0xfffffffc, + 4, 16); + if (ret) + return ret; + + ret = snd_soc_dai_set_sysclk(codec_dai, MC13783_CLK_CLIA, 26000000, 0); + if (ret) + return ret; + + ret = snd_soc_dai_set_tdm_slot(cpu_dai, 0x0, 0xfffffffc, 2, 16); + if (ret) + return ret; + + return 0; +} + +static struct snd_soc_ops imx_mc13783_hifi_ops = { + .hw_params = imx_mc13783_hifi_hw_params, +}; + +static struct snd_soc_dai_link imx_mc13783_dai_mc13783[] = { + { + .name = "MC13783", + .stream_name = "Sound", + .codec_dai_name = "mc13783-hifi", + .codec_name = "mc13783-codec", + .cpu_dai_name = "imx-ssi.0", + .platform_name = "imx-pcm-audio.0", + .ops = &imx_mc13783_hifi_ops, + .symmetric_rates = 1, + .dai_fmt = FMT_SSI, + }, +}; + +static const struct snd_soc_dapm_widget imx_mc13783_widget[] = { + SND_SOC_DAPM_MIC("Mic", NULL), + SND_SOC_DAPM_HP("Headphone", NULL), + SND_SOC_DAPM_SPK("Speaker", NULL), +}; + +static const struct snd_soc_dapm_route imx_mc13783_routes[] = { + {"Speaker", NULL, "LSP"}, + {"Headphone", NULL, "HSL"}, + {"Headphone", NULL, "HSR"}, + + {"MC1LIN", NULL, "MC1 Bias"}, + {"MC2IN", NULL, "MC2 Bias"}, + {"MC1 Bias", NULL, "Mic"}, + {"MC2 Bias", NULL, "Mic"}, +}; + +static struct snd_soc_card imx_mc13783 = { + .name = "imx_mc13783", + .dai_link = imx_mc13783_dai_mc13783, + .num_links = ARRAY_SIZE(imx_mc13783_dai_mc13783), + .dapm_widgets = imx_mc13783_widget, + .num_dapm_widgets = ARRAY_SIZE(imx_mc13783_widget), + .dapm_routes = imx_mc13783_routes, + .num_dapm_routes = ARRAY_SIZE(imx_mc13783_routes), +}; + +static int imx_mc13783_probe(struct platform_device *pdev) +{ + int ret; + + imx_mc13783.dev = &pdev->dev; + + ret = snd_soc_register_card(&imx_mc13783); + if (ret) { + dev_err(&pdev->dev, "snd_soc_register_card failed (%d)\n", + ret); + return ret; + } + + if (machine_is_mx31_3ds()) { + imx_audmux_v2_configure_port(MX31_AUDMUX_PORT4_SSI_PINS_4, + IMX_AUDMUX_V2_PTCR_SYN, + IMX_AUDMUX_V2_PDCR_RXDSEL(MX31_AUDMUX_PORT1_SSI0) | + IMX_AUDMUX_V2_PDCR_MODE(1) | + IMX_AUDMUX_V2_PDCR_INMMASK(0xfc)); + imx_audmux_v2_configure_port(MX31_AUDMUX_PORT1_SSI0, + IMX_AUDMUX_V2_PTCR_SYN | + IMX_AUDMUX_V2_PTCR_TFSDIR | + IMX_AUDMUX_V2_PTCR_TFSEL(MX31_AUDMUX_PORT4_SSI_PINS_4) | + IMX_AUDMUX_V2_PTCR_TCLKDIR | + IMX_AUDMUX_V2_PTCR_TCSEL(MX31_AUDMUX_PORT4_SSI_PINS_4) | + IMX_AUDMUX_V2_PTCR_RFSDIR | + IMX_AUDMUX_V2_PTCR_RFSEL(MX31_AUDMUX_PORT4_SSI_PINS_4) | + IMX_AUDMUX_V2_PTCR_RCLKDIR | + IMX_AUDMUX_V2_PTCR_RCSEL(MX31_AUDMUX_PORT4_SSI_PINS_4), + IMX_AUDMUX_V2_PDCR_RXDSEL(MX31_AUDMUX_PORT4_SSI_PINS_4)); + } else if (machine_is_mx27_3ds()) { + imx_audmux_v1_configure_port(MX27_AUDMUX_HPCR1_SSI0, + IMX_AUDMUX_V1_PCR_SYN | + IMX_AUDMUX_V1_PCR_TFSDIR | + IMX_AUDMUX_V1_PCR_TCLKDIR | + IMX_AUDMUX_V1_PCR_RFSDIR | + IMX_AUDMUX_V1_PCR_RCLKDIR | + IMX_AUDMUX_V1_PCR_TFCSEL(MX27_AUDMUX_HPCR3_SSI_PINS_4) | + IMX_AUDMUX_V1_PCR_RFCSEL(MX27_AUDMUX_HPCR3_SSI_PINS_4) | + IMX_AUDMUX_V1_PCR_RXDSEL(MX27_AUDMUX_HPCR3_SSI_PINS_4) + ); + imx_audmux_v1_configure_port(MX27_AUDMUX_HPCR3_SSI_PINS_4, + IMX_AUDMUX_V1_PCR_SYN | + IMX_AUDMUX_V1_PCR_RXDSEL(MX27_AUDMUX_HPCR1_SSI0) + ); + } + + return ret; +} + +static int imx_mc13783_remove(struct platform_device *pdev) +{ + snd_soc_unregister_card(&imx_mc13783); + + return 0; +} + +static struct platform_driver imx_mc13783_audio_driver = { + .driver = { + .name = "imx_mc13783", + .owner = THIS_MODULE, + }, + .probe = imx_mc13783_probe, + .remove = imx_mc13783_remove +}; + +module_platform_driver(imx_mc13783_audio_driver); + +MODULE_AUTHOR("Sascha Hauer "); +MODULE_AUTHOR("Philippe Retornaz +#include +#include +#include + +void proto_register_enc(void); +void proto_reg_handoff_enc(void); + +/* The header in OpenBSD Encapsulating Interface files. */ + +struct enchdr { + guint32 af; + guint32 spi; + guint32 flags; +}; +#define BSD_ENC_HDRLEN 12 + +#define BSD_ENC_M_CONF 0x0400 /* payload encrypted */ +#define BSD_ENC_M_AUTH 0x0800 /* payload authenticated */ +#define BSD_ENC_M_COMP 0x1000 /* payload compressed */ +#define BSD_ENC_M_AUTH_AH 0x2000 /* header authenticated */ + +static dissector_table_t enc_dissector_table; +static dissector_handle_t data_handle; + +/* header fields */ +static int proto_enc = -1; +static int hf_enc_af = -1; +static int hf_enc_spi = -1; +static int hf_enc_flags = -1; +static int hf_enc_flags_payload_enc = -1; +static int hf_enc_flags_payload_auth = -1; +static int hf_enc_flags_payload_compress = -1; +static int hf_enc_flags_header_auth = -1; + +static gint ett_enc = -1; +static gint ett_enc_flag = -1; + +static gboolean +capture_enc(const guchar *pd, int offset _U_, int len, capture_packet_info_t *cpinfo, const union wtap_pseudo_header *pseudo_header _U_) +{ + guint32 af; + + if (!BYTES_ARE_IN_FRAME(0, len, BSD_ENC_HDRLEN)) + return FALSE; + + af = pntoh32(pd); + return try_capture_dissector("enc", af, pd, BSD_ENC_HDRLEN, len, cpinfo, pseudo_header); +} + +static const value_string af_vals[] = { + { BSD_AF_INET, "IPv4" }, + { BSD_AF_INET6_BSD, "IPv6" }, + { 0, NULL } +}; + +static int +dissect_enc(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_) +{ + struct enchdr ench; + tvbuff_t *next_tvb; + proto_tree *enc_tree; + proto_item *ti; + + static const int *flags[] = { + &hf_enc_flags_payload_enc, + &hf_enc_flags_payload_auth, + &hf_enc_flags_payload_compress, + &hf_enc_flags_header_auth, + NULL + }; + + col_set_str(pinfo->cinfo, COL_PROTOCOL, "ENC"); + + ench.af = tvb_get_ntohl(tvb, 0); + ench.spi = tvb_get_ntohl(tvb, 4); + + if (tree) { + ti = proto_tree_add_protocol_format(tree, proto_enc, tvb, 0, + BSD_ENC_HDRLEN, + "Enc %s, SPI 0x%8.8x", + val_to_str(ench.af, af_vals, "unknown (%u)"), + ench.spi); + enc_tree = proto_item_add_subtree(ti, ett_enc); + + proto_tree_add_item(enc_tree, hf_enc_af, tvb, 0, 4, ENC_BIG_ENDIAN); + proto_tree_add_item(enc_tree, hf_enc_spi, tvb, 4, 4, ENC_BIG_ENDIAN); + proto_tree_add_bitmask(enc_tree, tvb, 8, hf_enc_flags, ett_enc_flag, flags, ENC_BIG_ENDIAN); + } + + /* Set the tvbuff for the payload after the header */ + next_tvb = tvb_new_subset_remaining(tvb, BSD_ENC_HDRLEN); + if (!dissector_try_uint(enc_dissector_table, ench.af, next_tvb, pinfo, tree)) + call_dissector(data_handle, next_tvb, pinfo, tree); + + return tvb_captured_length(tvb); +} + +void +proto_register_enc(void) +{ + static hf_register_info hf[] = { + { &hf_enc_af, + { "Address Family", "enc.af", FT_UINT32, BASE_DEC, VALS(af_vals), 0x0, + "Protocol (IPv4 vs IPv6)", HFILL }}, + { &hf_enc_spi, + { "SPI", "enc.spi", FT_UINT32, BASE_HEX, NULL, 0x0, + "Security Parameter Index", HFILL }}, + { &hf_enc_flags, + { "Flags", "enc.flags", FT_UINT32, BASE_HEX, NULL, 0x0, + "ENC flags", HFILL }}, + { &hf_enc_flags_payload_enc, + { "Payload encrypted", "enc.flags.payload_enc", FT_BOOLEAN, 32, NULL, BSD_ENC_M_CONF, + NULL, HFILL }}, + { &hf_enc_flags_payload_auth, + { "Payload encrypted", "enc.flags.payload_auth", FT_BOOLEAN, 32, NULL, BSD_ENC_M_AUTH, + NULL, HFILL }}, + { &hf_enc_flags_payload_compress, + { "Payload encrypted", "enc.flags.payload_compress", FT_BOOLEAN, 32, NULL, BSD_ENC_M_COMP, + NULL, HFILL }}, + { &hf_enc_flags_header_auth, + { "Payload encrypted", "enc.flags.header_auth", FT_BOOLEAN, 32, NULL, BSD_ENC_M_AUTH_AH, + NULL, HFILL }}, + }; + static gint *ett[] = + { + &ett_enc, + &ett_enc_flag + }; + + proto_enc = proto_register_protocol("OpenBSD Encapsulating device", + "ENC", "enc"); + proto_register_field_array(proto_enc, hf, array_length(hf)); + proto_register_subtree_array(ett, array_length(ett)); + + enc_dissector_table = register_dissector_table("enc", "OpenBSD Encapsulating device", FT_UINT32, BASE_DEC, DISSECTOR_TABLE_NOT_ALLOW_DUPLICATE); + register_capture_dissector_table("enc", "ENC"); +} + +void +proto_reg_handoff_enc(void) +{ + dissector_handle_t enc_handle; + + data_handle = find_dissector("data"); + + enc_handle = create_dissector_handle(dissect_enc, proto_enc); + dissector_add_uint("wtap_encap", WTAP_ENCAP_ENC, enc_handle); + + register_capture_dissector("wtap_encap", WTAP_ENCAP_ENC, capture_enc, proto_enc); +} + +/* + * Editor modelines - http://www.wireshark.org/tools/modelines.html + * + * Local Variables: + * c-basic-offset: 2 + * tab-width: 8 + * indent-tabs-mode: nil + * End: + * + * ex: set shiftwidth=2 tabstop=8 expandtab: + * :indentSize=2:tabSize=8:noTabs=true: + */ diff --git a/pool/shard008/C/0129608_test_ahrs.c b/pool/shard008/C/0129608_test_ahrs.c new file mode 100644 index 0000000000000000000000000000000000000000..a8a433fcf8f0fa178b0829e90ca5f43a98496320 --- /dev/null +++ b/pool/shard008/C/0129608_test_ahrs.c @@ -0,0 +1,134 @@ +/* + * Copyright (C) 2011 The Paparazzi Team + * + * This file is part of paparazzi. + * + * paparazzi 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, or (at your option) + * any later version. + * + * paparazzi 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 paparazzi; see the file COPYING. If not, write to + * the Free Software Foundation, 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +#include + +#define DATALINK_C + +/* PERIODIC_C_MAIN is defined before generated/periodic_telemetry.h + * in order to implement telemetry_mode_Main_* + */ +#define PERIODIC_C_MAIN + +#include "generated/periodic_telemetry.h" + +#define ABI_C +#include "subsystems/abi.h" + +#include "std.h" +#include "mcu.h" +#include "mcu_periph/sys_time.h" +#include "led.h" +#include "mcu_periph/i2c.h" +#include "messages.h" +#include "subsystems/datalink/downlink.h" +#include "subsystems/datalink/telemetry.h" + +#include "subsystems/datalink/datalink.h" +#include "generated/settings.h" + +#include "subsystems/imu.h" +#include "subsystems/ahrs.h" +#include "subsystems/ahrs/ahrs_aligner.h" + +static inline void main_init(void); +static inline void main_periodic_task(void); +static inline void main_event_task(void); +static inline void main_report(void); + +int main(void) +{ + main_init(); + while (1) { + if (sys_time_check_and_ack_timer(0)) { + main_periodic_task(); + } + main_event_task(); + } + return 0; +} + +static inline void main_init(void) +{ + mcu_init(); + sys_time_register_timer((1. / PERIODIC_FREQUENCY), NULL); + imu_init(); +#if USE_AHRS_ALIGNER + ahrs_aligner_init(); +#endif + ahrs_init(); + downlink_init(); + + mcu_int_enable(); +} + +static inline void main_periodic_task(void) +{ + if (sys_time.nb_sec > 1) { + imu_periodic(); + } + RunOnceEvery(10, { LED_PERIODIC();}); + RunOnceEvery(PERIODIC_FREQUENCY, { datalink_time++; }); + main_report(); +} + +static inline void main_event_task(void) +{ + mcu_event(); + DatalinkEvent(); + ImuEvent(); +} + +static inline void main_report(void) +{ + RunOnceEvery(512, DOWNLINK_SEND_ALIVE(DefaultChannel, DefaultDevice, 16, MD5SUM)); + + periodic_telemetry_send_Main(DefaultPeriodic, &(DefaultChannel).trans_tx, &(DefaultDevice).device); +} + +void dl_parse_msg(void) +{ + uint8_t msg_id = dl_buffer[1]; + switch (msg_id) { + + case DL_PING: { + DOWNLINK_SEND_PONG(DefaultChannel, DefaultDevice); + } + break; + case DL_SETTING: + if (DL_SETTING_ac_id(dl_buffer) == AC_ID) { + uint8_t i = DL_SETTING_index(dl_buffer); + float val = DL_SETTING_value(dl_buffer); + DlSetting(i, val); + DOWNLINK_SEND_DL_VALUE(DefaultChannel, DefaultDevice, &i, &val); + } + break; + case DL_GET_SETTING : { + if (DL_GET_SETTING_ac_id(dl_buffer) != AC_ID) { break; } + uint8_t i = DL_GET_SETTING_index(dl_buffer); + float val = settings_get_value(i); + DOWNLINK_SEND_DL_VALUE(DefaultChannel, DefaultDevice, &i, &val); + } + break; + default: + break; + } +} diff --git a/pool/shard008/C/0129609_pop.c b/pool/shard008/C/0129609_pop.c new file mode 100644 index 0000000000000000000000000000000000000000..08ee71d3b3b726496d4e4fdf11bcabdfe984c553 --- /dev/null +++ b/pool/shard008/C/0129609_pop.c @@ -0,0 +1,29 @@ +#include "testing.h" + +void pop_test(void) +{ + cpu_state_t state; + int *test; + int tests[][7] = + { + {0xfffc, 0x5f, 0xfffd, 0x3c, 0xfffe} + }; + for(uint32_t i = 0; i < sizeof(tests) / sizeof(*tests); i++) + { + test = tests[i]; + state.sp = test[0]; + cpu_store8(&state, test[0], test[1]); + cpu_store8(&state, test[2], test[3]); + REG_INPUT input = { .r16 = REG16_BC }; + cpu_pop(&state, input); + if(state.sp == test[4] && state.b == test[3] && state.c == test[1]) + { + printf("Tests passed.\n"); + } + else + { + printf("Tests failed.\n"); + printf("0x%04x 0x%04x\n", state.bc, state.sp); + } + } +} diff --git a/pool/shard008/C/0129612_caesar.c b/pool/shard008/C/0129612_caesar.c new file mode 100644 index 0000000000000000000000000000000000000000..51471b2946e6ace27a520b2e2c8eecc60f9b50d4 --- /dev/null +++ b/pool/shard008/C/0129612_caesar.c @@ -0,0 +1,58 @@ +#include +#include +#include +#include +/* + problem: http://cdn.cs50.net/2016/x/psets/2/pset2/pset2.html#hail_caesar + check50 2015.fall.pset2.caesar caesar.c + */ + +#define ALPHABET 26 +string encrypt(string, int); +static const int start[] = {(int)'a', (int)'A'}; + +int main(int argc, char* argv[] ) +{ + int k; + char c; + string message; + + if(argc != 2) + { + printf("wrong number of argument, exist\n"); + return 1; + } + if ((sscanf(argv[1], "%d %c", &k, &c) != 1) || k < 0) + { + printf("argument has to be a possitive interger, exist\n"); + return 1; + } + + message = GetString(); + printf("%s\n",encrypt(message, k)); + return 0; +} + +string encrypt(string message, int k){ + int length = (int)strlen(message); + for(int i = 0; i < length; i ++) + { + int index_ascii = (int)message[i]; + int origin = index_ascii; + int transformed = origin; + + if(isalpha(message[i])) + { + int base = isupper(message[i]) ? start[1] : start[0]; + transformed = (origin - base + k)%ALPHABET + base; + } + + message[i] = (char)transformed; + } + + return message; +} + + + + diff --git a/pool/shard008/C/0129616_gpio-mxs.c b/pool/shard008/C/0129616_gpio-mxs.c new file mode 100644 index 0000000000000000000000000000000000000000..aaa69264b37687b9cbdd1ebcd267755de6d27bda --- /dev/null +++ b/pool/shard008/C/0129616_gpio-mxs.c @@ -0,0 +1,273 @@ +/* + * MXC GPIO support. (c) 2008 Daniel Mack + * Copyright 2008 Juergen Beisert, kernel@pengutronix.de + * + * Based on code from Freescale, + * Copyright (C) 2004-2010 Freescale Semiconductor, Inc. All Rights Reserved. + * + * 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MXS_SET 0x4 +#define MXS_CLR 0x8 + +#define PINCTRL_DOUT(n) ((cpu_is_mx23() ? 0x0500 : 0x0700) + (n) * 0x10) +#define PINCTRL_DIN(n) ((cpu_is_mx23() ? 0x0600 : 0x0900) + (n) * 0x10) +#define PINCTRL_DOE(n) ((cpu_is_mx23() ? 0x0700 : 0x0b00) + (n) * 0x10) +#define PINCTRL_PIN2IRQ(n) ((cpu_is_mx23() ? 0x0800 : 0x1000) + (n) * 0x10) +#define PINCTRL_IRQEN(n) ((cpu_is_mx23() ? 0x0900 : 0x1100) + (n) * 0x10) +#define PINCTRL_IRQLEV(n) ((cpu_is_mx23() ? 0x0a00 : 0x1200) + (n) * 0x10) +#define PINCTRL_IRQPOL(n) ((cpu_is_mx23() ? 0x0b00 : 0x1300) + (n) * 0x10) +#define PINCTRL_IRQSTAT(n) ((cpu_is_mx23() ? 0x0c00 : 0x1400) + (n) * 0x10) + +#define GPIO_INT_FALL_EDGE 0x0 +#define GPIO_INT_LOW_LEV 0x1 +#define GPIO_INT_RISE_EDGE 0x2 +#define GPIO_INT_HIGH_LEV 0x3 +#define GPIO_INT_LEV_MASK (1 << 0) +#define GPIO_INT_POL_MASK (1 << 1) + +#define irq_to_gpio(irq) ((irq) - MXS_GPIO_IRQ_START) + +struct mxs_gpio_port { + void __iomem *base; + int id; + int irq; + int virtual_irq_start; + struct bgpio_chip bgc; +}; + + +static int mxs_gpio_set_irq_type(struct irq_data *d, unsigned int type) +{ + u32 gpio = irq_to_gpio(d->irq); + u32 pin_mask = 1 << (gpio & 31); + struct irq_chip_generic *gc = irq_data_get_irq_chip_data(d); + struct mxs_gpio_port *port = gc->private; + void __iomem *pin_addr; + int edge; + + switch (type) { + case IRQ_TYPE_EDGE_RISING: + edge = GPIO_INT_RISE_EDGE; + break; + case IRQ_TYPE_EDGE_FALLING: + edge = GPIO_INT_FALL_EDGE; + break; + case IRQ_TYPE_LEVEL_LOW: + edge = GPIO_INT_LOW_LEV; + break; + case IRQ_TYPE_LEVEL_HIGH: + edge = GPIO_INT_HIGH_LEV; + break; + default: + return -EINVAL; + } + + + pin_addr = port->base + PINCTRL_IRQLEV(port->id); + if (edge & GPIO_INT_LEV_MASK) + writel(pin_mask, pin_addr + MXS_SET); + else + writel(pin_mask, pin_addr + MXS_CLR); + + + pin_addr = port->base + PINCTRL_IRQPOL(port->id); + if (edge & GPIO_INT_POL_MASK) + writel(pin_mask, pin_addr + MXS_SET); + else + writel(pin_mask, pin_addr + MXS_CLR); + + writel(1 << (gpio & 0x1f), + port->base + PINCTRL_IRQSTAT(port->id) + MXS_CLR); + + return 0; +} + +static void mxs_gpio_irq_handler(u32 irq, struct irq_desc *desc) +{ + u32 irq_stat; + struct mxs_gpio_port *port = irq_get_handler_data(irq); + u32 gpio_irq_no_base = port->virtual_irq_start; + + desc->irq_data.chip->irq_ack(&desc->irq_data); + + irq_stat = readl(port->base + PINCTRL_IRQSTAT(port->id)) & + readl(port->base + PINCTRL_IRQEN(port->id)); + + while (irq_stat != 0) { + int irqoffset = fls(irq_stat) - 1; + generic_handle_irq(gpio_irq_no_base + irqoffset); + irq_stat &= ~(1 << irqoffset); + } +} + +static int mxs_gpio_set_wake_irq(struct irq_data *d, unsigned int enable) +{ + struct irq_chip_generic *gc = irq_data_get_irq_chip_data(d); + struct mxs_gpio_port *port = gc->private; + + if (enable) + enable_irq_wake(port->irq); + else + disable_irq_wake(port->irq); + + return 0; +} + +static void __init mxs_gpio_init_gc(struct mxs_gpio_port *port) +{ + struct irq_chip_generic *gc; + struct irq_chip_type *ct; + + gc = irq_alloc_generic_chip("gpio-mxs", 1, port->virtual_irq_start, + port->base, handle_level_irq); + gc->private = port; + + ct = gc->chip_types; + ct->chip.irq_ack = irq_gc_ack_set_bit; + ct->chip.irq_mask = irq_gc_mask_clr_bit; + ct->chip.irq_unmask = irq_gc_mask_set_bit; + ct->chip.irq_set_type = mxs_gpio_set_irq_type; + ct->chip.irq_set_wake = mxs_gpio_set_wake_irq; + ct->regs.ack = PINCTRL_IRQSTAT(port->id) + MXS_CLR; + ct->regs.mask = PINCTRL_IRQEN(port->id); + + irq_setup_generic_chip(gc, IRQ_MSK(32), 0, IRQ_NOREQUEST, 0); +} + +static int mxs_gpio_to_irq(struct gpio_chip *gc, unsigned offset) +{ + struct bgpio_chip *bgc = to_bgpio_chip(gc); + struct mxs_gpio_port *port = + container_of(bgc, struct mxs_gpio_port, bgc); + + return port->virtual_irq_start + offset; +} + +static int __devinit mxs_gpio_probe(struct platform_device *pdev) +{ + static void __iomem *base; + struct mxs_gpio_port *port; + struct resource *iores = NULL; + int err; + + port = kzalloc(sizeof(struct mxs_gpio_port), GFP_KERNEL); + if (!port) + return -ENOMEM; + + port->id = pdev->id; + port->virtual_irq_start = MXS_GPIO_IRQ_START + port->id * 32; + + if (!base) { + iores = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!iores) { + err = -ENODEV; + goto out_kfree; + } + + if (!request_mem_region(iores->start, resource_size(iores), + pdev->name)) { + err = -EBUSY; + goto out_kfree; + } + + base = ioremap(iores->start, resource_size(iores)); + if (!base) { + err = -ENOMEM; + goto out_release_mem; + } + } + port->base = base; + + port->irq = platform_get_irq(pdev, 0); + if (port->irq < 0) { + err = -EINVAL; + goto out_iounmap; + } + + writel(~0U, port->base + PINCTRL_PIN2IRQ(port->id)); + writel(0, port->base + PINCTRL_IRQEN(port->id)); + + + writel(~0U, port->base + PINCTRL_IRQSTAT(port->id) + MXS_CLR); + + + mxs_gpio_init_gc(port); + + + irq_set_chained_handler(port->irq, mxs_gpio_irq_handler); + irq_set_handler_data(port->irq, port); + + err = bgpio_init(&port->bgc, &pdev->dev, 4, + port->base + PINCTRL_DIN(port->id), + port->base + PINCTRL_DOUT(port->id), NULL, + port->base + PINCTRL_DOE(port->id), NULL, false); + if (err) + goto out_iounmap; + + port->bgc.gc.to_irq = mxs_gpio_to_irq; + port->bgc.gc.base = port->id * 32; + + err = gpiochip_add(&port->bgc.gc); + if (err) + goto out_bgpio_remove; + + return 0; + +out_bgpio_remove: + bgpio_remove(&port->bgc); +out_iounmap: + if (iores) + iounmap(port->base); +out_release_mem: + if (iores) + release_mem_region(iores->start, resource_size(iores)); +out_kfree: + kfree(port); + dev_info(&pdev->dev, "%s failed with errno %d\n", __func__, err); + return err; +} + +static struct platform_driver mxs_gpio_driver = { + .driver = { + .name = "gpio-mxs", + .owner = THIS_MODULE, + }, + .probe = mxs_gpio_probe, +}; + +static int __init mxs_gpio_init(void) +{ + return platform_driver_register(&mxs_gpio_driver); +} +postcore_initcall(mxs_gpio_init); + +MODULE_AUTHOR("Freescale Semiconductor, " + "Daniel Mack , " + "Juergen Beisert "); +MODULE_DESCRIPTION("Freescale MXS GPIO"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard008/C/0129617_mex-notification-source.c b/pool/shard008/C/0129617_mex-notification-source.c new file mode 100644 index 0000000000000000000000000000000000000000..f04d176f7fc85c9cd05487053cd80f45bfe22d94 --- /dev/null +++ b/pool/shard008/C/0129617_mex-notification-source.c @@ -0,0 +1,148 @@ +/* + * Mex - a media explorer + * + * Copyright © 2010, 2011 Intel Corporation. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU Lesser General Public License, + * version 2.1, as published by the Free Software Foundation. + * + * This program is distributed in the hope 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 Lesser General Public License + * along with this program; if not, see + */ + +/* mex-notification-source.c */ + +#include "mex-notification-source.h" + +G_DEFINE_ABSTRACT_TYPE (MexNotificationSource, mex_notification_source, G_TYPE_OBJECT) + +enum +{ + NOTIFICATION_ADDED, + NOTIFICATION_REMOVED, + LAST_SIGNAL +}; + +static MexNotification *mex_notification_dup (MexNotification *notification); + +G_DEFINE_BOXED_TYPE (MexNotification, + mex_notification, + mex_notification_dup, + mex_notification_free) + +static guint signals[LAST_SIGNAL] = { 0, }; + +static void +mex_notification_source_class_init (MexNotificationSourceClass *klass) +{ + signals[NOTIFICATION_ADDED] = + g_signal_new ("notification-added", + MEX_TYPE_NOTIFICATION_SOURCE, + G_SIGNAL_RUN_FIRST, + G_STRUCT_OFFSET (MexNotificationSourceClass, + notification_added), + NULL, + NULL, + g_cclosure_marshal_VOID__BOXED, + G_TYPE_NONE, + 1, + MEX_TYPE_NOTIFICATION); + + signals[NOTIFICATION_REMOVED] = + g_signal_new ("notification-removed", + MEX_TYPE_NOTIFICATION_SOURCE, + G_SIGNAL_RUN_FIRST, + G_STRUCT_OFFSET (MexNotificationSourceClass, + notification_removed), + NULL, + NULL, + g_cclosure_marshal_VOID__BOXED, + G_TYPE_NONE, + 1, + MEX_TYPE_NOTIFICATION); +} + +static void +mex_notification_source_init (MexNotificationSource *self) +{ +} + +MexNotificationSource * +mex_notification_source_new (void) +{ + return g_object_new (MEX_TYPE_NOTIFICATION_SOURCE, NULL); +} + +static MexNotification * +_mex_notification_new (void) +{ + MexNotification *notification; + + notification = g_slice_new0 (MexNotification); + + return notification; +} + +MexNotification * +mex_notification_source_new_notification (MexNotificationSource *source, + const gchar *message, + const gchar *icon, + gint duration) +{ + MexNotification *notification; + + notification = _mex_notification_new (); + notification->message = g_strdup (message); + notification->icon = g_strdup (icon); + notification->duration = duration; + + notification->source = g_object_ref (source); + + return notification; +} + +void +mex_notification_source_emit_notification_added (MexNotificationSource *source, + MexNotification *notification) +{ + g_signal_emit (source, signals[NOTIFICATION_ADDED], 0, notification); +} + +void +mex_notification_source_emit_notification_remove (MexNotificationSource *source, + MexNotification *notification) +{ + g_signal_emit (source, signals[NOTIFICATION_REMOVED], 0, notification); +} + +void +mex_notification_free (MexNotification *notification) +{ + g_object_unref (notification->source); + g_free (notification->message); + g_free (notification->icon); + g_slice_free (MexNotification, notification); +} + +static MexNotification * +mex_notification_dup (MexNotification *notification) +{ + MexNotification *new_notification; + + new_notification = _mex_notification_new (); + + new_notification->message = g_strdup (notification->message); + new_notification->icon = g_strdup (notification->icon); + new_notification->duration = notification->duration; + new_notification->source = g_object_ref (notification->source); + + return new_notification; +} + + diff --git a/pool/shard008/C/0129622_SCB_SCBCLK.c b/pool/shard008/C/0129622_SCB_SCBCLK.c new file mode 100644 index 0000000000000000000000000000000000000000..b5fb4598f44c80ae8d74303600eb0671c4e8c271 --- /dev/null +++ b/pool/shard008/C/0129622_SCB_SCBCLK.c @@ -0,0 +1,210 @@ +/******************************************************************************* +* File Name: SCB_SCBCLK.c +* Version 2.20 +* +* Description: +* Provides system API for the clocking, interrupts and watchdog timer. +* +* Note: +* Documentation of the API's in this file is located in the +* System Reference Guide provided with PSoC Creator. +* +******************************************************************************** +* Copyright 2008-2012, Cypress Semiconductor Corporation. All rights reserved. +* You may use this file only in accordance with the license, terms, conditions, +* disclaimers, and limitations in the end user license agreement accompanying +* the software package with which this file was provided. +*******************************************************************************/ + +#include +#include "SCB_SCBCLK.h" + +#if defined CYREG_PERI_DIV_CMD + +/******************************************************************************* +* Function Name: SCB_SCBCLK_StartEx +******************************************************************************** +* +* Summary: +* Starts the clock, aligned to the specified running clock. +* +* Parameters: +* alignClkDiv: The divider to which phase alignment is performed when the +* clock is started. +* +* Returns: +* None +* +*******************************************************************************/ +void SCB_SCBCLK_StartEx(uint32 alignClkDiv) +{ + /* Make sure any previous start command has finished. */ + while((SCB_SCBCLK_CMD_REG & SCB_SCBCLK_CMD_ENABLE_MASK) != 0u) + { + } + + /* Specify the target divider and it's alignment divider, and enable. */ + SCB_SCBCLK_CMD_REG = + ((uint32)SCB_SCBCLK__DIV_ID << SCB_SCBCLK_CMD_DIV_SHIFT)| + (alignClkDiv << SCB_SCBCLK_CMD_PA_DIV_SHIFT) | + (uint32)SCB_SCBCLK_CMD_ENABLE_MASK; +} + +#else + +/******************************************************************************* +* Function Name: SCB_SCBCLK_Start +******************************************************************************** +* +* Summary: +* Starts the clock. +* +* Parameters: +* None +* +* Returns: +* None +* +*******************************************************************************/ + +void SCB_SCBCLK_Start(void) +{ + /* Set the bit to enable the clock. */ + SCB_SCBCLK_ENABLE_REG |= SCB_SCBCLK__ENABLE_MASK; +} + +#endif /* CYREG_PERI_DIV_CMD */ + + +/******************************************************************************* +* Function Name: SCB_SCBCLK_Stop +******************************************************************************** +* +* Summary: +* Stops the clock and returns immediately. This API does not require the +* source clock to be running but may return before the hardware is actually +* disabled. +* +* Parameters: +* None +* +* Returns: +* None +* +*******************************************************************************/ +void SCB_SCBCLK_Stop(void) +{ +#if defined CYREG_PERI_DIV_CMD + + /* Make sure any previous start command has finished. */ + while((SCB_SCBCLK_CMD_REG & SCB_SCBCLK_CMD_ENABLE_MASK) != 0u) + { + } + + /* Specify the target divider and it's alignment divider, and disable. */ + SCB_SCBCLK_CMD_REG = + ((uint32)SCB_SCBCLK__DIV_ID << SCB_SCBCLK_CMD_DIV_SHIFT)| + ((uint32)SCB_SCBCLK_CMD_DISABLE_MASK); + +#else + + /* Clear the bit to disable the clock. */ + SCB_SCBCLK_ENABLE_REG &= (uint32)(~SCB_SCBCLK__ENABLE_MASK); + +#endif /* CYREG_PERI_DIV_CMD */ +} + + +/******************************************************************************* +* Function Name: SCB_SCBCLK_SetFractionalDividerRegister +******************************************************************************** +* +* Summary: +* Modifies the clock divider and the fractional divider. +* +* Parameters: +* clkDivider: Divider register value (0-65535). This value is NOT the +* divider; the clock hardware divides by clkDivider plus one. For example, +* to divide the clock by 2, this parameter should be set to 1. +* fracDivider: Fractional Divider register value (0-31). +* Returns: +* None +* +*******************************************************************************/ +void SCB_SCBCLK_SetFractionalDividerRegister(uint16 clkDivider, uint8 clkFractional) +{ + uint32 maskVal; + uint32 regVal; + +#if defined (SCB_SCBCLK__FRAC_MASK) || defined (CYREG_PERI_DIV_CMD) + + /* get all but divider bits */ + maskVal = SCB_SCBCLK_DIV_REG & + (uint32)(~(uint32)(SCB_SCBCLK_DIV_INT_MASK | SCB_SCBCLK_DIV_FRAC_MASK)); + /* combine mask and new divider vals into 32-bit value */ + regVal = maskVal | + ((uint32)((uint32)clkDivider << SCB_SCBCLK_DIV_INT_SHIFT) & SCB_SCBCLK_DIV_INT_MASK) | + ((uint32)((uint32)clkFractional << SCB_SCBCLK_DIV_FRAC_SHIFT) & SCB_SCBCLK_DIV_FRAC_MASK); + +#else + /* get all but integer divider bits */ + maskVal = SCB_SCBCLK_DIV_REG & (uint32)(~(uint32)SCB_SCBCLK__DIVIDER_MASK); + /* combine mask and new divider val into 32-bit value */ + regVal = clkDivider | maskVal; + +#endif /* SCB_SCBCLK__FRAC_MASK || CYREG_PERI_DIV_CMD */ + + SCB_SCBCLK_DIV_REG = regVal; +} + + +/******************************************************************************* +* Function Name: SCB_SCBCLK_GetDividerRegister +******************************************************************************** +* +* Summary: +* Gets the clock divider register value. +* +* Parameters: +* None +* +* Returns: +* Divide value of the clock minus 1. For example, if the clock is set to +* divide by 2, the return value will be 1. +* +*******************************************************************************/ +uint16 SCB_SCBCLK_GetDividerRegister(void) +{ + return (uint16)((SCB_SCBCLK_DIV_REG & SCB_SCBCLK_DIV_INT_MASK) + >> SCB_SCBCLK_DIV_INT_SHIFT); +} + + +/******************************************************************************* +* Function Name: SCB_SCBCLK_GetFractionalDividerRegister +******************************************************************************** +* +* Summary: +* Gets the clock fractional divider register value. +* +* Parameters: +* None +* +* Returns: +* Fractional Divide value of the clock +* 0 if the fractional divider is not in use. +* +*******************************************************************************/ +uint8 SCB_SCBCLK_GetFractionalDividerRegister(void) +{ +#if defined (SCB_SCBCLK__FRAC_MASK) + /* return fractional divider bits */ + return (uint8)((SCB_SCBCLK_DIV_REG & SCB_SCBCLK_DIV_FRAC_MASK) + >> SCB_SCBCLK_DIV_FRAC_SHIFT); +#else + return 0u; +#endif /* SCB_SCBCLK__FRAC_MASK */ +} + + +/* [] END OF FILE */ diff --git a/pool/shard008/C/0129627_proto_parse.c b/pool/shard008/C/0129627_proto_parse.c new file mode 100644 index 0000000000000000000000000000000000000000..751017585028b7f412458b960d05f5e633c29207 --- /dev/null +++ b/pool/shard008/C/0129627_proto_parse.c @@ -0,0 +1,334 @@ +// +// Copyright (C) 2002-2008 Simon Howard +// +// 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., 59 Temple Place - Suite 330, Boston, MA +// 02111-1307, USA. +// + +// Parsing of received packets. +// This code runs on the assumption that the packets being given to +// it are well formed and valid; it does not do any checking on the data +// received. +// + +#include "arch/sysheaders.h" +#include "base/alloc.h" +#include "base/error.h" + +#include + +#include "protocol.h" +#include "sendatom.h" + +// alpha value used for estimating round trip time + +#define RTT_ALPHA 0.9f + +int irmo_proto_use_preexec = 1; + +// only the low 16 bits of the stream position is sent +// therefore we must expand positions we get based on the +// current position + +static unsigned int get_stream_position(unsigned int current, unsigned int low) +{ + unsigned int newpos = (current & ~0xffff) | low; + + // if new position is greater than 32768 behind the + // current position, we have probably wrapped around + // similarly wrap around the other way + + if (current > newpos && current - newpos > 0x8000) { + newpos += 0x10000; + } else if (newpos > current && newpos - current > 0x8000) { + newpos -= 0x10000; + } + + return newpos; +} + +static void proto_parse_insert_atom(IrmoClient *client, + IrmoSendAtom *atom, + unsigned int seq) +{ + unsigned int index = seq - client->recvwindow_start; + unsigned int i; + + // increase the receive window size if neccesary + + if (index >= client->recvwindow_size) { + unsigned int newsize = index + 1; + + client->recvwindow = irmo_renew(IrmoSendAtom *, + client->recvwindow, + newsize); + + for (i=client->recvwindow_size; irecvwindow[i] = NULL; + } + + client->recvwindow_size = newsize; + } + + // delete old sendatoms in the same position (assume + // new retransmitted atoms are more up to date) + + if (client->recvwindow[index] != NULL) { + irmo_sendatom_free(client->recvwindow[index]); + } + + client->recvwindow[index] = atom; +} + +static void proto_parse_packet_data(IrmoClient *client, IrmoPacket *packet) +{ + unsigned int i; + unsigned int seq; + unsigned int start; + + // get the start position + + irmo_packet_readi16(packet, &i); + + start = get_stream_position(client->recvwindow_start, i); + + //printf("stream position: %i->%i\n", i, start); + + seq = start; + + for (;;) { + IrmoSendAtomClass *klass; + IrmoSendAtomType atomtype; + unsigned int natoms; + unsigned int byte; + + // read type/count byte + // if none, end of packet + + if (!irmo_packet_readi8(packet, &byte)) { + break; + } + + atomtype = (byte >> 5) & 0x07; + natoms = (byte & 0x1f) + 1; + + klass = irmo_sendatom_types[atomtype]; + + //printf("%i atoms, type %i\n", natoms, atomtype); + + for (i=0; iread(packet, client); + atom->client = client; + atom->seqnum = seq; + + // set the need_ack flag if this is at the start + // or before the start of the recvwindow. We only + // send an ack when the atom is at the start of + // the recvwindow (seq == client->recvwindow_start) + // as this allows us to advance the window + // or if it is too old (as this could be resend + // because our previous ack was lost + + if (seq <= client->recvwindow_start) { + client->need_ack = 1; + } + + // too old? + + if (seq < client->recvwindow_start) { + irmo_sendatom_free(atom); + continue; + } + + // insert atom into receive window + + proto_parse_insert_atom(client, atom, seq); + } + } + + // try to preexec the new data + + if (irmo_proto_use_preexec) { + irmo_client_run_preexec(client, start, seq); + } +} + +// Perform a low pass filter of RTT values + +static float rtt_low_pass_filter(float last_value, + unsigned int new_value) +{ + float result; + + result = ( last_value * RTT_ALPHA ) + + ( (float) new_value * (1 - RTT_ALPHA) ); + + return result; +} + +// Update the congestion control values for the given client, after +// receiving a successful acknowledgement. + +static void proto_update_cc_values(IrmoClient *client) +{ + unsigned int nowtime, rtt; + unsigned int deviation; + + // We got a valid ack. open up the send window a bit more. + // If we are above the slow start congestion threshold, open + // slower. + + if (client->cwnd < client->ssthresh) { + client->cwnd += IRMO_PROTOCOL_MTU; + } else { + client->cwnd += + (IRMO_PROTOCOL_MTU * IRMO_PROTOCOL_MTU) / client->cwnd; + } + + // + // We are acking something valid and advancing the window + // Assume this is because the first atom in the window has + // been cleared. Therefore we can estimate the round-trip time + // by subtracting the current time from the send time of the + // first atom in the send window. + // + // If the atom was resent, this cannot be used. + // + + if (!client->sendwindow[0]->resent) { + nowtime = irmo_get_time(); + + // Round-trip time + + rtt = nowtime - client->sendwindow[0]->sendtime; + + deviation = (unsigned int) abs((int) rtt - (int) client->rtt); + + client->rtt + = rtt_low_pass_filter(client->rtt, rtt); + client->rtt_deviation + = rtt_low_pass_filter(client->rtt_deviation, + deviation); + + // Reset exponential backoff now that we have a valid packet + + client->backoff = 1; + } +} + +static void advance_send_window(IrmoClient *client, unsigned int length) +{ + IrmoSendAtom *atom; + unsigned int i; + + // destroy all atoms in the area acked + + for (i=0; isendwindow[i]; + + // Signal the atom that it has been acknowledged. + + if (atom->klass->acked != NULL) { + atom->klass->acked(atom); + } + + irmo_sendatom_free(atom); + } + + // advance the send window forward + + memcpy(client->sendwindow, + client->sendwindow + length, + sizeof(*client->sendwindow) + * (client->sendwindow_size - length)); + + // update counters + + client->sendwindow_start += length; + client->sendwindow_size -= length; +} + +static void proto_parse_ack(IrmoClient *client, unsigned int ack) +{ + unsigned int seq; + unsigned int relative; + + //printf("got an ack: %i\n", ack); + + // extrapolate the high bits from the low 16 bits + + seq = get_stream_position(client->sendwindow_start, ack); + + // get position in sendwindow array, relative to the start + + if (seq <= client->sendwindow_start) { + return; + } + + relative = seq - client->sendwindow_start; + + // Check that the acknowledgement is within the range of the + // send window. + + if ((unsigned) relative > client->sendwindow_size) { +/* + irmo_warning_message("proto_parse_ack", + "bogus ack (%i < %i < %i)", + client->sendwindow_start, seq, + client->sendwindow_start + client->sendwindow_size); +*/ + return; + } + + // Update congestion control values + + proto_update_cc_values(client); + advance_send_window(client, relative); +} + +void irmo_proto_parse_packet(IrmoPacket *packet, + IrmoClient *client, + unsigned int flags) +{ + // verify packet before parsing for security + + if (!irmo_proto_verify_packet(packet, client, flags)) { +/* + irmo_warning_message("irmo_proto_parse_packet", + "dropped packet (failed security verification)"); +*/ + return; + } + + // read ack field if there is one + + if ((flags & PACKET_FLAG_ACK) != 0) { + unsigned int i; + + irmo_packet_readi16(packet, &i); + + proto_parse_ack(client, i); + } + + if ((flags & PACKET_FLAG_DTA) != 0) { + proto_parse_packet_data(client, packet); + + irmo_client_run_recvwindow(client); + } +} + diff --git a/pool/shard008/C/0129629_cpu.c b/pool/shard008/C/0129629_cpu.c new file mode 100644 index 0000000000000000000000000000000000000000..69fca8c068d170d15f703fd630dcccbd04109279 --- /dev/null +++ b/pool/shard008/C/0129629_cpu.c @@ -0,0 +1,220 @@ +/* + * TriCore emulation for qemu: main translation routines. + * + * Copyright (c) 2012-2014 Bastian Koppelmann C-Lab/University Paderborn + * + * 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 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. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + */ + +#include "qemu/osdep.h" +#include "qapi/error.h" +#include "cpu.h" +#include "qemu-common.h" + +static inline void set_feature(CPUTriCoreState *env, int feature) +{ + env->features |= 1ULL << feature; +} + +static void tricore_cpu_set_pc(CPUState *cs, vaddr value) +{ + TriCoreCPU *cpu = TRICORE_CPU(cs); + CPUTriCoreState *env = &cpu->env; + + env->PC = value & ~(target_ulong)1; +} + +static void tricore_cpu_synchronize_from_tb(CPUState *cs, + TranslationBlock *tb) +{ + TriCoreCPU *cpu = TRICORE_CPU(cs); + CPUTriCoreState *env = &cpu->env; + + env->PC = tb->pc; +} + +static void tricore_cpu_reset(CPUState *s) +{ + TriCoreCPU *cpu = TRICORE_CPU(s); + TriCoreCPUClass *tcc = TRICORE_CPU_GET_CLASS(cpu); + CPUTriCoreState *env = &cpu->env; + + tcc->parent_reset(s); + + tlb_flush(s, 1); + + cpu_state_reset(env); +} + +static bool tricore_cpu_has_work(CPUState *cs) +{ + return true; +} + +static void tricore_cpu_realizefn(DeviceState *dev, Error **errp) +{ + CPUState *cs = CPU(dev); + TriCoreCPU *cpu = TRICORE_CPU(dev); + TriCoreCPUClass *tcc = TRICORE_CPU_GET_CLASS(dev); + CPUTriCoreState *env = &cpu->env; + + /* Some features automatically imply others */ + if (tricore_feature(env, TRICORE_FEATURE_161)) { + set_feature(env, TRICORE_FEATURE_16); + } + + if (tricore_feature(env, TRICORE_FEATURE_16)) { + set_feature(env, TRICORE_FEATURE_131); + } + if (tricore_feature(env, TRICORE_FEATURE_131)) { + set_feature(env, TRICORE_FEATURE_13); + } + cpu_reset(cs); + qemu_init_vcpu(cs); + + tcc->parent_realize(dev, errp); +} + + +static void tricore_cpu_initfn(Object *obj) +{ + CPUState *cs = CPU(obj); + TriCoreCPU *cpu = TRICORE_CPU(obj); + CPUTriCoreState *env = &cpu->env; + + cs->env_ptr = env; + cpu_exec_init(cs, &error_abort); + + if (tcg_enabled()) { + tricore_tcg_init(); + } +} + +static ObjectClass *tricore_cpu_class_by_name(const char *cpu_model) +{ + ObjectClass *oc; + char *typename; + + if (!cpu_model) { + return NULL; + } + + typename = g_strdup_printf("%s-" TYPE_TRICORE_CPU, cpu_model); + oc = object_class_by_name(typename); + g_free(typename); + if (!oc || !object_class_dynamic_cast(oc, TYPE_TRICORE_CPU) || + object_class_is_abstract(oc)) { + return NULL; + } + return oc; +} + +static void tc1796_initfn(Object *obj) +{ + TriCoreCPU *cpu = TRICORE_CPU(obj); + + set_feature(&cpu->env, TRICORE_FEATURE_13); +} + +static void tc1797_initfn(Object *obj) +{ + TriCoreCPU *cpu = TRICORE_CPU(obj); + + set_feature(&cpu->env, TRICORE_FEATURE_131); +} + +static void tc27x_initfn(Object *obj) +{ + TriCoreCPU *cpu = TRICORE_CPU(obj); + + set_feature(&cpu->env, TRICORE_FEATURE_161); +} + +typedef struct TriCoreCPUInfo { + const char *name; + void (*initfn)(Object *obj); + void (*class_init)(ObjectClass *oc, void *data); +} TriCoreCPUInfo; + +static const TriCoreCPUInfo tricore_cpus[] = { + { .name = "tc1796", .initfn = tc1796_initfn }, + { .name = "tc1797", .initfn = tc1797_initfn }, + { .name = "tc27x", .initfn = tc27x_initfn }, + { .name = NULL } +}; + +static void tricore_cpu_class_init(ObjectClass *c, void *data) +{ + TriCoreCPUClass *mcc = TRICORE_CPU_CLASS(c); + CPUClass *cc = CPU_CLASS(c); + DeviceClass *dc = DEVICE_CLASS(c); + + mcc->parent_realize = dc->realize; + dc->realize = tricore_cpu_realizefn; + + mcc->parent_reset = cc->reset; + cc->reset = tricore_cpu_reset; + cc->class_by_name = tricore_cpu_class_by_name; + cc->has_work = tricore_cpu_has_work; + + cc->dump_state = tricore_cpu_dump_state; + cc->set_pc = tricore_cpu_set_pc; + cc->synchronize_from_tb = tricore_cpu_synchronize_from_tb; + + /* + * Reason: tricore_cpu_initfn() calls cpu_exec_init(), which saves + * the object in cpus -> dangling pointer after final + * object_unref(). + */ + dc->cannot_destroy_with_object_finalize_yet = true; +} + +static void cpu_register(const TriCoreCPUInfo *info) +{ + TypeInfo type_info = { + .parent = TYPE_TRICORE_CPU, + .instance_size = sizeof(TriCoreCPU), + .instance_init = info->initfn, + .class_size = sizeof(TriCoreCPUClass), + .class_init = info->class_init, + }; + + type_info.name = g_strdup_printf("%s-" TYPE_TRICORE_CPU, info->name); + type_register(&type_info); + g_free((void *)type_info.name); +} + +static const TypeInfo tricore_cpu_type_info = { + .name = TYPE_TRICORE_CPU, + .parent = TYPE_CPU, + .instance_size = sizeof(TriCoreCPU), + .instance_init = tricore_cpu_initfn, + .abstract = true, + .class_size = sizeof(TriCoreCPUClass), + .class_init = tricore_cpu_class_init, +}; + +static void tricore_cpu_register_types(void) +{ + const TriCoreCPUInfo *info = tricore_cpus; + + type_register_static(&tricore_cpu_type_info); + + while (info->name) { + cpu_register(info); + info++; + } +} + +type_init(tricore_cpu_register_types) diff --git a/pool/shard008/C/0129630_modesp.c b/pool/shard008/C/0129630_modesp.c new file mode 100644 index 0000000000000000000000000000000000000000..59a261e8c27ff0f7e2ad81d4bdc92835fccdffc3 --- /dev/null +++ b/pool/shard008/C/0129630_modesp.c @@ -0,0 +1,156 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * Development of the code in this file was sponsored by Microbric Pty Ltd + * + * The MIT License (MIT) + * + * Copyright (c) 2015 Paul Sokolovsky + * Copyright (c) 2016 Damien P. George + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include + +#include "esp_log.h" +#include "esp_spi_flash.h" + +#include "py/runtime.h" +#include "py/mperrno.h" +#include "py/mphal.h" +#include "drivers/dht/dht.h" +#include "modesp.h" + +STATIC mp_obj_t esp_osdebug(size_t n_args, const mp_obj_t *args) { + esp_log_level_t level = LOG_LOCAL_LEVEL; + if (n_args == 2) { + level = mp_obj_get_int(args[1]); + } + if (args[0] == mp_const_none) { + // Disable logging + esp_log_level_set("*", ESP_LOG_ERROR); + } else { + // Enable logging at the given level + // TODO args[0] should set the UART to which debug is sent + esp_log_level_set("*", level); + } + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(esp_osdebug_obj, 1, 2, esp_osdebug); + +STATIC mp_obj_t esp_flash_read(mp_obj_t offset_in, mp_obj_t buf_in) { + mp_int_t offset = mp_obj_get_int(offset_in); + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_WRITE); + esp_err_t res = spi_flash_read(offset, bufinfo.buf, bufinfo.len); + if (res != ESP_OK) { + mp_raise_OSError(MP_EIO); + } + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(esp_flash_read_obj, esp_flash_read); + +STATIC mp_obj_t esp_flash_write(mp_obj_t offset_in, mp_obj_t buf_in) { + mp_int_t offset = mp_obj_get_int(offset_in); + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); + esp_err_t res = spi_flash_write(offset, bufinfo.buf, bufinfo.len); + if (res != ESP_OK) { + mp_raise_OSError(MP_EIO); + } + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(esp_flash_write_obj, esp_flash_write); + +STATIC mp_obj_t esp_flash_erase(mp_obj_t sector_in) { + mp_int_t sector = mp_obj_get_int(sector_in); + esp_err_t res = spi_flash_erase_sector(sector); + if (res != ESP_OK) { + mp_raise_OSError(MP_EIO); + } + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(esp_flash_erase_obj, esp_flash_erase); + +STATIC mp_obj_t esp_flash_size(void) { + return mp_obj_new_int_from_uint(spi_flash_get_chip_size()); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_0(esp_flash_size_obj, esp_flash_size); + +STATIC mp_obj_t esp_flash_user_start(void) { + return MP_OBJ_NEW_SMALL_INT(0x200000); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_0(esp_flash_user_start_obj, esp_flash_user_start); + +STATIC mp_obj_t esp_gpio_matrix_in(mp_obj_t pin, mp_obj_t sig, mp_obj_t inv) { + gpio_matrix_in(mp_obj_get_int(pin), mp_obj_get_int(sig), mp_obj_get_int(inv)); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp_gpio_matrix_in_obj, esp_gpio_matrix_in); + +STATIC mp_obj_t esp_gpio_matrix_out(size_t n_args, const mp_obj_t *args) { + (void)n_args; + gpio_matrix_out(mp_obj_get_int(args[0]), mp_obj_get_int(args[1]), mp_obj_get_int(args[2]), mp_obj_get_int(args[3])); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(esp_gpio_matrix_out_obj, 4, 4, esp_gpio_matrix_out); + +STATIC mp_obj_t esp_neopixel_write_(mp_obj_t pin, mp_obj_t buf, mp_obj_t timing) { + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_READ); + esp_neopixel_write(mp_hal_get_pin_obj(pin), + (uint8_t *)bufinfo.buf, bufinfo.len, mp_obj_get_int(timing)); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_3(esp_neopixel_write_obj, esp_neopixel_write_); + +STATIC const mp_rom_map_elem_t esp_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_esp) }, + + { MP_ROM_QSTR(MP_QSTR_osdebug), MP_ROM_PTR(&esp_osdebug_obj) }, + + { MP_ROM_QSTR(MP_QSTR_flash_read), MP_ROM_PTR(&esp_flash_read_obj) }, + { MP_ROM_QSTR(MP_QSTR_flash_write), MP_ROM_PTR(&esp_flash_write_obj) }, + { MP_ROM_QSTR(MP_QSTR_flash_erase), MP_ROM_PTR(&esp_flash_erase_obj) }, + { MP_ROM_QSTR(MP_QSTR_flash_size), MP_ROM_PTR(&esp_flash_size_obj) }, + { MP_ROM_QSTR(MP_QSTR_flash_user_start), MP_ROM_PTR(&esp_flash_user_start_obj) }, + + { MP_ROM_QSTR(MP_QSTR_gpio_matrix_in), MP_ROM_PTR(&esp_gpio_matrix_in_obj) }, + { MP_ROM_QSTR(MP_QSTR_gpio_matrix_out), MP_ROM_PTR(&esp_gpio_matrix_out_obj) }, + + { MP_ROM_QSTR(MP_QSTR_neopixel_write), MP_ROM_PTR(&esp_neopixel_write_obj) }, + { MP_ROM_QSTR(MP_QSTR_dht_readinto), MP_ROM_PTR(&dht_readinto_obj) }, + + // Constants for second arg of osdebug() + { MP_ROM_QSTR(MP_QSTR_LOG_NONE), MP_ROM_INT((mp_uint_t)ESP_LOG_NONE)}, + { MP_ROM_QSTR(MP_QSTR_LOG_ERROR), MP_ROM_INT((mp_uint_t)ESP_LOG_ERROR)}, + { MP_ROM_QSTR(MP_QSTR_LOG_WARNING), MP_ROM_INT((mp_uint_t)ESP_LOG_WARN)}, + { MP_ROM_QSTR(MP_QSTR_LOG_INFO), MP_ROM_INT((mp_uint_t)ESP_LOG_INFO)}, + { MP_ROM_QSTR(MP_QSTR_LOG_DEBUG), MP_ROM_INT((mp_uint_t)ESP_LOG_DEBUG)}, + { MP_ROM_QSTR(MP_QSTR_LOG_VERBOSE), MP_ROM_INT((mp_uint_t)ESP_LOG_VERBOSE)}, +}; + +STATIC MP_DEFINE_CONST_DICT(esp_module_globals, esp_module_globals_table); + +const mp_obj_module_t esp_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&esp_module_globals, +}; + diff --git a/pool/shard008/C/0129632_test-undefinedfield.c b/pool/shard008/C/0129632_test-undefinedfield.c new file mode 100644 index 0000000000000000000000000000000000000000..538b791405a461ed7c21a20a3efdeb897e9aaa2f --- /dev/null +++ b/pool/shard008/C/0129632_test-undefinedfield.c @@ -0,0 +1,30 @@ +#include +#include + +gint +main (gint argc, + gchar **argv) +{ + EContact *contact; + gpointer test; + + g_type_init (); + + contact = e_contact_new (); + + printf ("testing e_contact_get of something suitably out of range\n"); + test = e_contact_get (contact, 6000 /* something suitably high. */); + if (test) + printf ("failed, e_contact_get return non-NULL\n"); + else + printf ("passed\n"); + + printf ("testing e_contact_get of something we don't handle yet\n"); + test = e_contact_get (contact, E_CONTACT_CATEGORY_LIST); + if (test) + printf ("failed, e_contact_get return non-NULL\n"); + else + printf ("passed\n"); + + exit (0); +} diff --git a/pool/shard008/C/0129642_empty-Seed1-RandomFuns-Type_int-ControlStructures_12-BB1-ForBound_input-Operators_Shiftlt_Shiftrt_Lt_Gt_Le_Ge_Eq_Ne_BAnd_BXor_BOr.c b/pool/shard008/C/0129642_empty-Seed1-RandomFuns-Type_int-ControlStructures_12-BB1-ForBound_input-Operators_Shiftlt_Shiftrt_Lt_Gt_Le_Ge_Eq_Ne_BAnd_BXor_BOr.c new file mode 100644 index 0000000000000000000000000000000000000000..957a4c48915fa6131d0488e36d60ac802ae29177 --- /dev/null +++ b/pool/shard008/C/0129642_empty-Seed1-RandomFuns-Type_int-ControlStructures_12-BB1-ForBound_input-Operators_Shiftlt_Shiftrt_Lt_Gt_Le_Ge_Eq_Ne_BAnd_BXor_BOr.c @@ -0,0 +1,116 @@ +/* Generated by CIL v. 1.7.0 */ +/* print_CIL_Input is false */ + +struct _IO_FILE; +struct timeval; +extern void signal(int sig , void *func ) ; +extern float strtof(char const *str , char const *endptr ) ; +typedef struct _IO_FILE FILE; +extern int atoi(char const *s ) ; +extern double strtod(char const *str , char const *endptr ) ; +extern int fclose(void *stream ) ; +extern void *fopen(char const *filename , char const *mode ) ; +extern void abort() ; +extern void exit(int status ) ; +extern int raise(int sig ) ; +extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; +extern int strcmp(char const *a , char const *b ) ; +extern int rand() ; +extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; +void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ; +extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; +extern int gettimeofday(struct timeval *tv , void *tz , ...) ; +extern int printf(char const *format , ...) ; +int main(int argc , char *argv[] ) ; +void megaInit(void) ; +extern unsigned long strlen(char const *s ) ; +extern long strtol(char const *str , char const *endptr , int base ) ; +extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; +extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; +struct timeval { + long tv_sec ; + long tv_usec ; +}; +extern void *malloc(unsigned long size ) ; +extern int scanf(char const *format , ...) ; +void megaInit(void) +{ + + + { + +} +} +void RandomFunc(unsigned int input[1] , unsigned int output[1] ) +{ + unsigned int state[1] ; + unsigned int local1 ; + char copy11 ; + char copy12 ; + char copy13 ; + + { + state[0UL] = (input[0UL] | 51238316UL) >> 3U; + local1 = 0UL; + while (local1 < input[1UL]) { + if (state[0UL] > local1) { + if (state[0UL] > local1) { + copy11 = *((char *)(& state[local1]) + 1); + *((char *)(& state[local1]) + 1) = *((char *)(& state[local1]) + 2); + *((char *)(& state[local1]) + 2) = copy11; + copy11 = *((char *)(& state[local1]) + 2); + *((char *)(& state[local1]) + 2) = *((char *)(& state[local1]) + 0); + *((char *)(& state[local1]) + 0) = copy11; + } else { + copy12 = *((char *)(& state[0UL]) + 0); + *((char *)(& state[0UL]) + 0) = *((char *)(& state[0UL]) + 3); + *((char *)(& state[0UL]) + 3) = copy12; + copy12 = *((char *)(& state[0UL]) + 3); + *((char *)(& state[0UL]) + 3) = *((char *)(& state[0UL]) + 0); + *((char *)(& state[0UL]) + 0) = copy12; + } + } else { + copy13 = *((char *)(& state[local1]) + 0); + *((char *)(& state[local1]) + 0) = *((char *)(& state[local1]) + 1); + *((char *)(& state[local1]) + 1) = copy13; + } + local1 += 2UL; + } + output[0UL] = (state[0UL] | 501610228UL) ^ 537133824U; +} +} +int main(int argc , char *argv[] ) +{ + unsigned int input[1] ; + unsigned int output[1] ; + int randomFuns_i5 ; + unsigned int randomFuns_value6 ; + int randomFuns_main_i7 ; + + { + megaInit(); + if (argc != 2) { + printf("Call this program with %i arguments\n", 1); + exit(-1); + } else { + + } + randomFuns_i5 = 0; + while (randomFuns_i5 < 1) { + randomFuns_value6 = (unsigned int )strtoul(argv[randomFuns_i5 + 1], 0, 10); + input[randomFuns_i5] = randomFuns_value6; + randomFuns_i5 ++; + } + RandomFunc(input, output); + if (output[0] == 1038220791U) { + printf("You win!\n"); + } else { + + } + randomFuns_main_i7 = 0; + while (randomFuns_main_i7 < 1) { + printf("%u\n", output[randomFuns_main_i7]); + randomFuns_main_i7 ++; + } +} +} diff --git a/pool/shard008/C/0129643_buffer.c b/pool/shard008/C/0129643_buffer.c new file mode 100644 index 0000000000000000000000000000000000000000..111aee72d3a16c180e2168a600dc7a09a16ce20c --- /dev/null +++ b/pool/shard008/C/0129643_buffer.c @@ -0,0 +1,248 @@ +/* + ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (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.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * Copyright (C) 2008-2012 Laurent Gautier + * + * Portions created by Alexander Belopolsky are + * Copyright (C) 2006 Alexander Belopolsky. + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include +#include + +#include "_rinterface.h" +#include "buffer.h" + +static int +sexp_rank(SEXP sexp) +{ + /* Return the number of dimensions for the buffer + * (e.g., a vector will return 1, a matrix 2, ...) + */ + SEXP dim = getAttrib(sexp, R_DimSymbol); + if (dim == R_NilValue) + return 1; + return GET_LENGTH(dim); +} + +static void +sexp_shape(SEXP sexp, Py_intptr_t *shape, int nd) +{ + /* Set the buffer 'shape', that is a vector of Py_intptr_t + * containing the size of each dimension (see sexp_rank). + */ + int i; + SEXP dim = getAttrib(sexp, R_DimSymbol); + if (dim == R_NilValue) + shape[0] = LENGTH(sexp); + else for (i = 0; i < nd; i++) { + shape[i] = INTEGER(dim)[i]; + } +} + +static void +sexp_strides(SEXP sexp, Py_intptr_t *strides, Py_ssize_t itemsize, + Py_intptr_t *shape, int nd) +{ + /* Set the buffer 'strides', that is a vector or Py_intptr_t + * containing the offset (in bytes) when progressing along + * each dimension. + */ + int i; + strides[0] = itemsize; + for (i = 1; i < nd; i++) { + strides[i] = shape[i-1] * strides[i-1]; + } +} + + +#if PY_VERSION_HEX >= 0x02060000 + +static int +VectorSexp_getbuffer(PyObject *obj, Py_buffer *view, int flags) +{ + + if (view == NULL) { + return 0; + } + + if ((flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) { + PyErr_SetString(PyExc_ValueError, "Only FORTRAN-style contiguous arrays allowed."); + return -1; + } + + view->obj = obj; + if (obj) { + Py_INCREF(obj); + } + view->readonly = 0; + + PySexpObject *self = (PySexpObject *)obj; + SEXP sexp = RPY_SEXP(self); + + switch (TYPEOF(sexp)) { + case REALSXP: + view->buf = NUMERIC_POINTER(sexp); + view->len = GET_LENGTH(sexp) * sizeof(double); + view->itemsize = sizeof(double); + view->format = "d"; + break; + case INTSXP: + view->buf = INTEGER_POINTER(sexp); + view->len = GET_LENGTH(sexp) * sizeof(int); + view->itemsize = sizeof(int); + view->format = "i"; + break; + case LGLSXP: + view->buf = LOGICAL_POINTER(sexp); + view->len = GET_LENGTH(sexp) * sizeof(int); + view->itemsize = sizeof(int); + view->format = "i"; + break; + case CPLXSXP: + view->buf = COMPLEX_POINTER(sexp); + view->len = GET_LENGTH(sexp) * sizeof(Rcomplex); + view->itemsize = sizeof(Rcomplex); + view->format = "B"; /* FIXME: correct format for complex ? */ + break; + case RAWSXP: + view->buf = RAW_POINTER(sexp); + view->len = GET_LENGTH(sexp); + view->itemsize = 1; + view->format = "B"; + break; + default: + PyErr_Format(PyExc_ValueError, "Buffer for this type not yet supported."); + return -1; + } + + view->ndim = sexp_rank(sexp); + + view->shape = NULL; + if ((flags & PyBUF_ND) == PyBUF_ND) { + view->shape = (Py_intptr_t*)PyMem_Malloc(sizeof(Py_intptr_t) * view->ndim); + sexp_shape(sexp, view->shape, view->ndim); + } + + view->strides = NULL; + if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) { + view->strides = (Py_intptr_t*)PyMem_Malloc(sizeof(Py_intptr_t) * view->ndim); + sexp_strides(sexp, view->strides, view->itemsize, view->shape, view->ndim); + } + /* view->suboffsets = (Py_intptr_t*)PyMem_Malloc(sizeof(Py_intptr_t) * view->ndim); */ + /* int i; */ + /* for (i = 0; i < view->ndim; i++) { */ + /* view->suboffsets[i] = 0; */ + /* } */ + view->suboffsets = NULL; + view->internal = NULL; + return 0; +} +#endif + +#if (PY_VERSION_HEX < 0x03010000) +static Py_ssize_t +VectorSexp_getsegcount(PySexpObject *self, Py_ssize_t *lenp) +{ + + if (lenp == NULL) { + return 1; + } else { + printf("--->\n"); + return 0; + } +} + +static Py_ssize_t +VectorSexp_getreadbuf(PySexpObject *self, Py_ssize_t segment, + const void **ptrptr) +{ + if (segment != 0) { + PyErr_SetString(PyExc_ValueError, + "accessing non-existing data segment"); + return -1; + } + SEXP sexp = RPY_SEXP(self); + Py_ssize_t len; + + switch (TYPEOF(sexp)) { + case REALSXP: + *ptrptr = (void *)NUMERIC_POINTER(sexp); + len = GET_LENGTH(sexp) * sizeof(double); + break; + case INTSXP: + *ptrptr = (void *)INTEGER_POINTER(sexp); + len = GET_LENGTH(sexp) * sizeof(int); + break; + case LGLSXP: + *ptrptr = (void *)LOGICAL_POINTER(sexp); + len = GET_LENGTH(sexp) * sizeof(int); + break; + case CPLXSXP: + *ptrptr = (void *)COMPLEX_POINTER(sexp); + len = GET_LENGTH(sexp) * sizeof(Rcomplex); + break; + case RAWSXP: + *ptrptr = (void *)RAW_POINTER(sexp); + len = GET_LENGTH(sexp) * 1; + break; + default: + PyErr_Format(PyExc_ValueError, "Buffer for this type not yet supported."); + *ptrptr = NULL; + return -1; + } + return len; +} + +static Py_ssize_t +VectorSexp_getwritebuf(PySexpObject *self, Py_ssize_t segment, const void **ptrptr) +{ + printf("getwritebuf\n"); + /*FIXME: introduce a "writeable" flag for SexpVector objects ? */ + return VectorSexp_getreadbuf(self, segment, ptrptr); +} + +static Py_ssize_t +VectorSexp_getcharbuf(PySexpObject *self, Py_ssize_t segment, const char **ptrptr) +{ + /*FIXME: introduce a "writeable" flag for SexpVector objects ? */ + return VectorSexp_getreadbuf(self, segment, (const void **)ptrptr); +} +#endif + +static PyBufferProcs VectorSexp_as_buffer = { +#if (PY_VERSION_HEX < 0x03010000) + (readbufferproc)VectorSexp_getreadbuf, + (writebufferproc)VectorSexp_getwritebuf, + (segcountproc)VectorSexp_getsegcount, + (charbufferproc)VectorSexp_getcharbuf, +#endif +#if PY_VERSION_HEX >= 0x02060000 + (getbufferproc)VectorSexp_getbuffer, + (releasebufferproc)0, +#endif +}; diff --git a/pool/shard008/C/0129645_hal_diag.c b/pool/shard008/C/0129645_hal_diag.c new file mode 100644 index 0000000000000000000000000000000000000000..3a8086a6714a62b78a6a6209e791af44ce57cb64 --- /dev/null +++ b/pool/shard008/C/0129645_hal_diag.c @@ -0,0 +1,275 @@ +//============================================================================= +// +// hal_diag.c +// +// HAL diagnostic output code +// +//============================================================================= +//####ECOSGPLCOPYRIGHTBEGIN#### +// ------------------------------------------- +// This file is part of eCos, the Embedded Configurable Operating System. +// Copyright (C) 1998, 1999, 2000, 2001, 2002 Red Hat, Inc. +// +// eCos 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 or (at your option) any later version. +// +// eCos 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 eCos; if not, write to the Free Software Foundation, Inc., +// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. +// +// As a special exception, if other files instantiate templates or use macros +// or inline functions from this file, or you compile this file and link it +// with other works to produce a work based on this file, this file does not +// by itself cause the resulting work to be covered by the GNU General Public +// License. However the source code for this file must still be made available +// in accordance with section (3) of the GNU General Public License. +// +// This exception does not invalidate any other reasons why a work based on +// this file might be covered by the GNU General Public License. +// +// Alternative licenses for eCos may be arranged by contacting Red Hat, Inc. +// at http://sources.redhat.com/ecos/ecos-license/ +// ------------------------------------------- +//####ECOSGPLCOPYRIGHTEND#### +//============================================================================= +//#####DESCRIPTIONBEGIN#### +// +// Author(s): hmt +// Contributors:hmt, jskov +// Date: 1999-06-08 +// Purpose: HAL diagnostic output +// Description: Implementations of HAL diagnostic output support. +// +//####DESCRIPTIONEND#### +// +//============================================================================= + +#include + +#include // base types +#include // tracing macros +#include // assertion macros + +#include // IO macros +#include +#include // Interrupt macros + +#if defined(CYGDBG_HAL_DEBUG_GDB_INCLUDE_STUBS) +#include // hal_output_gdb_string +#endif + +#include +#include + + +void +cyg_hal_plf_comms_init(void) +{ + static int initialized = 0; + + if (initialized) + return; + initialized = 1; + + cyg_hal_plf_serial_init(); +} + + +#if !defined(CYGSEM_HAL_VIRTUAL_VECTOR_DIAG) + +//----------------------------------------------------------------------------- +// Select default diag channel to use + +//#define CYG_KERNEL_DIAG_ROMART +//#define CYG_KERNEL_DIAG_SERIAL + +#if !defined(CYG_KERNEL_DIAG_SERIAL) +#define CYG_KERNEL_DIAG_SERIAL +#endif + +#ifdef CYGDBG_DIAG_BUF +// Keep diag messages in a buffer for later [re]display + +int enable_diag_uart = 1; +int enable_diag_buf = 1; +static char diag_buf[40960*4]; +static int diag_buf_ptr = 0; + +static void +diag_putc(char c) +{ + if (enable_diag_buf) { + diag_buf[diag_buf_ptr++] = c; + if (diag_buf_ptr == sizeof(diag_buf)) diag_buf_ptr--; + } +} + +void +dump_diag_buf(int start, int len) +{ + int i; + enable_diag_uart = 1; + enable_diag_buf = 0; + if (len == 0) len = diag_buf_ptr; + diag_printf("\nDiag buf\n"); + for (i = start; i < len; i++) { + hal_diag_write_char(diag_buf[i]); + } +} +#endif // CYGDBG_DIAG_BUF + + +//----------------------------------------------------------------------------- +// MBX board specific serial output; using GDB protocol by default: + + +#if defined(CYG_KERNEL_DIAG_SERIAL) + +EPPC *eppc; + +void hal_diag_init(void) +{ + static int init = 0; + if (init) return; + init++; + + // hardwired base + eppc = eppc_base(); + + // init the actual serial port + cyg_hal_plf_serial_init_channel(); +#ifdef CYGSEM_HAL_DIAG_MANGLER_GDB +#ifndef CYG_HAL_STARTUP_ROM + // We are talking to GDB; ack the "go" packet! + cyg_hal_plf_serial_putc(eppc, '+'); +#endif +#endif +} + +void hal_diag_write_char_serial( char c ) +{ + unsigned long __state; + HAL_DISABLE_INTERRUPTS(__state); + cyg_hal_plf_serial_putc(eppc, c); + HAL_RESTORE_INTERRUPTS(__state); +} + +#if defined(CYG_HAL_STARTUP_ROM) || !defined(CYGDBG_HAL_DIAG_TO_DEBUG_CHAN) +void hal_diag_write_char(char c) +{ +#ifdef CYGDBG_DIAG_BUF + diag_putc(c); + if (!enable_diag_uart) return; +#endif // CYGDBG_DIAG_BUF + hal_diag_write_char_serial(c); +} + +#else // RAM start so encode for GDB + +void hal_diag_write_char(char c) +{ + static char line[100]; + static int pos = 0; + +#ifdef CYGDBG_DIAG_BUF + diag_putc(c); + if (!enable_diag_uart) return; +#endif // CYGDBG_DIAG_BUF + + // No need to send CRs + if( c == '\r' ) return; + + line[pos++] = c; + + if( c == '\n' || pos == sizeof(line) ) + { + CYG_INTERRUPT_STATE old; + + // Disable interrupts. This prevents GDB trying to interrupt us + // while we are in the middle of sending a packet. The serial + // receive interrupt will be seen when we re-enable interrupts + // later. + +#ifdef CYGDBG_HAL_DEBUG_GDB_INCLUDE_STUBS + CYG_HAL_GDB_ENTER_CRITICAL_IO_REGION(old); +#else + HAL_DISABLE_INTERRUPTS(old); +#endif + + while(1) + { + static char hex[] = "0123456789ABCDEF"; + cyg_uint8 csum = 0; + int i; + + hal_diag_write_char_serial('$'); + hal_diag_write_char_serial('O'); + csum += 'O'; + for( i = 0; i < pos; i++ ) + { + char ch = line[i]; + char h = hex[(ch>>4)&0xF]; + char l = hex[ch&0xF]; + hal_diag_write_char_serial(h); + hal_diag_write_char_serial(l); + csum += h; + csum += l; + } + hal_diag_write_char_serial('#'); + hal_diag_write_char_serial(hex[(csum>>4)&0xF]); + hal_diag_write_char_serial(hex[csum&0xF]); + +#ifndef CYGDBG_HAL_DEBUG_GDB_BREAK_SUPPORT + // only gobble characters if no interrupt handler to grab ^Cs + // is installed (which is exclusive with device driver use) + + // Wait for the ACK character '+' from GDB here and handle + // receiving a ^C instead. This is the reason for this clause + // being a loop. + c = cyg_hal_plf_serial_getc(eppc); + + if( c == '+' ) + break; // a good acknowledge +#if 0 + if( c1 == 3 ) { + // Ctrl-C: breakpoint. + breakpoint(); + break; + } +#endif + // otherwise, loop round again +#else + break; +#endif + } + + pos = 0; + + // And re-enable interrupts +#ifdef CYGDBG_HAL_DEBUG_GDB_INCLUDE_STUBS + CYG_HAL_GDB_LEAVE_CRITICAL_IO_REGION(old); +#else + HAL_RESTORE_INTERRUPTS(old); +#endif + + } +} +#endif // NOT def CYG_HAL_STARTUP_ROM + + +void hal_diag_read_char(char *c) +{ + *c = cyg_hal_plf_serial_getc(eppc); +} + +#endif // CYG_KERNEL_DIAG_SERIAL + +#endif // CYGSEM_HAL_VIRTUAL_VECTOR_DIAG + +// EOF hal_diag.c diff --git a/pool/shard008/C/0129647_CWE78_OS_Command_Injection__char_console_execlp_67a.c b/pool/shard008/C/0129647_CWE78_OS_Command_Injection__char_console_execlp_67a.c new file mode 100644 index 0000000000000000000000000000000000000000..ac8d517e4d8d7f3c0a40856c3cafa141fe5e66fc --- /dev/null +++ b/pool/shard008/C/0129647_CWE78_OS_Command_Injection__char_console_execlp_67a.c @@ -0,0 +1,139 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__char_console_execlp_67a.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-67a.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: console Read input from the console + * GoodSource: Fixed string + * Sinks: execlp + * BadSink : execute command with execlp + * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include + +#ifdef _WIN32 +#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT "cmd.exe" +#define COMMAND_ARG1 "/c" +#define COMMAND_ARG2 "dir " +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH "/bin/sh" +#define COMMAND_INT "sh" +#define COMMAND_ARG1 "-c" +#define COMMAND_ARG2 "ls " +#define COMMAND_ARG3 data +#endif + +#ifdef _WIN32 +#include +#define EXECLP _execlp +#else /* NOT _WIN32 */ +#define EXECLP execlp +#endif + +typedef struct _CWE78_OS_Command_Injection__char_console_execlp_67_structType +{ + char * structFirst; +} CWE78_OS_Command_Injection__char_console_execlp_67_structType; + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE78_OS_Command_Injection__char_console_execlp_67b_badSink(CWE78_OS_Command_Injection__char_console_execlp_67_structType myStruct); + +void CWE78_OS_Command_Injection__char_console_execlp_67_bad() +{ + char * data; + CWE78_OS_Command_Injection__char_console_execlp_67_structType myStruct; + char dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + { + /* Read input from the console */ + size_t dataLen = strlen(data); + /* if there is room in data, read into it from the console */ + if (100-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgets() */ + dataLen = strlen(data); + if (dataLen > 0 && data[dataLen-1] == '\n') + { + data[dataLen-1] = '\0'; + } + } + else + { + printLine("fgets() failed"); + /* Restore NUL terminator if fgets fails */ + data[dataLen] = '\0'; + } + } + } + myStruct.structFirst = data; + CWE78_OS_Command_Injection__char_console_execlp_67b_badSink(myStruct); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE78_OS_Command_Injection__char_console_execlp_67b_goodG2BSink(CWE78_OS_Command_Injection__char_console_execlp_67_structType myStruct); + +static void goodG2B() +{ + char * data; + CWE78_OS_Command_Injection__char_console_execlp_67_structType myStruct; + char dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + /* FIX: Append a fixed string to data (not user / external input) */ + strcat(data, "*.*"); + myStruct.structFirst = data; + CWE78_OS_Command_Injection__char_console_execlp_67b_goodG2BSink(myStruct); +} + +void CWE78_OS_Command_Injection__char_console_execlp_67_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__char_console_execlp_67_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__char_console_execlp_67_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard008/C/0129648_messaging.c b/pool/shard008/C/0129648_messaging.c new file mode 100644 index 0000000000000000000000000000000000000000..2c0639a53ad2b723fb03dcedd71b80572fd97486 --- /dev/null +++ b/pool/shard008/C/0129648_messaging.c @@ -0,0 +1,92 @@ +#include "weather.h" +#include "messaging.h" +#include "settings.h" + +void messaging_requestNewWeatherData() { + // just send an empty message for now + DictionaryIterator *iter; + app_message_outbox_begin(&iter); + dict_write_uint32(iter, 0, 0); + app_message_outbox_send(); +} + + +void messaging_init(void (*processed_callback)(void)) { + // register my custom callback + message_processed_callback = processed_callback; + + // Register callbacks + app_message_register_inbox_received(inbox_received_callback); + app_message_register_inbox_dropped(inbox_dropped_callback); + app_message_register_outbox_failed(outbox_failed_callback); + app_message_register_outbox_sent(outbox_sent_callback); + + // Open AppMessage + app_message_open(app_message_inbox_size_maximum(), app_message_outbox_size_maximum()); + + APP_LOG(APP_LOG_LEVEL_DEBUG, "Watch messaging is started!"); + app_message_register_inbox_received(inbox_received_callback); +} + +void inbox_received_callback(DictionaryIterator *iterator, void *context) { + // does this message contain weather information? + Tuple *weatherTemp_tuple = dict_find(iterator, KEY_TEMPERATURE); + Tuple *weatherConditions_tuple = dict_find(iterator, KEY_CONDITION_CODE); + Tuple *weatherIsNight_tuple = dict_find(iterator, KEY_USE_NIGHT_ICON); + + if(weatherTemp_tuple != NULL && weatherConditions_tuple != NULL && weatherIsNight_tuple != NULL) { + bool isNight = (bool)weatherIsNight_tuple->value->int32; + + // now set the weather conditions properly + Weather_weatherInfo.currentTemp = (int)weatherTemp_tuple->value->int32; + Weather_setCondition((int)weatherConditions_tuple->value->int32, isNight); + } + + // does this message contain new config information? + Tuple *timeColor_tuple = dict_find(iterator, KEY_SETTING_COLOR_TIME); + Tuple *bgColor_tuple = dict_find(iterator, KEY_SETTING_COLOR_BG); + Tuple *sidebarColor_tuple = dict_find(iterator, KEY_SETTING_COLOR_SIDEBAR); + Tuple *sidebarPos_tuple = dict_find(iterator, KEY_SETTING_SIDEBAR_RIGHT); + Tuple *useMetric_tuple = dict_find(iterator, KEY_SETTING_USE_METRIC); + Tuple *btVibe_tuple = dict_find(iterator, KEY_SETTING_BT_VIBE); + + if(timeColor_tuple != NULL) { + globalSettings.timeColor = GColorFromHEX(timeColor_tuple->value->int32); + } + + if(bgColor_tuple != NULL) { + globalSettings.timeBgColor = GColorFromHEX(bgColor_tuple->value->int32); + } + + if(sidebarColor_tuple != NULL) { + globalSettings.sidebarColor = GColorFromHEX(sidebarColor_tuple->value->int32); + } + + if(sidebarPos_tuple != NULL) { + globalSettings.sidebarOnRight = (bool)sidebarPos_tuple->value->int8; + } + + if(useMetric_tuple != NULL) { + globalSettings.useMetric = (bool)useMetric_tuple->value->int8; + } + + if(btVibe_tuple != NULL) { + globalSettings.btVibe = (bool)btVibe_tuple->value->int8; + } + + // notify the main screen, in case something changed + message_processed_callback(); +} + +void inbox_dropped_callback(AppMessageResult reason, void *context) { + APP_LOG(APP_LOG_LEVEL_ERROR, "Message dropped!"); +} + +void outbox_failed_callback(DictionaryIterator *iterator, AppMessageResult reason, void *context) { + APP_LOG(APP_LOG_LEVEL_ERROR, "Outbox send failed! %d %d %d", reason, APP_MSG_SEND_TIMEOUT, APP_MSG_SEND_REJECTED); + +} + +void outbox_sent_callback(DictionaryIterator *iterator, void *context) { + APP_LOG(APP_LOG_LEVEL_INFO, "Outbox send success!"); +} \ No newline at end of file diff --git a/pool/shard008/C/0129651_fwide.c b/pool/shard008/C/0129651_fwide.c new file mode 100644 index 0000000000000000000000000000000000000000..a060d8f6590d202f9130627cb6204be891048939 --- /dev/null +++ b/pool/shard008/C/0129651_fwide.c @@ -0,0 +1,89 @@ +/* +FUNCTION +<>---set and determine the orientation of a FILE stream + +INDEX + fwide +INDEX + _fwide_r + +ANSI_SYNOPSIS + #include + int fwide(FILE *<[fp]>, int <[mode]>) + + int _fwide_r(struct _reent *<[ptr]>, FILE *<[fp]>, int <[mode]>) + +TRAD_SYNOPSIS + #include + int fwide(<[fp]>, <[mode]>) + FILE *<[fp]>; + int <[mode]>; + + int _fwide_r(<[ptr]>, <[fp]>, <[mode]>) + struct _reent *<[ptr]>; + FILE *<[fp]>; + int <[mode]>; + +DESCRIPTION +When <[mode]> is zero, the <> function determines the current +orientation of <[fp]>. It returns a value > 0 if <[fp]> is +wide-character oriented, i.e. if wide character I/O is permitted but +char I/O is disallowed. It returns a value < 0 if <[fp]> is byte +oriented, i.e. if char I/O is permitted but wide character I/O is +disallowed. It returns zero if <[fp]> has no orientation yet; in +this case the next I/O operation might change the orientation (to byte +oriented if it is a char I/O operation, or to wide-character oriented +if it is a wide character I/O operation). + +Once a stream has an orientation, it cannot be changed and persists +until the stream is closed, unless the stream is re-opened with freopen, +which removes the orientation of the stream. + +When <[mode]> is non-zero, the <> function first attempts to set +<[fp]>'s orientation (to wide-character oriented if <[mode]> > 0, or to +byte oriented if <[mode]> < 0). It then returns a value denoting the +current orientation, as above. + +RETURNS +The <> function returns <[fp]>'s orientation, after possibly +changing it. A return value > 0 means wide-character oriented. A return +value < 0 means byte oriented. A return value of zero means undecided. + +PORTABILITY +C99, POSIX.1-2001. + +*/ + +#include <_ansi.h> +#include +#include "local.h" + +int +_DEFUN(_fwide_r, (ptr, fp, mode), + struct _reent *ptr _AND + FILE *fp _AND + int mode) +{ + int ret; + + CHECK_INIT(ptr, fp); + + _newlib_flockfile_start (fp); + if (mode != 0) { + ORIENT (fp, mode); + } + if (!(fp->_flags & __SORD)) + ret = 0; + else + ret = (fp->_flags2 & __SWID) ? 1 : -1; + _newlib_flockfile_end (fp); + return ret; +} + +int +_DEFUN(fwide, (fp, mode), + FILE *fp _AND + int mode) +{ + return _fwide_r (_REENT, fp, mode); +} diff --git a/pool/shard008/C/0129652_courage.c b/pool/shard008/C/0129652_courage.c new file mode 100644 index 0000000000000000000000000000000000000000..d0024f75001886cd1d7ea992a5fb1da2c09c2f51 --- /dev/null +++ b/pool/shard008/C/0129652_courage.c @@ -0,0 +1,92 @@ +#include +#include +#define min(a, b) a r || cr < l) + return NULL; + else if (cl >= l && cr <= r) { + return tree+i; + } + else { + int mid = (cl + cr) / 2; + struct node* a = count(l, r, 2*i, cl, mid); + struct node* b = count(l, r, 2*i+1, mid+1, cr); + if (a != NULL && b != NULL) { + struct node* result = (struct node*) calloc(1, sizeof(struct node)); + result->sum = a->sum + b->sum; + result->m = min(a->m, b->m); + return result; + } + else if (a != NULL) + return a; + else if (b != NULL) + return b; + } +} + +int main(void) { + char choice[10]; + int n; + scanf("%d", &n); + int i; + for (i = 0; i < n; i++) + scanf("%lld", a+i); + build(1, 0, n-1); + int p, x, y; + scanf("%d", &p); + while (p--) { + scanf("%s %d %d", choice, &x, &y); + if (choice[0] == 'E') + update(y, 1, 0, n-1, -x); + else if (choice[0] == 'G') + update(y, 1, 0, n-1, x); + else { + struct node* ans = count(x, y, 1, 0, n-1); + printf("%lld\n", ans->sum - ans->m); + } + } + return 0; +} + diff --git a/pool/shard008/C/0129657_dns_resolver_connectivity_test.c b/pool/shard008/C/0129657_dns_resolver_connectivity_test.c new file mode 100644 index 0000000000000000000000000000000000000000..8e15faa1dd8d0e1ea09a7b7fc714e3ff73e9f5db --- /dev/null +++ b/pool/shard008/C/0129657_dns_resolver_connectivity_test.c @@ -0,0 +1,172 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include + +#include +#include + +#include "src/core/ext/filters/client_channel/resolver.h" +#include "src/core/ext/filters/client_channel/resolver_registry.h" +#include "src/core/lib/channel/channel_args.h" +#include "src/core/lib/iomgr/combiner.h" +#include "src/core/lib/iomgr/resolve_address.h" +#include "src/core/lib/iomgr/timer.h" +#include "test/core/util/test_config.h" + +static gpr_mu g_mu; +static bool g_fail_resolution = true; +static grpc_combiner *g_combiner; + +static void my_resolve_address(grpc_exec_ctx *exec_ctx, const char *addr, + const char *default_port, + grpc_pollset_set *interested_parties, + grpc_closure *on_done, + grpc_resolved_addresses **addrs) { + gpr_mu_lock(&g_mu); + GPR_ASSERT(0 == strcmp("test", addr)); + grpc_error *error = GRPC_ERROR_NONE; + if (g_fail_resolution) { + g_fail_resolution = false; + gpr_mu_unlock(&g_mu); + error = GRPC_ERROR_CREATE_FROM_STATIC_STRING("Forced Failure"); + } else { + gpr_mu_unlock(&g_mu); + *addrs = gpr_malloc(sizeof(**addrs)); + (*addrs)->naddrs = 1; + (*addrs)->addrs = gpr_malloc(sizeof(*(*addrs)->addrs)); + (*addrs)->addrs[0].len = 123; + } + grpc_closure_sched(exec_ctx, on_done, error); +} + +static grpc_resolver *create_resolver(grpc_exec_ctx *exec_ctx, + const char *name) { + grpc_resolver_factory *factory = grpc_resolver_factory_lookup("dns"); + grpc_uri *uri = grpc_uri_parse(exec_ctx, name, 0); + GPR_ASSERT(uri); + grpc_resolver_args args; + memset(&args, 0, sizeof(args)); + args.uri = uri; + args.combiner = g_combiner; + grpc_resolver *resolver = + grpc_resolver_factory_create_resolver(exec_ctx, factory, &args); + grpc_resolver_factory_unref(factory); + grpc_uri_destroy(uri); + return resolver; +} + +static void on_done(grpc_exec_ctx *exec_ctx, void *ev, grpc_error *error) { + gpr_event_set(ev, (void *)1); +} + +// interleave waiting for an event with a timer check +static bool wait_loop(int deadline_seconds, gpr_event *ev) { + while (deadline_seconds) { + gpr_log(GPR_DEBUG, "Test: waiting for %d more seconds", deadline_seconds); + if (gpr_event_wait(ev, grpc_timeout_seconds_to_deadline(1))) return true; + deadline_seconds--; + + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_timer_check(&exec_ctx, gpr_now(GPR_CLOCK_MONOTONIC), NULL); + grpc_exec_ctx_finish(&exec_ctx); + } + return false; +} + +typedef struct next_args { + grpc_resolver *resolver; + grpc_channel_args **result; + grpc_closure *on_complete; +} next_args; + +static void call_resolver_next_now_lock_taken(grpc_exec_ctx *exec_ctx, + void *arg, + grpc_error *error_unused) { + next_args *a = arg; + grpc_resolver_next_locked(exec_ctx, a->resolver, a->result, a->on_complete); + gpr_free(a); +} + +static void call_resolver_next_after_locking(grpc_exec_ctx *exec_ctx, + grpc_resolver *resolver, + grpc_channel_args **result, + grpc_closure *on_complete) { + next_args *a = gpr_malloc(sizeof(*a)); + a->resolver = resolver; + a->result = result; + a->on_complete = on_complete; + grpc_closure_sched( + exec_ctx, + grpc_closure_create(call_resolver_next_now_lock_taken, a, + grpc_combiner_scheduler(resolver->combiner, false)), + GRPC_ERROR_NONE); +} + +int main(int argc, char **argv) { + grpc_test_init(argc, argv); + + grpc_init(); + gpr_mu_init(&g_mu); + g_combiner = grpc_combiner_create(NULL); + grpc_resolve_address = my_resolve_address; + grpc_channel_args *result = (grpc_channel_args *)1; + + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_resolver *resolver = create_resolver(&exec_ctx, "dns:test"); + gpr_event ev1; + gpr_event_init(&ev1); + call_resolver_next_after_locking( + &exec_ctx, resolver, &result, + grpc_closure_create(on_done, &ev1, grpc_schedule_on_exec_ctx)); + grpc_exec_ctx_flush(&exec_ctx); + GPR_ASSERT(wait_loop(5, &ev1)); + GPR_ASSERT(result == NULL); + + gpr_event ev2; + gpr_event_init(&ev2); + call_resolver_next_after_locking( + &exec_ctx, resolver, &result, + grpc_closure_create(on_done, &ev2, grpc_schedule_on_exec_ctx)); + grpc_exec_ctx_flush(&exec_ctx); + GPR_ASSERT(wait_loop(30, &ev2)); + GPR_ASSERT(result != NULL); + + grpc_channel_args_destroy(&exec_ctx, result); + GRPC_RESOLVER_UNREF(&exec_ctx, resolver, "test"); + GRPC_COMBINER_UNREF(&exec_ctx, g_combiner, "test"); + grpc_exec_ctx_finish(&exec_ctx); + + grpc_shutdown(); + gpr_mu_destroy(&g_mu); +} diff --git a/pool/shard008/C/0129661_gdbstub.c b/pool/shard008/C/0129661_gdbstub.c new file mode 100644 index 0000000000000000000000000000000000000000..89d38980bf15bd9210b026893840b1a1028aebca --- /dev/null +++ b/pool/shard008/C/0129661_gdbstub.c @@ -0,0 +1,56 @@ +/* + * MicroBlaze gdb server stub + * + * Copyright (c) 2003-2005 Fabrice Bellard + * Copyright (c) 2013 SUSE LINUX Products GmbH + * + * 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 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. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + */ +#include "qemu/osdep.h" +#include "qemu-common.h" +#include "exec/gdbstub.h" + +int mb_cpu_gdb_read_register(CPUState *cs, uint8_t *mem_buf, int n) +{ + MicroBlazeCPU *cpu = MICROBLAZE_CPU(cs); + CPUMBState *env = &cpu->env; + + if (n < 32) { + return gdb_get_reg32(mem_buf, env->regs[n]); + } else { + return gdb_get_reg32(mem_buf, env->sregs[n - 32]); + } + return 0; +} + +int mb_cpu_gdb_write_register(CPUState *cs, uint8_t *mem_buf, int n) +{ + MicroBlazeCPU *cpu = MICROBLAZE_CPU(cs); + CPUClass *cc = CPU_GET_CLASS(cs); + CPUMBState *env = &cpu->env; + uint32_t tmp; + + if (n > cc->gdb_num_core_regs) { + return 0; + } + + tmp = ldl_p(mem_buf); + + if (n < 32) { + env->regs[n] = tmp; + } else { + env->sregs[n - 32] = tmp; + } + return 4; +} diff --git a/pool/shard008/C/0129662_PJ_aitoff.c b/pool/shard008/C/0129662_PJ_aitoff.c new file mode 100644 index 0000000000000000000000000000000000000000..8090bd78d2b53139544bb945a6d61003a2217923 --- /dev/null +++ b/pool/shard008/C/0129662_PJ_aitoff.c @@ -0,0 +1,82 @@ +/****************************************************************************** + * $Id: PJ_aitoff.c,v 1.3 2002/12/14 19:32:27 warmerda Exp $ + * + * Project: PROJ.4 + * Purpose: Implementation of the aitoff (Aitoff) and wintri (Winkel Tripel) + * projections. + * Author: Gerald Evenden + * + ****************************************************************************** + * Copyright (c) 1995, Gerald Evenden + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + ****************************************************************************** + * + * $Log: PJ_aitoff.c,v $ + * Revision 1.3 2002/12/14 19:32:27 warmerda + * updated header + * + */ + +#define PROJ_PARMS__ \ + double cosphi1; \ + int mode; +#define PJ_LIB__ +#include "projects.h" + +PJ_CVSID("$Id: PJ_aitoff.c,v 1.3 2002/12/14 19:32:27 warmerda Exp $"); + +PROJ_HEAD(aitoff, "Aitoff") "\n\tMisc Sph"; +PROJ_HEAD(wintri, "Winkel Tripel") "\n\tMisc Sph\n\tlat_1"; + +FORWARD(s_forward); /* spheroid */ + double c, d; + + if((d = acos(cos(lp.phi) * cos(c = 0.5 * lp.lam)))) {/* basic Aitoff */ + xy.x = 2. * d * cos(lp.phi) * sin(c) * (xy.y = 1. / sin(d)); + xy.y *= d * sin(lp.phi); + } else + xy.x = xy.y = 0.; + if (P->mode) { /* Winkel Tripel */ + xy.x = (xy.x + lp.lam * P->cosphi1) * 0.5; + xy.y = (xy.y + lp.phi) * 0.5; + } + return (xy); +} +FREEUP; if (P) pj_dalloc(P); } + static PJ * +setup(PJ *P) { + P->inv = 0; + P->fwd = s_forward; + P->es = 0.; + return P; +} +ENTRY0(aitoff) + P->mode = 0; +ENDENTRY(setup(P)) +ENTRY0(wintri) + P->mode = 1; + if (pj_param(P->params, "tlat_1").i) + { + if ((P->cosphi1 = cos(pj_param(P->params, "rlat_1").f)) == 0.) + E_ERROR(-22) + } + else /* 50d28' or acos(2/pi) */ + P->cosphi1 = 0.636619772367581343; +ENDENTRY(setup(P)) diff --git a/pool/shard008/C/0129664_ndblookval.c b/pool/shard008/C/0129664_ndblookval.c new file mode 100644 index 0000000000000000000000000000000000000000..47294ea81f725a8fe9eb166866b0d8bcdd4caab5 --- /dev/null +++ b/pool/shard008/C/0129664_ndblookval.c @@ -0,0 +1,53 @@ +/* + * This file is part of the UCB release of Plan 9. It is subject to the license + * terms in the LICENSE file found in the top-level directory of this + * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No + * part of the UCB release of Plan 9, including this file, may be copied, + * modified, propagated, or distributed except according to the terms contained + * in the LICENSE file. + */ + +#include +#include +#include +#include +#include + +/* + * Look for a pair with the given attribute. look first on the same line, + * then in the whole entry. + */ +Ndbtuple* +ndbfindattr(Ndbtuple *entry, Ndbtuple *line, char *attr) +{ + Ndbtuple *nt; + + /* first look on same line (closer binding) */ + for(nt = line; nt;){ + if(strcmp(attr, nt->attr) == 0) + return nt; + nt = nt->line; + if(nt == line) + break; + } + + /* search whole tuple */ + for(nt = entry; nt; nt = nt->entry) + if(strcmp(attr, nt->attr) == 0) + return nt; + + return nil; +} + +Ndbtuple* +ndblookval(Ndbtuple *entry, Ndbtuple *line, char *attr, char *to) +{ + Ndbtuple *t; + + t = ndbfindattr(entry, line, attr); + if(t != nil){ + strncpy(to, t->val, Ndbvlen-1); + to[Ndbvlen-1] = 0; + } + return t; +} diff --git a/pool/shard008/C/0129665_lis3lv02d_spi.c b/pool/shard008/C/0129665_lis3lv02d_spi.c new file mode 100644 index 0000000000000000000000000000000000000000..31c42b60e8b053bb4b93350e3124118e719f8d53 --- /dev/null +++ b/pool/shard008/C/0129665_lis3lv02d_spi.c @@ -0,0 +1,135 @@ + + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "lis3lv02d.h" + +#define DRV_NAME "lis3lv02d_spi" +#define LIS3_SPI_READ 0x80 + +static int lis3_spi_read(struct lis3lv02d *lis3, int reg, u8 *v) +{ + struct spi_device *spi = lis3->bus_priv; + int ret = spi_w8r8(spi, reg | LIS3_SPI_READ); + if (ret < 0) + return -EINVAL; + + *v = (u8) ret; + return 0; +} + +static int lis3_spi_write(struct lis3lv02d *lis3, int reg, u8 val) +{ + u8 tmp[2] = { reg, val }; + struct spi_device *spi = lis3->bus_priv; + return spi_write(spi, tmp, sizeof(tmp)); +} + +static int lis3_spi_init(struct lis3lv02d *lis3) +{ + u8 reg; + int ret; + + + ret = lis3->read(lis3, CTRL_REG1, ®); + if (ret < 0) + return ret; + + reg |= CTRL1_PD0; + return lis3->write(lis3, CTRL_REG1, reg); +} + +static struct axis_conversion lis3lv02d_axis_normal = { 1, 2, 3 }; + +static int __devinit lis302dl_spi_probe(struct spi_device *spi) +{ + int ret; + + spi->bits_per_word = 8; + spi->mode = SPI_MODE_0; + ret = spi_setup(spi); + if (ret < 0) + return ret; + + lis3_dev.bus_priv = spi; + lis3_dev.init = lis3_spi_init; + lis3_dev.read = lis3_spi_read; + lis3_dev.write = lis3_spi_write; + lis3_dev.irq = spi->irq; + lis3_dev.ac = lis3lv02d_axis_normal; + lis3_dev.pdata = spi->dev.platform_data; + spi_set_drvdata(spi, &lis3_dev); + + return lis3lv02d_init_device(&lis3_dev); +} + +static int __devexit lis302dl_spi_remove(struct spi_device *spi) +{ + struct lis3lv02d *lis3 = spi_get_drvdata(spi); + lis3lv02d_joystick_disable(); + lis3lv02d_poweroff(lis3); + + return lis3lv02d_remove_fs(&lis3_dev); +} + +#ifdef CONFIG_PM +static int lis3lv02d_spi_suspend(struct spi_device *spi, pm_message_t mesg) +{ + struct lis3lv02d *lis3 = spi_get_drvdata(spi); + + if (!lis3->pdata->wakeup_flags) + lis3lv02d_poweroff(&lis3_dev); + + return 0; +} + +static int lis3lv02d_spi_resume(struct spi_device *spi) +{ + struct lis3lv02d *lis3 = spi_get_drvdata(spi); + + if (!lis3->pdata->wakeup_flags) + lis3lv02d_poweron(lis3); + + return 0; +} + +#else +#define lis3lv02d_spi_suspend NULL +#define lis3lv02d_spi_resume NULL +#endif + +static struct spi_driver lis302dl_spi_driver = { + .driver = { + .name = DRV_NAME, + .owner = THIS_MODULE, + }, + .probe = lis302dl_spi_probe, + .remove = __devexit_p(lis302dl_spi_remove), + .suspend = lis3lv02d_spi_suspend, + .resume = lis3lv02d_spi_resume, +}; + +static int __init lis302dl_init(void) +{ + return spi_register_driver(&lis302dl_spi_driver); +} + +static void __exit lis302dl_exit(void) +{ + spi_unregister_driver(&lis302dl_spi_driver); +} + +module_init(lis302dl_init); +module_exit(lis302dl_exit); + +MODULE_AUTHOR("Daniel Mack "); +MODULE_DESCRIPTION("lis3lv02d SPI glue layer"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("spi:" DRV_NAME); diff --git a/pool/shard008/C/0129677_dmsub.c b/pool/shard008/C/0129677_dmsub.c new file mode 100644 index 0000000000000000000000000000000000000000..16be6170e4fe3da5114323527a5918d95b5df389 --- /dev/null +++ b/pool/shard008/C/0129677_dmsub.c @@ -0,0 +1,59 @@ +#include "io.h" + +int main(void) +{ + long long rt, rs; + long long achi, acli; + long long acho, aclo; + long long resh, resl; + achi = 0x1; + acli = 0x8; + + rs = 0x0000000100000001; + rt = 0x0000000200000002; + + resh = 0x1; + resl = 0x4; + + __asm + ("mthi %2, $ac1 \t\n" + "mtlo %3, $ac1 \t\n" + "dmsub $ac1, %4, %5\t\n" + "mfhi %0, $ac1 \t\n" + "mflo %1, $ac1 \t\n" + : "=r"(acho), "=r"(aclo) + : "r"(achi), "r"(acli), "r"(rs), "r"(rt) + ); + if ((acho != resh) || (aclo != resl)) { + printf("1 dmsub error\n"); + + return -1; + } + + achi = 0xfffffffF; + acli = 0xfffffffF; + + rs = 0x8888999977776666; + rt = 0x9999888877776666; + + resh = 0xffffffffffffffff; + resl = 0x789aae13; + + __asm + ("mthi %2, $ac1 \t\n" + "mtlo %3, $ac1 \t\n" + "dmsub $ac1, %4, %5\t\n" + "mfhi %0, $ac1 \t\n" + "mflo %1, $ac1 \t\n" + : "=r"(acho), "=r"(aclo) + : "r"(achi), "r"(acli), "r"(rs), "r"(rt) + ); + + if ((acho != resh) || (aclo != resl)) { + printf("2 dmsub error\n"); + + return -1; + } + + return 0; +} diff --git a/pool/shard008/C/0129679_posc3.c b/pool/shard008/C/0129679_posc3.c new file mode 100644 index 0000000000000000000000000000000000000000..1f26a89a77216909952c7b6f0a4b9bd013ee187f --- /dev/null +++ b/pool/shard008/C/0129679_posc3.c @@ -0,0 +1,69 @@ +#include +#include "plumber.h" + +int sporth_posc3(sporth_stack *stack, void *ud) +{ + plumber_data *pd = ud; + SPFLOAT out; + sp_ftbl *tbl; + char *str; + SPFLOAT freq; + SPFLOAT amp; + sp_posc3 *posc3; + + switch(pd->mode) { + case PLUMBER_CREATE: + +#ifdef DEBUG_MODE + fprintf(stderr, "posc3: Creating\n"); +#endif + + sp_posc3_create(&posc3); + plumber_add_ugen(pd, SPORTH_POSC3, posc3); + if(sporth_check_args(stack, "ffs") != SPORTH_OK) { + fprintf(stderr,"Not enough arguments for posc3\n"); + stack->error++; + return PLUMBER_NOTOK; + } + str = sporth_stack_pop_string(stack); + amp = sporth_stack_pop_float(stack); + freq = sporth_stack_pop_float(stack); + if(plumber_ftmap_search(pd, str, &tbl) == PLUMBER_NOTOK) { + stack->error++; + return PLUMBER_NOTOK; + } + sp_posc3_init(pd->sp, posc3, tbl); + sporth_stack_push_float(stack, 0); + break; + case PLUMBER_INIT: + +#ifdef DEBUG_MODE + fprintf(stderr, "posc3: Initialising\n"); +#endif + + str = sporth_stack_pop_string(stack); + amp = sporth_stack_pop_float(stack); + freq = sporth_stack_pop_float(stack); + posc3 = pd->last->ud; + + sporth_stack_push_float(stack, 0); + break; + case PLUMBER_COMPUTE: + amp = sporth_stack_pop_float(stack); + freq = sporth_stack_pop_float(stack); + posc3 = pd->last->ud; + posc3->freq = freq; + posc3->amp = amp; + sp_posc3_compute(pd->sp, posc3, NULL, &out); + sporth_stack_push_float(stack, out); + break; + case PLUMBER_DESTROY: + posc3 = pd->last->ud; + sp_posc3_destroy(&posc3); + break; + default: + fprintf(stderr, "posc3: Unknown mode!\n"); + break; + } + return PLUMBER_OK; +} diff --git a/pool/shard008/C/0129682_fileio.c b/pool/shard008/C/0129682_fileio.c new file mode 100644 index 0000000000000000000000000000000000000000..b8711dcc57ab3b819fc9fbc3ad5c52d9b9747842 --- /dev/null +++ b/pool/shard008/C/0129682_fileio.c @@ -0,0 +1,272 @@ +/** + * @file lib/fileio.c + * @brief ファイルIO + * + * @author higashi + * @date 2011-12-20 higashi 新規作成 + * @version \$Id$ + * + * Copyright (C) 2011-2018 Tetsuya Higashi. All Rights Reserved. + */ +/* 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include /* fflush fdopen */ +#include /* read write */ +#include /* bool */ +#include /* open */ +#include /* va_start va_arg va_end */ +#include /* errno */ + +#include "def.h" +#include "log.h" +#include "fileio.h" + +/** + * 受信 + * + * @param[in] fd ソケット + * @param[in] vptr 受信バッファ + * @param[in] n バッファ長さ + * @retval EX_NG エラー + * @return 受信されたバイト数 + */ +ssize_t +readn(int fd, void *vptr, size_t n) +{ + size_t nleft = 0; /* 受信する残りのバイト数 */ + ssize_t nread = 0; /* 受信されたバイト数 */ + char *ptr = NULL; /* ポインタ */ + + ptr = (char *)vptr; + nleft = n; + while (nleft > 0) { + nread = read(fd, ptr, nleft); + if (nread < 0) { + if (errno == EINTR) + nread = 0; + else + return EX_NG; + } else if (nread == 0) { + break; + } + nleft -= nread; + ptr += nread; + } + return n - nleft; +} + +/** + * 送信 + * + * @param[in] fd ソケット + * @param[in] vptr 送信バッファ + * @param[in] n バッファ長さ + * @retval EX_NG エラー + * @return 送信されたバイト数 + */ +ssize_t +writen(int fd, const void *vptr, size_t n) +{ + size_t nleft = 0; /* 送信する残りのバイト数 */ + ssize_t nwritten = 0; /* 送信されたバイト数 */ + const char *ptr = NULL; /* ポインタ */ + + ptr = (char *)vptr; + nleft = n; + while (nleft > 0) { + nwritten = write(fd, ptr, nleft); + if (nwritten <= 0) { + if (errno == EINTR) + nwritten = 0; + else + return EX_NG; + } + nleft -= nwritten; + ptr += nwritten; + } + return n; +} + +/** + * パイプ複製 + * + * @param[in] fd ファイルディスクリプタ + * @retval EX_NG エラー + * @return ファイルディスクリプタ + */ +int +pipe_fd(const int fd) +{ + int pfd[] = {-1, -1}; /* pipe */ + int retval = 0; /* 戻り値 */ + int newfd = 0; /* dup2戻り値 */ + + if (fd < 0) + return EX_NG; + + retval = pipe(pfd); + if (retval < 0) { + outlog("pipe: pfd=%p", pfd); + return EX_NG; + } + + retval = close(fd); + if (retval < 0) { + outlog("close: fd=%d", fd); + return EX_NG; + } + + newfd = dup2(pfd[PIPE_W], fd); + if (newfd < 0) { + outlog("dup2: pfd[PIPE_W]=%d, fd=%d", pfd[PIPE_W], fd); + close_fd(&pfd[PIPE_R], &pfd[PIPE_W], NULL); + return EX_NG; + } + dbglog("newfd=%d, pfd[PIPE_W]=%d, fd=%d", newfd, pfd[PIPE_W], fd); + + close_fd(&pfd[PIPE_W], NULL); + + return pfd[PIPE_R]; +} + +/** + * パイプ複製 2 + * + * @param[in] pipefd パイプ + * @param[in] oldfd コピー元 + * @param[in] newfd コピー先 + */ +int +pipe_fd2(int *pipefd, int *oldfd, const int newfd) +{ + int retval = 0; /* 戻り値 */ + int fd = 0; /* dup戻り値 */ + + close_fd(pipefd, NULL); + + retval = close(newfd); + if (retval < 0) + outlog("close=%d", retval); + + fd = dup2(*oldfd, newfd); + if (fd < 0) { + outlog("dup2=%d", retval); + close_fd(oldfd, NULL); + return EX_NG; + } + + close_fd(oldfd, NULL); + + return fd; +} + +/** + * リダイレクト + * + * @param[in] fd ファイルディスクリプタ + * @param[in] path ファイルパス + * @retval EX_NG エラー + */ +int +redirect(int fd, const char *path) +{ + FILE *fp = NULL; /* ファイルポインタ */ + int f = 0; /* ファイルディスクリプタ */ + + if (fd < 0 || !path) + return EX_NG; + + /* フラッシュする */ + fp = fdopen(fd, "a+"); + if (!fp) { /* エラー */ + outlog("fdopen: fd=%d", fd); + } else { + if (fflush(fp) == EOF) + outlog("fflush: %p", fp); + } + + /* 書込権限の確認 */ + if (access(path, W_OK) < 0) { + outlog("access: %s", path); + return EX_NG; + } + + f = open(path, O_WRONLY|O_APPEND); + if (f < 0) { + outlog("open=%d", f); + return EX_NG; + } + + if (close(fd) < 0) + outlog("close: fd=%d", fd); + + if (dup2(f, fd) < 0) { + outlog("dup2"); + return EX_NG; + } + + if (close(f) < 0) + outlog("close: f=%d", f); + + return EX_OK; +} + +/** + * クローズ + * + * @param[in,out] fd ファイルディスクリプタ + * @param[in] ... 可変引数 + * @retval EX_NG エラー + * @attention 最後の引数はNULLにすること. + */ +int +close_fd(int *fd, ...) +{ + va_list ap; /* va_list */ + int *ptr = NULL; /* ポインタ */ + bool err = false; /* エラーフラグ */ + + dbglog("start"); + + if (fd && *fd >= 0) { + dbglog("%p fd=%d", fd, *fd); + if (close(*fd) < 0) { + outlog("close: fd=%d", *fd); + err = true; + } + } + *fd = -1; + + va_start(ap, fd); + + while ((ptr = va_arg(ap, int *)) != NULL) { + dbglog("%p ptr=%d", ptr, *ptr); + if (*ptr >= 0) { + if (close(*ptr) < 0) { + outlog("close: ptr=%d", *ptr); + err = true; + } + } + *ptr = -1; + } + va_end(ap); + + if (err) + return EX_NG; + + return EX_OK; +} + diff --git a/pool/shard008/C/0129685_pthread_mutexattr_setpshared.c b/pool/shard008/C/0129685_pthread_mutexattr_setpshared.c new file mode 100644 index 0000000000000000000000000000000000000000..dcf7be2019861014139655f9ce96f0806abbf5b2 --- /dev/null +++ b/pool/shard008/C/0129685_pthread_mutexattr_setpshared.c @@ -0,0 +1,100 @@ +/* + * ===================================================================================== + * + * Filename: pthread_mutexattr_setpshared.c + * + * Description: + * + * Version: 1.0 + * Created: 09/25/2017 11:46:24 AM + * Revision: none + * Compiler: gcc + * + * Author: YOUR NAME (), fengbohello@foxmail.com + * Organization: + * + * ===================================================================================== + */ +#include +#include +#include +#include +#include +#include "tool.h" + +#ifndef _POSIX_THREAD_PROCESS_SHARED +#error "This platform does not support process shared mutex" +#endif + +int main(int argc, char * argv[]) { + int usepid = 0; + if(argc > 1) { + usepid = 1; + } + int err = 0; + pthread_mutexattr_t attr; + err = pthread_mutexattr_init(&attr); + check_errno(err); + + int flag = 0; + err = pthread_mutexattr_getpshared(&attr, &flag); + check_errno(err); + switch(flag) { + case PTHREAD_PROCESS_SHARED : printf("PTHREAD_PROCESS_SHARED\n"); break; + case PTHREAD_PROCESS_PRIVATE : printf("PTHREAD_PROCESS_PRIVATE\n"); break; + default : printf("no such shared type : [%d]\n", flag); break; + } + + err = pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); + check_errno(err); + + flag = 0; + err = pthread_mutexattr_getpshared(&attr, &flag); + check_errno(err); + switch(flag) { + case PTHREAD_PROCESS_SHARED : printf("PTHREAD_PROCESS_SHARED\n"); break; + case PTHREAD_PROCESS_PRIVATE : printf("PTHREAD_PROCESS_PRIVATE\n"); break; + default : printf("no such shared type : [%d]\n", flag); break; + } + +#if 0 + err = pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST); + check_errno(err); +#endif + + pthread_mutex_t mtx; + err = pthread_mutex_init(&mtx, &attr); + check_errno(err); + + pid_t pid = 0; + if(usepid) { + pid = fork(); + if(pid < 0) { + xdebug("fork faild"); + return -1; + } + } + xdebug("wait mutex in process [%d]", getpid()); + while(1) { + //err = pthread_mutex_trylock(&mtx); + err = pthread_mutex_lock(&mtx); + if(0 == err) { + xdebug("get lock in process [%d]", getpid()); + break; + } + check_errno(err); + xdebug("mutex is busy, in process [%d]", getpid()); + usleep(3000000);//3 sec + } + sleep(2); + pthread_mutex_unlock(&mtx); + xdebug("release mutex in process [%d]", getpid()); + if(0 != pid) { + int st = 0; + xdebug("wait child [%d]", pid); + waitpid(pid, &st, 0); + } + + return 0; +} + diff --git a/pool/shard008/C/0129690_reset-ipq4019.c b/pool/shard008/C/0129690_reset-ipq4019.c new file mode 100644 index 0000000000000000000000000000000000000000..f216db4ce5c2efff19607b311286b49bffc2987e --- /dev/null +++ b/pool/shard008/C/0129690_reset-ipq4019.c @@ -0,0 +1,173 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Copyright (c) 2020 Sartura Ltd. + * + * Author: Robert Marko + * + * Based on Linux driver + */ + +#include +#include +#include +#include +#include +#include +#include + +struct ipq4019_reset_priv { + phys_addr_t base; +}; + +struct qcom_reset_map { + unsigned int reg; + u8 bit; +}; + +static const struct qcom_reset_map gcc_ipq4019_resets[] = { + [WIFI0_CPU_INIT_RESET] = { 0x1f008, 5 }, + [WIFI0_RADIO_SRIF_RESET] = { 0x1f008, 4 }, + [WIFI0_RADIO_WARM_RESET] = { 0x1f008, 3 }, + [WIFI0_RADIO_COLD_RESET] = { 0x1f008, 2 }, + [WIFI0_CORE_WARM_RESET] = { 0x1f008, 1 }, + [WIFI0_CORE_COLD_RESET] = { 0x1f008, 0 }, + [WIFI1_CPU_INIT_RESET] = { 0x20008, 5 }, + [WIFI1_RADIO_SRIF_RESET] = { 0x20008, 4 }, + [WIFI1_RADIO_WARM_RESET] = { 0x20008, 3 }, + [WIFI1_RADIO_COLD_RESET] = { 0x20008, 2 }, + [WIFI1_CORE_WARM_RESET] = { 0x20008, 1 }, + [WIFI1_CORE_COLD_RESET] = { 0x20008, 0 }, + [USB3_UNIPHY_PHY_ARES] = { 0x1e038, 5 }, + [USB3_HSPHY_POR_ARES] = { 0x1e038, 4 }, + [USB3_HSPHY_S_ARES] = { 0x1e038, 2 }, + [USB2_HSPHY_POR_ARES] = { 0x1e01c, 4 }, + [USB2_HSPHY_S_ARES] = { 0x1e01c, 2 }, + [PCIE_PHY_AHB_ARES] = { 0x1d010, 11 }, + [PCIE_AHB_ARES] = { 0x1d010, 10 }, + [PCIE_PWR_ARES] = { 0x1d010, 9 }, + [PCIE_PIPE_STICKY_ARES] = { 0x1d010, 8 }, + [PCIE_AXI_M_STICKY_ARES] = { 0x1d010, 7 }, + [PCIE_PHY_ARES] = { 0x1d010, 6 }, + [PCIE_PARF_XPU_ARES] = { 0x1d010, 5 }, + [PCIE_AXI_S_XPU_ARES] = { 0x1d010, 4 }, + [PCIE_AXI_M_VMIDMT_ARES] = { 0x1d010, 3 }, + [PCIE_PIPE_ARES] = { 0x1d010, 2 }, + [PCIE_AXI_S_ARES] = { 0x1d010, 1 }, + [PCIE_AXI_M_ARES] = { 0x1d010, 0 }, + [ESS_RESET] = { 0x12008, 0}, + [GCC_BLSP1_BCR] = {0x01000, 0}, + [GCC_BLSP1_QUP1_BCR] = {0x02000, 0}, + [GCC_BLSP1_UART1_BCR] = {0x02038, 0}, + [GCC_BLSP1_QUP2_BCR] = {0x03008, 0}, + [GCC_BLSP1_UART2_BCR] = {0x03028, 0}, + [GCC_BIMC_BCR] = {0x04000, 0}, + [GCC_TLMM_BCR] = {0x05000, 0}, + [GCC_IMEM_BCR] = {0x0E000, 0}, + [GCC_ESS_BCR] = {0x12008, 0}, + [GCC_PRNG_BCR] = {0x13000, 0}, + [GCC_BOOT_ROM_BCR] = {0x13008, 0}, + [GCC_CRYPTO_BCR] = {0x16000, 0}, + [GCC_SDCC1_BCR] = {0x18000, 0}, + [GCC_SEC_CTRL_BCR] = {0x1A000, 0}, + [GCC_AUDIO_BCR] = {0x1B008, 0}, + [GCC_QPIC_BCR] = {0x1C000, 0}, + [GCC_PCIE_BCR] = {0x1D000, 0}, + [GCC_USB2_BCR] = {0x1E008, 0}, + [GCC_USB2_PHY_BCR] = {0x1E018, 0}, + [GCC_USB3_BCR] = {0x1E024, 0}, + [GCC_USB3_PHY_BCR] = {0x1E034, 0}, + [GCC_SYSTEM_NOC_BCR] = {0x21000, 0}, + [GCC_PCNOC_BCR] = {0x2102C, 0}, + [GCC_DCD_BCR] = {0x21038, 0}, + [GCC_SNOC_BUS_TIMEOUT0_BCR] = {0x21064, 0}, + [GCC_SNOC_BUS_TIMEOUT1_BCR] = {0x2106C, 0}, + [GCC_SNOC_BUS_TIMEOUT2_BCR] = {0x21074, 0}, + [GCC_SNOC_BUS_TIMEOUT3_BCR] = {0x2107C, 0}, + [GCC_PCNOC_BUS_TIMEOUT0_BCR] = {0x21084, 0}, + [GCC_PCNOC_BUS_TIMEOUT1_BCR] = {0x2108C, 0}, + [GCC_PCNOC_BUS_TIMEOUT2_BCR] = {0x21094, 0}, + [GCC_PCNOC_BUS_TIMEOUT3_BCR] = {0x2109C, 0}, + [GCC_PCNOC_BUS_TIMEOUT4_BCR] = {0x210A4, 0}, + [GCC_PCNOC_BUS_TIMEOUT5_BCR] = {0x210AC, 0}, + [GCC_PCNOC_BUS_TIMEOUT6_BCR] = {0x210B4, 0}, + [GCC_PCNOC_BUS_TIMEOUT7_BCR] = {0x210BC, 0}, + [GCC_PCNOC_BUS_TIMEOUT8_BCR] = {0x210C4, 0}, + [GCC_PCNOC_BUS_TIMEOUT9_BCR] = {0x210CC, 0}, + [GCC_TCSR_BCR] = {0x22000, 0}, + [GCC_MPM_BCR] = {0x24000, 0}, + [GCC_SPDM_BCR] = {0x25000, 0}, +}; + +static int ipq4019_reset_assert(struct reset_ctl *rst) +{ + struct ipq4019_reset_priv *priv = dev_get_priv(rst->dev); + const struct qcom_reset_map *reset_map = gcc_ipq4019_resets; + const struct qcom_reset_map *map; + u32 value; + + map = &reset_map[rst->id]; + + value = readl(priv->base + map->reg); + value |= BIT(map->bit); + writel(value, priv->base + map->reg); + + return 0; +} + +static int ipq4019_reset_deassert(struct reset_ctl *rst) +{ + struct ipq4019_reset_priv *priv = dev_get_priv(rst->dev); + const struct qcom_reset_map *reset_map = gcc_ipq4019_resets; + const struct qcom_reset_map *map; + u32 value; + + map = &reset_map[rst->id]; + + value = readl(priv->base + map->reg); + value &= ~BIT(map->bit); + writel(value, priv->base + map->reg); + + return 0; +} + +static int ipq4019_reset_free(struct reset_ctl *rst) +{ + return 0; +} + +static int ipq4019_reset_request(struct reset_ctl *rst) +{ + return 0; +} + +static const struct reset_ops ipq4019_reset_ops = { + .request = ipq4019_reset_request, + .rfree = ipq4019_reset_free, + .rst_assert = ipq4019_reset_assert, + .rst_deassert = ipq4019_reset_deassert, +}; + +static const struct udevice_id ipq4019_reset_ids[] = { + { .compatible = "qcom,gcc-reset-ipq4019" }, + { } +}; + +static int ipq4019_reset_probe(struct udevice *dev) +{ + struct ipq4019_reset_priv *priv = dev_get_priv(dev); + + priv->base = dev_read_addr(dev); + if (priv->base == FDT_ADDR_T_NONE) + return -EINVAL; + + return 0; +} + +U_BOOT_DRIVER(ipq4019_reset) = { + .name = "ipq4019_reset", + .id = UCLASS_RESET, + .of_match = ipq4019_reset_ids, + .ops = &ipq4019_reset_ops, + .probe = ipq4019_reset_probe, + .priv_auto_alloc_size = sizeof(struct ipq4019_reset_priv), +}; diff --git a/pool/shard008/C/0129695_listener.c b/pool/shard008/C/0129695_listener.c new file mode 100644 index 0000000000000000000000000000000000000000..17f85e38bf35a02f43ef5f33c4d52c1a7d6624c8 --- /dev/null +++ b/pool/shard008/C/0129695_listener.c @@ -0,0 +1,101 @@ +/* +** listener.c - a datagram sockets "server" demo +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MYPORT "6000" //the port users will be connecting to + +#define MAXBUFLEN 100 + +//get sockaddr, IPv4 or IPv6: +void *get_in_addr(struct sockaddr *sa) +{ + if (sa->sa_family == AF_INET) + { + return &(((struct sockaddr_in*)sa)->sin_addr); + } + + return &(((struct sockaddr_in6*)sa)->sin6_addr); +} + +int main(int argc, char *argv[]) +{ + int sockfd; + struct addrinfo hints, *servinfo, *p; //listen on sock_fd + int rv; + int numbytes; + struct sockaddr_storage their_addr; //client's address information + char buf[MAXBUFLEN]; + socklen_t addr_len; + char s[INET6_ADDRSTRLEN]; + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; //AF_INET or AF_INET6 to force version + hints.ai_socktype = SOCK_DGRAM; //create UDP socket, SOCK_STREAM for TCP, SOCK_RAW to bypass transport layer + hints.ai_flags = AI_PASSIVE; //fill in my IP for me if no IP address or domain name is specified in getaddrinfo() + + //create structs for a socket + if ((rv = getaddrinfo(NULL, MYPORT, &hints, &servinfo)) != 0) + { + printf("Listener: getaddrinfo() error: %s\n", gai_strerror(rv)); + return 1; + } + + //loop through all the results and bind to the first we can + for(p = servinfo; p != NULL; p = p->ai_next) + { + //create a socket descriptor + if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) + { + printf("Listener: Error creating Socket Descriptor\n"); + continue; + } + + //bind socket to the IP address and port + if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) + { + close(sockfd); + printf("Listener: Error binding Socket Decriptor to IP Address and Port\n"); + continue; + } + + break; + } + + if (p == NULL) + { + printf("Listener: Socket Creation and Bind failed\n"); + return 2; + } + + freeaddrinfo(servinfo); //all done with this struct + + printf("Listener: waiting to recvfrom()...\n"); + + addr_len = sizeof(their_addr); + if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0, (struct sockaddr *)&their_addr, &addr_len)) == -1) + { + printf("Listener: recvfrom() failed"); + exit(1); + } + + inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof(s)); + printf("Listener: Got packet from %s\n", s); + printf("Listener: Packet is %d bytes long\n", numbytes); + buf[numbytes] = '\0'; + printf("Listener: Packet contains \"%s\"\n", buf); + + close(sockfd); + + return 0; +} diff --git a/pool/shard008/C/0129698_addext.c b/pool/shard008/C/0129698_addext.c new file mode 100644 index 0000000000000000000000000000000000000000..550a610e63468d2e7fd67579d1381df6aee4742d --- /dev/null +++ b/pool/shard008/C/0129698_addext.c @@ -0,0 +1,103 @@ +/* addext.c -- add an extension to a file name + Copyright (C) 1990, 1997-1999, 2001-2003 Free Software Foundation, Inc. + + 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, 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; see the file COPYING. + If not, write to the Free Software Foundation, + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ + +/* Written by David MacKenzie and Paul Eggert */ + +#if HAVE_CONFIG_H +# include +#endif + +#ifndef HAVE_DOS_FILE_NAMES +# define HAVE_DOS_FILE_NAMES 0 +#endif +#ifndef HAVE_LONG_FILE_NAMES +# define HAVE_LONG_FILE_NAMES 0 +#endif + +#include "backupfile.h" + +#include +#ifndef _POSIX_NAME_MAX +# define _POSIX_NAME_MAX 14 +#endif + +#include +#if HAVE_STRING_H +# include +#else +# include +#endif + +#if HAVE_UNISTD_H +# include +#endif + +#include "basename.h" + +/* Append to FILENAME the extension EXT, unless the result would be too long, + in which case just append the character E. */ + +void +addext (char *filename, char const *ext, char e) +{ + char *s = basename (filename); + size_t slen = strlen (s), extlen = strlen (ext); + long slen_max = -1; + +#if HAVE_PATHCONF && defined _PC_NAME_MAX + if (slen + extlen <= _POSIX_NAME_MAX && ! HAVE_DOS_FILE_NAMES) + /* The file name is so short there's no need to call pathconf. */ + slen_max = _POSIX_NAME_MAX; + else if (s == filename) + slen_max = pathconf (".", _PC_NAME_MAX); + else + { + char c = *s; + *s = 0; + slen_max = pathconf (filename, _PC_NAME_MAX); + *s = c; + } +#endif + if (slen_max < 0) + slen_max = HAVE_LONG_FILE_NAMES ? 255 : 14; + + if (HAVE_DOS_FILE_NAMES && slen_max <= 12) + { + /* Live within DOS's 8.3 limit. */ + char *dot = strchr (s, '.'); + if (dot) + { + slen -= dot + 1 - s; + s = dot + 1; + slen_max = 3; + } + else + slen_max = 8; + extlen = 9; /* Don't use EXT. */ + } + + if (slen + extlen <= slen_max) + strcpy (s + slen, ext); + else + { + if (slen_max <= slen) + slen = slen_max - 1; + s[slen] = e; + s[slen + 1] = 0; + } +} diff --git a/pool/shard008/C/0129704_cnf-renumber.c b/pool/shard008/C/0129704_cnf-renumber.c new file mode 100644 index 0000000000000000000000000000000000000000..e6d7dae2aa5e10fd89a4320cc73deaeaa49c2a97 --- /dev/null +++ b/pool/shard008/C/0129704_cnf-renumber.c @@ -0,0 +1,237 @@ +/***************************************************************************** +intocr -- Copyright (c) 2011 Martin Maurer + +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 . +******************************************************************************/ + +#include +#include +#include +#include + +long *variables; +long *new_variables; +unsigned long *clause_length; +long **clauses; +long *one_clause; + +int main(int argc, char** argv) +{ + unsigned long nr_of_variables, nr_of_clauses; + unsigned long nr_of_new_variables, nr_of_fixed_variable, nr_of_new_clauses; + unsigned long current_nr_of_clause; + unsigned long current_nr_of_literal; + unsigned long preallocated_space_for_literals; + unsigned long i; + + FILE * outfile; + FILE * infile; + + long literal; + long factor; + char needOutFile = 0; + + nr_of_new_clauses = 0; + + if (argc == 1) { + infile = stdin; + //infile = fdopen(0, "r"); + //printf("c reading from stdin\n"); + } else { + infile = fopen(argv[1], "r"); + assert(infile != NULL); + } + + if(fscanf(infile, "p cnf %lu %lu\n", &nr_of_variables, &nr_of_clauses) != 2) + { + fprintf(stderr, "error: expected: p cnf \n"); + exit(1); + } + //printf("c num vars: %ld\n", nr_of_variables); + //printf("c num clauses: %ld\n", nr_of_clauses); + + variables = (long *)malloc((nr_of_variables + 1) * sizeof(long)); + if(variables == 0) + { + fprintf(stderr, "error allocating memory for variables\n"); + exit(1); + } + + new_variables = (long *)malloc((nr_of_variables + 1) * sizeof(long)); + if(new_variables == 0) + { + fprintf(stderr, "error allocating memory for new_variables\n"); + exit(1); + } + + for(i = 1; i <= nr_of_variables; i++) + { + variables[i] = new_variables[i] = 0; // means undef + } + + clause_length = (unsigned long *)malloc(nr_of_clauses * sizeof(unsigned long)); + if(clause_length == 0) + { + fprintf(stderr, "error allocating memory for clause_length\n"); + exit(1); + } + + clauses = (long **)malloc(nr_of_clauses * sizeof(unsigned long *)); + if(clauses == 0) + { + fprintf(stderr, "error allocating memory for clauses\n"); + exit(1); + } + + preallocated_space_for_literals = 128; + one_clause = (long *)malloc(preallocated_space_for_literals * sizeof(long)); + + //Read through the CNF file + for(current_nr_of_clause = 0; current_nr_of_clause < nr_of_clauses; current_nr_of_clause++) + { + //Read one clause + next: + current_nr_of_literal = 0; + while(1) + { + if(fscanf(infile, "%ld", &literal) != 1) + { + //Check if we are at comment + if (current_nr_of_literal == 0) { + char c; + int ret = fscanf(infile, "%c", &c); + assert(ret == 1); + if (c == 'c') { + while(c != '\n') { + int ret = fscanf(infile, "%c", &c); + assert(ret == 1); + } + goto next; + } + } + + //Not comment, so error! + fprintf(stderr, "error reading file (clause %lu)\n", current_nr_of_clause + 1); + exit(1); + } + + //End of clause + if (literal == 0) + break; + + one_clause[current_nr_of_literal++] = literal; + + if (current_nr_of_literal == preallocated_space_for_literals) + { + preallocated_space_for_literals *= 2; + one_clause = (long *)realloc(one_clause, preallocated_space_for_literals * sizeof(long)); + } + } + + //reading end of line + int ret = fscanf(infile, "\n"); + assert(ret == 1); + + //Check if the clause was unit + if(current_nr_of_literal == 1) + { + //It was unit + variables[abs(one_clause[0])] = one_clause[0]; + } + else + { + //It was a longer clause, so allocate space + clause_length[nr_of_new_clauses] = current_nr_of_literal; + clauses[nr_of_new_clauses] = (long *)malloc(current_nr_of_literal * sizeof(long)); + memcpy(clauses[nr_of_new_clauses], one_clause, current_nr_of_literal * sizeof(long)); + nr_of_new_clauses++; + } + } + //printf("c finished reading CNF\n"); + + //Re-Numbering variables + for(i = 1,nr_of_new_variables = 0,nr_of_fixed_variable=0; i <= nr_of_variables; i++) + { + if(variables[i] == 0) // means undef + { + nr_of_new_variables++; + new_variables[i] = nr_of_new_variables; + } + else + { + nr_of_fixed_variable++; + } + } + + //Print to file the variables that have been set + if (needOutFile) { + outfile = fopen("outfile.tmp", "w" ); + if (outfile == NULL) { + fprintf(stderr, "Cannot write to file output.tmp\n"); + exit(-1); + } + fprintf(outfile, "p tmp %lu %lu\n", nr_of_fixed_variable, nr_of_variables); + + for(i = 1; i <= nr_of_variables; i++) + { + if(variables[i] != 0) // means undef + { + fprintf(outfile, "%ld 0\n", variables[i]); + } + } + + fclose(outfile); + } + + + //Print to console simplified CNF + printf("p cnf %lu %lu\n", nr_of_new_variables, nr_of_new_clauses); + long lit; + for(current_nr_of_clause = 0; current_nr_of_clause < nr_of_new_clauses; current_nr_of_clause++) + { + //Print clause + for(current_nr_of_literal = 0; current_nr_of_literal < clause_length[current_nr_of_clause]; current_nr_of_literal++) + { + lit = clauses[current_nr_of_clause][current_nr_of_literal]; + factor = 1; + if (lit < 0) { + factor = -1; + } + + //Only print variable if not set + if (variables[abs(lit)] != 0) { + printf("ERROR: clause contains variable set: "); + for (i = 0; i < clause_length[current_nr_of_clause]; i++) { + printf("%ld ", clauses[current_nr_of_clause][i]); + } + printf("0\n"); + assert(0); + } + printf("%ld ", ((long int)new_variables[abs(lit)])*factor); + } + printf("0\n"); + + //Free clause printed + free(clauses[current_nr_of_clause]); + } + + //Free structures + free(variables); + free(new_variables); + free(clause_length); + free(clauses); + free(one_clause); + + return 0; +} diff --git a/pool/shard008/C/0129705_fault.c b/pool/shard008/C/0129705_fault.c new file mode 100644 index 0000000000000000000000000000000000000000..4a7cdd9ea1ee70c2522c25f926233cf9101895b2 --- /dev/null +++ b/pool/shard008/C/0129705_fault.c @@ -0,0 +1,346 @@ +/* + * linux/arch/cris/mm/fault.c + * + * Copyright (C) 2000-2006 Axis Communications AB + * + * Authors: Bjorn Wesen + * + */ + +#include +#include +#include +#include + +extern int find_fixup_code(struct pt_regs *); +extern void die_if_kernel(const char *, struct pt_regs *, long); + +/* debug of low-level TLB reload */ +#undef DEBUG + +#ifdef DEBUG +#define D(x) x +#else +#define D(x) +#endif + +/* debug of higher-level faults */ +#define DPG(x) + +/* current active page directory */ + +DEFINE_PER_CPU(pgd_t *, current_pgd); +unsigned long cris_signal_return_page; + +/* + * This routine handles page faults. It determines the address, + * and the problem, and then passes it off to one of the appropriate + * routines. + * + * Notice that the address we're given is aligned to the page the fault + * occurred in, since we only get the PFN in R_MMU_CAUSE not the complete + * address. + * + * error_code: + * bit 0 == 0 means no page found, 1 means protection fault + * bit 1 == 0 means read, 1 means write + * + * If this routine detects a bad access, it returns 1, otherwise it + * returns 0. + */ + +asmlinkage void +do_page_fault(unsigned long address, struct pt_regs *regs, + int protection, int writeaccess) +{ + struct task_struct *tsk; + struct mm_struct *mm; + struct vm_area_struct * vma; + siginfo_t info; + int fault; + + D(printk(KERN_DEBUG + "Page fault for %lX on %X at %lX, prot %d write %d\n", + address, smp_processor_id(), instruction_pointer(regs), + protection, writeaccess)); + + tsk = current; + + /* + * We fault-in kernel-space virtual memory on-demand. The + * 'reference' page table is init_mm.pgd. + * + * NOTE! We MUST NOT take any locks for this case. We may + * be in an interrupt or a critical region, and should + * only copy the information from the master page table, + * nothing more. + * + * NOTE2: This is done so that, when updating the vmalloc + * mappings we don't have to walk all processes pgdirs and + * add the high mappings all at once. Instead we do it as they + * are used. However vmalloc'ed page entries have the PAGE_GLOBAL + * bit set so sometimes the TLB can use a lingering entry. + * + * This verifies that the fault happens in kernel space + * and that the fault was not a protection error (error_code & 1). + */ + + if (address >= VMALLOC_START && + !protection && + !user_mode(regs)) + goto vmalloc_fault; + + /* When stack execution is not allowed we store the signal + * trampolines in the reserved cris_signal_return_page. + * Handle this in the exact same way as vmalloc (we know + * that the mapping is there and is valid so no need to + * call handle_mm_fault). + */ + if (cris_signal_return_page && + address == cris_signal_return_page && + !protection && user_mode(regs)) + goto vmalloc_fault; + + /* we can and should enable interrupts at this point */ + local_irq_enable(); + + mm = tsk->mm; + info.si_code = SEGV_MAPERR; + + /* + * If we're in an interrupt or have no user + * context, we must not take the fault.. + */ + + if (in_interrupt() || !mm) + goto no_context; + + down_read(&mm->mmap_sem); + vma = find_vma(mm, address); + if (!vma) + goto bad_area; + if (vma->vm_start <= address) + goto good_area; + if (!(vma->vm_flags & VM_GROWSDOWN)) + goto bad_area; + if (user_mode(regs)) { + /* + * accessing the stack below usp is always a bug. + * we get page-aligned addresses so we can only check + * if we're within a page from usp, but that might be + * enough to catch brutal errors at least. + */ + if (address + PAGE_SIZE < rdusp()) + goto bad_area; + } + if (expand_stack(vma, address)) + goto bad_area; + + /* + * Ok, we have a good vm_area for this memory access, so + * we can handle it.. + */ + + good_area: + info.si_code = SEGV_ACCERR; + + /* first do some preliminary protection checks */ + + if (writeaccess == 2){ + if (!(vma->vm_flags & VM_EXEC)) + goto bad_area; + } else if (writeaccess == 1) { + if (!(vma->vm_flags & VM_WRITE)) + goto bad_area; + } else { + if (!(vma->vm_flags & (VM_READ | VM_EXEC))) + goto bad_area; + } + + /* + * If for any reason at all we couldn't handle the fault, + * make sure we exit gracefully rather than endlessly redo + * the fault. + */ + + fault = handle_mm_fault(mm, vma, address, (writeaccess & 1) ? FAULT_FLAG_WRITE : 0); + if (unlikely(fault & VM_FAULT_ERROR)) { + if (fault & VM_FAULT_OOM) + goto out_of_memory; + else if (fault & VM_FAULT_SIGBUS) + goto do_sigbus; + BUG(); + } + if (fault & VM_FAULT_MAJOR) + tsk->maj_flt++; + else + tsk->min_flt++; + + up_read(&mm->mmap_sem); + return; + + /* + * Something tried to access memory that isn't in our memory map.. + * Fix it, but check if it's kernel or user first.. + */ + + bad_area: + up_read(&mm->mmap_sem); + + bad_area_nosemaphore: + DPG(show_registers(regs)); + + /* User mode accesses just cause a SIGSEGV */ + + if (user_mode(regs)) { + info.si_signo = SIGSEGV; + info.si_errno = 0; + /* info.si_code has been set above */ + info.si_addr = (void *)address; + force_sig_info(SIGSEGV, &info, tsk); + printk(KERN_NOTICE "%s (pid %d) segfaults for page " + "address %08lx at pc %08lx\n", + tsk->comm, tsk->pid, address, instruction_pointer(regs)); + return; + } + + no_context: + + /* Are we prepared to handle this kernel fault? + * + * (The kernel has valid exception-points in the source + * when it acesses user-memory. When it fails in one + * of those points, we find it in a table and do a jump + * to some fixup code that loads an appropriate error + * code) + */ + + if (find_fixup_code(regs)) + return; + + /* + * Oops. The kernel tried to access some bad page. We'll have to + * terminate things with extreme prejudice. + */ + + if (!oops_in_progress) { + oops_in_progress = 1; + if ((unsigned long) (address) < PAGE_SIZE) + printk(KERN_ALERT "Unable to handle kernel NULL " + "pointer dereference"); + else + printk(KERN_ALERT "Unable to handle kernel access" + " at virtual address %08lx\n", address); + + die_if_kernel("Oops", regs, (writeaccess << 1) | protection); + oops_in_progress = 0; + } + + do_exit(SIGKILL); + + /* + * We ran out of memory, or some other thing happened to us that made + * us unable to handle the page fault gracefully. + */ + + out_of_memory: + up_read(&mm->mmap_sem); + printk("VM: killing process %s\n", tsk->comm); + if (user_mode(regs)) + do_exit(SIGKILL); + goto no_context; + + do_sigbus: + up_read(&mm->mmap_sem); + + /* + * Send a sigbus, regardless of whether we were in kernel + * or user mode. + */ + info.si_signo = SIGBUS; + info.si_errno = 0; + info.si_code = BUS_ADRERR; + info.si_addr = (void *)address; + force_sig_info(SIGBUS, &info, tsk); + + /* Kernel mode? Handle exceptions or die */ + if (!user_mode(regs)) + goto no_context; + return; + +vmalloc_fault: + { + /* + * Synchronize this task's top level page-table + * with the 'reference' page table. + * + * Use current_pgd instead of tsk->active_mm->pgd + * since the latter might be unavailable if this + * code is executed in a misfortunately run irq + * (like inside schedule() between switch_mm and + * switch_to...). + */ + + int offset = pgd_index(address); + pgd_t *pgd, *pgd_k; + pud_t *pud, *pud_k; + pmd_t *pmd, *pmd_k; + pte_t *pte_k; + + pgd = (pgd_t *)per_cpu(current_pgd, smp_processor_id()) + offset; + pgd_k = init_mm.pgd + offset; + + /* Since we're two-level, we don't need to do both + * set_pgd and set_pmd (they do the same thing). If + * we go three-level at some point, do the right thing + * with pgd_present and set_pgd here. + * + * Also, since the vmalloc area is global, we don't + * need to copy individual PTE's, it is enough to + * copy the pgd pointer into the pte page of the + * root task. If that is there, we'll find our pte if + * it exists. + */ + + pud = pud_offset(pgd, address); + pud_k = pud_offset(pgd_k, address); + if (!pud_present(*pud_k)) + goto no_context; + + pmd = pmd_offset(pud, address); + pmd_k = pmd_offset(pud_k, address); + + if (!pmd_present(*pmd_k)) + goto bad_area_nosemaphore; + + set_pmd(pmd, *pmd_k); + + /* Make sure the actual PTE exists as well to + * catch kernel vmalloc-area accesses to non-mapped + * addresses. If we don't do this, this will just + * silently loop forever. + */ + + pte_k = pte_offset_kernel(pmd_k, address); + if (!pte_present(*pte_k)) + goto no_context; + + return; + } +} + +/* Find fixup code. */ +int +find_fixup_code(struct pt_regs *regs) +{ + const struct exception_table_entry *fixup; + + if ((fixup = search_exception_tables(instruction_pointer(regs))) != 0) { + /* Adjust the instruction pointer in the stackframe. */ + instruction_pointer(regs) = fixup->fixup; + arch_fixup(regs); + return 1; + } + + return 0; +} diff --git a/pool/shard008/C/0129712_ef_set_axis_influence.c b/pool/shard008/C/0129712_ef_set_axis_influence.c new file mode 100644 index 0000000000000000000000000000000000000000..d478284530a284ef04c7f7247568c1b89bdef30d --- /dev/null +++ b/pool/shard008/C/0129712_ef_set_axis_influence.c @@ -0,0 +1,15 @@ +/* Make sure Python.h is included first */ +#include +#include "ferret.h" +#include "EF_Util.h" + +/* calls the 6D function with NO for the E and F axes */ +void FORTRAN(ef_set_axis_influence)(int *id_ptr, int *arg, int *xax, int *yax, int *zax, int *tax) +{ + int eax_val, fax_val; + + eax_val = NO; + fax_val = NO; + FORTRAN(ef_set_axis_influence_6d)(id_ptr, arg, xax, yax, zax, tax, &eax_val, &fax_val); +} + diff --git a/pool/shard008/C/0129713_transpose_generic.c b/pool/shard008/C/0129713_transpose_generic.c new file mode 100644 index 0000000000000000000000000000000000000000..571f62d45897692ca95aec4aa568548b72bce2fe --- /dev/null +++ b/pool/shard008/C/0129713_transpose_generic.c @@ -0,0 +1,151 @@ +/* Implementation of the TRANSPOSE intrinsic + Copyright (C) 2003-2013 Free Software Foundation, Inc. + Contributed by Tobias Schlüter + +This file is part of the GNU Fortran runtime library (libgfortran). + +Libgfortran 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. + +Libgfortran 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. + +Under Section 7 of GPL version 3, you are granted additional +permissions described in the GCC Runtime Library Exception, version +3.1, as published by the Free Software Foundation. + +You should have received a copy of the GNU General Public License and +a copy of the GCC Runtime Library Exception along with this program; +see the files COPYING3 and COPYING.RUNTIME respectively. If not, see +. */ + +#include "libgfortran.h" +#include +#include +#include + +extern void transpose (gfc_array_char *, gfc_array_char *); +export_proto(transpose); + +static void +transpose_internal (gfc_array_char *ret, gfc_array_char *source) +{ + /* r.* indicates the return array. */ + index_type rxstride, rystride; + char *rptr; + /* s.* indicates the source array. */ + index_type sxstride, systride; + const char *sptr; + + index_type xcount, ycount; + index_type x, y; + index_type size; + + assert (GFC_DESCRIPTOR_RANK (source) == 2 + && GFC_DESCRIPTOR_RANK (ret) == 2); + + size = GFC_DESCRIPTOR_SIZE(ret); + + if (ret->base_addr == NULL) + { + assert (ret->dtype == source->dtype); + + GFC_DIMENSION_SET(ret->dim[0], 0, GFC_DESCRIPTOR_EXTENT(source,1) - 1, + 1); + + GFC_DIMENSION_SET(ret->dim[1], 0, GFC_DESCRIPTOR_EXTENT(source,0) - 1, + GFC_DESCRIPTOR_EXTENT(source, 1)); + + ret->base_addr = xmalloc (size * size0 ((array_t*)ret)); + ret->offset = 0; + } + else if (unlikely (compile_options.bounds_check)) + { + index_type ret_extent, src_extent; + + ret_extent = GFC_DESCRIPTOR_EXTENT(ret,0); + src_extent = GFC_DESCRIPTOR_EXTENT(source,1); + + if (src_extent != ret_extent) + runtime_error ("Incorrect extent in return value of TRANSPOSE" + " intrinsic in dimension 1: is %ld," + " should be %ld", (long int) src_extent, + (long int) ret_extent); + + ret_extent = GFC_DESCRIPTOR_EXTENT(ret,1); + src_extent = GFC_DESCRIPTOR_EXTENT(source,0); + + if (src_extent != ret_extent) + runtime_error ("Incorrect extent in return value of TRANSPOSE" + " intrinsic in dimension 2: is %ld," + " should be %ld", (long int) src_extent, + (long int) ret_extent); + + } + + sxstride = GFC_DESCRIPTOR_STRIDE_BYTES(source,0); + systride = GFC_DESCRIPTOR_STRIDE_BYTES(source,1); + xcount = GFC_DESCRIPTOR_EXTENT(source,0); + ycount = GFC_DESCRIPTOR_EXTENT(source,1); + + rxstride = GFC_DESCRIPTOR_STRIDE_BYTES(ret,0); + rystride = GFC_DESCRIPTOR_STRIDE_BYTES(ret,1); + + rptr = ret->base_addr; + sptr = source->base_addr; + + for (y = 0; y < ycount; y++) + { + for (x = 0; x < xcount; x++) + { + memcpy (rptr, sptr, size); + + sptr += sxstride; + rptr += rystride; + } + sptr += systride - (sxstride * xcount); + rptr += rxstride - (rystride * xcount); + } +} + + +extern void transpose (gfc_array_char *, gfc_array_char *); +export_proto(transpose); + +void +transpose (gfc_array_char *ret, gfc_array_char *source) +{ + transpose_internal (ret, source); +} + + +extern void transpose_char (gfc_array_char *, GFC_INTEGER_4, + gfc_array_char *, GFC_INTEGER_4); +export_proto(transpose_char); + +void +transpose_char (gfc_array_char *ret, + GFC_INTEGER_4 ret_length __attribute__((unused)), + gfc_array_char *source, + GFC_INTEGER_4 source_length __attribute__((unused))) +{ + transpose_internal (ret, source); +} + + +extern void transpose_char4 (gfc_array_char *, GFC_INTEGER_4, + gfc_array_char *, GFC_INTEGER_4); +export_proto(transpose_char4); + +void +transpose_char4 (gfc_array_char *ret, + GFC_INTEGER_4 ret_length __attribute__((unused)), + gfc_array_char *source, + GFC_INTEGER_4 source_length __attribute__((unused))) +{ + transpose_internal (ret, source); +} diff --git a/pool/shard008/C/0129718_vect-outer-1-big-array.c b/pool/shard008/C/0129718_vect-outer-1-big-array.c new file mode 100644 index 0000000000000000000000000000000000000000..e277ab2ca33d3d453860a9e2d13e0c16648084c2 --- /dev/null +++ b/pool/shard008/C/0129718_vect-outer-1-big-array.c @@ -0,0 +1,27 @@ +/* { dg-do compile } */ + +#define N 256 +signed short image[N][N] __attribute__ ((__aligned__(__BIGGEST_ALIGNMENT__))); +signed short block[N][N] __attribute__ ((__aligned__(__BIGGEST_ALIGNMENT__))); +signed short out[N] __attribute__ ((__aligned__(__BIGGEST_ALIGNMENT__))); + +/* Can't do outer-loop vectorization because of non-consecutive access. */ + +void +foo (){ + int i,j; + int diff; + + for (i = 0; i < N; i++) { + diff = 0; + for (j = 0; j < N; j+=8) { + diff += (image[i][j] - block[i][j]); + } + out[i]=diff; + } +} + +/* { dg-final { scan-tree-dump-times "OUTER LOOP VECTORIZED" 1 "vect" { xfail *-*-* } } } */ +/* { dg-final { scan-tree-dump-times "strided access in outer loop" 1 "vect" { target { ! vect_multiple_sizes } } } } */ +/* { dg-final { scan-tree-dump-times "strided access in outer loop" 2 "vect" { target vect_multiple_sizes } } } */ +/* { dg-final { cleanup-tree-dump "vect" } } */ diff --git a/pool/shard008/C/0129720_GreatestMultiple.c b/pool/shard008/C/0129720_GreatestMultiple.c new file mode 100644 index 0000000000000000000000000000000000000000..f2c9615212e1afd40c325b39d52231dde71e2fe9 --- /dev/null +++ b/pool/shard008/C/0129720_GreatestMultiple.c @@ -0,0 +1,17 @@ +#include + +int main() { + int num1, num2; + scanf("%d", &num1); + scanf("%d", &num2); + if (num1 > num2) { + int temp = num1; + num1 = num2; + num2 = temp; + } + int multiplo = (num2 / num1) * num1; + if (multiplo <= num2) printf("%d\n", multiplo); + else printf("sem multiplos menores que %d", num2); +} + +//https://pt.stackoverflow.com/q/393490/101 diff --git a/pool/shard008/C/0129722_read_cache.c b/pool/shard008/C/0129722_read_cache.c new file mode 100644 index 0000000000000000000000000000000000000000..8142f1a6b31826643957b26b38e952840d07ab75 --- /dev/null +++ b/pool/shard008/C/0129722_read_cache.c @@ -0,0 +1,170 @@ +#include "read_cache.h" +#include "../media_clip.h" + +#define MIN_BUFFER_COUNT (2) + +void +read_cache_init(read_cache_state_t* state, request_context_t* request_context, size_t buffer_size) +{ + state->request_context = request_context; + state->buffer_size = buffer_size; + state->buffer_count = 0; + state->reuse_buffers = TRUE; +} + +vod_status_t +read_cache_allocate_buffer_slots(read_cache_state_t* state, size_t buffer_count) +{ + size_t alloc_size; + + if (buffer_count < MIN_BUFFER_COUNT) + { + buffer_count = MIN_BUFFER_COUNT; + } + + if (state->buffer_count >= buffer_count) + { + return VOD_OK; + } + + alloc_size = sizeof(state->buffers[0]) * buffer_count; + + state->buffers = vod_alloc(state->request_context->pool, alloc_size); + if (state->buffers == NULL) + { + vod_log_debug0(VOD_LOG_DEBUG_LEVEL, state->request_context->log, 0, + "read_cache_allocate_buffer_slots: vod_alloc failed"); + return VOD_ALLOC_FAILED; + } + + state->buffers_end = state->buffers + buffer_count; + state->buffer_count = buffer_count; + + vod_memzero(state->buffers, alloc_size); + + return VOD_OK; +} + +bool_t +read_cache_get_from_cache( + read_cache_state_t* state, + read_cache_request_t* request, + u_char** buffer, + uint32_t* size) +{ + media_clip_source_t* source = request->source; + read_cache_hint_t* hint; + cache_buffer_t* target_buffer; + cache_buffer_t* cur_buffer; + uint32_t read_size; + uint64_t aligned_last_offset; + uint64_t offset = request->cur_offset; + size_t alignment; + int cache_slot_id; + + // check whether we already have the requested offset + for (cur_buffer = state->buffers; cur_buffer < state->buffers_end; cur_buffer++) + { + if (cur_buffer->source == source && + offset >= cur_buffer->start_offset && offset < cur_buffer->end_offset) + { + *buffer = cur_buffer->buffer_pos + (offset - cur_buffer->start_offset); + *size = cur_buffer->end_offset - offset; + return TRUE; + } + } + + // don't have the offset in cache + alignment = source->alignment - 1; + cache_slot_id = request->cache_slot_id; + + // start reading from the min offset, if that would contain the whole frame + // Note: this condition is intended to optimize the case in which the frame order + // in the output segment is while on disk it's . + // in this case it would be better to start reading from the beginning, even + // though the first frame that is requested is the second one + hint = &request->hint; + if (hint->min_offset < offset && + hint->min_offset + state->buffer_size / 4 > offset && + request->end_offset < (hint->min_offset & ~alignment) + state->buffer_size) + { + offset = hint->min_offset; + cache_slot_id = hint->min_offset_slot_id; + } + offset &= ~alignment; + + // calculate the read size + read_size = state->buffer_size; + target_buffer = &state->buffers[cache_slot_id % state->buffer_count]; + + // don't read anything that is already in the cache + for (cur_buffer = state->buffers; cur_buffer < state->buffers_end; cur_buffer++) + { + if (cur_buffer == target_buffer || + cur_buffer->source != source) + { + continue; + } + + if (cur_buffer->start_offset > offset) + { + read_size = vod_min(read_size, cur_buffer->start_offset - offset); + } + else if (cur_buffer->end_offset > offset) + { + offset = cur_buffer->end_offset & ~alignment; + } + } + + // don't read past the max required offset + if (offset + read_size > source->last_offset) + { + aligned_last_offset = (source->last_offset + alignment) & ~alignment; + if (aligned_last_offset > offset) + { + read_size = aligned_last_offset - offset; + } + } + + target_buffer->source = source; + target_buffer->start_offset = offset; + target_buffer->buffer_size = read_size; + state->target_buffer = target_buffer; + + return FALSE; +} + +void +read_cache_disable_buffer_reuse(read_cache_state_t* state) +{ + state->reuse_buffers = FALSE; +} + +void +read_cache_get_read_buffer( + read_cache_state_t* state, + read_cache_get_read_buffer_t* result) +{ + cache_buffer_t* target_buffer = state->target_buffer; + + // return the target buffer pointer and size + result->source = target_buffer->source; + result->offset = target_buffer->start_offset; + result->buffer = state->reuse_buffers ? target_buffer->buffer_start : NULL; + result->size = target_buffer->buffer_size; +} + +void +read_cache_read_completed(read_cache_state_t* state, vod_buf_t* buf) +{ + cache_buffer_t* target_buffer = state->target_buffer; + + // update the buffer size + target_buffer->buffer_start = buf->start; + target_buffer->buffer_pos = buf->pos; + target_buffer->buffer_size = buf->last - buf->pos; + target_buffer->end_offset = target_buffer->start_offset + target_buffer->buffer_size; + + // no longer have an active request + state->target_buffer = NULL; +} diff --git a/pool/shard008/C/0129724_ckinit.c b/pool/shard008/C/0129724_ckinit.c new file mode 100644 index 0000000000000000000000000000000000000000..ff0464c8f27d2a48a95a123d7f8642072c2e7a2c --- /dev/null +++ b/pool/shard008/C/0129724_ckinit.c @@ -0,0 +1,120 @@ +/* ckinit.c + * + * This file provides a template for the clock device driver initialization. + * + * Modified for sun4v - niagara + */ + +/* + * Copyright (c) 2010 Gedare Bloom. + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rtems.org/license/LICENSE. + */ + +#include + +#include +#include +#include +#include + +/* This is default frequency for simics simulator of niagara. Use the + * get_Frequency function to determine the CPU clock frequency at runtime. + */ +#define CPU_FREQ (5000000) + +uint64_t sparc64_cycles_per_tick; + +/* TICK_CMPR and STICK_CMPR trigger soft interrupt 14 */ +#define CLOCK_VECTOR SPARC_SYNCHRONOUS_TRAP(0x4E) + +static unsigned int get_Frequency(void) +{ + phandle root = ofw_find_device("/"); + unsigned int freq; + + if (ofw_get_property(root, "clock-frequency", &freq, sizeof(freq)) <= 0) { + printk("Unable to determine frequency, default: 0x%x\n",CPU_FREQ); + return CPU_FREQ; + } + + return freq; +} + +static void Clock_driver_support_at_tick(void) +{ + uint64_t tick_reg; + int bit_mask; + uint64_t pil_reg; + + bit_mask = SPARC_SOFTINT_TM_MASK | SPARC_SOFTINT_SM_MASK | (1<<14); + sparc64_clear_interrupt_bits(bit_mask); + + sparc64_get_pil(pil_reg); + if(pil_reg == 0xe) { /* 0xe is the tick compare interrupt (softint(14)) */ + pil_reg--; + sparc64_set_pil(pil_reg); /* enable the next timer interrupt */ + } + /* Note: sun4v uses stick_cmpr for clock driver for M5 simulator, which + * does not currently have tick_cmpr implemented */ + /* TODO: this could be more efficiently implemented as a single assembly + * inline */ +#if defined (SUN4U) + sparc64_read_tick(tick_reg); +#elif defined (SUN4V) + sparc64_read_stick(tick_reg); +#endif + tick_reg &= ~(1UL<<63); /* mask out NPT bit, prevents int_dis from being set */ + + tick_reg += sparc64_cycles_per_tick; + +#if defined (SUN4U) + sparc64_write_tick_cmpr(tick_reg); +#elif defined (SUN4V) + sparc64_write_stick_cmpr(tick_reg); +#endif +} + +#define Clock_driver_support_install_isr(_new, _old) \ + do { \ + _old = set_vector( _new, CLOCK_VECTOR, 1 ); \ + } while ( 0 ) + +static void Clock_driver_support_initialize_hardware(void) +{ + uint64_t tick_reg; + int bit_mask; + + bit_mask = SPARC_SOFTINT_TM_MASK | SPARC_SOFTINT_SM_MASK | (1<<14); + sparc64_clear_interrupt_bits(bit_mask); + + sparc64_cycles_per_tick = + rtems_configuration_get_microseconds_per_tick()*(get_Frequency()/1000000); + +#if defined (SUN4U) + sparc64_read_tick(tick_reg); +#elif defined (SUN4V) + sparc64_read_stick(tick_reg); +#endif + + tick_reg &= ~(1UL<<63); /* mask out NPT bit, prevents int_dis from being set */ + tick_reg += sparc64_cycles_per_tick; + +#if defined (SUN4U) + sparc64_write_tick_cmpr(tick_reg); +#elif defined (SUN4V) + sparc64_write_stick_cmpr(tick_reg); +#endif +} + +#define Clock_driver_support_shutdown_hardware( ) \ + do { \ + \ + } while ( 0 ) + +#define CLOCK_DRIVER_USE_DUMMY_TIMECOUNTER + +#include "../../../shared/clockdrv_shell.h" + diff --git a/pool/shard008/C/0129726_main.c b/pool/shard008/C/0129726_main.c new file mode 100644 index 0000000000000000000000000000000000000000..e89b78c25b97b4cc9c2758c0f91df3d9a84a3ce9 --- /dev/null +++ b/pool/shard008/C/0129726_main.c @@ -0,0 +1,236 @@ +/* + * Copyright (c) 2016 Intel Corporation + * + * SPDX-License-Identifier: Apache-2.0 + */ + + +/** + * @brief Thread Tests + * @defgroup kernel_thread_tests Threads + * @ingroup all_tests + * @{ + * @} + */ + +#include +#include +#include +#include +#include + +extern void test_threads_spawn_params(void); +extern void test_threads_spawn_priority(void); +extern void test_threads_spawn_delay(void); +extern void test_threads_spawn_forever(void); +extern void test_thread_start(void); +extern void test_threads_suspend_resume_cooperative(void); +extern void test_threads_suspend_resume_preemptible(void); +extern void test_threads_abort_self(void); +extern void test_threads_abort_others(void); +extern void test_threads_abort_repeat(void); +extern void test_abort_handler(void); +extern void test_essential_thread_operation(void); +extern void test_threads_priority_set(void); +extern void test_delayed_thread_abort(void); +extern void test_k_thread_foreach(void); +extern void test_threads_cpu_mask(void); + +struct k_thread tdata; +#define STACK_SIZE (512 + CONFIG_TEST_EXTRA_STACKSIZE) +K_THREAD_STACK_DEFINE(tstack, STACK_SIZE); +size_t tstack_size = K_THREAD_STACK_SIZEOF(tstack); + +/*local variables*/ +static K_THREAD_STACK_DEFINE(tstack_custom, STACK_SIZE); +static K_THREAD_STACK_DEFINE(tstack_name, STACK_SIZE); +static struct k_thread tdata_custom; +static struct k_thread tdata_name; + +static int main_prio; + +/** + * @ingroup kernel_thread_tests + * @brief Verify main thread + */ +void test_systhreads_main(void) +{ + zassert_true(main_prio == CONFIG_MAIN_THREAD_PRIORITY, NULL); +} + +/** + * @ingroup kernel_thread_tests + * @brief Verify idle thread + */ +void test_systhreads_idle(void) +{ + k_sleep(100); + /** TESTPOINT: check working thread priority should */ + zassert_true(k_thread_priority_get(k_current_get()) < + K_IDLE_PRIO, NULL); +} + +static void thread_name_entry(void) +{ +} + +static void customdata_entry(void *p1, void *p2, void *p3) +{ + u32_t data = 1U; + + zassert_is_null(k_thread_custom_data_get(), NULL); + while (1) { + k_thread_custom_data_set((void *)data); + /* relinguish cpu for a while */ + k_sleep(50); + /** TESTPOINT: custom data comparison */ + zassert_equal(data, (u32_t)k_thread_custom_data_get(), NULL); + data++; + } +} + +/** + * @ingroup kernel_thread_tests + * @brief test thread custom data get/set from coop thread + * + * @see k_thread_custom_data_get(), k_thread_custom_data_set() + */ +void test_customdata_get_set_coop(void) +{ + k_tid_t tid = k_thread_create(&tdata_custom, tstack_custom, STACK_SIZE, + customdata_entry, NULL, NULL, NULL, + K_PRIO_COOP(1), 0, 0); + + k_sleep(500); + + /* cleanup environment */ + k_thread_abort(tid); +} + + +/** + * @ingroup kernel_thread_tests + * @brief test thread name get/set from preempt thread + * @see k_thread_name_get(), k_thread_name_set() + */ +void test_thread_name_get_set(void) +{ + int ret; + const char *thread_name; + + /* Set and get current thread's name */ + k_thread_name_set(NULL, "parent_thread"); + thread_name = k_thread_name_get(k_current_get()); + + ret = strcmp(thread_name, "parent_thread"); + zassert_equal(ret, 0, "parent thread name does not match"); + + /* Set and get child thread's name */ + k_tid_t tid = k_thread_create(&tdata_name, tstack_name, STACK_SIZE, + (k_thread_entry_t)thread_name_entry, + NULL, NULL, NULL, + K_PRIO_COOP(1), 0, 0); + + k_thread_name_set(tid, "customdata"); + + k_sleep(500); + + thread_name = k_thread_name_get(tid); + + ret = strcmp(thread_name, "customdata"); + zassert_equal(ret, 0, "child thread name does not match"); + + /* cleanup environment */ + k_thread_abort(tid); +} + +/** + * @ingroup kernel_thread_tests + * @brief test thread custom data get/set from preempt thread + * @see k_thread_custom_data_get(), k_thread_custom_data_set() + */ +void test_customdata_get_set_preempt(void) +{ + /** TESTPOINT: custom data of preempt thread */ + k_tid_t tid = k_thread_create(&tdata_custom, tstack_custom, STACK_SIZE, + customdata_entry, NULL, NULL, NULL, + K_PRIO_PREEMPT(0), K_USER, 0); + + k_sleep(500); + + /* cleanup environment */ + k_thread_abort(tid); +} + +#ifndef CONFIG_ARCH_HAS_USERSPACE +static void umode_entry(void *thread_id, void *p2, void *p3) +{ + ARG_UNUSED(p2); + ARG_UNUSED(p3); + + if (!z_is_thread_essential() && + (k_current_get() == (k_tid_t)thread_id)) { + ztest_test_pass(); + } else { + zassert_unreachable("User thread is essential or thread" + " structure is corrupted\n"); + } +} + +/** + * @ingroup kernel_thread_tests + * @brief Test k_thread_user_mode_enter() to cover when userspace + * is not supported/enabled + * @see k_thread_user_mode_enter() + */ +void test_user_mode(void) +{ + z_thread_essential_set(); + + zassert_true(z_is_thread_essential(), "Thread isn't set" + " as essential\n"); + + k_thread_user_mode_enter((k_thread_entry_t)umode_entry, + k_current_get(), NULL, NULL); +} +#else +void test_user_mode(void) +{ + ztest_test_skip(); +} +#endif + + +void test_main(void) +{ + k_thread_access_grant(k_current_get(), &tdata, tstack); + k_thread_access_grant(k_current_get(), &tdata_custom, tstack_custom); + main_prio = k_thread_priority_get(k_current_get()); + + ztest_test_suite(threads_lifecycle, + ztest_user_unit_test(test_threads_spawn_params), + ztest_unit_test(test_threads_spawn_priority), + ztest_user_unit_test(test_threads_spawn_delay), + ztest_unit_test(test_threads_spawn_forever), + ztest_unit_test(test_thread_start), + ztest_unit_test(test_threads_suspend_resume_cooperative), + ztest_unit_test(test_threads_suspend_resume_preemptible), + ztest_unit_test(test_threads_priority_set), + ztest_user_unit_test(test_threads_abort_self), + ztest_user_unit_test(test_threads_abort_others), + ztest_unit_test(test_threads_abort_repeat), + ztest_unit_test(test_abort_handler), + ztest_unit_test(test_delayed_thread_abort), + ztest_unit_test(test_essential_thread_operation), + ztest_unit_test(test_systhreads_main), + ztest_unit_test(test_systhreads_idle), + ztest_unit_test(test_customdata_get_set_coop), + ztest_user_unit_test(test_customdata_get_set_preempt), + ztest_unit_test(test_k_thread_foreach), + ztest_unit_test(test_thread_name_get_set), + ztest_unit_test(test_user_mode), + ztest_unit_test(test_threads_cpu_mask) + ); + + ztest_run_test_suite(threads_lifecycle); +} diff --git a/pool/shard008/C/0129727_keyblocks.c b/pool/shard008/C/0129727_keyblocks.c new file mode 100644 index 0000000000000000000000000000000000000000..98696f5086e133d9fa2189ef24f939f9a595a03f --- /dev/null +++ b/pool/shard008/C/0129727_keyblocks.c @@ -0,0 +1,108 @@ +/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ +/* lib/crypto/krb/keyblocks.c - Keyblock utility functions */ +/* + * Copyright (C) 2002, 2005 by the Massachusetts Institute of Technology. + * All rights reserved. + * + * Export of this software from the United States of America may + * require a specific license from the United States Government. + * It is the responsibility of any person or organization contemplating + * export to obtain such a license before exporting. + * + * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and + * distribute this software and its documentation for any purpose and + * without fee is hereby granted, provided that the above copyright + * notice appear in all copies and that both that copyright notice and + * this permission notice appear in supporting documentation, and that + * the name of M.I.T. not be used in advertising or publicity pertaining + * to distribution of the software without specific, written prior + * permission. Furthermore if you modify this software you must label + * your software as modified software and not distribute it in such a + * fashion that it might be confused with the original M.I.T. software. + * M.I.T. makes no representations about the suitability of + * this software for any purpose. It is provided "as is" without express + * or implied warranty. + */ + +#include "crypto_int.h" + +krb5_error_code +krb5int_c_init_keyblock(krb5_context context, krb5_enctype enctype, + size_t length, krb5_keyblock **out) +{ + krb5_keyblock *kb; + + assert(out); + *out = NULL; + + kb = malloc(sizeof(krb5_keyblock)); + if (kb == NULL) + return ENOMEM; + kb->magic = KV5M_KEYBLOCK; + kb->enctype = enctype; + kb->length = length; + if (length) { + kb->contents = malloc(length); + if (!kb->contents) { + free(kb); + return ENOMEM; + } + } else { + kb->contents = NULL; + } + + *out = kb; + return 0; +} + +void +krb5int_c_free_keyblock(krb5_context context, register krb5_keyblock *val) +{ + krb5int_c_free_keyblock_contents(context, val); + free(val); +} + +void +krb5int_c_free_keyblock_contents(krb5_context context, krb5_keyblock *key) +{ + if (key && key->contents) { + zapfree(key->contents, key->length); + key->contents = NULL; + key->length = 0; + } +} + +krb5_error_code +krb5int_c_copy_keyblock(krb5_context context, const krb5_keyblock *from, + krb5_keyblock **to) +{ + krb5_keyblock *new_key; + krb5_error_code code; + + *to = NULL; + new_key = malloc(sizeof(*new_key)); + if (!new_key) + return ENOMEM; + code = krb5int_c_copy_keyblock_contents(context, from, new_key); + if (code) { + free(new_key); + return code; + } + *to = new_key; + return 0; +} + +krb5_error_code +krb5int_c_copy_keyblock_contents(krb5_context context, + const krb5_keyblock *from, krb5_keyblock *to) +{ + *to = *from; + if (to->length) { + to->contents = malloc(to->length); + if (!to->contents) + return ENOMEM; + memcpy(to->contents, from->contents, to->length); + } else + to->contents = 0; + return 0; +} diff --git a/pool/shard008/C/0129728_sysfile_update.c b/pool/shard008/C/0129728_sysfile_update.c new file mode 100644 index 0000000000000000000000000000000000000000..ec35d2ec53b83324d3dae1b1ec536c84033c4927 --- /dev/null +++ b/pool/shard008/C/0129728_sysfile_update.c @@ -0,0 +1,90 @@ +/****************************** + *Filname : sysfile_update.c + *Date : 2015-03-05 + * *****************************/ + + +#include +#include +#include +#include +#include +#include "sqlite3.h" + +# define sysfile_db "/ailvgo/system/box/sysfile.db" + +void bail(char *s) +{ + fputs(s, stderr); + fputc('\n', stderr); +} + +int main() +{ + sqlite3 *db = NULL; + sqlite3_stmt *ppstmt = NULL; + int rc = 0; + char sql_cmd[100] = {0}; + char sh_cmd[200] = {0}; + char *errorMsg = NULL; + const char *filename =NULL, *filepath = NULL; + char filename_all[100] = {0}; + int delete_flag = 0; + + printf("**********************************\n"); + printf("sysfile_update : start\n"); + printf("**********************************\n"); + + /*************************************************/ + + //sysfile check + printf("check sysfile in sysfile_update | sysfile.db\n"); + + rc=sqlite3_open(sysfile_db, &db); + if(rc == SQLITE_ERROR) + { + bail("open sysfile.db failed"); + } + ppstmt=NULL; + memset(sql_cmd, 0, sizeof(sql_cmd)); + strcpy(sql_cmd, "select filename, filepath from sysfile_update;"); + printf("sql_cmd : %s\n", sql_cmd); + sqlite3_prepare(db, sql_cmd, -1, &ppstmt, 0); + while(sqlite3_step(ppstmt) == SQLITE_ROW) + { + filename=sqlite3_column_text(ppstmt, 0); + printf("filename : %s\n", filename); + filepath=sqlite3_column_text(ppstmt, 1); + printf("filepath : %s\n", filepath); + + delete_flag = 1; + + memset(filename_all, 0, sizeof(filename_all)); + sprintf(filename_all, "/ailvgo/system/temp/%s", filename); + if(access(filename_all, R_OK) == 0) + { + memset(sh_cmd, 0, sizeof(sh_cmd)); + sprintf(sh_cmd, "mv -f %s %s%s", filename_all, filepath, filename); + printf("sh_cmd : %s\n", sh_cmd); + system(sh_cmd); + sleep(1); + } + } + if(delete_flag == 1) + { + printf("delete all files in sysfile_update | sysfile.db!\n"); + memset(sql_cmd, 0, sizeof(sql_cmd)); + strcpy(sql_cmd, "delete from sysfile_update;"); + printf("sql_cmd : %s\n", sql_cmd); + sqlite3_exec(db, sql_cmd, NULL, NULL, &errorMsg); + } + else + printf("no file in sysfile_update | sysfile.db\n"); + + sqlite3_finalize(ppstmt); + sqlite3_close(db); + + printf("sysfile_update : complete!\n"); + + system("chmod -R 777 /ailvgo/system/"); +} diff --git a/pool/shard008/C/0129735_bitbuf.c b/pool/shard008/C/0129735_bitbuf.c new file mode 100644 index 0000000000000000000000000000000000000000..aeb84eb54752ad74ab3bc6c253f2fc4a7fb5a58e --- /dev/null +++ b/pool/shard008/C/0129735_bitbuf.c @@ -0,0 +1,131 @@ +/*! \file bitbuf.c \brief Multipurpose bit buffer structure and methods. */ +//***************************************************************************** +// +// File Name : 'bitbuf.c' +// Title : Multipurpose bit buffer structure and methods +// Author : Pascal Stang - Copyright (C) 2001-2002 +// Created : 7/10/2002 +// Revised : 7/10/2002 +// Version : 0.5 +// Target MCU : any +// Editor Tabs : 4 +// +// This code is distributed under the GNU Public License +// which can be found at http://www.gnu.org/licenses/gpl.txt +// +//***************************************************************************** + +#include "bitbuf.h" + +// global variables + +//! Initialize the bit buffer +// sets the start location and size of the buffer in memory +void bitbufInit(BitBuf* bitBuffer, unsigned char *start, unsigned short bytesize) +{ + // set start pointer of the buffer + bitBuffer->dataptr = start; + bitBuffer->size = bytesize; + // initialize indexing and length + bitBuffer->dataindex = 0; + bitbufFlush(bitBuffer); +} + +// access routines + +//! Get a bit from the current position in the buffer +// returns the bit at the current position in the buffer +// and increments the bit position +unsigned char bitbufGet(BitBuf* bitBuffer) +{ + unsigned char byte; + unsigned char bit; + + // get current working byte + byte = bitBuffer->dataptr[bitBuffer->bytePos]; + // read data bit + bit = (byte & (1<bitPos))?(1):(0); + + // increment bit counter + if(bitBuffer->bitPos < 7) + { + bitBuffer->bitPos++; + } + else + { + // increment byte counter + bitBuffer->bitPos = 0; + bitBuffer->bytePos++; + } + + // return bit value + return bit; +} + +//! Get a bit from a given index into the buffer +// returns the bit at position [bitIndex] in the buffer +unsigned char bitbufGetAtIndex(BitBuf* bitBuffer, unsigned short bitIndex) +{ + // return bit at index in buffer + return (bitBuffer->dataptr[bitIndex>>3] & (1<<(bitIndex & 0x07)))?(1):(0); +} + +//! Store a bit at the current position in the buffer +// stores the bit at the current position in the buffer +// and increments the bit position +void bitbufStore(BitBuf* bitBuffer, unsigned char bit) +{ + unsigned char byte; + // get current working byte + byte = bitBuffer->dataptr[bitBuffer->bytePos]; + // apply data bit + if(bit) + byte |= (1<bitPos); + else + byte &= ~(1<bitPos); + // store data + bitBuffer->dataptr[bitBuffer->bytePos] = byte; + bitBuffer->datalength++; + + // increment bit counter + if(bitBuffer->bitPos < 7) + { + bitBuffer->bitPos++; + } + else + { + // increment byte counter + bitBuffer->bitPos = 0; + bitBuffer->bytePos++; + } +} + +void bitbufReset(BitBuf* bitBuffer) +{ + // reset counters + bitBuffer->bytePos = 0; + bitBuffer->bitPos = 0; +} + +void bitbufFlush(BitBuf* bitBuffer) +{ + // flush contents of the buffer + bitBuffer->datalength = 0; + // reset indexing + bitbufReset(bitBuffer); +} + +unsigned short bitbufGetDataLength(BitBuf* bitBuffer) +{ + return bitBuffer->datalength; +} + +/* +unsigned char bitbufIsNotFull(cBuffer* buffer) +{ + // check to see if the buffer has room + // return true if there is room + return (buffer->datalength < buffer->size); +} +*/ + diff --git a/pool/shard008/C/0129736_pr_exit.c b/pool/shard008/C/0129736_pr_exit.c new file mode 100644 index 0000000000000000000000000000000000000000..676b1bfa38fd7c963b243b9585dfebcfad6d212c --- /dev/null +++ b/pool/shard008/C/0129736_pr_exit.c @@ -0,0 +1,110 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License, Version 1.0 only + * (the "License"). You may not use this file except in compliance + * with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ +/* + * Copyright 1997-2003 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "@(#)pr_exit.c 1.4 05/06/08 SMI" + +#include +#include +#include +#include +#include "libproc.h" + +/* + * exit() system call -- executed by subject process. + */ +int +pr_exit(struct ps_prochandle *Pr, int status) +{ + sysret_t rval; /* return value from exit() */ + argdes_t argd[1]; /* arg descriptors for exit() */ + argdes_t *adp; + int error; + + if (Pr == NULL) { /* no subject process */ + exit(status); + return (0); /* not reached */ + } + + adp = &argd[0]; /* status argument */ + adp->arg_value = status; + adp->arg_object = NULL; + adp->arg_type = AT_BYVAL; + adp->arg_inout = AI_INPUT; + adp->arg_size = 0; + + error = Psyscall(Pr, &rval, SYS_exit, 1, &argd[0]); + /* actually -- never returns. Expect ENOENT */ + + if (error < 0) { + if (errno == ENOENT) /* expected case */ + error = ENOENT; + else + error = ENOSYS; + } + + if (error == 0) /* can't happen? */ + return (rval.sys_rval1); + + if (error == ENOENT) /* expected case */ + return (0); + + errno = error; + return (-1); +} + +/* + * lwp_exit() system call -- executed by subject lwp. + */ +int +pr_lwp_exit(struct ps_prochandle *Pr) +{ + sysret_t rval; /* return value from lwp_exit() */ + int error; + + if (Pr == NULL) { /* no subject process */ + (void) syscall(SYS_lwp_exit); + return (0); /* not reached */ + } + + error = Psyscall(Pr, &rval, SYS_lwp_exit, 0, NULL); + /* actually -- never returns. Expect ENOENT */ + + if (error < 0) { + if (errno == ENOENT) /* expected case */ + error = ENOENT; + else + error = ENOSYS; + } + + if (error == 0) /* can't happen? */ + return (rval.sys_rval1); + + if (error == ENOENT) /* expected case */ + return (0); + + errno = error; + return (-1); +} diff --git a/pool/shard008/C/0129738_m_svinfo.c b/pool/shard008/C/0129738_m_svinfo.c new file mode 100644 index 0000000000000000000000000000000000000000..280b08f030a7b79c6430fb75ce1fb7a3dc67bf6d --- /dev/null +++ b/pool/shard008/C/0129738_m_svinfo.c @@ -0,0 +1,109 @@ +/* + * ircd-ratbox: A slightly useful ircd. + * m_svinfo.c: Sends TS information for clock & compatibility checks. + * + * Copyright (C) 1990 Jarkko Oikarinen and University of Oulu, Co Center + * Copyright (C) 1996-2002 Hybrid Development Team + * Copyright (C) 2002-2005 ircd-ratbox development team + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * $Id: m_svinfo.c 21277 2005-11-21 20:10:49Z leeh $ + */ +#include "stdinc.h" +#include "client.h" +#include "common.h" /* TRUE bleah */ +#include "irc_string.h" +#include "ircd.h" +#include "numeric.h" +#include "send.h" +#include "s_conf.h" +#include "s_log.h" +#include "msg.h" +#include "parse.h" +#include "modules.h" + +static int ms_svinfo(struct Client *, struct Client *, int, const char **); + +struct Message svinfo_msgtab = { + "SVINFO", 0, 0, 0, MFLG_SLOW, + {mg_unreg, mg_ignore, mg_ignore, {ms_svinfo, 5}, mg_ignore, mg_ignore} +}; + +mapi_clist_av1 svinfo_clist[] = { &svinfo_msgtab, NULL }; +DECLARE_MODULE_AV1(svinfo, NULL, NULL, svinfo_clist, NULL, NULL, "$Revision: 21277 $"); + +/* + * ms_svinfo - SVINFO message handler + * parv[0] = sender prefix + * parv[1] = TS_CURRENT for the server + * parv[2] = TS_MIN for the server + * parv[3] = unused, send 0 + * parv[4] = server's idea of UTC time + */ +static int +ms_svinfo(struct Client *client_p, struct Client *source_p, int parc, const char *parv[]) +{ + signed int deltat; + time_t theirtime; + + /* SVINFO isnt remote. */ + if(source_p != client_p) + return 0; + + if(TS_CURRENT < atoi(parv[2]) || atoi(parv[1]) < TS_MIN) + { + /* TS version is too low on one of the sides, drop the link */ + sendto_realops_flags(UMODE_ALL, L_ALL, + "Link %s dropped, wrong TS protocol version (%s,%s)", + source_p->name, parv[1], parv[2]); + exit_client(source_p, source_p, source_p, "Incompatible TS version"); + return 0; + } + + /* + * since we're here, might as well set CurrentTime while we're at it + */ + set_time(); + theirtime = atol(parv[4]); + deltat = abs(theirtime - CurrentTime); + + if(deltat > ConfigFileEntry.ts_max_delta) + { + sendto_realops_flags(UMODE_ALL, L_ALL, + "Link %s dropped, excessive TS delta" + " (my TS=%ld, their TS=%ld, delta=%d)", + source_p->name, + (long) CurrentTime, (long) theirtime, deltat); + ilog(L_SERVER, + "Link %s dropped, excessive TS delta" + " (my TS=%ld, their TS=%ld, delta=%d)", + log_client_name(source_p, SHOW_IP), (long) CurrentTime, (long) theirtime, deltat); + exit_client(source_p, source_p, source_p, "Excessive TS delta"); + return 0; + } + + if(deltat > ConfigFileEntry.ts_warn_delta) + { + sendto_realops_flags(UMODE_ALL, L_ALL, + "Link %s notable TS delta" + " (my TS=%ld, their TS=%ld, delta=%d)", + source_p->name, (long) CurrentTime, (long) theirtime, deltat); + } + + return 0; +} + diff --git a/pool/shard008/C/0129741_blx.c b/pool/shard008/C/0129741_blx.c new file mode 100644 index 0000000000000000000000000000000000000000..9ac295fff99c806b6ffa6ba2c27d37c21a735825 --- /dev/null +++ b/pool/shard008/C/0129741_blx.c @@ -0,0 +1,105 @@ +/* drivers/misc/blx.c + * + * Copyright 2011 Ezekeel + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#include +#include +#include +#include + +#define BATTERYLIFEEXTENDER_VERSION 1 + +static int charging_limit = MAX_CHARGINGLIMIT; + +static ssize_t blx_charginglimit_read(struct device * dev, struct device_attribute * attr, char * buf) +{ + return sprintf(buf, "%u\n", charging_limit); +} + +static ssize_t blx_charginglimit_write(struct device * dev, struct device_attribute * attr, const char * buf, size_t size) +{ + unsigned int data; + + if(sscanf(buf, "%u\n", &data) == 1) + { + if (data >= 0 && data <= MAX_CHARGINGLIMIT) + { + charging_limit = data; + + pr_info("BLX charging limit set to %u\n", charging_limit); + } + else + { + pr_info("%s: invalid input range %u\n", __FUNCTION__, data); + } + } + else + { + pr_info("%s: invalid input\n", __FUNCTION__); + } + + return size; +} + +static ssize_t blx_version(struct device * dev, struct device_attribute * attr, char * buf) +{ + return sprintf(buf, "%u\n", BATTERYLIFEEXTENDER_VERSION); +} + +static DEVICE_ATTR(charging_limit, S_IRUGO | S_IWUGO, blx_charginglimit_read, blx_charginglimit_write); +static DEVICE_ATTR(version, S_IRUGO , blx_version, NULL); + +static struct attribute *blx_attributes[] = + { + &dev_attr_charging_limit.attr, + &dev_attr_version.attr, + NULL + }; + +static struct attribute_group blx_group = + { + .attrs = blx_attributes, + }; + +static struct miscdevice blx_device = + { + .minor = MISC_DYNAMIC_MINOR, + .name = "batterylifeextender", + }; + +int get_charginglimit(void) +{ + return charging_limit; +} +EXPORT_SYMBOL(get_charginglimit); + +static int __init blx_init(void) +{ + int ret; + + pr_info("%s misc_register(%s)\n", __FUNCTION__, blx_device.name); + + ret = misc_register(&blx_device); + + if (ret) + { + pr_err("%s misc_register(%s) fail\n", __FUNCTION__, blx_device.name); + + return 1; + } + + if (sysfs_create_group(&blx_device.this_device->kobj, &blx_group) < 0) + { + pr_err("%s sysfs_create_group fail\n", __FUNCTION__); + pr_err("Failed to create sysfs group for device (%s)!\n", blx_device.name); + } + + return 0; +} + +device_initcall(blx_init); diff --git a/pool/shard008/C/0129743_mesons_offdiag.c b/pool/shard008/C/0129743_mesons_offdiag.c new file mode 100644 index 0000000000000000000000000000000000000000..219d0144216e69b075cc3a0e1f05c4e6fdae269b --- /dev/null +++ b/pool/shard008/C/0129743_mesons_offdiag.c @@ -0,0 +1,163 @@ +/** + @file mesons_offdiag.c + @brief flavour off-diagonal meson contractions + + split from mesons for clarity + */ +#include "common.h" + +#include "basis_conversions.h" // chiral->nrel +#include "contractions.h" // meson contract +#include "correlators.h" // write_momcorr() +#include "gammas.h" // gt_Gdag_gt() +#include "io.h" // read_ahead() +#include "progress_bar.h" // progress_bar() +#include "quark_smear.h" // sink_smear() +#include "setup.h" // init_measurements() +#include "spinor_ops.h" // sumwalls() + +// number of propagators +#define Nprops (2) + +// computes flavour-off diagonal correlators with ND-1 momentum projection +int +mesons_offdiagonal( struct propagator prop1 , + struct propagator prop2 , + const struct cut_info CUTINFO , + const char *outfile ) +{ + // counters + const size_t stride1 = M_CHANNELS ; + const size_t stride2 = M_CHANNELS ; + + // flat dirac indices are all colors and all single gamma combinations + const size_t flat_dirac = stride1*stride2 ; + + // error flag for if the code messes up + int error_code = SUCCESS ; + + // initialise our measurement struct + struct propagator prop[ Nprops ] = { prop1 , prop2 } ; + const int sign[ Nprops ] = { -1 , +1 } ; + struct measurements M ; + if( init_measurements( &M , prop , Nprops , CUTINFO , + stride1 , stride2 , flat_dirac , sign ) == FAILURE ) { + fprintf( stderr , "[MESONS] failure to initialise measurements\n" ) ; + error_code = FAILURE ; goto memfree ; + } + + // open the parallel region +#pragma omp parallel + { + // loop counters + size_t t = 0 , site ; + + // initial read of a timeslice + read_ahead( prop , M.S , &error_code , Nprops , t ) ; + + // smear it if we wish + sink_smear( M.S , M.S1 , t , CUTINFO , Nprops ) ; + + { + #pragma omp barrier + } + + // Time slice loop + for( t = 0 ; t < LT && error_code == SUCCESS ; t++ ) { + + // if we are doing nonrel-chiral mesons we switch chiral to nrel + rotate_offdiag( M.S , prop , Nprops ) ; + + // compute wall-wall sum + #pragma omp single nowait + { + sumwalls( M.SUM , (const struct spinor**)M.S , Nprops ) ; + } + + // support for multiple time sources + const size_t tshifted = ( t - prop1.origin[ ND-1 ] + LT ) % LT ; + + // master-slave the IO and perform each FFT in parallel + if( t < ( LT - 1 ) ) { + read_ahead( prop , M.Sf , &error_code , Nprops , t+1 ) ; + } + + // parallelise the furthest out loop :: flatten the gammas + #pragma omp for private(site) + for( site = 0 ; site < LCU ; site++ ) { + + // sum over possible rs + struct spinor SUM_r2[ Nprops ] ; + sum_spatial_sep( SUM_r2 , M , site ) ; + + size_t GSGK ; + for( GSGK = 0 ; GSGK < flat_dirac ; GSGK++ ) { + const size_t GSRC = GSGK / stride1 ; + const size_t GSNK = GSGK % stride2 ; + #ifdef TWOPOINT_FILTER + if( !filter[ GSRC ][ GSNK ] ) continue ; + #endif + + const struct gamma gt_GSNKdag_gt = gt_Gdag_gt( M.GAMMAS[ GSNK ] , + M.GAMMAS[ GAMMA_T ] ) ; + M.in[ GSGK ][ site ] = + meson_contract( gt_GSNKdag_gt , SUM_r2[1] , + M.GAMMAS[ GSRC ] , SUM_r2[0] , + M.GAMMAS[ GAMMA_5 ] ) ; + } + } + size_t GSGK ; + #pragma omp for private(GSGK) schedule(dynamic) + for( GSGK = 0 ; GSGK < flat_dirac ; GSGK++ ) { + const size_t GSRC = GSGK / stride1 ; + const size_t GSNK = GSGK % stride2 ; + #ifdef TWOPOINT_FILTER + if( !filter[ GSRC ][ GSNK ] ) continue ; + #endif + + const struct gamma gt_GSNKdag_gt = gt_Gdag_gt( M.GAMMAS[ GSNK ] , + M.GAMMAS[ GAMMA_T ] ) ; + // and contract the walls + M.wwcorr[ GSRC ][ GSNK ].mom[ 0 ].C[ tshifted ] = \ + meson_contract( gt_GSNKdag_gt , M.SUM[1] , + M.GAMMAS[ GSRC ] , M.SUM[0] , + M.GAMMAS[ GAMMA_5 ] ) ; + } + + // compute the contracted correlator + compute_correlator( &M , stride1 , stride2 , tshifted ) ; + + // smear the forward prop + if( t < (LT-1) ) { + sink_smear( M.Sf , M.S1 , t+1 , CUTINFO , Nprops ) ; + } + + #pragma omp single + { + // copy the forward timeslice into the active timeslice + copy_props( &M , Nprops ) ; + + // status of the computation + progress_bar( t , LT ) ; + } + // tloop + } + // parallel regione + } + + if( error_code == FAILURE ) goto memfree ; + + // write out the ND-1 momentum-injected correlator + write_momcorr_WW( M , outfile , stride1 , stride2 ) ; + + // memory freeing part + memfree : + + // free our measurement struct + free_measurements( &M , Nprops , stride1 , stride2 , flat_dirac ) ; + + return error_code ; +} + +// clean up number of props +#undef Nprops diff --git a/pool/shard008/C/0129752_gl_model_brush.c b/pool/shard008/C/0129752_gl_model_brush.c new file mode 100644 index 0000000000000000000000000000000000000000..e30ff9822a4fdd3ce9bc4d2e758f769c9a05a54e --- /dev/null +++ b/pool/shard008/C/0129752_gl_model_brush.c @@ -0,0 +1,101 @@ +/* + gl_model_brush.c + + model loading and caching + + Copyright (C) 1996-1997 Id Software, Inc. + + 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: + + Free Software Foundation, Inc. + 59 Temple Place - Suite 330 + Boston, MA 02111-1307, USA + + $Id$ +*/ + +// models are the only shared resource between a client and server running +// on the same machine. + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include "r_local.h" +#include "sys.h" +#include "console.h" +#include "qendian.h" +#include "checksum.h" +#include "glquake.h" + +extern char loadname[]; +extern model_t *loadmodel; +extern byte mod_novis[]; +extern byte *mod_base; + +int Mod_Fullbright(byte *skin, int width, int height, char *name); + +const int mod_lightmap_bytes = 3; + +void +Mod_ProcessTexture(miptex_t *mt, texture_t *tx) +{ + char name[32]; + + texture_mode = GL_LINEAR_MIPMAP_NEAREST; //_LINEAR; + snprintf (name, sizeof(name), "fb_%s", mt->name); + tx->gl_fb_texturenum = Mod_Fullbright ((byte *)(tx+1), tx->width, tx->height, name); + tx->gl_texturenum = GL_LoadTexture (mt->name, tx->width, tx->height, (byte *)(tx+1), true, false, 1); + texture_mode = GL_LINEAR; +} + +/* +================= +Mod_LoadLighting +================= +*/ +void Mod_LoadLighting (lump_t *l) +{ + int i; + byte *in, *out; + byte d; + char litfilename[1024]; + + if (!l->filelen) + { + loadmodel->lightdata = NULL; + return; + } + + strcpy(litfilename, loadmodel->name); + COM_StripExtension(litfilename, litfilename); + strcat(litfilename, ".lit"); + + loadmodel->lightdata = (byte*) COM_LoadHunkFile (litfilename); + if (!loadmodel->lightdata) // expand the white lighting data + { + loadmodel->lightdata = Hunk_AllocName ( l->filelen*3, litfilename); + in = loadmodel->lightdata + l->filelen*2; // place the file at the end, so it will not be overwritten until the very last write + out = loadmodel->lightdata; + memcpy (in, mod_base + l->fileofs, l->filelen); + for (i = 0;i < l->filelen;i++) + { + d = *in++; + *out++ = d; + *out++ = d; + *out++ = d; + } + } +} diff --git a/pool/shard008/C/0129753_tc_watchdog.c b/pool/shard008/C/0129753_tc_watchdog.c new file mode 100644 index 0000000000000000000000000000000000000000..8becb4ac067d3484251579d4c266648a5255b5fa --- /dev/null +++ b/pool/shard008/C/0129753_tc_watchdog.c @@ -0,0 +1,166 @@ +/**************************************************************************** + * + * Copyright 2017 Samsung Electronics All Rights Reserved. + * + * 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. + * + ****************************************************************************/ + +/// @file tc_watchdog.c +/// @brief Test Case Example for watchdog driver +#include +#include +#include +#include "tc_internal.h" +#include + +/** + * @brief Closes all open files + */ +static inline void close_fds(int *fds, int count) +{ + for (; count >= 0; count--) { + close(fds[count]); + } +} + +/** +* @fn :tc_driver_watchdog_open_close +* @brief :Test the watchdog driver open and close +* @scenario :Test the watchdog driver open and close +* API's covered :open, close +* Preconditions :none +* Postconditions :none +* @return :void +*/ +static void tc_driver_watchdog_open_close(void) +{ + int fd = 0; + int ret = 0; + + fd = open("/dev/watchdog0", O_RDWR); + TC_ASSERT_GT("watchdog_open", fd, 0); + + ret = close(fd); + TC_ASSERT_EQ("watchdog_close", ret, OK); + + /* Negative test cases */ + int count = 0; + int fds[255] = { 0, }; + for (count = 0; count < 255; count++) { + fds[count] = open("/dev/watchdog0", O_RDWR); + if (fds[count] < 0) { + TC_ASSERT_EQ_CLEANUP("watchdog_open", errno, EMFILE, close_fds(fds, --count)); + break; + } + } + + close_fds(fds, --count); + + TC_SUCCESS_RESULT(); +} + +/** +* @fn :tc_driver_watchdog_read_write +* @brief :Test the watchdog driver read and write +* @scenario :Test the watchdog driver read and write +* API's covered :read, write +* Preconditions :none +* Postconditions :none +* @return :void +*/ +static void tc_driver_watchdog_read_write(void) +{ + int fd = 0; + int ret = 0; + + fd = open("/dev/watchdog0", O_RDWR); + TC_ASSERT_GT("watchdog_open", fd, 0); + + ret = read(fd, NULL, 0); + TC_ASSERT_EQ_CLEANUP("watchdog_read", ret, 0, close(fd)); + + ret = write(fd, NULL, 1); + TC_ASSERT_EQ_CLEANUP("watchdog_write", ret, 0, close(fd)); + + close(fd); + + TC_SUCCESS_RESULT(); +} + +/** +* @fn :tc_driver_watchdog_ioctl +* @brief :Test the watchdog driver ioctl +* @scenario :Test the watchdog driver ioctl +* API's covered :ioctl +* Preconditions :none +* Postconditions :none +* @return :void +*/ +static void tc_driver_watchdog_ioctl(void) +{ + int fd = 0; + int ret = 0; + + fd = open("/dev/watchdog0", O_RDWR); + TC_ASSERT_GT("watchdog_open", fd, 0); + + ret = ioctl(fd, WDIOC_SETTIMEOUT, 1000); + TC_ASSERT_EQ_CLEANUP("watchdog_ioctl", ret, OK, close(fd)); + + ret = ioctl(fd, WDIOC_START, 0); + TC_ASSERT_EQ_CLEANUP("watchdog_ioctl", ret, OK, close(fd)); + + FAR struct watchdog_status_s status; + ret = ioctl(fd, WDIOC_GETSTATUS, &status); + TC_ASSERT_EQ_CLEANUP("watchdog_ioctl", ret, OK, close(fd)); + TC_ASSERT_EQ_CLEANUP("watchdog_ioctl", status.flags & WDFLAGS_ACTIVE, WDFLAGS_ACTIVE, close(fd)); + TC_ASSERT_EQ_CLEANUP("watchdog_ioctl", status.timeout, 1000, close(fd)); + + /* Negative testcase for WDIOC_GETSTATUS */ + ret = ioctl(fd, WDIOC_GETSTATUS, NULL); + TC_ASSERT_LT_CLEANUP("watchdog_ioctl", ret, 0, close(fd)); + + FAR struct watchdog_capture_s cap; + ret = ioctl(fd, WDIOC_CAPTURE, &cap); + TC_ASSERT_EQ_CLEANUP("watchdog_ioctl", ret, OK, close(fd)); + + /* Negative testcase for WDIOC_CAPTURE */ + ret = ioctl(fd, WDIOC_CAPTURE, NULL); + TC_ASSERT_LT_CLEANUP("watchdog_ioctl", ret, 0, close(fd)); + + ret = ioctl(fd, WDIOC_KEEPALIVE, 0); + TC_ASSERT_EQ_CLEANUP("watchdog_ioctl", ret, OK, close(fd)); + + ret = ioctl(fd, WDIOC_STOP, 0); + TC_ASSERT_EQ_CLEANUP("watchdog_ioctl", ret, OK, close(fd)); + + ret = ioctl(fd, -1, 0); + TC_ASSERT_EQ_CLEANUP("watchdog_ioctl", ret, OK, close(fd)); + + close(fd); + + TC_SUCCESS_RESULT(); +} + +/**************************************************************************** + * Name: watchdog driver test + ****************************************************************************/ +void watchdog_main(void) +{ + tc_driver_watchdog_open_close(); + tc_driver_watchdog_read_write(); + tc_driver_watchdog_ioctl(); + + return; +} diff --git a/pool/shard008/C/0129754_insert-name.c b/pool/shard008/C/0129754_insert-name.c new file mode 100644 index 0000000000000000000000000000000000000000..4f414c4e3b15ebf1e2b5b3a0ad3292cabeaab4bf --- /dev/null +++ b/pool/shard008/C/0129754_insert-name.c @@ -0,0 +1,97 @@ +#include +#include +#include + +/** + * names.c: sorts the given arguments in ascending order and writes them to + * a file. + * + * usage: ./names.c [name1] [name2] [name3] ... + */ + +#define FILENAME "names.txt" +#define BUFFER_SIZE 1024 + +/* Removes trailing escape characters from s (i.e., newlines) */ +static void +strchomp (char *s) +{ + while (*s > 20) + { + s++; + } + + *s = '\0'; +} + +static void +insert_str_in_file (const char *str) +{ + FILE *fpr; + FILE *fpw; + char buffer[BUFFER_SIZE]; + int printed = 0; + + fpr = fopen (FILENAME, "r"); + + /* If file doesn't exist, write a new one and return */ + if (fpr == NULL) + { + fpw = fopen (FILENAME, "w"); + if (fpw == NULL) + { + perror ("Could not open for write"); + return; + } + fprintf (fpw, "%s\n", str); + fclose (fpw); + return; + } + + /* unlink the existing file (we can still read from it until fclose) */ + remove (FILENAME); + + fpw = fopen (FILENAME ".new", "w"); + if (fpw == NULL) + { + perror ("Could not open for write"); + fclose (fpr); + return; + } + + /* copy input to output, inserting str if it's in the right order */ + while (fgets (buffer, BUFFER_SIZE, fpr) != NULL) + { + strchomp (buffer); + if (printed != 1 && strcmp (buffer, str) > 0) + { + fprintf (fpw, "%s\n", str); + printed = 1; + } + fprintf (fpw, "%s\n", buffer); + } + + if (printed != 1) + { + fprintf (fpw, "%s\n", str); + } + + fclose (fpr); + fclose (fpw); + + rename (FILENAME ".new", FILENAME); +} + +int +main (int argc, char **argv) +{ + if (argc != 2) + { + printf ("Usage: %s [name]\n", argv[0]); + return 1; + } + + insert_str_in_file (argv[1]); + + return 0; +} diff --git a/pool/shard008/C/0129756_soc.c b/pool/shard008/C/0129756_soc.c new file mode 100644 index 0000000000000000000000000000000000000000..8835e0a5a50256fa3bc8c2c48d3d3c68335567a1 --- /dev/null +++ b/pool/shard008/C/0129756_soc.c @@ -0,0 +1,306 @@ +/* + * Copyright (c) 2017 Oticon A/S + * + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * For all purposes, Zephyr threads see a CPU running at an infinitly high + * clock. + * + * Therefore, the code will always run until completion after each interrupt, + * after which k_cpu_idle() will be called releasing the execution back to the + * HW models. + * + * The HW models raising an interrupt will "awake the cpu" by calling + * poisix_interrupt_raised() which will transfer control to the irq handler, + * which will run inside SW/Zephyr contenxt. After which a __swap() to whatever + * Zephyr thread may follow. + * Again, once Zephyr is done, control is given back to the HW models. + * + * + * The Zephyr OS+APP code and the HW models are gated by a mutex + + * condition as there is no reason to let the zephyr threads run while the + * HW models run or vice versa + * + */ + +#include +#include +#include +#include "posix_soc_if.h" +#include "posix_soc.h" +#include "posix_board_if.h" +#include "posix_core.h" +#include "posix_arch_internal.h" +#include "kernel_internal.h" +#include "soc.h" + +#define POSIX_ARCH_SOC_DEBUG_PRINTS 0 + +#define PREFIX "POSIX SOC: " +#define ERPREFIX PREFIX"error on " + +#if POSIX_ARCH_SOC_DEBUG_PRINTS +#define PS_DEBUG(fmt, ...) posix_print_trace(PREFIX fmt, __VA_ARGS__) +#else +#define PS_DEBUG(...) +#endif + +/* Conditional variable to know if the CPU is running or halted/idling */ +static pthread_cond_t cond_cpu = PTHREAD_COND_INITIALIZER; +/* Mutex for the conditional variable posix_soc_cond_cpu */ +static pthread_mutex_t mtx_cpu = PTHREAD_MUTEX_INITIALIZER; +/* Variable which tells if the CPU is halted (1) or not (0) */ +static bool cpu_halted = true; + +static bool soc_terminate; /* Is the program being closed */ + + +int posix_is_cpu_running(void) +{ + return !cpu_halted; +} + + +/** + * Helper function which changes the status of the CPU (halted or running) + * and waits until somebody else changes it to the opposite + * + * Both HW and SW threads will use this function to transfer control to the + * other side. + * + * This is how the idle thread halts the CPU and gets halted until the HW models + * raise a new interrupt; and how the HW models awake the CPU, and wait for it + * to complete and go to idle. + */ +static void posix_change_cpu_state_and_wait(bool halted) +{ + _SAFE_CALL(pthread_mutex_lock(&mtx_cpu)); + + PS_DEBUG("Going to halted = %d\n", halted); + + cpu_halted = halted; + + /* We let the other side know the CPU has changed state */ + _SAFE_CALL(pthread_cond_broadcast(&cond_cpu)); + + /* We wait until the CPU state has been changed. Either: + * we just awoke it, and therefore wait until the CPU has run until + * completion before continuing (before letting the HW models do + * anything else) + * or + * we are just hanging it, and therefore wait until the HW models awake + * it again + */ + while (cpu_halted == halted) { + /* Here we unlock the mutex while waiting */ + pthread_cond_wait(&cond_cpu, &mtx_cpu); + } + + PS_DEBUG("Awaken after halted = %d\n", halted); + + _SAFE_CALL(pthread_mutex_unlock(&mtx_cpu)); +} + +/** + * HW models shall call this function to "awake the CPU" + * when they are raising an interrupt + */ +void posix_interrupt_raised(void) +{ + /* We change the CPU to running state (we awake it), and block this + * thread until the CPU is hateld again + */ + posix_change_cpu_state_and_wait(false); + + /* + * If while the SW was running it was decided to terminate the execution + * we stop immediately. + */ + if (soc_terminate) { + posix_exit(0); + } +} + + +/** + * Normally called from k_cpu_idle(): + * the idle loop will call this function to set the CPU to "sleep". + * Others may also call this function with care. The CPU will be set to sleep + * until some interrupt awakes it. + * Interrupts should be enabled before calling. + */ +void posix_halt_cpu(void) +{ + /* + * We set the CPU in the halted state (this blocks this pthread + * until the CPU is awoken again by the HW models) + */ + posix_change_cpu_state_and_wait(true); + + /* We are awoken, normally that means some interrupt has just come + * => let the "irq handler" check if/what interrupt was raised + * and call the appropriate irq handler. + * + * Note that, the interrupt handling may trigger a __swap() to another + * Zephyr thread. When posix_irq_handler() returns, the Zephyr + * kernel has swapped back to this thread again + */ + posix_irq_handler(); + + /* + * And we go back to whatever Zephyr thread calleed us. + */ +} + + +/** + * Implementation of k_cpu_atomic_idle() for this SOC + */ +void posix_atomic_halt_cpu(unsigned int imask) +{ + posix_irq_full_unlock(); + posix_halt_cpu(); + posix_irq_unlock(imask); +} + + +/** + * Just a wrapper function to call Zephyr's _Cstart() + * called from posix_boot_cpu() + */ +static void *zephyr_wrapper(void *a) +{ + /* Ensure posix_boot_cpu has reached the cond loop */ + _SAFE_CALL(pthread_mutex_lock(&mtx_cpu)); + _SAFE_CALL(pthread_mutex_unlock(&mtx_cpu)); + +#if (POSIX_ARCH_SOC_DEBUG_PRINTS) + pthread_t zephyr_thread = pthread_self(); + + PS_DEBUG("Zephyr init started (%lu)\n", + zephyr_thread); +#endif + + posix_init_multithreading(); + + /* Start Zephyr: */ + _Cstart(); + CODE_UNREACHABLE; + + return NULL; +} + + +/** + * The HW models will call this function to "boot" the CPU + * == spawn the Zephyr init thread, which will then spawn + * anything it wants, and run until the CPU is set back to idle again + */ +void posix_boot_cpu(void) +{ + _SAFE_CALL(pthread_mutex_lock(&mtx_cpu)); + + cpu_halted = false; + + pthread_t zephyr_thread; + + /* Create a thread for Zephyr init: */ + _SAFE_CALL(pthread_create(&zephyr_thread, NULL, zephyr_wrapper, NULL)); + + /* And we wait until Zephyr has run til completion (has gone to idle) */ + while (cpu_halted == false) { + pthread_cond_wait(&cond_cpu, &mtx_cpu); + } + _SAFE_CALL(pthread_mutex_unlock(&mtx_cpu)); + + if (soc_terminate) { + posix_exit(0); + } +} + +/** + * @brief Run the set of special native tasks corresponding to the given level + * + * @param level One of _NATIVE_*_LEVEL as defined in soc.h + */ +void run_native_tasks(int level) +{ + extern void (*__native_PRE_BOOT_1_tasks_start[])(void); + extern void (*__native_PRE_BOOT_2_tasks_start[])(void); + extern void (*__native_PRE_BOOT_3_tasks_start[])(void); + extern void (*__native_FIRST_SLEEP_tasks_start[])(void); + extern void (*__native_ON_EXIT_tasks_start[])(void); + extern void (*__native_tasks_end[])(void); + + static void (**native_pre_tasks[])(void) = { + __native_PRE_BOOT_1_tasks_start, + __native_PRE_BOOT_2_tasks_start, + __native_PRE_BOOT_3_tasks_start, + __native_FIRST_SLEEP_tasks_start, + __native_ON_EXIT_tasks_start, + __native_tasks_end + }; + + void (**fptr)(void); + + for (fptr = native_pre_tasks[level]; fptr < native_pre_tasks[level+1]; + fptr++) { + if (*fptr) { /* LCOV_EXCL_BR_LINE */ + (*fptr)(); + } + } +} + +/** + * Clean up all memory allocated by the SOC and POSIX core + * + * This function can be called from both HW and SW threads + */ +void posix_soc_clean_up(void) +{ + /* LCOV_EXCL_START */ /* See Note1 */ + /* + * If we are being called from a HW thread we can cleanup + * + * Otherwise (!cpu_halted) we give back control to the HW thread and + * tell it to terminate ASAP + */ + if (cpu_halted) { + + posix_core_clean_up(); + run_native_tasks(_NATIVE_ON_EXIT_LEVEL); + + } else if (soc_terminate == false) { + + soc_terminate = true; + + _SAFE_CALL(pthread_mutex_lock(&mtx_cpu)); + + cpu_halted = true; + + _SAFE_CALL(pthread_cond_broadcast(&cond_cpu)); + _SAFE_CALL(pthread_mutex_unlock(&mtx_cpu)); + + while (1) { + sleep(1); + /* This SW thread will wait until being cancelled from + * the HW thread. sleep() is a cancellation point, so it + * won't really wait 1 second + */ + } + } + /* LCOV_EXCL_STOP */ +} + +/* + * Notes about coverage: + * + * Note1: When the application is closed due to a SIGTERM, the path in this + * function will depend on when that signal was received. Typically during a + * regression run, both paths will be covered. But in some cases they won't. + * Therefore and to avoid confusing developers with spurious coverage changes + * we exclude this function from the coverage check + * + */ diff --git a/pool/shard008/C/0129762_memmap.c b/pool/shard008/C/0129762_memmap.c new file mode 100644 index 0000000000000000000000000000000000000000..12baa33a5e26fd9156186d5ca4870d55549e11e5 --- /dev/null +++ b/pool/shard008/C/0129762_memmap.c @@ -0,0 +1,65 @@ +/* ----------------------------------------------------------------------- * + * + * Copyright 2007-2009 H. Peter Anvin - All Rights Reserved + * Copyright 2009 Intel Corporation; author: H. Peter Anvin + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom + * the Software is furnished to do so, subject to the following + * conditions: + * + * The above copyright notice and this permission notice shall + * be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * ----------------------------------------------------------------------- */ + +/* + * memmap.c + * + * Create initial memory map for "shuffle and boot" operation + */ + +#include +#include +#include +#include + +#include +#include + +static int syslinux_memory_map_callback(void *map, addr_t start, + addr_t len, bool valid) +{ + struct syslinux_memmap **mmap = map; + return syslinux_add_memmap(mmap, start, len, + valid ? SMT_FREE : SMT_RESERVED); +} + +struct syslinux_memmap *syslinux_memory_map(void) +{ + struct syslinux_memmap *mmap; + + mmap = syslinux_init_memmap(); + if (!mmap) + return NULL; + + if (syslinux_scan_memory(syslinux_memory_map_callback, &mmap)) { + syslinux_free_memmap(mmap); + return NULL; + } + + return mmap; +} diff --git a/pool/shard008/C/0129763_omap_sx1.c b/pool/shard008/C/0129763_omap_sx1.c new file mode 100644 index 0000000000000000000000000000000000000000..2a8419e0b2422f96b3121d73889eb144e0d9e3b8 --- /dev/null +++ b/pool/shard008/C/0129763_omap_sx1.c @@ -0,0 +1,251 @@ +/* omap_sx1.c Support for the Siemens SX1 smartphone emulation. + * + * Copyright (C) 2008 + * Jean-Christophe PLAGNIOL-VILLARD + * Copyright (C) 2007 Vladimir Ananiev + * + * based on PalmOne's (TM) PDAs support (palm.c) + */ + +/* + * PalmOne's (TM) PDAs. + * + * Copyright (C) 2006-2007 Andrzej Zaborowski + * + * 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, see . + */ +#include "hw.h" +#include "sysemu.h" +#include "console.h" +#include "omap.h" +#include "boards.h" +#include "arm-misc.h" +#include "flash.h" + +/*****************************************************************************/ +/* Siemens SX1 Cellphone V1 */ +/* - ARM OMAP310 processor + * - SRAM 192 kB + * - SDRAM 32 MB at 0x10000000 + * - Boot flash 16 MB at 0x00000000 + * - Application flash 8 MB at 0x04000000 + * - 3 serial ports + * - 1 SecureDigital + * - 1 LCD display + * - 1 RTC + */ + +/*****************************************************************************/ +/* Siemens SX1 Cellphone V2 */ +/* - ARM OMAP310 processor + * - SRAM 192 kB + * - SDRAM 32 MB at 0x10000000 + * - Boot flash 32 MB at 0x00000000 + * - 3 serial ports + * - 1 SecureDigital + * - 1 LCD display + * - 1 RTC + */ + +static uint32_t static_readb(void *opaque, target_phys_addr_t offset) +{ + uint32_t *val = (uint32_t *) opaque; + + return *val >> ((offset & 3) << 3); +} + +static uint32_t static_readh(void *opaque, target_phys_addr_t offset) +{ + uint32_t *val = (uint32_t *) opaque; + + return *val >> ((offset & 1) << 3); +} + +static uint32_t static_readw(void *opaque, target_phys_addr_t offset) +{ + uint32_t *val = (uint32_t *) opaque; + + return *val >> ((offset & 0) << 3); +} + +static void static_write(void *opaque, target_phys_addr_t offset, + uint32_t value) +{ +#ifdef SPY + printf("%s: value %08lx written at " PA_FMT "\n", + __FUNCTION__, value, offset); +#endif +} + +static CPUReadMemoryFunc * const static_readfn[] = { + static_readb, + static_readh, + static_readw, +}; + +static CPUWriteMemoryFunc * const static_writefn[] = { + static_write, + static_write, + static_write, +}; + +#define sdram_size 0x02000000 +#define sector_size (128 * 1024) +#define flash0_size (16 * 1024 * 1024) +#define flash1_size ( 8 * 1024 * 1024) +#define flash2_size (32 * 1024 * 1024) +#define total_ram_v1 (sdram_size + flash0_size + flash1_size + OMAP15XX_SRAM_SIZE) +#define total_ram_v2 (sdram_size + flash2_size + OMAP15XX_SRAM_SIZE) + +static struct arm_boot_info sx1_binfo = { + .loader_start = OMAP_EMIFF_BASE, + .ram_size = sdram_size, + .board_id = 0x265, +}; + +static void sx1_init(ram_addr_t ram_size, + const char *boot_device, + const char *kernel_filename, const char *kernel_cmdline, + const char *initrd_filename, const char *cpu_model, + const int version) +{ + struct omap_mpu_state_s *cpu; + int io; + static uint32_t cs0val = 0x00213090; + static uint32_t cs1val = 0x00215070; + static uint32_t cs2val = 0x00001139; + static uint32_t cs3val = 0x00001139; + ram_addr_t phys_flash; + DriveInfo *dinfo; + int fl_idx; + uint32_t flash_size = flash0_size; + int be; + + if (version == 2) { + flash_size = flash2_size; + } + + cpu = omap310_mpu_init(sx1_binfo.ram_size, cpu_model); + + /* External Flash (EMIFS) */ + cpu_register_physical_memory(OMAP_CS0_BASE, flash_size, + (phys_flash = qemu_ram_alloc(flash_size)) | IO_MEM_ROM); + + io = cpu_register_io_memory(static_readfn, static_writefn, &cs0val); + cpu_register_physical_memory(OMAP_CS0_BASE + flash_size, + OMAP_CS0_SIZE - flash_size, io); + io = cpu_register_io_memory(static_readfn, static_writefn, &cs2val); + cpu_register_physical_memory(OMAP_CS2_BASE, OMAP_CS2_SIZE, io); + io = cpu_register_io_memory(static_readfn, static_writefn, &cs3val); + cpu_register_physical_memory(OMAP_CS3_BASE, OMAP_CS3_SIZE, io); + + fl_idx = 0; +#ifdef TARGET_WORDS_BIGENDIAN + be = 1; +#else + be = 0; +#endif + + if ((dinfo = drive_get(IF_PFLASH, 0, fl_idx)) != NULL) { + if (!pflash_cfi01_register(OMAP_CS0_BASE, qemu_ram_alloc(flash_size), + dinfo->bdrv, sector_size, + flash_size / sector_size, + 4, 0, 0, 0, 0, be)) { + fprintf(stderr, "qemu: Error registering flash memory %d.\n", + fl_idx); + } + fl_idx++; + } + + if ((version == 1) && + (dinfo = drive_get(IF_PFLASH, 0, fl_idx)) != NULL) { + cpu_register_physical_memory(OMAP_CS1_BASE, flash1_size, + (phys_flash = qemu_ram_alloc(flash1_size)) | + IO_MEM_ROM); + io = cpu_register_io_memory(static_readfn, static_writefn, &cs1val); + cpu_register_physical_memory(OMAP_CS1_BASE + flash1_size, + OMAP_CS1_SIZE - flash1_size, io); + + if (!pflash_cfi01_register(OMAP_CS1_BASE, qemu_ram_alloc(flash1_size), + dinfo->bdrv, sector_size, + flash1_size / sector_size, + 4, 0, 0, 0, 0, be)) { + fprintf(stderr, "qemu: Error registering flash memory %d.\n", + fl_idx); + } + fl_idx++; + } else { + io = cpu_register_io_memory(static_readfn, static_writefn, &cs1val); + cpu_register_physical_memory(OMAP_CS1_BASE, OMAP_CS1_SIZE, io); + } + + if (!kernel_filename && !fl_idx) { + fprintf(stderr, "Kernel or Flash image must be specified\n"); + exit(1); + } + + /* Load the kernel. */ + if (kernel_filename) { + /* Start at bootloader. */ + cpu->env->regs[15] = sx1_binfo.loader_start; + + sx1_binfo.kernel_filename = kernel_filename; + sx1_binfo.kernel_cmdline = kernel_cmdline; + sx1_binfo.initrd_filename = initrd_filename; + arm_load_kernel(cpu->env, &sx1_binfo); + } else { + cpu->env->regs[15] = 0x00000000; + } + + /* TODO: fix next line */ + //~ qemu_console_resize(ds, 640, 480); +} + +static void sx1_init_v1(ram_addr_t ram_size, + const char *boot_device, + const char *kernel_filename, const char *kernel_cmdline, + const char *initrd_filename, const char *cpu_model) +{ + sx1_init(ram_size, boot_device, kernel_filename, + kernel_cmdline, initrd_filename, cpu_model, 1); +} + +static void sx1_init_v2(ram_addr_t ram_size, + const char *boot_device, + const char *kernel_filename, const char *kernel_cmdline, + const char *initrd_filename, const char *cpu_model) +{ + sx1_init(ram_size, boot_device, kernel_filename, + kernel_cmdline, initrd_filename, cpu_model, 2); +} + +static QEMUMachine sx1_machine_v2 = { + .name = "sx1", + .desc = "Siemens SX1 (OMAP310) V2", + .init = sx1_init_v2, +}; + +static QEMUMachine sx1_machine_v1 = { + .name = "sx1-v1", + .desc = "Siemens SX1 (OMAP310) V1", + .init = sx1_init_v1, +}; + +static void sx1_machine_init(void) +{ + qemu_register_machine(&sx1_machine_v2); + qemu_register_machine(&sx1_machine_v1); +} + +machine_init(sx1_machine_init); diff --git a/pool/shard008/C/0129765_mem.c b/pool/shard008/C/0129765_mem.c new file mode 100644 index 0000000000000000000000000000000000000000..7d2195a87fcd29aa41c1725a28efe8b3a9c13a99 --- /dev/null +++ b/pool/shard008/C/0129765_mem.c @@ -0,0 +1,151 @@ +/** + * @file + * @brief read from memory + * + * @date 13.02.09 + * @author Alexey Fomin + * @author Anton Kozlov + * - access_type added + */ + +#include +#include +#include +#include +#include +#include + +#define DEFAULT_LENGTH 0x4 + +#if (__WORDSIZE == 32) +#define PRINT_POINTER_WIDTH "8" +#elif (__WORDSIZE == 64) +#define PRINT_POINTER_WIDTH "16" +#endif + +enum access_type { + MEM_AT_CHAR, + MEM_AT_SHORT, + MEM_AT_LONG, +}; + +static const char *fmts[] = { + "0x%02lx ", + "0x%04lx ", + "0x%0" PRINT_POINTER_WIDTH "lx ", +}; + +static const size_t aalign[] = { + sizeof(char), + sizeof(short), + sizeof(long), +}; + +static void print_usage(void) { + printf("Usage: mem [-h] [-l -s -c] addr [-n count]\n"); +} + +static int parse_option(char *optarg, int opt, long unsigned int *number) { + char *endptr; + + if ((optarg == NULL) || (*optarg == '\0')) { + printf("mem -%c: option expected\n", opt); + print_usage(); + return -EINVAL; + } + + *number = strtoul(optarg, &endptr, 0); + if (*endptr != '\0') { + printf("mem -%c: invalid option: %s\n", opt, optarg); + print_usage(); + return -EINVAL; + } + + return 0; +} + +int main(int argc, char **argv) { + int opt, ret; + void *address; + unsigned long val; + size_t length = DEFAULT_LENGTH; + size_t align; + bool length_passed = false; + enum access_type at = MEM_AT_LONG; + + while (-1 != (opt = getopt(argc, argv, "n:hcsl"))) { + switch (opt) { + case 'n': + length_passed = true; + ret = parse_option(optarg, opt, (unsigned long int *) &length); + if (ret != 0) { + return ret; + } + break; + + case 'l': + at = MEM_AT_LONG; + break; + case 's': + at = MEM_AT_SHORT; + break; + case 'c': + at = MEM_AT_CHAR; + break; + + case '?': + case 'h': + print_usage(); + /* FALLTHROUGH */ + default: + return 0; + } + } + + errno = 0; + if (length_passed) { + address = (void *) strtoul(argv[argc - 3], 0, 0); + } else { + address = (void *) strtoul(argv[argc - 1], 0, 0); + } + + if (errno != 0) { + printf("Failed to get address!\n"); + print_usage(); + return -EINVAL; + } + + if ((uintptr_t) address & ((1 << at) - 1)) { + printf("address is not aligned to selected mem access\n"); + return -EINVAL; + } + + align = (uintptr_t) address & 0xF; + /*address = (unsigned int *) ((int) address & ~(sizeof(address) - 1));*/ + /*length = (length + sizeof(address) - 1) / sizeof(address);*/ + while (length--) { + if (0 == (((uintptr_t)address - align) & 0xF)) { + printf("\n0x%0" PRIxPTR ":\t", (uintptr_t) address); + } + + switch (at) { + default: + case MEM_AT_LONG: + val = *(unsigned long *) address; + break; + case MEM_AT_SHORT: + val = *(unsigned short *) address; + break; + case MEM_AT_CHAR: + val = *(unsigned char *) address; + break; + } + + printf(fmts[at], val); + + address += aalign[at]; + } + printf("\n"); + + return 0; +} diff --git a/pool/shard008/C/0129767_mic_reg_5430.c b/pool/shard008/C/0129767_mic_reg_5430.c new file mode 100644 index 0000000000000000000000000000000000000000..d4d73b69c88688ff97528c744e15305d1b362273 --- /dev/null +++ b/pool/shard008/C/0129767_mic_reg_5430.c @@ -0,0 +1,160 @@ +/* linux/drivers/video/decon_display/mic_reg_5430.c + * + * Copyright 2013-2015 Samsung Electronics + * Jiun Yu + * + * Jiun Yu + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. +*/ + +#include "mic_reg.h" + +/******************* CAL raw functions implementation *************************/ +int mic_reg_sw_reset(void) +{ + int tries; + + mic_write_mask(MIC_OP, ~0, MIC_OP_SW_RST); + + for (tries = 100; tries; --tries) { + if (~(mic_read(MIC_OP) & MIC_OP_SW_RST)) + break; + udelay(1); + } + + if (!tries) { + mic_err("failed to reset MIC\n"); + return -EBUSY; + } + + return 0; +} + +void mic_reg_set_image_size(struct decon_lcd *lcd) +{ + u32 val; + + val = MIC_IMG_V_SIZE(lcd->yres) | MIC_IMG_H_SIZE(lcd->xres); + mic_write(MIC_IMG_SIZE, val); +} + +void mic_reg_set_mic_base_operation(struct decon_lcd *lcd, bool enable) +{ + u32 data = mic_read(MIC_OP); + + if (enable) { + data &= ~(MIC_OP_CORE_ENABLE | MIC_OP_COMMAND_MODE | + MIC_OP_OLD_CORE | MIC_OP_PSR_EN | + MIC_OP_BS_CHG_OUT | MIC_OP_ON_REG | + MIC_OP_UPDATE_REG); + data |= MIC_OP_CORE_ENABLE | MIC_OP_NEW_CORE | + MIC_OP_UPDATE_REG | MIC_OP_ON_REG; + + if(lcd->mic_bitstream_swap) + data |= MIC_OP_BS_CHG_OUT; + + if (lcd->mode == COMMAND_MODE) + data |= MIC_OP_COMMAND_MODE; + else + data |= MIC_OP_VIDEO_MODE; + } else { + data &= ~MIC_OP_CORE_ENABLE; + data |= MIC_OP_UPDATE_REG; + } + + mic_write(MIC_OP, data); +} + +void mic_reg_set_update(u32 en) +{ + u32 val = en ? ~0 : 0; + mic_write_mask(MIC_OP, val, MIC_OP_UPDATE_REG); +} + +void mic_reg_set_porch_timing(struct decon_lcd *lcd) +{ + u32 data, v_period, h_period; + + if(lcd->mode != COMMAND_MODE) { + v_period = lcd->vsa + lcd->yres + lcd->vbp + lcd->vfp; + data = MIC_V_TIMING_0_V_PULSE_WIDTH(lcd->vsa) | + MIC_V_TIMING_0_V_PERIOD_LINE(v_period); + mic_write(MIC_V_TIMING_0, data); + + data = MIC_V_TIMING_1_VBP_SIZE(lcd->vbp) | + MIC_V_TIMING_1_VFP_SIZE(lcd->vfp); + mic_write(MIC_V_TIMING_1, data); + + h_period = lcd->hsa + lcd->xres + lcd->hbp + lcd->hfp; + data = MIC_INPUT_TIMING_0_H_PULSE_WIDTH(lcd->hsa) | + MIC_INPUT_TIMING_0_H_PERIOD_PIXEL(h_period); + mic_write(MIC_INPUT_TIMING_0, data); + + data = MIC_INPUT_TIMING_1_HBP_SIZE(lcd->hbp) | + MIC_INPUT_TIMING_1_HFP_SIZE(lcd->hfp); + mic_write(MIC_INPUT_TIMING_1, data); + } +} + +void mic_reg_set_output_timing(struct decon_lcd *lcd) +{ + u32 data, h_period_2d; + u32 bs_2d = (lcd->xres >> 1) + (lcd->xres % 4); + u32 hsa_2d = lcd->hsa; + u32 hbp_2d = lcd->hbp; + u32 hfp_2d = lcd->hfp + bs_2d; + + /* is it correct? plus bs_2d twice */ + h_period_2d = hsa_2d + hbp_2d + bs_2d + hfp_2d; + + if(lcd->mode != COMMAND_MODE) { + data = MIC_2D_OUTPUT_TIMING_0_H_PULSE_WIDTH_2D(hsa_2d) | + MIC_2D_OUTPUT_TIMING_0_H_PERIOD_PIXEL_2D(h_period_2d); + mic_write(MIC_2D_OUTPUT_TIMING_0, data); + + data = MIC_2D_OUTPUT_TIMING_1_HBP_SIZE_2D(hbp_2d) | + MIC_2D_OUTPUT_TIMING_1_HFP_SIZE_2D(hfp_2d); + mic_write(MIC_2D_OUTPUT_TIMING_1, data); + } + + mic_write(MIC_2D_OUTPUT_TIMING_2, bs_2d); +} + +void mic_reg_set_win_update_conf(u32 w, u32 h) +{ + u32 data; + u32 bs_2d = ((w >> 2) << 1) + (w & 0x3); + + mic_reg_set_update(0); + /* Image Size */ + data = MIC_IMG_V_SIZE(h) | MIC_IMG_H_SIZE(w); + mic_write(MIC_IMG_SIZE, data); + + /* 2d_bit_stream_size */ + mic_write(MIC_2D_OUTPUT_TIMING_2, bs_2d); + mic_reg_set_update(1); + + /* TODO: porch settings */ +} + +/***************** CAL APIs implementation *******************/ +int mic_reg_start(struct decon_lcd *lcd) +{ + mic_reg_sw_reset(); + mic_reg_set_porch_timing(lcd); + mic_reg_set_image_size(lcd); + mic_reg_set_output_timing(lcd); + mic_reg_set_mic_base_operation(lcd, 1); + + return 0; +} + +int mic_reg_stop(struct decon_lcd *lcd) +{ + mic_reg_set_mic_base_operation(lcd, 0); + + return 0; +} diff --git a/pool/shard008/C/0129768_program_options.c b/pool/shard008/C/0129768_program_options.c new file mode 100644 index 0000000000000000000000000000000000000000..a11544a408bbd92870387e86dfe5e068f62f877b --- /dev/null +++ b/pool/shard008/C/0129768_program_options.c @@ -0,0 +1,71 @@ +#include "program_options.h" +#include +#include +#include +#include + +bool silence_program_options_parse = false; + +const char* program_options_usage() { + return + "\n" + "OPTIONS:\n" + " -p Set the port to listen on\n" + " -v Enable verbose output\n" + " -e Echo the request, for debugging\n" + " -h Show this help message\n" + "\n" + ; +} + +void program_options_print(ProgramOptions* options) { + printf("Options\n"); + printf(" - port: %i\n", options->config.port); + printf(" - verbose: %s\n", options->config.verbose ? "yes" : "no"); + printf(" - echo: %s\n", options->config.echo ? "yes" : "no"); +} + +bool program_options_parse(ProgramOptions* options, int argc, char** argv) { + // Tell getopt() not to print error messages + opterr = 0; + + // Reset the option-parsing index (so tests can use getopt more than once) + optind = 1; + + // Set defaults + options->help = false; + webserver_config_init(&options->config); + + // Parse command-line inputs + char c = 0; + while((c = getopt(argc, argv, "p:veh")) != -1) { + switch(c) { + case 'p': + options->config.port = atoi(optarg); + break; + case 'v': + options->config.verbose = true; + break; + case 'e': + options->config.echo = true; + break; + case 'h': + options->help = true; + break; + case '?': + if(!silence_program_options_parse) { + if(optopt == 'p') { + fprintf(stderr, "ERROR: Option -p requires an argument\n"); + } + else if(isprint(optopt)) { + fprintf(stderr, "ERROR: Unknown option '-%c'\n", optopt); + } + else { + fprintf(stderr, "ERROR: Unknown option character '\\x%x'\n", optopt); + } + } + return false; + } + } + return true; +} diff --git a/pool/shard008/C/0129772_cos.zep.c b/pool/shard008/C/0129772_cos.zep.c new file mode 100644 index 0000000000000000000000000000000000000000..693c0a38a957803aada57911d999eeb654088dc6 --- /dev/null +++ b/pool/shard008/C/0129772_cos.zep.c @@ -0,0 +1,109 @@ + +#ifdef HAVE_CONFIG_H +#include "../../ext_config.h" +#endif + +#include +#include "../../php_ext.h" +#include "../../ext.h" + +#include +#include +#include + +#include "kernel/main.h" +#include "kernel/memory.h" +#include "math.h" +#include "kernel/operators.h" +#include "kernel/math.h" + + +ZEPHIR_INIT_CLASS(Test_Optimizers_Cos) { + + ZEPHIR_REGISTER_CLASS(Test\\Optimizers, Cos, test, optimizers_cos, test_optimizers_cos_method_entry, 0); + + return SUCCESS; + +} + +PHP_METHOD(Test_Optimizers_Cos, testInt) { + + zval *_0; + int a; + + ZEPHIR_MM_GROW(); + + a = 4; + ZEPHIR_INIT_VAR(_0); + ZVAL_LONG(_0, a); + RETURN_MM_DOUBLE(cos(a)); + +} + +PHP_METHOD(Test_Optimizers_Cos, testVar) { + + zval *_0; + int a; + + ZEPHIR_MM_GROW(); + + a = 4; + ZEPHIR_INIT_VAR(_0); + ZVAL_LONG(_0, a); + RETURN_MM_DOUBLE(cos(a)); + +} + +PHP_METHOD(Test_Optimizers_Cos, testIntValue1) { + + zval *_0; + + ZEPHIR_MM_GROW(); + + ZEPHIR_INIT_VAR(_0); + ZVAL_LONG(_0, 4); + RETURN_MM_DOUBLE(cos(4)); + +} + +PHP_METHOD(Test_Optimizers_Cos, testIntValue2) { + + zval *_0; + + ZEPHIR_MM_GROW(); + + ZEPHIR_INIT_VAR(_0); + ZVAL_LONG(_0, 16); + RETURN_MM_DOUBLE(cos(16)); + +} + +PHP_METHOD(Test_Optimizers_Cos, testIntParameter) { + + zval *a_param = NULL, *_0; + int a; + + ZEPHIR_MM_GROW(); + zephir_fetch_params(1, 1, 0, &a_param); + + a = zephir_get_intval(a_param); + + + ZEPHIR_INIT_VAR(_0); + ZVAL_LONG(_0, a); + RETURN_MM_DOUBLE(cos(a)); + +} + +PHP_METHOD(Test_Optimizers_Cos, testVarParameter) { + + zval *a; + + zephir_fetch_params(0, 1, 0, &a); + + + + RETURN_DOUBLE(zephir_cos(a TSRMLS_CC)); + +} + diff --git a/pool/shard008/C/0129776_Filter.c b/pool/shard008/C/0129776_Filter.c new file mode 100644 index 0000000000000000000000000000000000000000..73c0d6e9018b459c63cebbe27279bd28f335a5e5 --- /dev/null +++ b/pool/shard008/C/0129776_Filter.c @@ -0,0 +1,52 @@ +int rightValues[5]; +int leftValues[5]; + +int doFilter(int * valueList) { + // get total + int total = 0; + + + int biggest = valueList[0]; + int lowest = valueList[0]; + + + for(int i = 0; i < 5; i++){ + total += valueList[i]; + + if(valueList[i] > biggest){ + biggest = valueList[i]; + } + + if(valueList[i] < lowest){ + lowest = valueList[i]; + } + + } +int filteredTotal = total - (biggest + lowest); +int filterAverage = (filteredTotal/3); + +return filterAverage; + +} + +int filterLeft(int value){ + // maintain left list + for(int i=4; i > 0; --i){ + leftValues[i] = leftValues[i-1]; + } + + leftValues[0] = value; + //get total + return doFilter(leftValues); +} + +int filterRight(int value){ + // maintain list + for(int i = 4; i > 0; --i){ + rightValues[i] = rightValues[i-1]; + } + + rightValues[0] = value; + // get total + return doFilter(rightValues); +} diff --git a/pool/shard008/C/0129781_mtv.c b/pool/shard008/C/0129781_mtv.c new file mode 100644 index 0000000000000000000000000000000000000000..fff72b4739b95207ba7efe50e8fe64073aa1b4b9 --- /dev/null +++ b/pool/shard008/C/0129781_mtv.c @@ -0,0 +1,186 @@ +/* + * mtv demuxer + * Copyright (c) 2006 Reynaldo H. Verdejo Pinochet + * + * This file is part of FFmpeg. + * + * FFmpeg 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. + * + * FFmpeg 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 FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/** + * @file mtv.c + * MTV demuxer. + */ + +#include "avformat.h" +#include "bswap.h" + +#define MTV_ASUBCHUNK_DATA_SIZE 500 +#define MTV_HEADER_SIZE 512 +#define MTV_AUDIO_PADDING_SIZE 12 +#define AUDIO_SAMPLING_RATE 44100 +#define VIDEO_SID 0 +#define AUDIO_SID 1 + +typedef struct MTVDemuxContext { + + unsigned int file_size; ///< filesize, not always right + unsigned int segments; ///< number of 512 byte segments + unsigned int audio_identifier; ///< 'MP3' on all files I have seen + unsigned int audio_br; ///< bitrate of audio chanel (mp3) + unsigned int img_colorfmt; ///< frame colorfmt rgb 565/555 + unsigned int img_bpp; ///< frame bits per pixel + unsigned int img_width; // + unsigned int img_height; // + unsigned int img_segment_size; ///< size of image segment + unsigned int video_fps; // + unsigned int audio_subsegments; ///< audio subsegments on one segment + + uint8_t audio_packet_count; + +} MTVDemuxContext; + +static int mtv_probe(AVProbeData *p) +{ + if(p->buf_size < 3) + return 0; + + /* Magic is 'AMV' */ + + if(*(p->buf) != 'A' || *(p->buf+1) != 'M' || *(p->buf+2) != 'V') + return 0; + + return AVPROBE_SCORE_MAX; +} + +static int mtv_read_header(AVFormatContext *s, AVFormatParameters *ap) +{ + MTVDemuxContext *mtv = s->priv_data; + ByteIOContext *pb = &s->pb; + AVStream *st; + + + url_fskip(pb, 3); + mtv->file_size = get_le32(pb); + mtv->segments = get_le32(pb); + url_fskip(pb, 32); + mtv->audio_identifier = get_le24(pb); + mtv->audio_br = get_le16(pb); + mtv->img_colorfmt = get_le24(pb); + mtv->img_bpp = get_byte(pb); + mtv->img_width = get_le16(pb); + mtv->img_height = get_le16(pb); + mtv->img_segment_size = get_le16(pb); + url_fskip(pb, 4); + mtv->audio_subsegments = get_le16(pb); + mtv->video_fps = (mtv->audio_br / 4) / mtv->audio_subsegments; + + /* FIXME Add sanity check here */ + + /* first packet is allways audio*/ + + mtv->audio_packet_count = 1; + + /* all systems go! init decoders */ + + /* video - raw rgb565 */ + + st = av_new_stream(s, VIDEO_SID); + if(!st) + return AVERROR_NOMEM; + + av_set_pts_info(st, 64, 1, mtv->video_fps); + st->codec->codec_type = CODEC_TYPE_VIDEO; + st->codec->codec_id = CODEC_ID_RAWVIDEO; + st->codec->width = mtv->img_width; + st->codec->height = mtv->img_height; + st->codec->bits_per_sample = mtv->img_bpp; + st->codec->sample_rate = mtv->video_fps; + + /* audio - mp3 */ + + st = av_new_stream(s, AUDIO_SID); + if(!st) + return AVERROR_NOMEM; + + av_set_pts_info(st, 64, 1, AUDIO_SAMPLING_RATE); + st->codec->codec_type = CODEC_TYPE_AUDIO; + st->codec->codec_id = CODEC_ID_MP3; + st->codec->bit_rate = mtv->audio_br; + st->need_parsing=1; + + /* Jump over header */ + + if(url_fseek(pb, MTV_HEADER_SIZE, SEEK_SET) != MTV_HEADER_SIZE) + return AVERROR_IO; + + return(0); + +} + +static int mtv_read_packet(AVFormatContext *s, AVPacket *pkt) +{ + MTVDemuxContext *mtv = s->priv_data; + ByteIOContext *pb = &s->pb; + int ret; +#ifndef WORDS_BIGENDIAN + int i; +#endif + + ret = 0; + + if(mtv->audio_subsegments >= mtv->audio_packet_count) + { + url_fskip(pb, MTV_AUDIO_PADDING_SIZE); + + ret = av_get_packet(pb, pkt, MTV_ASUBCHUNK_DATA_SIZE); + if(ret != MTV_ASUBCHUNK_DATA_SIZE) + return AVERROR_IO; + + mtv->audio_packet_count++; + pkt->stream_index = AUDIO_SID; + + }else + { + ret = av_get_packet(pb, pkt, mtv->img_segment_size); + if(ret != mtv->img_segment_size) + return AVERROR_IO; + +#ifndef WORDS_BIGENDIAN + + /* pkt->data is GGGRRRR BBBBBGGG + * and we need RRRRRGGG GGGBBBBB + * for PIX_FMT_RGB565 so here we + * just swap bytes as they come + */ + + for(i=0;iimg_segment_size/2;i++) + *((uint16_t *)pkt->data+i) = bswap_16(*((uint16_t *)pkt->data+i)); +#endif + mtv->audio_packet_count = 1; + pkt->stream_index = VIDEO_SID; + } + + return(ret); +} + +AVInputFormat mtv_demuxer = { + "MTV", + "MTV format", + sizeof(MTVDemuxContext), + mtv_probe, + mtv_read_header, + mtv_read_packet, +}; diff --git a/pool/shard008/C/0129784_st_pressure_spi.c b/pool/shard008/C/0129784_st_pressure_spi.c new file mode 100644 index 0000000000000000000000000000000000000000..7c8b70221e705f38aa6dbf6a3fcd50decc75a6f6 --- /dev/null +++ b/pool/shard008/C/0129784_st_pressure_spi.c @@ -0,0 +1,129 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * STMicroelectronics pressures driver + * + * Copyright 2013 STMicroelectronics Inc. + * + * Denis Ciocca + */ + +#include +#include +#include +#include +#include + +#include +#include +#include "st_pressure.h" + +#ifdef CONFIG_OF +/* + * For new single-chip sensors use as compatible string. + * For old single-chip devices keep -press to maintain + * compatibility + */ +static const struct of_device_id st_press_of_match[] = { + { + .compatible = "st,lps001wp-press", + .data = LPS001WP_PRESS_DEV_NAME, + }, + { + .compatible = "st,lps25h-press", + .data = LPS25H_PRESS_DEV_NAME, + }, + { + .compatible = "st,lps331ap-press", + .data = LPS331AP_PRESS_DEV_NAME, + }, + { + .compatible = "st,lps22hb-press", + .data = LPS22HB_PRESS_DEV_NAME, + }, + { + .compatible = "st,lps33hw", + .data = LPS33HW_PRESS_DEV_NAME, + }, + { + .compatible = "st,lps35hw", + .data = LPS35HW_PRESS_DEV_NAME, + }, + { + .compatible = "st,lps22hh", + .data = LPS22HH_PRESS_DEV_NAME, + }, + {}, +}; +MODULE_DEVICE_TABLE(of, st_press_of_match); +#else +#define st_press_of_match NULL +#endif + +static int st_press_spi_probe(struct spi_device *spi) +{ + const struct st_sensor_settings *settings; + struct st_sensor_data *press_data; + struct iio_dev *indio_dev; + int err; + + st_sensors_of_name_probe(&spi->dev, st_press_of_match, + spi->modalias, sizeof(spi->modalias)); + + settings = st_press_get_settings(spi->modalias); + if (!settings) { + dev_err(&spi->dev, "device name %s not recognized.\n", + spi->modalias); + return -ENODEV; + } + + indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*press_data)); + if (!indio_dev) + return -ENOMEM; + + press_data = iio_priv(indio_dev); + press_data->sensor_settings = (struct st_sensor_settings *)settings; + + err = st_sensors_spi_configure(indio_dev, spi); + if (err < 0) + return err; + + err = st_press_common_probe(indio_dev); + if (err < 0) + return err; + + return 0; +} + +static int st_press_spi_remove(struct spi_device *spi) +{ + st_press_common_remove(spi_get_drvdata(spi)); + + return 0; +} + +static const struct spi_device_id st_press_id_table[] = { + { LPS001WP_PRESS_DEV_NAME }, + { LPS25H_PRESS_DEV_NAME }, + { LPS331AP_PRESS_DEV_NAME }, + { LPS22HB_PRESS_DEV_NAME }, + { LPS33HW_PRESS_DEV_NAME }, + { LPS35HW_PRESS_DEV_NAME }, + { LPS22HH_PRESS_DEV_NAME }, + {}, +}; +MODULE_DEVICE_TABLE(spi, st_press_id_table); + +static struct spi_driver st_press_driver = { + .driver = { + .name = "st-press-spi", + .of_match_table = of_match_ptr(st_press_of_match), + }, + .probe = st_press_spi_probe, + .remove = st_press_spi_remove, + .id_table = st_press_id_table, +}; +module_spi_driver(st_press_driver); + +MODULE_AUTHOR("Denis Ciocca "); +MODULE_DESCRIPTION("STMicroelectronics pressures spi driver"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard008/C/0129791_lapacke_sgtrfs_work.c b/pool/shard008/C/0129791_lapacke_sgtrfs_work.c new file mode 100644 index 0000000000000000000000000000000000000000..b4ec17eea491ccc05c734d109ef9579d43240956 --- /dev/null +++ b/pool/shard008/C/0129791_lapacke_sgtrfs_work.c @@ -0,0 +1,107 @@ +/***************************************************************************** + Copyright (c) 2011, Intel Corp. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Intel Corporation nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + THE POSSIBILITY OF SUCH DAMAGE. +***************************************************************************** +* Contents: Native middle-level C interface to LAPACK function sgtrfs +* Author: Intel Corporation +* Generated November, 2011 +*****************************************************************************/ + +#include "lapacke.h" +#include "lapacke_utils.h" + +lapack_int LAPACKE_sgtrfs_work( int matrix_order, char trans, lapack_int n, + lapack_int nrhs, const float* dl, + const float* d, const float* du, + const float* dlf, const float* df, + const float* duf, const float* du2, + const lapack_int* ipiv, const float* b, + lapack_int ldb, float* x, lapack_int ldx, + float* ferr, float* berr, float* work, + lapack_int* iwork ) +{ + lapack_int info = 0; + if( matrix_order == LAPACK_COL_MAJOR ) { + /* Call LAPACK function and adjust info */ + LAPACK_sgtrfs( &trans, &n, &nrhs, dl, d, du, dlf, df, duf, du2, ipiv, b, + &ldb, x, &ldx, ferr, berr, work, iwork, &info ); + if( info < 0 ) { + info = info - 1; + } + } else if( matrix_order == LAPACK_ROW_MAJOR ) { + lapack_int ldb_t = MAX(1,n); + lapack_int ldx_t = MAX(1,n); + float* b_t = NULL; + float* x_t = NULL; + /* Check leading dimension(s) */ + if( ldb < nrhs ) { + info = -14; + LAPACKE_xerbla( "LAPACKE_sgtrfs_work", info ); + return info; + } + if( ldx < nrhs ) { + info = -16; + LAPACKE_xerbla( "LAPACKE_sgtrfs_work", info ); + return info; + } + /* Allocate memory for temporary array(s) */ + b_t = (float*)LAPACKE_malloc( sizeof(float) * ldb_t * MAX(1,nrhs) ); + if( b_t == NULL ) { + info = LAPACK_TRANSPOSE_MEMORY_ERROR; + goto exit_level_0; + } + x_t = (float*)LAPACKE_malloc( sizeof(float) * ldx_t * MAX(1,nrhs) ); + if( x_t == NULL ) { + info = LAPACK_TRANSPOSE_MEMORY_ERROR; + goto exit_level_1; + } + /* Transpose input matrices */ + LAPACKE_sge_trans( matrix_order, n, nrhs, b, ldb, b_t, ldb_t ); + LAPACKE_sge_trans( matrix_order, n, nrhs, x, ldx, x_t, ldx_t ); + /* Call LAPACK function and adjust info */ + LAPACK_sgtrfs( &trans, &n, &nrhs, dl, d, du, dlf, df, duf, du2, ipiv, + b_t, &ldb_t, x_t, &ldx_t, ferr, berr, work, iwork, + &info ); + if( info < 0 ) { + info = info - 1; + } + /* Transpose output matrices */ + LAPACKE_sge_trans( LAPACK_COL_MAJOR, n, nrhs, x_t, ldx_t, x, ldx ); + /* Release memory and exit */ + LAPACKE_free( x_t ); +exit_level_1: + LAPACKE_free( b_t ); +exit_level_0: + if( info == LAPACK_TRANSPOSE_MEMORY_ERROR ) { + LAPACKE_xerbla( "LAPACKE_sgtrfs_work", info ); + } + } else { + info = -1; + LAPACKE_xerbla( "LAPACKE_sgtrfs_work", info ); + } + return info; +} diff --git a/pool/shard008/C/0129792_set_ui.c b/pool/shard008/C/0129792_set_ui.c new file mode 100644 index 0000000000000000000000000000000000000000..7a9f8efcf0b0f8523aacbdbedf05a962268e09fb --- /dev/null +++ b/pool/shard008/C/0129792_set_ui.c @@ -0,0 +1,31 @@ +/* + Copyright (C) 2016 William Hart + Copyright (C) 2017 Daniel Schultz + + This file is part of FLINT. + + FLINT is free software: you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License (LGPL) as published + by the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. See . +*/ + +#include "fmpz_mpoly.h" + +void fmpz_mpoly_set_ui(fmpz_mpoly_t A, ulong c, const fmpz_mpoly_ctx_t ctx) +{ + slong N = mpoly_words_per_exp(A->bits, ctx->minfo); + + if (c == 0) + { + _fmpz_mpoly_set_length(A, 0, ctx); + return; + } + + N = mpoly_words_per_exp(A->bits, ctx->minfo); + + fmpz_mpoly_fit_length(A, 1, ctx); + fmpz_set_ui(A->coeffs + 0, c); + mpoly_monomial_zero(A->exps + N*0, N); + _fmpz_mpoly_set_length(A, 1, ctx); +} diff --git a/pool/shard008/C/0129793_sockets.c b/pool/shard008/C/0129793_sockets.c new file mode 100644 index 0000000000000000000000000000000000000000..7053aee5bc719242d409b33954a4d339ba54e20a --- /dev/null +++ b/pool/shard008/C/0129793_sockets.c @@ -0,0 +1,156 @@ +/* -*- buffer-read-only: t -*- vi: set ro: */ +/* DO NOT EDIT! GENERATED AUTOMATICALLY! */ +/* sockets.c --- wrappers for Windows socket functions + + Copyright (C) 2008-2011 Free Software Foundation, Inc. + + 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 2.1 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 . */ + +/* Written by Simon Josefsson */ + +#include + +/* Specification. */ +#include "sockets.h" + +#if WINDOWS_SOCKETS + +/* This includes winsock2.h on MinGW. */ +# include + +# include "fd-hook.h" +# include "msvc-nothrow.h" + +/* Get set_winsock_errno, FD_TO_SOCKET etc. */ +# include "w32sock.h" + +static int +close_fd_maybe_socket (const struct fd_hook *remaining_list, + gl_close_fn primary, + int fd) +{ + /* Note about multithread-safety: There is a race condition where, between + our calls to closesocket() and the primary close(), some other thread + could make system calls that allocate precisely the same HANDLE value + as sock; then the primary close() would call CloseHandle() on it. */ + SOCKET sock; + WSANETWORKEVENTS ev; + + /* Test whether fd refers to a socket. */ + sock = FD_TO_SOCKET (fd); + ev.lNetworkEvents = 0xDEADBEEF; + WSAEnumNetworkEvents (sock, NULL, &ev); + if (ev.lNetworkEvents != 0xDEADBEEF) + { + /* fd refers to a socket. */ + /* FIXME: other applications, like squid, use an undocumented + _free_osfhnd free function. But this is not enough: The 'osfile' + flags for fd also needs to be cleared, but it is hard to access it. + Instead, here we just close twice the file descriptor. */ + if (closesocket (sock)) + { + set_winsock_errno (); + return -1; + } + else + { + /* This call frees the file descriptor and does a + CloseHandle ((HANDLE) _get_osfhandle (fd)), which fails. */ + _close (fd); + return 0; + } + } + else + /* Some other type of file descriptor. */ + return execute_close_hooks (remaining_list, primary, fd); +} + +static int +ioctl_fd_maybe_socket (const struct fd_hook *remaining_list, + gl_ioctl_fn primary, + int fd, int request, void *arg) +{ + SOCKET sock; + WSANETWORKEVENTS ev; + + /* Test whether fd refers to a socket. */ + sock = FD_TO_SOCKET (fd); + ev.lNetworkEvents = 0xDEADBEEF; + WSAEnumNetworkEvents (sock, NULL, &ev); + if (ev.lNetworkEvents != 0xDEADBEEF) + { + /* fd refers to a socket. */ + if (ioctlsocket (sock, request, arg) < 0) + { + set_winsock_errno (); + return -1; + } + else + return 0; + } + else + /* Some other type of file descriptor. */ + return execute_ioctl_hooks (remaining_list, primary, fd, request, arg); +} + +static struct fd_hook fd_sockets_hook; + +static int initialized_sockets_version /* = 0 */; + +#endif /* WINDOWS_SOCKETS */ + +int +gl_sockets_startup (int version _GL_UNUSED) +{ +#if WINDOWS_SOCKETS + if (version > initialized_sockets_version) + { + WSADATA data; + int err; + + err = WSAStartup (version, &data); + if (err != 0) + return 1; + + if (data.wVersion < version) + return 2; + + if (initialized_sockets_version == 0) + register_fd_hook (close_fd_maybe_socket, ioctl_fd_maybe_socket, + &fd_sockets_hook); + + initialized_sockets_version = version; + } +#endif + + return 0; +} + +int +gl_sockets_cleanup (void) +{ +#if WINDOWS_SOCKETS + int err; + + initialized_sockets_version = 0; + + unregister_fd_hook (&fd_sockets_hook); + + err = WSACleanup (); + if (err != 0) + return 1; +#endif + + return 0; +} diff --git a/pool/shard008/C/0129794_timer.c b/pool/shard008/C/0129794_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..0c055da94151a0b7b26246daf8e3f57157951fb3 --- /dev/null +++ b/pool/shard008/C/0129794_timer.c @@ -0,0 +1,230 @@ +/* Copyright Joyent, Inc. and other Node contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include +#include + +#include "uv.h" +#include "internal.h" +#include "tree.h" +#include "handle-inl.h" + + +void uv_update_time(uv_loop_t* loop) { + DWORD ticks = GetTickCount(); + + /* The assumption is made that LARGE_INTEGER.QuadPart has the same type */ + /* loop->time, which happens to be. Is there any way to assert this? */ + LARGE_INTEGER* time = (LARGE_INTEGER*) &loop->time; + + /* If the timer has wrapped, add 1 to it's high-order dword. */ + /* uv_poll must make sure that the timer can never overflow more than */ + /* once between two subsequent uv_update_time calls. */ + if (ticks < time->LowPart) { + time->HighPart += 1; + } + time->LowPart = ticks; +} + + +uint64_t uv_now(uv_loop_t* loop) { + return loop->time; +} + + +static int uv_timer_compare(uv_timer_t* a, uv_timer_t* b) { + if (a->due < b->due) + return -1; + if (a->due > b->due) + return 1; + /* + * compare start_id when both has the same due. start_id is + * allocated with loop->timer_counter in uv_timer_start(). + */ + if (a->start_id < b->start_id) + return -1; + if (a->start_id > b->start_id) + return 1; + return 0; +} + + +RB_GENERATE_STATIC(uv_timer_tree_s, uv_timer_s, tree_entry, uv_timer_compare); + + +int uv_timer_init(uv_loop_t* loop, uv_timer_t* handle) { + uv__handle_init(loop, (uv_handle_t*) handle, UV_TIMER); + handle->timer_cb = NULL; + handle->repeat = 0; + + return 0; +} + + +void uv_timer_endgame(uv_loop_t* loop, uv_timer_t* handle) { + if (handle->flags & UV__HANDLE_CLOSING) { + assert(!(handle->flags & UV_HANDLE_CLOSED)); + uv__handle_close(handle); + } +} + + +int uv_timer_start(uv_timer_t* handle, uv_timer_cb timer_cb, uint64_t timeout, + uint64_t repeat) { + uv_loop_t* loop = handle->loop; + uv_timer_t* old; + + if (handle->flags & UV_HANDLE_ACTIVE) { + RB_REMOVE(uv_timer_tree_s, &loop->timers, handle); + } + + handle->timer_cb = timer_cb; + handle->due = loop->time + timeout; + handle->repeat = repeat; + handle->flags |= UV_HANDLE_ACTIVE; + uv__handle_start(handle); + + /* start_id is the second index to be compared in uv__timer_cmp() */ + handle->start_id = handle->loop->timer_counter++; + + old = RB_INSERT(uv_timer_tree_s, &loop->timers, handle); + assert(old == NULL); + + return 0; +} + + +int uv_timer_stop(uv_timer_t* handle) { + uv_loop_t* loop = handle->loop; + + if (!(handle->flags & UV_HANDLE_ACTIVE)) + return 0; + + RB_REMOVE(uv_timer_tree_s, &loop->timers, handle); + + handle->flags &= ~UV_HANDLE_ACTIVE; + uv__handle_stop(handle); + + return 0; +} + + +int uv_timer_again(uv_timer_t* handle) { + uv_loop_t* loop = handle->loop; + + /* If timer_cb is NULL that means that the timer was never started. */ + if (!handle->timer_cb) { + uv__set_sys_error(loop, ERROR_INVALID_DATA); + return -1; + } + + if (handle->flags & UV_HANDLE_ACTIVE) { + RB_REMOVE(uv_timer_tree_s, &loop->timers, handle); + handle->flags &= ~UV_HANDLE_ACTIVE; + uv__handle_stop(handle); + } + + if (handle->repeat) { + handle->due = loop->time + handle->repeat; + + if (RB_INSERT(uv_timer_tree_s, &loop->timers, handle) != NULL) { + uv_fatal_error(ERROR_INVALID_DATA, "RB_INSERT"); + } + + handle->flags |= UV_HANDLE_ACTIVE; + uv__handle_start(handle); + } + + return 0; +} + + +void uv_timer_set_repeat(uv_timer_t* handle, uint64_t repeat) { + assert(handle->type == UV_TIMER); + handle->repeat = repeat; +} + + +uint64_t uv_timer_get_repeat(const uv_timer_t* handle) { + assert(handle->type == UV_TIMER); + return handle->repeat; +} + + +DWORD uv_get_poll_timeout(uv_loop_t* loop) { + uv_timer_t* timer; + int64_t delta; + + /* Check if there are any running timers */ + timer = RB_MIN(uv_timer_tree_s, &loop->timers); + if (timer) { + uv_update_time(loop); + + delta = timer->due - loop->time; + if (delta >= UINT_MAX >> 1) { + /* A timeout value of UINT_MAX means infinite, so that's no good. But */ + /* more importantly, there's always the risk that GetTickCount wraps. */ + /* uv_update_time can detect this, but we must make sure that the */ + /* tick counter never overflows twice between two subsequent */ + /* uv_update_time calls. We do this by never sleeping more than half */ + /* the time it takes to wrap the counter - which is huge overkill, */ + /* but hey, it's not so bad to wake up every 25 days. */ + return UINT_MAX >> 1; + } else if (delta < 0) { + /* Negative timeout values are not allowed */ + return 0; + } else { + return (DWORD)delta; + } + } else { + /* No timers */ + return INFINITE; + } +} + + +void uv_process_timers(uv_loop_t* loop) { + uv_timer_t* timer; + + /* Call timer callbacks */ + for (timer = RB_MIN(uv_timer_tree_s, &loop->timers); + timer != NULL && timer->due <= loop->time; + timer = RB_MIN(uv_timer_tree_s, &loop->timers)) { + RB_REMOVE(uv_timer_tree_s, &loop->timers, timer); + + if (timer->repeat != 0) { + /* If it is a repeating timer, reschedule with repeat timeout. */ + timer->due += timer->repeat; + if (timer->due < loop->time) { + timer->due = loop->time; + } + if (RB_INSERT(uv_timer_tree_s, &loop->timers, timer) != NULL) { + uv_fatal_error(ERROR_INVALID_DATA, "RB_INSERT"); + } + } else { + /* If non-repeating, mark the timer as inactive. */ + timer->flags &= ~UV_HANDLE_ACTIVE; + uv__handle_stop(timer); + } + + timer->timer_cb((uv_timer_t*) timer, 0); + } +} diff --git a/pool/shard008/C/0129805_naviframe_example.c b/pool/shard008/C/0129805_naviframe_example.c new file mode 100644 index 0000000000000000000000000000000000000000..9fb55e7b2ca6a1363ca5e2adc24d322c26a087d1 --- /dev/null +++ b/pool/shard008/C/0129805_naviframe_example.c @@ -0,0 +1,47 @@ +//Compile with: +//gcc -g naviframe_example.c -o naviframe_example `pkg-config --cflags --libs elementary` + +#include + +void +_btn_cb(void *data, Evas_Object *obj, void *event_info) +{ + Evas_Object *nf = data, *btn; + if (!nf) return; + + btn = elm_button_add(nf); + elm_object_text_set(btn, "Go to Second Page."); + evas_object_smart_callback_add(btn, "clicked", _btn_cb, nf); + + elm_naviframe_item_push(nf, "Next Page", NULL, NULL, btn, NULL); +} + +EAPI_MAIN int +elm_main(int argc, char **argv) +{ + Evas_Object *win, *nf, *btn; + + elm_policy_set(ELM_POLICY_QUIT, ELM_POLICY_QUIT_LAST_WINDOW_CLOSED); + + win = elm_win_util_standard_add("naviframe", "Naviframe"); + elm_win_autodel_set(win, EINA_TRUE); + + nf = elm_naviframe_add(win); + evas_object_size_hint_weight_set(nf, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); + elm_win_resize_object_add(win, nf); + evas_object_show(nf); + + btn = elm_button_add(nf); + elm_object_text_set(btn, "Go to Second Page."); + evas_object_smart_callback_add(btn, "clicked", _btn_cb, nf); + + elm_naviframe_item_push(nf, "First Page", NULL, NULL, btn, NULL); + + evas_object_resize(win, 400, 400); + evas_object_show(win); + + elm_run(); + + return 0; +} +ELM_MAIN() diff --git a/pool/shard008/C/0129806_query.c b/pool/shard008/C/0129806_query.c new file mode 100644 index 0000000000000000000000000000000000000000..973a247aaa8d6a4f9d239fa75f4ce0947f053b69 --- /dev/null +++ b/pool/shard008/C/0129806_query.c @@ -0,0 +1,29 @@ +/* + * Copyright (c) 1980 Regents of the University of California. + * All rights reserved. The Berkeley software License Agreement + * specifies the terms and conditions for redistribution. + */ +#include "robots.h" + +/* + * query: + * Ask a question and get a yes or no answer. Default is "no". + */ +int +query(prompt) +char *prompt; +{ + register int c, retval; + register int y, x; + + getyx(stdscr, y, x); + move(Y_PROMPT, X_PROMPT); + addstr(prompt); + clrtoeol(); + refresh(); + retval = ((c = getchar()) == 'y' || c == 'Y'); + move(Y_PROMPT, X_PROMPT); + clrtoeol(); + move(y, x); + return retval; +} diff --git a/pool/shard008/C/0129808_test_bpnn_train.c b/pool/shard008/C/0129808_test_bpnn_train.c new file mode 100644 index 0000000000000000000000000000000000000000..3ae129834c933318ef00167650d3bb311c726132 --- /dev/null +++ b/pool/shard008/C/0129808_test_bpnn_train.c @@ -0,0 +1,93 @@ +// +// Created by wcjzj on 2017/5/22. +// + +#include +#include +#include "bpnn.h" + +static bool test_set_get(double *in, double *out); + +static bool test_set_init(void); + +static FILE *in_file = NULL; +static FILE *out_file = NULL; + +int main(void) { + in_file = fopen(TEST_IN_PATH, "r"); + if (in_file == NULL) { + fprintf(stderr, "open file %s failed.\n", TEST_IN_PATH); + return 0; + } + + out_file = fopen(TEST_OUT_PATH, "r"); + if (out_file == NULL) { + fprintf(stderr, "open file %s failed.\n", TEST_OUT_PATH); + return 0; + } + + bpnn_init(); + bpnn_train(test_set_get, test_set_init); + + fclose(in_file); + fclose(out_file); + + in_file = fopen(IN_PATH, "r"); + if (in_file == NULL) { + fprintf(stderr, "open file %s failed.\n", IN_PATH); + return 0; + } + + out_file = fopen(OUT_PATH, "r"); + if (out_file == NULL) { + fprintf(stderr, "open file %s failed.\n", OUT_PATH); + return 0; + } + + bpnn_sim(test_set_get); + + fclose(in_file); + fclose(out_file); + + return 0; +} + +static bool test_set_get(double *in, double *out) { + assert(in && out); +#define BUFFER_SIZE 256 + static char buffer[BUFFER_SIZE]; + + if (in_file && out_file) { + if (fgets(buffer, BUFFER_SIZE, in_file) != NULL) { + char *token = strtok(buffer, ","); + for (size_t i = 0; i < IN_N; i++) { + if (token == NULL) { + fprintf(stderr, "the format of input is not correct!\n"); + return false; + } + in[i] = strtod(token, NULL); + token = strtok(NULL, ","); + } + + } else { + return false; + } + + if (fgets(buffer, BUFFER_SIZE, out_file) != NULL) { + out[0] = strtod(buffer, NULL); + } else { + return false; + } + + return true; + } + + return false; + +} + +static bool test_set_init(void) { + fseek(in_file, 0, SEEK_SET); + fseek(out_file, 0, SEEK_SET); + return true; +} diff --git a/pool/shard008/C/0129809_t-atanh.c b/pool/shard008/C/0129809_t-atanh.c new file mode 100644 index 0000000000000000000000000000000000000000..240df1ac5acb7191352fe3ec118bf7f5f3e9f2da --- /dev/null +++ b/pool/shard008/C/0129809_t-atanh.c @@ -0,0 +1,84 @@ +/* + Copyright (C) 2013 Fredrik Johansson + + This file is part of Arb. + + Arb is free software: you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License (LGPL) as published + by the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. See . +*/ + +#include "acb.h" + +int main() +{ + slong iter; + flint_rand_t state; + + flint_printf("atanh...."); + fflush(stdout); + + flint_randinit(state); + + for (iter = 0; iter < 1000 * arb_test_multiplier(); iter++) + { + acb_t x, a, b; + slong prec1, prec2; + + prec1 = 2 + n_randint(state, 1000); + prec2 = prec1 + 30; + + acb_init(x); + acb_init(a); + acb_init(b); + + acb_randtest_special(x, state, 1 + n_randint(state, 1000), 2 + n_randint(state, 100)); + acb_randtest_special(a, state, 1 + n_randint(state, 1000), 2 + n_randint(state, 100)); + acb_randtest_special(b, state, 1 + n_randint(state, 1000), 2 + n_randint(state, 100)); + + acb_atanh(a, x, prec1); + acb_atanh(b, x, prec2); + + /* check consistency */ + if (!acb_overlaps(a, b)) + { + flint_printf("FAIL: overlap\n\n"); + flint_printf("x = "); acb_printd(x, 15); flint_printf("\n\n"); + flint_printf("a = "); acb_printd(a, 15); flint_printf("\n\n"); + flint_printf("b = "); acb_printd(b, 15); flint_printf("\n\n"); + flint_abort(); + } + + /* check tanh(atanh(x)) = x */ + acb_tanh(b, b, prec1); + + if (!acb_contains(b, x)) + { + flint_printf("FAIL: functional equation\n\n"); + flint_printf("x = "); acb_printd(x, 15); flint_printf("\n\n"); + flint_printf("b = "); acb_printd(b, 15); flint_printf("\n\n"); + flint_abort(); + } + + acb_atanh(x, x, prec1); + + if (!acb_overlaps(a, x)) + { + flint_printf("FAIL: aliasing\n\n"); + flint_printf("a = "); acb_printd(a, 15); flint_printf("\n\n"); + flint_printf("x = "); acb_printd(x, 15); flint_printf("\n\n"); + flint_abort(); + } + + acb_clear(x); + acb_clear(a); + acb_clear(b); + } + + flint_randclear(state); + flint_cleanup(); + flint_printf("PASS\n"); + return EXIT_SUCCESS; +} + diff --git a/pool/shard008/C/0129811_IoState_eval.c b/pool/shard008/C/0129811_IoState_eval.c new file mode 100644 index 0000000000000000000000000000000000000000..4f19319b521c93ff12629aa28bac25b41b170a28 --- /dev/null +++ b/pool/shard008/C/0129811_IoState_eval.c @@ -0,0 +1,94 @@ + +//--metadoc State copyright Steve Dekorte 2002 +//--metadoc State license BSD revised + +#include "IoState.h" +#include "IoObject.h" +#include +#include "PortableGettimeofday.h" + +IoObject *IoState_tryToPerform(IoState *self, + IoObject *target, + IoObject *locals, + IoMessage *m) +{ + IoCoroutine *tryCoro = IoCoroutine_newWithTry(self, target, locals, m); + + if (IoCoroutine_rawException(tryCoro) != self->ioNil) + { + IoState_exception_(self, tryCoro); + } + + return IoCoroutine_rawResult(tryCoro); +} + +void IoState_zeroSandboxCounts(IoState *self) +{ + self->messageCount = 0; + self->endTime = 0; +} + +void IoState_resetSandboxCounts(IoState *self) +{ + struct timeval startTv; + double start; + + // Get the start and current time + gettimeofday(&startTv, NULL); + start = (double)startTv.tv_sec + ((double)startTv.tv_usec/1000000.0); + + // Calculate the end of time + self->endTime = start + self->timeLimit; + + self->messageCount = self->messageCountLimit; +} + +IoObject *IoState_on_doCString_withLabel_(IoState *self, + IoObject *target, + const char *s, + const char *label) +{ + IoObject *result; + + IoState_pushRetainPool(self); + + { + IoMessage *m = IoMessage_newWithName_andCachedArg_(self, SIOSYMBOL("doString"), SIOSYMBOL(s)); + + if (label) + { + IoMessage_addCachedArg_(m, SIOSYMBOL(label)); + } + + IoState_zeroSandboxCounts(self); + + result = IoState_tryToPerform(self, target, target, m); + } + + IoState_popRetainPoolExceptFor_(self, result); + + return result; +} + +IoObject *IoState_doCString_(IoState *self, const char *s) +{ + return IoState_on_doCString_withLabel_(self, self->lobby, s, "IoState_doCString"); +} + +IoObject *IoState_doSandboxCString_(IoState *self, const char *s) +{ + IoMessage *m = IoMessage_newWithName_andCachedArg_(self, SIOSYMBOL("doString"), SIOSYMBOL(s)); + IoState_resetSandboxCounts(self); + return IoState_tryToPerform(self, self->lobby, self->lobby, m); +} + +double IoState_endTime(IoState *self) +{ + return self->endTime; +} + +IoObject *IoState_doFile_(IoState *self, const char *path) +{ + IoMessage *m = IoMessage_newWithName_andCachedArg_(self, SIOSYMBOL("doFile"), SIOSYMBOL(path)); + return IoState_tryToPerform(self, self->lobby, self->lobby, m); +} diff --git a/pool/shard008/C/0129817_yg1006.c b/pool/shard008/C/0129817_yg1006.c new file mode 100644 index 0000000000000000000000000000000000000000..c7da40bec858ede42953a215a98d1c7c71c264f9 --- /dev/null +++ b/pool/shard008/C/0129817_yg1006.c @@ -0,0 +1,64 @@ +/* + * Author: Jon Trulson + * Copyright (c) 2016 Intel Corporation. + * + * This program and the accompanying materials are made available under the + * terms of the The MIT License which is available at + * https://opensource.org/licenses/MIT. + * + * SPDX-License-Identifier: MIT + */ + +#include +#include "yg1006.h" + +yg1006_context yg1006_init(unsigned int pin) +{ + yg1006_context dev = + (yg1006_context)malloc(sizeof(struct _yg1006_context)); + + if (!dev) + return NULL; + + dev->gpio = NULL; + + // make sure MRAA is initialized + int mraa_rv; + if ((mraa_rv = mraa_init()) != MRAA_SUCCESS) + { + printf("%s: mraa_init() failed (%d).\n", __FUNCTION__, mraa_rv); + yg1006_close(dev); + return NULL; + } + + // initialize the MRAA context + + if (!(dev->gpio = mraa_gpio_init(pin))) + { + printf("%s: mraa_gpio_init() failed.\n", __FUNCTION__); + yg1006_close(dev); + return NULL; + } + + mraa_gpio_dir(dev->gpio, MRAA_GPIO_IN); + + return dev; +} + +void yg1006_close(yg1006_context dev) +{ + assert(dev != NULL); + + if (dev->gpio) + mraa_gpio_close(dev->gpio); + + free(dev); +} + +bool yg1006_flame_detected(const yg1006_context dev) +{ + assert(dev != NULL); + + // gpio is low when a flame is detected + return (mraa_gpio_read(dev->gpio) ? false : true); +} diff --git a/pool/shard008/C/0129830_tcp-thread-sorted-once-client.c b/pool/shard008/C/0129830_tcp-thread-sorted-once-client.c new file mode 100644 index 0000000000000000000000000000000000000000..fdf105e3c2ef8788786a526bfc85706db034e4b6 --- /dev/null +++ b/pool/shard008/C/0129830_tcp-thread-sorted-once-client.c @@ -0,0 +1,101 @@ +/* (C) IT Sky Consulting GmbH 2014 + * http://www.it-sky-consulting.com/ + * Author: Karl Brodowsky + * Date: 2014-02-27 + * License: GPL v2 (See https://de.wikipedia.org/wiki/GNU_General_Public_License ) + * + * This file is inspired by http://cs.baylor.edu/~donahoo/practical/CSockets/code/HandleTCPClient.c + */ + +#include /* for sockaddr_in and inet_addr() */ +#include +#include +#include +#include +#include /* for printf() and fprintf() and ... */ +#include /* for atoi() and exit() and ... */ +#include /* for memset() and ... */ +#include /* for socket(), connect(), send(), and recv() */ +#include +#include /* for close() */ + +#include +#include + +#define RCVBUFSIZE 4096 /* Size of receive buffer */ + +void consume(const char *buff, size_t count); + +void usage(const char *argv0, const char *msg) { + if (msg != NULL && strlen(msg) > 0) { + printf("%s\n\n", msg); + } + printf("Usage\n\n"); + printf("%s []\n", argv0); + exit(1); +} + +int main(int argc, char *argv[]) { + + int retcode; + + if (is_help_requested(argc, argv)) { + usage(argv[0], ""); + } + + int sock; /* Socket descriptor */ + struct sockaddr_in server_address; /* Square server address */ + unsigned short server_port; /* Square server port */ + char *server_ip; /* Server IP address (dotted quad) */ + char receive_buffer[RCVBUFSIZE]; /* Buffer for received string */ + + if (argc < 2 || argc > 3) { /* Test for correct number of arguments */ + usage(argv[0], "wrong number of arguments"); + } + + server_ip = argv[1]; /* First arg: server IP address (dotted quad) */ + + if (argc == 3) { + server_port = atoi(argv[2]); /* Use given port, if any */ + } else { + server_port = 7000; /* 7000 is a free port */ + } + + /* Create a reliable, stream socket using TCP */ + sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); + handle_error(sock, "socket() failed", PROCESS_EXIT); + + /* Construct the server address structure */ + memset(&server_address, 0, sizeof(server_address)); /* Zero out structure */ + server_address.sin_family = AF_INET; /* Internet address family */ + server_address.sin_addr.s_addr = inet_addr(server_ip); /* Server IP address */ + server_address.sin_port = htons(server_port); /* Server port: htons host to network byte order */ + + /* Establish the connection to the square server */ + retcode = connect(sock, (struct sockaddr *) &server_address, sizeof(server_address)); + handle_error(retcode, "connect() failed", PROCESS_EXIT); + + const char *cmd_string = "GETX"; + /* Send the string to the server */ + write_4byte_string(sock, cmd_string); + + /* Receive the same string containing the square back from the server */ + printf("Received: \n"); /* Setup to print the squared string */ + while (TRUE) { + + size_t ulen = read_string_fragmentable(sock, receive_buffer, RCVBUFSIZE, consume); + if (ulen == 0) { + break; + } + } + + const char *done_string = "DONE"; + write_4byte_string(sock, done_string); + close(sock); + printf("\nDONE\n"); + exit(0); +} + +void consume(const char *buff, size_t count) { + write(STDOUT_FILENO, buff, count); +} diff --git a/pool/shard008/C/0129834_sf_ainput.c b/pool/shard008/C/0129834_sf_ainput.c new file mode 100644 index 0000000000000000000000000000000000000000..0c67bc88a03f018b871682df8fc2366e6bf3c7ae --- /dev/null +++ b/pool/shard008/C/0129834_sf_ainput.c @@ -0,0 +1,92 @@ +/** + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP: A Remote Desktop Protocol Implementation + * FreeRDP Sample Server (Advanced Input) + * + * Copyright 2022 Armin Novak + * Copyright 2022 Thincast Technologies GmbH + * + * 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. + */ + +#include + +#include + +#include "sfreerdp.h" + +#include "sf_ainput.h" + +#include +#include + +#include +#define TAG SERVER_TAG("sample.ainput") + +/** + * Function description + * + * @return 0 on success, otherwise a Win32 error code + */ +static UINT sf_peer_ainput_mouse_event(ainput_server_context* context, UINT64 timestamp, + UINT64 flags, INT32 x, INT32 y) +{ + /* TODO: Implement */ + WINPR_ASSERT(context); + + WLog_WARN(TAG, "%s not implemented: 0x%08" PRIx64 ", 0x%08" PRIx64 ", %" PRId32 "x%" PRId32, + __FUNCTION__, timestamp, flags, x, y); + return CHANNEL_RC_OK; +} + +void sf_peer_ainput_init(testPeerContext* context) +{ + WINPR_ASSERT(context); + + context->ainput = ainput_server_context_new(context->vcm); + WINPR_ASSERT(context->ainput); + + context->ainput->rdpcontext = &context->_p; + context->ainput->data = context; + + context->ainput->MouseEvent = sf_peer_ainput_mouse_event; +} + +BOOL sf_peer_ainput_start(testPeerContext* context) +{ + if (!context || !context->ainput || !context->ainput->Open) + return FALSE; + + return context->ainput->Open(context->ainput) == CHANNEL_RC_OK; +} + +BOOL sf_peer_ainput_stop(testPeerContext* context) +{ + if (!context || !context->ainput || !context->ainput->Close) + return FALSE; + + return context->ainput->Close(context->ainput) == CHANNEL_RC_OK; +} + +BOOL sf_peer_ainput_running(testPeerContext* context) +{ + if (!context || !context->ainput || !context->ainput->IsOpen) + return FALSE; + + return context->ainput->IsOpen(context->ainput); +} + +void sf_peer_ainput_uninit(testPeerContext* context) +{ + ainput_server_context_free(context->ainput); +} diff --git a/pool/shard008/C/0129835_psw.c b/pool/shard008/C/0129835_psw.c new file mode 100644 index 0000000000000000000000000000000000000000..a3222129a5ac2cf43d5db2c943d9a7378f221861 --- /dev/null +++ b/pool/shard008/C/0129835_psw.c @@ -0,0 +1,132 @@ + +#include +#include +#include +#include +#include +#include + +static irqreturn_t psw_irq_handler(int irq, void *arg) +{ + struct platform_device *pdev = arg; + struct push_switch *psw = platform_get_drvdata(pdev); + struct push_switch_platform_info *psw_info = pdev->dev.platform_data; + unsigned int sw_value; + int ret = 0; + + sw_value = (0x0ff & (~__raw_readb(PA_STATUS))); + + /* Nothing to do if there's no state change */ + if (psw->state) { + ret = 1; + goto out; + } + + /* Figure out who raised it */ + if (sw_value & (1 << psw_info->bit)) { + psw->state = 1; + mod_timer(&psw->debounce, jiffies + 50); + ret = 1; + } + +out: + /* Clear the switch IRQs */ + __raw_writeb(0x00, PA_PWRINT_CLR); + + return IRQ_RETVAL(ret); +} + +static struct resource psw_power_resources[] = { + [0] = { + .start = IRQ_POWER, + .flags = IORESOURCE_IRQ, + }, +}; + +static struct resource psw_usl5p_resources[] = { + [0] = { + .start = IRQ_BUTTON, + .flags = IORESOURCE_IRQ, + }, +}; + +static struct push_switch_platform_info psw_power_platform_data = { + .name = "psw_power", + .bit = 4, + .irq_flags = IRQF_SHARED, + .irq_handler = psw_irq_handler, +}; + +static struct push_switch_platform_info psw1_platform_data = { + .name = "psw1", + .bit = 0, + .irq_flags = IRQF_SHARED, + .irq_handler = psw_irq_handler, +}; + +static struct push_switch_platform_info psw2_platform_data = { + .name = "psw2", + .bit = 2, + .irq_flags = IRQF_SHARED, + .irq_handler = psw_irq_handler, +}; + +static struct push_switch_platform_info psw3_platform_data = { + .name = "psw3", + .bit = 1, + .irq_flags = IRQF_SHARED, + .irq_handler = psw_irq_handler, +}; + +static struct platform_device psw_power_switch_device = { + .name = "push-switch", + .id = 0, + .num_resources = ARRAY_SIZE(psw_power_resources), + .resource = psw_power_resources, + .dev = { + .platform_data = &psw_power_platform_data, + }, +}; + +static struct platform_device psw1_switch_device = { + .name = "push-switch", + .id = 1, + .num_resources = ARRAY_SIZE(psw_usl5p_resources), + .resource = psw_usl5p_resources, + .dev = { + .platform_data = &psw1_platform_data, + }, +}; + +static struct platform_device psw2_switch_device = { + .name = "push-switch", + .id = 2, + .num_resources = ARRAY_SIZE(psw_usl5p_resources), + .resource = psw_usl5p_resources, + .dev = { + .platform_data = &psw2_platform_data, + }, +}; + +static struct platform_device psw3_switch_device = { + .name = "push-switch", + .id = 3, + .num_resources = ARRAY_SIZE(psw_usl5p_resources), + .resource = psw_usl5p_resources, + .dev = { + .platform_data = &psw3_platform_data, + }, +}; + +static struct platform_device *psw_devices[] = { + &psw_power_switch_device, + &psw1_switch_device, + &psw2_switch_device, + &psw3_switch_device, +}; + +static int __init psw_init(void) +{ + return platform_add_devices(psw_devices, ARRAY_SIZE(psw_devices)); +} +module_init(psw_init); diff --git a/pool/shard008/C/0129839_if.c b/pool/shard008/C/0129839_if.c new file mode 100644 index 0000000000000000000000000000000000000000..8a936184f78bd31820ab1536f5c19d7e4236f269 --- /dev/null +++ b/pool/shard008/C/0129839_if.c @@ -0,0 +1,160 @@ +/* GNU Mailutils -- a suite of utilities for electronic mail + Copyright (C) 1999, 2001, 2002, 2007, 2010 Free Software Foundation, + Inc. + + GNU Mailutils 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, or (at your option) + any later version. + + GNU Mailutils 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 GNU Mailutils; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301 USA */ + +#include "mail.h" + +#define COND_STK_SIZE 64 +#define COND_STK_INCR 16 +static int *_cond_stack; /* Stack of conditions */ +static int _cond_stack_size; /* Number of elements allocated this far */ +static int _cond_level; /* Number of nested `if' blocks */ + +static void _cond_push(int val); +static int _cond_pop(void); + +int +if_cond() +{ + if (_cond_level == 0) + return 1; + return _cond_stack[_cond_level-1]; +} + +void +_cond_push(int val) +{ + if (!_cond_stack) + { + _cond_stack = calloc(COND_STK_SIZE, sizeof(_cond_stack[0])); + _cond_stack_size = COND_STK_SIZE; + _cond_level = 0; + } + else if (_cond_level >= _cond_stack_size) + { + _cond_stack_size += COND_STK_INCR; + _cond_stack = realloc(_cond_stack, + sizeof(_cond_stack[0])*_cond_stack_size); + } + + if (!_cond_stack) + { + util_error(_("Not enough memory")); + exit (EXIT_FAILURE); + } + _cond_stack[_cond_level++] = val; +} + +int +_cond_pop() +{ + if (_cond_level == 0) + { + util_error(_("Internal error: condition stack underflow")); + abort(); + } + return _cond_stack[--_cond_level]; +} + +/* + * i[f] s|r|t + * mail-commands + * el[se] + * mail-commands + * en[dif] + */ + +int +mail_if (int argc, char **argv) +{ + char *mode; + int cond; + + if (argc != 2) + { + /* TRANSLATORS: 'if' is the function name. Do not translate it */ + util_error(_("if requires an argument: s | r | t")); + return 1; + } + + if (argv[1][1] != 0) + { + util_error(_("Valid if arguments are: s | r | t")); + return 1; + } + + if (mailvar_get (&mode, "mode", mailvar_type_string, 1)) + exit (EXIT_FAILURE); + + if (if_cond() == 0) + /* Propagate negative condition */ + cond = 0; + else + { + switch (argv[1][0]) + { + case 's': /* Send mode */ + cond = strcmp(mode, "send") == 0; + break; + case 'r': /* Read mode */ + cond = strcmp(mode, "read") == 0; + break; + case 't': /* Stdout is a terminal device? */ + cond = isatty (fileno (stdout)); + break; + default: + util_error(_("Valid if arguments are: s | r | t")); + return 1; + } + } + _cond_push(cond); + return 0; +} + + +int +mail_else (int argc MU_ARG_UNUSED, char **argv MU_ARG_UNUSED) +{ + int cond; + + if (_cond_level == 0) + { + /* TRANSLATORS: 'else' and 'if' are function names. Do not translate them */ + util_error(_("else without matching if")); + return 1; + } + cond = _cond_pop(); + if (if_cond ()) + cond = !cond; + _cond_push(cond); + return 0; +} + +int +mail_endif (int argc MU_ARG_UNUSED, char **argv MU_ARG_UNUSED) +{ + if (_cond_level == 0) + { + /* TRANSLATORS: 'endif' and 'if' are function names. Do not translate them */ + util_error(_("endif without matching if")); + return 1; + } + _cond_pop(); + return 1; +} + diff --git a/pool/shard008/C/0129840_cled.c b/pool/shard008/C/0129840_cled.c new file mode 100644 index 0000000000000000000000000000000000000000..dcb91bdffad707e4d0f0e9f3320cbb516e669488 --- /dev/null +++ b/pool/shard008/C/0129840_cled.c @@ -0,0 +1,32 @@ +/* + * cled.c - control color led + * + * Copyright (c) 2010 BCT Electronic GmbH + * + * Licensed under the GPL-2 or later. + */ + +#include +#include +#include +#include + +int do_cled(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) +{ + ulong addr = 0x20000000 + 0x200000; /* AMS2 */ + uchar data; + + if (argc < 2) + return cmd_usage(cmdtp); + + data = simple_strtoul(argv[1], NULL, 10); + outb(data, addr); + + printf("cled, write %02x\n", data); + + return 0; +} + +U_BOOT_CMD(cled, 2, 0, do_cled, + "set/clear color LED", + ""); diff --git a/pool/shard008/C/0129841_rockchip_drm_fbdev.c b/pool/shard008/C/0129841_rockchip_drm_fbdev.c new file mode 100644 index 0000000000000000000000000000000000000000..f261512bb4a03539f55e40b0e545c3ee8469c57e --- /dev/null +++ b/pool/shard008/C/0129841_rockchip_drm_fbdev.c @@ -0,0 +1,190 @@ +/* + * Copyright (C) Fuzhou Rockchip Electronics Co.Ltd + * Author:Mark Yao + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * 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. + */ + +#include +#include +#include +#include + +#include "rockchip_drm_drv.h" +#include "rockchip_drm_gem.h" +#include "rockchip_drm_fb.h" + +#define PREFERRED_BPP 32 +#define to_drm_private(x) \ + container_of(x, struct rockchip_drm_private, fbdev_helper) + +static int rockchip_fbdev_mmap(struct fb_info *info, + struct vm_area_struct *vma) +{ + struct drm_fb_helper *helper = info->par; + struct rockchip_drm_private *private = to_drm_private(helper); + + return rockchip_gem_mmap_buf(private->fbdev_bo, vma); +} + +static struct fb_ops rockchip_drm_fbdev_ops = { + .owner = THIS_MODULE, + .fb_mmap = rockchip_fbdev_mmap, + .fb_fillrect = drm_fb_helper_cfb_fillrect, + .fb_copyarea = drm_fb_helper_cfb_copyarea, + .fb_imageblit = drm_fb_helper_cfb_imageblit, + .fb_check_var = drm_fb_helper_check_var, + .fb_set_par = drm_fb_helper_set_par, + .fb_blank = drm_fb_helper_blank, + .fb_pan_display = drm_fb_helper_pan_display, + .fb_setcmap = drm_fb_helper_setcmap, +}; + +static int rockchip_drm_fbdev_create(struct drm_fb_helper *helper, + struct drm_fb_helper_surface_size *sizes) +{ + struct rockchip_drm_private *private = to_drm_private(helper); + struct drm_mode_fb_cmd2 mode_cmd = { 0 }; + struct drm_device *dev = helper->dev; + struct rockchip_gem_object *rk_obj; + struct drm_framebuffer *fb; + unsigned int bytes_per_pixel; + unsigned long offset; + struct fb_info *fbi; + size_t size; + int ret; + + bytes_per_pixel = DIV_ROUND_UP(sizes->surface_bpp, 8); + + mode_cmd.width = sizes->surface_width; + mode_cmd.height = sizes->surface_height; + mode_cmd.pitches[0] = sizes->surface_width * bytes_per_pixel; + mode_cmd.pixel_format = drm_mode_legacy_fb_format(sizes->surface_bpp, + sizes->surface_depth); + + size = mode_cmd.pitches[0] * mode_cmd.height; + + rk_obj = rockchip_gem_create_object(dev, size, true); + if (IS_ERR(rk_obj)) + return -ENOMEM; + + private->fbdev_bo = &rk_obj->base; + + fbi = drm_fb_helper_alloc_fbi(helper); + if (IS_ERR(fbi)) { + dev_err(dev->dev, "Failed to create framebuffer info.\n"); + ret = PTR_ERR(fbi); + goto err_rockchip_gem_free_object; + } + + helper->fb = rockchip_drm_framebuffer_init(dev, &mode_cmd, + private->fbdev_bo); + if (IS_ERR(helper->fb)) { + dev_err(dev->dev, "Failed to allocate DRM framebuffer.\n"); + ret = PTR_ERR(helper->fb); + goto err_release_fbi; + } + + fbi->par = helper; + fbi->flags = FBINFO_FLAG_DEFAULT; + fbi->fbops = &rockchip_drm_fbdev_ops; + + fb = helper->fb; + drm_fb_helper_fill_fix(fbi, fb->pitches[0], fb->depth); + drm_fb_helper_fill_var(fbi, helper, sizes->fb_width, sizes->fb_height); + + offset = fbi->var.xoffset * bytes_per_pixel; + offset += fbi->var.yoffset * fb->pitches[0]; + + dev->mode_config.fb_base = 0; + fbi->screen_base = rk_obj->kvaddr + offset; + fbi->screen_size = rk_obj->base.size; + fbi->fix.smem_len = rk_obj->base.size; + + DRM_DEBUG_KMS("FB [%dx%d]-%d kvaddr=%p offset=%ld size=%d\n", + fb->width, fb->height, fb->depth, rk_obj->kvaddr, + offset, size); + + fbi->skip_vt_switch = true; + + return 0; + +err_release_fbi: + drm_fb_helper_release_fbi(helper); +err_rockchip_gem_free_object: + rockchip_gem_free_object(&rk_obj->base); + return ret; +} + +static const struct drm_fb_helper_funcs rockchip_drm_fb_helper_funcs = { + .fb_probe = rockchip_drm_fbdev_create, +}; + +int rockchip_drm_fbdev_init(struct drm_device *dev) +{ + struct rockchip_drm_private *private = dev->dev_private; + struct drm_fb_helper *helper; + unsigned int num_crtc; + int ret; + + if (!dev->mode_config.num_crtc || !dev->mode_config.num_connector) + return -EINVAL; + + num_crtc = dev->mode_config.num_crtc; + + helper = &private->fbdev_helper; + + drm_fb_helper_prepare(dev, helper, &rockchip_drm_fb_helper_funcs); + + ret = drm_fb_helper_init(dev, helper, num_crtc, ROCKCHIP_MAX_CONNECTOR); + if (ret < 0) { + dev_err(dev->dev, "Failed to initialize drm fb helper - %d.\n", + ret); + return ret; + } + + ret = drm_fb_helper_single_add_all_connectors(helper); + if (ret < 0) { + dev_err(dev->dev, "Failed to add connectors - %d.\n", ret); + goto err_drm_fb_helper_fini; + } + + /* disable all the possible outputs/crtcs before entering KMS mode */ + drm_helper_disable_unused_functions(dev); + + ret = drm_fb_helper_initial_config(helper, PREFERRED_BPP); + if (ret < 0) { + dev_err(dev->dev, "Failed to set initial hw config - %d.\n", + ret); + goto err_drm_fb_helper_fini; + } + + return 0; + +err_drm_fb_helper_fini: + drm_fb_helper_fini(helper); + return ret; +} + +void rockchip_drm_fbdev_fini(struct drm_device *dev) +{ + struct rockchip_drm_private *private = dev->dev_private; + struct drm_fb_helper *helper; + + helper = &private->fbdev_helper; + + drm_fb_helper_unregister_fbi(helper); + drm_fb_helper_release_fbi(helper); + + if (helper->fb) + drm_framebuffer_unreference(helper->fb); + + drm_fb_helper_fini(helper); +} diff --git a/pool/shard008/C/0129850_bitops.c b/pool/shard008/C/0129850_bitops.c new file mode 100644 index 0000000000000000000000000000000000000000..d6267b0ea6134b0d2eb6558064681e55f7730f09 --- /dev/null +++ b/pool/shard008/C/0129850_bitops.c @@ -0,0 +1,104 @@ +#include +#include + +/** + * find_next_bit - find the first set bit in a memory region + * @addr: The address to base the search on + * @offset: The bitnumber to start searching at + * @size: The maximum size to search + */ +int find_next_bit(const unsigned long *addr, int size, int offset) +{ + const unsigned long *p = addr + (offset >> 5); + int set = 0, bit = offset & 31, res; + + if (bit) { + /* + * Look for nonzero in the first 32 bits: + */ + __asm__("bsfl %1,%0\n\t" + "jne 1f\n\t" + "movl $32, %0\n" + "1:" + : "=r" (set) + : "r" (*p >> bit)); + if (set < (32 - bit)) + return set + offset; + set = 32 - bit; + p++; + } + /* + * No set bit yet, search remaining full words for a bit + */ + res = find_first_bit (p, size - 32 * (p - addr)); + return (offset + set + res); +} +EXPORT_SYMBOL(find_next_bit); + +/** + * find_next_zero_bit - find the first zero bit in a memory region + * @addr: The address to base the search on + * @offset: The bitnumber to start searching at + * @size: The maximum size to search + */ +int find_next_zero_bit(const unsigned long *addr, int size, int offset) +{ + unsigned long * p = ((unsigned long *) addr) + (offset >> 5); + int set = 0, bit = offset & 31, res; + + if (bit) { + /* + * Look for zero in the first 32 bits. + */ + __asm__("bsfl %1,%0\n\t" + "jne 1f\n\t" + "movl $32, %0\n" + "1:" + : "=r" (set) + : "r" (~(*p >> bit))); + if (set < (32 - bit)) + return set + offset; + set = 32 - bit; + p++; + } + /* + * No zero yet, search remaining full bytes for a zero + */ + res = find_first_zero_bit (p, size - 32 * (p - (unsigned long *) addr)); + return (offset + set + res); +} +EXPORT_SYMBOL(find_next_zero_bit); + + +/* + * rw spinlock fallbacks + */ +#if defined(CONFIG_SMP) +asm( +".section .sched.text\n" +".align 4\n" +".globl __write_lock_failed\n" +"__write_lock_failed:\n\t" + LOCK "addl $" RW_LOCK_BIAS_STR ",(%eax)\n" +"1: rep; nop\n\t" + "cmpl $" RW_LOCK_BIAS_STR ",(%eax)\n\t" + "jne 1b\n\t" + LOCK "subl $" RW_LOCK_BIAS_STR ",(%eax)\n\t" + "jnz __write_lock_failed\n\t" + "ret" +); + +asm( +".section .sched.text\n" +".align 4\n" +".globl __read_lock_failed\n" +"__read_lock_failed:\n\t" + LOCK "incl (%eax)\n" +"1: rep; nop\n\t" + "cmpl $1,(%eax)\n\t" + "js 1b\n\t" + LOCK "decl (%eax)\n\t" + "js __read_lock_failed\n\t" + "ret" +); +#endif diff --git a/pool/shard008/C/0129851_client.c b/pool/shard008/C/0129851_client.c new file mode 100644 index 0000000000000000000000000000000000000000..42a18286ec371c12c0bd199881e02e731336aba7 --- /dev/null +++ b/pool/shard008/C/0129851_client.c @@ -0,0 +1,136 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * 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. + */ + +#include "argv.h" +#include "client.h" +#include "kubernetes.h" +#include "settings.h" +#include "user.h" + +#include +#include +#include + +#include +#include +#include +#include +#include + +guac_client* guac_kubernetes_lws_current_client = NULL; + +/** + * Logging callback invoked by libwebsockets to log a single line of logging + * output. As libwebsockets messages are all generally low-level, the log + * level provided by libwebsockets is ignored here, with all messages logged + * instead at guacd's debug level. + * + * @param level + * The libwebsockets log level associated with the log message. This value + * is ignored by this implementation of the logging callback. + * + * @param line + * The line of logging output to log. + */ +static void guac_kubernetes_log(int level, const char* line) { + + char buffer[1024]; + + /* Drop log message if there's nowhere to log yet */ + if (guac_kubernetes_lws_current_client == NULL) + return; + + /* Trim length of line to fit buffer (plus null terminator) */ + int length = strlen(line); + if (length > sizeof(buffer) - 1) + length = sizeof(buffer) - 1; + + /* Copy as much of the received line as will fit in the buffer */ + memcpy(buffer, line, length); + + /* If the line ends with a newline character, trim the character */ + if (length > 0 && buffer[length - 1] == '\n') + length--; + + /* Null-terminate the trimmed string */ + buffer[length] = '\0'; + + /* Log using guacd's own log facilities */ + guac_client_log(guac_kubernetes_lws_current_client, GUAC_LOG_DEBUG, + "libwebsockets: %s", buffer); + +} + +int guac_client_init(guac_client* client) { + + /* Ensure reference to main guac_client remains available in all + * libwebsockets contexts */ + guac_kubernetes_lws_current_client = client; + + /* Redirect libwebsockets logging */ + lws_set_log_level(LLL_ERR | LLL_WARN | LLL_NOTICE | LLL_INFO, + guac_kubernetes_log); + + /* Set client args */ + client->args = GUAC_KUBERNETES_CLIENT_ARGS; + + /* Allocate client instance data */ + guac_kubernetes_client* kubernetes_client = calloc(1, sizeof(guac_kubernetes_client)); + client->data = kubernetes_client; + + /* Set handlers */ + client->join_handler = guac_kubernetes_user_join_handler; + client->free_handler = guac_kubernetes_client_free_handler; + client->leave_handler = guac_kubernetes_user_leave_handler; + + /* Register handlers for argument values that may be sent after the handshake */ + guac_argv_register(GUAC_KUBERNETES_ARGV_COLOR_SCHEME, guac_kubernetes_argv_callback, NULL, GUAC_ARGV_OPTION_ECHO); + guac_argv_register(GUAC_KUBERNETES_ARGV_FONT_NAME, guac_kubernetes_argv_callback, NULL, GUAC_ARGV_OPTION_ECHO); + guac_argv_register(GUAC_KUBERNETES_ARGV_FONT_SIZE, guac_kubernetes_argv_callback, NULL, GUAC_ARGV_OPTION_ECHO); + + /* Set locale and warn if not UTF-8 */ + setlocale(LC_CTYPE, ""); + if (strcmp(nl_langinfo(CODESET), "UTF-8") != 0) { + guac_client_log(client, GUAC_LOG_INFO, + "Current locale does not use UTF-8. Some characters may " + "not render correctly."); + } + + /* Success */ + return 0; + +} + +int guac_kubernetes_client_free_handler(guac_client* client) { + + guac_kubernetes_client* kubernetes_client = + (guac_kubernetes_client*) client->data; + + /* Wait client thread to terminate */ + pthread_join(kubernetes_client->client_thread, NULL); + + /* Free settings */ + if (kubernetes_client->settings != NULL) + guac_kubernetes_settings_free(kubernetes_client->settings); + + free(kubernetes_client); + return 0; + +} + diff --git a/pool/shard008/C/0129856_test_property_proxy_get_notify_function_structure.c b/pool/shard008/C/0129856_test_property_proxy_get_notify_function_structure.c new file mode 100644 index 0000000000000000000000000000000000000000..0b91af428da6a879b4cb6fd43bf590d6beec07c8 --- /dev/null +++ b/pool/shard008/C/0129856_test_property_proxy_get_notify_function_structure.c @@ -0,0 +1,180 @@ +void +my_com_netsplit_Nih_Test_property_get_notify (DBusPendingCall * pending_call, + NihDBusPendingData *pending_data) +{ + DBusMessage * reply; + DBusMessageIter iter; + DBusMessageIter variter; + NihDBusMessage *message; + DBusError error; + DBusMessageIter value_iter; + const char * value_item0_dbus; + char * value_item0; + uint32_t value_item1; + MyProperty * value; + + nih_assert (pending_call != NULL); + nih_assert (pending_data != NULL); + + nih_assert (dbus_pending_call_get_completed (pending_call)); + + /* Steal the reply from the pending call. */ + reply = dbus_pending_call_steal_reply (pending_call); + nih_assert (reply != NULL); + + /* Handle error replies */ + if (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_ERROR) { + message = NIH_MUST (nih_dbus_message_new (pending_data, pending_data->connection, reply)); + + dbus_error_init (&error); + dbus_set_error_from_message (&error, message->message); + + nih_error_push_context (); + nih_dbus_error_raise (error.name, error.message); + pending_data->error_handler (pending_data->data, message); + nih_error_pop_context (); + + dbus_error_free (&error); + nih_free (message); + dbus_message_unref (reply); + return; + } + + nih_assert (dbus_message_get_type (reply) == DBUS_MESSAGE_TYPE_METHOD_RETURN); + + do { + __label__ enomem; + + /* Create a message context for the reply, and iterate + * over and recurse into the arguments. + */ + message = nih_dbus_message_new (pending_data, pending_data->connection, reply); + if (! message) + goto enomem; + + dbus_message_iter_init (message->message, &iter); + + if (dbus_message_iter_get_arg_type (&iter) != DBUS_TYPE_VARIANT) { + nih_error_push_context (); + nih_error_raise (NIH_DBUS_INVALID_ARGS, + _(NIH_DBUS_INVALID_ARGS_STR)); + pending_data->error_handler (pending_data->data, message); + nih_error_pop_context (); + + nih_free (message); + dbus_message_unref (reply); + return; + } + + dbus_message_iter_recurse (&iter, &variter); + + /* Demarshal a structure from the message */ + if (dbus_message_iter_get_arg_type (&variter) != DBUS_TYPE_STRUCT) { + nih_error_push_context (); + nih_error_raise (NIH_DBUS_INVALID_ARGS, + _(NIH_DBUS_INVALID_ARGS_STR)); + pending_data->error_handler (pending_data->data, message); + nih_error_pop_context (); + + nih_free (message); + dbus_message_unref (reply); + return; + } + + dbus_message_iter_recurse (&variter, &value_iter); + + value = nih_new (message, MyProperty); + if (! value) { + nih_free (message); + message = NULL; + goto enomem; + } + + /* Demarshal a char * from the message */ + if (dbus_message_iter_get_arg_type (&value_iter) != DBUS_TYPE_STRING) { + nih_free (value); + nih_error_push_context (); + nih_error_raise (NIH_DBUS_INVALID_ARGS, + _(NIH_DBUS_INVALID_ARGS_STR)); + pending_data->error_handler (pending_data->data, message); + nih_error_pop_context (); + + nih_free (message); + dbus_message_unref (reply); + return; + } + + dbus_message_iter_get_basic (&value_iter, &value_item0_dbus); + + value_item0 = nih_strdup (value, value_item0_dbus); + if (! value_item0) { + nih_free (value); + nih_free (message); + message = NULL; + goto enomem; + } + + dbus_message_iter_next (&value_iter); + + value->item0 = value_item0; + + /* Demarshal a uint32_t from the message */ + if (dbus_message_iter_get_arg_type (&value_iter) != DBUS_TYPE_UINT32) { + nih_free (value); + nih_error_push_context (); + nih_error_raise (NIH_DBUS_INVALID_ARGS, + _(NIH_DBUS_INVALID_ARGS_STR)); + pending_data->error_handler (pending_data->data, message); + nih_error_pop_context (); + + nih_free (message); + dbus_message_unref (reply); + return; + } + + dbus_message_iter_get_basic (&value_iter, &value_item1); + + dbus_message_iter_next (&value_iter); + + value->item1 = value_item1; + + if (dbus_message_iter_get_arg_type (&value_iter) != DBUS_TYPE_INVALID) { + nih_free (value); + nih_error_push_context (); + nih_error_raise (NIH_DBUS_INVALID_ARGS, + _(NIH_DBUS_INVALID_ARGS_STR)); + pending_data->error_handler (pending_data->data, message); + nih_error_pop_context (); + + nih_free (message); + dbus_message_unref (reply); + return; + } + + dbus_message_iter_next (&variter); + + dbus_message_iter_next (&iter); + + if (dbus_message_iter_get_arg_type (&iter) != DBUS_TYPE_INVALID) { + nih_error_push_context (); + nih_error_raise (NIH_DBUS_INVALID_ARGS, + _(NIH_DBUS_INVALID_ARGS_STR)); + pending_data->error_handler (pending_data->data, message); + nih_error_pop_context (); + + nih_free (message); + dbus_message_unref (reply); + return; + } + + enomem: __attribute__ ((unused)); + } while (! message); + + /* Call the handler function */ + nih_error_push_context (); + ((MyGetPropertyReply)pending_data->handler) (pending_data->data, message, value); + nih_error_pop_context (); + + nih_free (message); + dbus_message_unref (reply); +} diff --git a/pool/shard008/C/0129860_H5Fio.c b/pool/shard008/C/0129860_H5Fio.c new file mode 100644 index 0000000000000000000000000000000000000000..81fa514c4cd3ca9e0d9f658115d9152cbf2687d7 --- /dev/null +++ b/pool/shard008/C/0129860_H5Fio.c @@ -0,0 +1,370 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * Copyright by The HDF Group. * + * Copyright by the Board of Trustees of the University of Illinois. * + * All rights reserved. * + * * + * This file is part of HDF5. The full HDF5 copyright notice, including * + * terms governing use, modification, and redistribution, is contained in * + * the COPYING file, which can be found at the root of the source code * + * distribution tree, or in https://support.hdfgroup.org/ftp/HDF5/releases. * + * If you do not have access to either file, you may request a copy from * + * help@hdfgroup.org. * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +/*------------------------------------------------------------------------- + * + * Created: H5Fio.c + * Jan 10 2008 + * Quincey Koziol + * + * Purpose: File I/O routines. + * + *------------------------------------------------------------------------- + */ + +/****************/ +/* Module Setup */ +/****************/ + +#include "H5Fmodule.h" /* This source code file is part of the H5F module */ + + +/***********/ +/* Headers */ +/***********/ +#include "H5private.h" /* Generic Functions */ +#include "H5Eprivate.h" /* Error handling */ +#include "H5Fpkg.h" /* File access */ +#include "H5FDprivate.h" /* File drivers */ +#include "H5Iprivate.h" /* IDs */ +#include "H5PBprivate.h" /* Page Buffer */ + + +/****************/ +/* Local Macros */ +/****************/ + + +/******************/ +/* Local Typedefs */ +/******************/ + + +/********************/ +/* Package Typedefs */ +/********************/ + + +/********************/ +/* Local Prototypes */ +/********************/ + + +/*********************/ +/* Package Variables */ +/*********************/ + + +/*****************************/ +/* Library Private Variables */ +/*****************************/ + + +/*******************/ +/* Local Variables */ +/*******************/ + + + +/*------------------------------------------------------------------------- + * Function: H5F_block_read + * + * Purpose: Reads some data from a file/server/etc into a buffer. + * The data is contiguous. The address is relative to the base + * address for the file. + * + * Return: Non-negative on success/Negative on failure + * + * Programmer: Robb Matzke + * matzke@llnl.gov + * Jul 10 1997 + * + *------------------------------------------------------------------------- + */ +herr_t +H5F_block_read(const H5F_t *f, H5FD_mem_t type, haddr_t addr, size_t size, + hid_t dxpl_id, void *buf/*out*/) +{ + H5F_io_info2_t fio_info; /* I/O info for operation */ + H5FD_mem_t map_type; /* Mapped memory type */ + herr_t ret_value = SUCCEED; /* Return value */ + + FUNC_ENTER_NOAPI(FAIL) + + HDassert(f); + HDassert(f->shared); + HDassert(buf); + HDassert(H5F_addr_defined(addr)); + + /* Check for attempting I/O on 'temporary' file address */ + if(H5F_addr_le(f->shared->tmp_addr, (addr + size))) + HGOTO_ERROR(H5E_IO, H5E_BADRANGE, FAIL, "attempting I/O in temporary file space") + + /* Treat global heap as raw data */ + map_type = (type == H5FD_MEM_GHEAP) ? H5FD_MEM_DRAW : type; + + /* Set up the I/O info object */ + fio_info.f = f; + if(H5FD_MEM_DRAW == type) { + if(NULL == (fio_info.meta_dxpl = (H5P_genplist_t *)H5I_object(H5AC_ind_read_dxpl_id))) + HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "can't get property list") + if(NULL == (fio_info.raw_dxpl = (H5P_genplist_t *)H5I_object(dxpl_id))) + HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "can't get property list") + } /* end if */ + else { + if(NULL == (fio_info.meta_dxpl = (H5P_genplist_t *)H5I_object(dxpl_id))) + HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "can't get property list") + if(NULL == (fio_info.raw_dxpl = (H5P_genplist_t *)H5I_object(H5AC_rawdata_dxpl_id))) + HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "can't get property list") + } /* end else */ + + /* Pass through page buffer layer */ + if(H5PB_read(&fio_info, map_type, addr, size, buf) < 0) + HGOTO_ERROR(H5E_IO, H5E_READERROR, FAIL, "read through page buffer failed") + +done: + FUNC_LEAVE_NOAPI(ret_value) +} /* end H5F_block_read() */ + + +/*------------------------------------------------------------------------- + * Function: H5F_block_write + * + * Purpose: Writes some data from memory to a file/server/etc. The + * data is contiguous. The address is relative to the base + * address. + * + * Return: Non-negative on success/Negative on failure + * + * Programmer: Robb Matzke + * matzke@llnl.gov + * Jul 10 1997 + * + *------------------------------------------------------------------------- + */ +herr_t +H5F_block_write(const H5F_t *f, H5FD_mem_t type, haddr_t addr, size_t size, + hid_t dxpl_id, const void *buf) +{ + H5F_io_info2_t fio_info; /* I/O info for operation */ + H5FD_mem_t map_type; /* Mapped memory type */ + herr_t ret_value = SUCCEED; /* Return value */ + + FUNC_ENTER_NOAPI(FAIL) + + HDassert(f); + HDassert(f->shared); + HDassert(H5F_INTENT(f) & H5F_ACC_RDWR); + HDassert(buf); + HDassert(H5F_addr_defined(addr)); + + /* Check for attempting I/O on 'temporary' file address */ + if(H5F_addr_le(f->shared->tmp_addr, (addr + size))) + HGOTO_ERROR(H5E_IO, H5E_BADRANGE, FAIL, "attempting I/O in temporary file space") + + /* Treat global heap as raw data */ + map_type = (type == H5FD_MEM_GHEAP) ? H5FD_MEM_DRAW : type; + + /* Set up the I/O info object */ + fio_info.f = f; + if(H5FD_MEM_DRAW == type) { + if(NULL == (fio_info.meta_dxpl = (H5P_genplist_t *)H5I_object(H5AC_ind_read_dxpl_id))) + HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "can't get property list") + if(NULL == (fio_info.raw_dxpl = (H5P_genplist_t *)H5I_object(dxpl_id))) + HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "can't get property list") + } /* end if */ + else { + if(NULL == (fio_info.meta_dxpl = (H5P_genplist_t *)H5I_object(dxpl_id))) + HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "can't get property list") + if(NULL == (fio_info.raw_dxpl = (H5P_genplist_t *)H5I_object(H5AC_rawdata_dxpl_id))) + HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "can't get property list") + } /* end else */ + + /* Pass through page buffer layer */ + if(H5PB_write(&fio_info, map_type, addr, size, buf) < 0) + HGOTO_ERROR(H5E_IO, H5E_WRITEERROR, FAIL, "write through page buffer failed") + +done: + FUNC_LEAVE_NOAPI(ret_value) +} /* end H5F_block_write() */ + + +/*------------------------------------------------------------------------- + * Function: H5F_flush_tagged_metadata + * + * Purpose: Flushes metadata with specified tag in the metadata cache + * to disk. + * + * Return: Non-negative on success/Negative on failure + * + * Programmer: Mike McGreevy + * September 9, 2010 + * + *------------------------------------------------------------------------- + */ +herr_t +H5F_flush_tagged_metadata(H5F_t * f, haddr_t tag, hid_t dxpl_id) +{ + H5F_io_info2_t fio_info; /* I/O info for operation */ + herr_t ret_value = SUCCEED; + + FUNC_ENTER_NOAPI(FAIL) + + /* Use tag to search for and flush associated metadata */ + if(H5AC_flush_tagged_metadata(f, tag, dxpl_id)<0) + HGOTO_ERROR(H5E_CACHE, H5E_CANTFLUSH, FAIL, "unable to flush tagged metadata") + + /* Set up I/O info for operation */ + fio_info.f = f; + if(NULL == (fio_info.meta_dxpl = (H5P_genplist_t *)H5I_object(dxpl_id))) + HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "can't get property list") + if(NULL == (fio_info.raw_dxpl = (H5P_genplist_t *)H5I_object(H5AC_rawdata_dxpl_id))) + HGOTO_ERROR(H5E_ARGS, H5E_BADTYPE, FAIL, "can't get property list") + + /* Flush and reset the accumulator */ + if(H5F__accum_reset(&fio_info, TRUE) < 0) + HGOTO_ERROR(H5E_IO, H5E_CANTRESET, FAIL, "can't reset accumulator") + + /* Flush file buffers to disk. */ + if(H5FD_flush(f->shared->lf, dxpl_id, FALSE) < 0) + HGOTO_ERROR(H5E_IO, H5E_WRITEERROR, FAIL, "low level flush failed") + +done: + FUNC_LEAVE_NOAPI(ret_value); +} /* end H5F_flush_tagged_metadata */ + + +/*------------------------------------------------------------------------- + * Function: H5F_evict_tagged_metadata + * + * Purpose: Evicts metadata from the cache with specified tag. + * + * Return: Non-negative on success/Negative on failure + * + * Programmer: Mike McGreevy + * September 9, 2010 + * + *------------------------------------------------------------------------- + */ +herr_t +H5F_evict_tagged_metadata(H5F_t * f, haddr_t tag, hid_t dxpl_id) +{ + herr_t ret_value = SUCCEED; + + FUNC_ENTER_NOAPI(FAIL) + + /* Evict the object's metadata */ + if(H5AC_evict_tagged_metadata(f, tag, TRUE, dxpl_id) < 0) + HGOTO_ERROR(H5E_CACHE, H5E_CANTEXPUNGE, FAIL, "unable to evict tagged metadata") + +done: + FUNC_LEAVE_NOAPI(ret_value); +} /* end H5F_evict_tagged_metadata */ + + +/*------------------------------------------------------------------------- + * Function: H5F__evict_cache_entries + * + * Purpose: To evict all cache entries except the pinned superblock entry + * + * Return: Non-negative on success/Negative on failure + * + * Programmer: Vailin Choi + * Dec 2013 + * + *------------------------------------------------------------------------- + */ +herr_t +H5F__evict_cache_entries(H5F_t *f, hid_t dxpl_id) +{ + herr_t ret_value = SUCCEED; + + FUNC_ENTER_PACKAGE + + HDassert(f); + HDassert(f->shared); + + /* Evict all except pinned entries in the cache */ + if(H5AC_evict(f, dxpl_id) < 0) + HGOTO_ERROR(H5E_CACHE, H5E_CANTEXPUNGE, FAIL, "unable to evict all except pinned entries") + +#ifndef NDEBUG +{ + unsigned status = 0; + uint32_t cur_num_entries; + + /* Retrieve status of the superblock */ + if(H5AC_get_entry_status(f, (haddr_t)0, &status) < 0) + HGOTO_ERROR(H5E_HEAP, H5E_CANTGET, FAIL, "unable to get entry status") + + /* Verify status of the superblock entry in the cache */ + if(!(status & H5AC_ES__IN_CACHE) || !(status & H5AC_ES__IS_PINNED)) + HGOTO_ERROR(H5E_HEAP, H5E_CANTGET, FAIL, "unable to get entry status") + + /* Get the number of cache entries */ + if(H5AC_get_cache_size(f->shared->cache, NULL, NULL, NULL, &cur_num_entries) < 0) + HGOTO_ERROR(H5E_CACHE, H5E_SYSTEM, FAIL, "H5AC_get_cache_size() failed.") + + /* Should be the only one left in the cache (the superblock) */ + if(cur_num_entries != 1) + HGOTO_ERROR(H5E_CACHE, H5E_SYSTEM, FAIL, "number of cache entries is not correct") +} +#endif /* NDEBUG */ + +done: + FUNC_LEAVE_NOAPI(ret_value); +} /* end H5F__evict_cache_entries() */ + + +/*------------------------------------------------------------------------- + * Function: H5F_get_checksums + * + * Purpose: Decode checksum stored in the buffer + * Calculate checksum for the data in the buffer + * + * Note: Assumes that the checksum is the last data in the buffer + * + * Return: Non-negative on success/Negative on failure + * + * Programmer: Vailin Choi + * Sept 2013 + * + *------------------------------------------------------------------------- + */ +herr_t +H5F_get_checksums(const uint8_t *buf, size_t buf_size, uint32_t *s_chksum/*out*/, uint32_t *c_chksum/*out*/) +{ + FUNC_ENTER_NOAPI_NOINIT_NOERR + + /* Check arguments */ + HDassert(buf); + HDassert(buf_size); + + /* Return the stored checksum */ + if(s_chksum) { + const uint8_t *chk_p; /* Pointer into raw data buffer */ + + /* Offset to the checksum in the buffer */ + chk_p = buf + buf_size - H5_SIZEOF_CHKSUM; + + /* Decode the checksum stored in the buffer */ + UINT32DECODE(chk_p, *s_chksum); + } /* end if */ + + /* Return the computed checksum for the buffer */ + if(c_chksum) + *c_chksum = H5_checksum_metadata(buf, buf_size - H5_SIZEOF_CHKSUM, 0); + + FUNC_LEAVE_NOAPI(SUCCEED) +} /* end H5F_get_chksums() */ + diff --git a/pool/shard008/C/0129861_jdapistd.c b/pool/shard008/C/0129861_jdapistd.c new file mode 100644 index 0000000000000000000000000000000000000000..b8253ebae25ef8eed8749a09316692602f76958e --- /dev/null +++ b/pool/shard008/C/0129861_jdapistd.c @@ -0,0 +1,284 @@ +// +// Copyright (c) .NET Foundation and Contributors +// Original work Copyright (c) 1994-1998, Thomas G. Lane +// See LICENSE file in the project root for full license information. +// + +/* + * jdapistd.c + * + * Copyright (C) 1994-1996, Thomas G. Lane. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains application interface code for the decompression half + * of the JPEG library. These are the "standard" API routines that are + * used in the normal full-decompression case. They are not used by a + * transcoding-only application. Note that if an application links in + * jpeg_start_decompress, it will end up linking in the entire decompressor. + * We thus must separate this file from jdapimin.c to avoid linking the + * whole decompression library into a transcoder. + */ + +#define JPEG_INTERNALS +#include "jinclude.h" +#include "jpeglib.h" + + + /* Forward declarations */ +LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo)); + + +/* + * Decompression initialization. + * jpeg_read_header must be completed before calling this. + * + * If a multipass operating mode was selected, this will do all but the + * last pass, and thus may take a great deal of time. + * + * Returns FALSE if suspended. The return value need be inspected only if + * a suspending data source is used. + */ + +GLOBAL(boolean) +jpeg_start_decompress(j_decompress_ptr cinfo) +{ + if (cinfo->global_state == DSTATE_READY) { + /* First call: initialize master control, select active modules */ + jinit_master_decompress(cinfo); + if (cinfo->buffered_image) { + /* No more work here; expecting jpeg_start_output next */ + cinfo->global_state = DSTATE_BUFIMAGE; + return TRUE; + } + cinfo->global_state = DSTATE_PRELOAD; + } + if (cinfo->global_state == DSTATE_PRELOAD) { + /* If file has multiple scans, absorb them all into the coef buffer */ + if (cinfo->inputctl->has_multiple_scans) { +#ifdef D_MULTISCAN_FILES_SUPPORTED + for (;;) { + int retcode; + /* Call progress monitor hook if present */ + if (cinfo->progress != NULL) + (*cinfo->progress->progress_monitor) ((j_common_ptr)cinfo); + /* Absorb some more input */ + retcode = (*cinfo->inputctl->consume_input) (cinfo); + if (retcode == JPEG_SUSPENDED) + return FALSE; + if (retcode == JPEG_REACHED_EOI) + break; + /* Advance progress counter if appropriate */ + if (cinfo->progress != NULL && + (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) { + if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) { + /* jdmaster underestimated number of scans; ratchet up one scan */ + cinfo->progress->pass_limit += (long)cinfo->total_iMCU_rows; + } + } + } +#else + ERREXIT(cinfo, JERR_NOT_COMPILED); +#endif /* D_MULTISCAN_FILES_SUPPORTED */ + } + cinfo->output_scan_number = cinfo->input_scan_number; + } + else if (cinfo->global_state != DSTATE_PRESCAN) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + /* Perform any dummy output passes, and set up for the final pass */ + return output_pass_setup(cinfo); +} + + +/* + * Set up for an output pass, and perform any dummy pass(es) needed. + * Common subroutine for jpeg_start_decompress and jpeg_start_output. + * Entry: global_state = DSTATE_PRESCAN only if previously suspended. + * Exit: If done, returns TRUE and sets global_state for proper output mode. + * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN. + */ + +LOCAL(boolean) +output_pass_setup(j_decompress_ptr cinfo) +{ + if (cinfo->global_state != DSTATE_PRESCAN) { + /* First call: do pass setup */ + (*cinfo->master->prepare_for_output_pass) (cinfo); + cinfo->output_scanline = 0; + cinfo->global_state = DSTATE_PRESCAN; + } + /* Loop over any required dummy passes */ + while (cinfo->master->is_dummy_pass) { +#ifdef QUANT_2PASS_SUPPORTED + /* Crank through the dummy pass */ + while (cinfo->output_scanline < cinfo->output_height) { + JDIMENSION last_scanline; + /* Call progress monitor hook if present */ + if (cinfo->progress != NULL) { + cinfo->progress->pass_counter = (long)cinfo->output_scanline; + cinfo->progress->pass_limit = (long)cinfo->output_height; + (*cinfo->progress->progress_monitor) ((j_common_ptr)cinfo); + } + /* Process some data */ + last_scanline = cinfo->output_scanline; + (*cinfo->main->process_data) (cinfo, (JSAMPARRAY)NULL, + &cinfo->output_scanline, (JDIMENSION)0); + if (cinfo->output_scanline == last_scanline) + return FALSE; /* No progress made, must suspend */ + } + /* Finish up dummy pass, and set up for another one */ + (*cinfo->master->finish_output_pass) (cinfo); + (*cinfo->master->prepare_for_output_pass) (cinfo); + cinfo->output_scanline = 0; +#else + ERREXIT(cinfo, JERR_NOT_COMPILED); +#endif /* QUANT_2PASS_SUPPORTED */ + } + /* Ready for application to drive output pass through + * jpeg_read_scanlines or jpeg_read_raw_data. + */ + cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING; + return TRUE; +} + + +/* + * Read some scanlines of data from the JPEG decompressor. + * + * The return value will be the number of lines actually read. + * This may be less than the number requested in several cases, + * including bottom of image, data source suspension, and operating + * modes that emit multiple scanlines at a time. + * + * Note: we warn about excess calls to jpeg_read_scanlines() since + * this likely signals an application programmer error. However, + * an oversize buffer (max_lines > scanlines remaining) is not an error. + */ + +GLOBAL(JDIMENSION) +jpeg_read_scanlines(j_decompress_ptr cinfo, JSAMPARRAY scanlines, + JDIMENSION max_lines) +{ + JDIMENSION row_ctr; + + if (cinfo->global_state != DSTATE_SCANNING) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + if (cinfo->output_scanline >= cinfo->output_height) { + WARNMS(cinfo, JWRN_TOO_MUCH_DATA); + return 0; + } + + /* Call progress monitor hook if present */ + if (cinfo->progress != NULL) { + cinfo->progress->pass_counter = (long)cinfo->output_scanline; + cinfo->progress->pass_limit = (long)cinfo->output_height; + (*cinfo->progress->progress_monitor) ((j_common_ptr)cinfo); + } + + /* Process some data */ + row_ctr = 0; + (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines); + cinfo->output_scanline += row_ctr; + return row_ctr; +} + + +/* + * Alternate entry point to read raw data. + * Processes exactly one iMCU row per call, unless suspended. + */ + +GLOBAL(JDIMENSION) +jpeg_read_raw_data(j_decompress_ptr cinfo, JSAMPIMAGE data, + JDIMENSION max_lines) +{ + JDIMENSION lines_per_iMCU_row; + + if (cinfo->global_state != DSTATE_RAW_OK) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + if (cinfo->output_scanline >= cinfo->output_height) { + WARNMS(cinfo, JWRN_TOO_MUCH_DATA); + return 0; + } + + /* Call progress monitor hook if present */ + if (cinfo->progress != NULL) { + cinfo->progress->pass_counter = (long)cinfo->output_scanline; + cinfo->progress->pass_limit = (long)cinfo->output_height; + (*cinfo->progress->progress_monitor) ((j_common_ptr)cinfo); + } + + /* Verify that at least one iMCU row can be returned. */ + lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size; + if (max_lines < lines_per_iMCU_row) + ERREXIT(cinfo, JERR_BUFFER_SIZE); + + /* Decompress directly into user's buffer. */ + if (!(*cinfo->coef->decompress_data) (cinfo, data)) + return 0; /* suspension forced, can do nothing more */ + + /* OK, we processed one iMCU row. */ + cinfo->output_scanline += lines_per_iMCU_row; + return lines_per_iMCU_row; +} + + +/* Additional entry points for buffered-image mode. */ + +#ifdef D_MULTISCAN_FILES_SUPPORTED + +/* + * Initialize for an output pass in buffered-image mode. + */ + +GLOBAL(boolean) +jpeg_start_output(j_decompress_ptr cinfo, int scan_number) +{ + if (cinfo->global_state != DSTATE_BUFIMAGE && + cinfo->global_state != DSTATE_PRESCAN) + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + /* Limit scan number to valid range */ + if (scan_number <= 0) + scan_number = 1; + if (cinfo->inputctl->eoi_reached && + scan_number > cinfo->input_scan_number) + scan_number = cinfo->input_scan_number; + cinfo->output_scan_number = scan_number; + /* Perform any dummy output passes, and set up for the real pass */ + return output_pass_setup(cinfo); +} + + +/* + * Finish up after an output pass in buffered-image mode. + * + * Returns FALSE if suspended. The return value need be inspected only if + * a suspending data source is used. + */ + +GLOBAL(boolean) +jpeg_finish_output(j_decompress_ptr cinfo) +{ + if ((cinfo->global_state == DSTATE_SCANNING || + cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) { + /* Terminate this pass. */ + /* We do not require the whole pass to have been completed. */ + (*cinfo->master->finish_output_pass) (cinfo); + cinfo->global_state = DSTATE_BUFPOST; + } + else if (cinfo->global_state != DSTATE_BUFPOST) { + /* BUFPOST = repeat call after a suspension, anything else is error */ + ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); + } + /* Read markers looking for SOS or EOI */ + while (cinfo->input_scan_number <= cinfo->output_scan_number && + !cinfo->inputctl->eoi_reached) { + if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED) + return FALSE; /* Suspend, come back later */ + } + cinfo->global_state = DSTATE_BUFIMAGE; + return TRUE; +} + +#endif /* D_MULTISCAN_FILES_SUPPORTED */ + diff --git a/pool/shard008/C/0129862_rtpp_acct_rtcp_hep.c b/pool/shard008/C/0129862_rtpp_acct_rtcp_hep.c new file mode 100644 index 0000000000000000000000000000000000000000..9d5b1e070a23be396aae73a392cfa2afb4d74aef --- /dev/null +++ b/pool/shard008/C/0129862_rtpp_acct_rtcp_hep.c @@ -0,0 +1,219 @@ +/* + * Copyright (c) 2006-2018 Sippy Software, Inc., http://www.sippysoft.com + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + */ + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "config_pp.h" + +#include "rtpp_types.h" +#include "rtpp_module.h" +#include "rtpp_module_acct.h" +#include "rtpp_log.h" +#include "rtpp_log_obj.h" +#include "rtpp_cfg.h" +#include "rtpp_acct_rtcp.h" +#include "rtpp_network.h" +#include "rtpp_time.h" +#include "rtp.h" +#include "rtp_packet.h" +#include "rtpp_ssrc.h" +#include "rtpp_ucl.h" +#include "rtpa_stats.h" + +#include "rtcp2json.h" +#include "core_hep.h" +#include "hep_api.h" +#include "hepconnector.h" +#include "rtpp_sbuf.h" + +#include "_acct_rtcp_hep_config.h" + +struct rtpp_module_priv { + struct rtpp_sbuf *sbp; + struct hep_ctx *ctx; +}; + +static struct rtpp_module_priv *rtpp_acct_rtcp_hep_ctor(const struct rtpp_cfg *); +static void rtpp_acct_rtcp_hep_dtor(struct rtpp_module_priv *); +static void rtpp_acct_rtcp_hep_do(struct rtpp_module_priv *, struct rtpp_acct_rtcp *); +static struct rtpp_module_conf *rtpp_acct_rtcp_hep_get_mconf(void); +static int rtpp_acct_rtcp_hep_config(struct rtpp_module_priv *); + +extern struct rtpp_module_conf *rtpp_arh_conf; + +#ifdef RTPP_CHECK_LEAKS +#include "rtpp_memdeb_internal.h" + +RTPP_MEMDEB_APP_STATIC; +#endif + +static const struct rtpp_acct_handlers acct_rtcp_hep_aapi = { + .on_rtcp_rcvd = AAPI_FUNC(rtpp_acct_rtcp_hep_do, rtpp_acct_rtcp_OSIZE()) +}; + +struct rtpp_minfo rtpp_module = { + .descr.name = "acct_rtcp_hep", + .descr.ver = MI_VER_INIT(), + .descr.module_id = 2, + .proc.ctor = rtpp_acct_rtcp_hep_ctor, + .proc.dtor = rtpp_acct_rtcp_hep_dtor, + .proc.get_mconf = rtpp_acct_rtcp_hep_get_mconf, + .proc.config = rtpp_acct_rtcp_hep_config, +#ifdef RTPP_CHECK_LEAKS + .memdeb_p = &MEMDEB_SYM, +#endif + .aapi = &acct_rtcp_hep_aapi +}; + +static struct rtpp_module_priv * +rtpp_acct_rtcp_hep_ctor(const struct rtpp_cfg *cfsp) +{ + struct rtpp_module_priv *pvt; + + pvt = mod_zmalloc(sizeof(struct rtpp_module_priv)); + if (pvt == NULL) { + goto e0; + } + pvt->sbp = rtpp_sbuf_ctor(512); + if (pvt->sbp == NULL) { + goto e1; + } + return (pvt); + +#if 0 +e2: + rtpp_sbuf_dtor(pvt->sbp); +#endif +e1: + mod_free(pvt); +e0: + return (NULL); +} + +static int +rtpp_acct_rtcp_hep_config(struct rtpp_module_priv *pvt) +{ + pvt->ctx = rtpp_arh_conf->conf_data; + if (init_hepsocket(pvt->ctx) != 0) { + return (-1); + } + return (0); +} + +static void +rtpp_acct_rtcp_hep_dtor(struct rtpp_module_priv *pvt) +{ + if (pvt->ctx->capt_host != default_ctx.capt_host && pvt->ctx->capt_host != NULL) { + mod_free(pvt->ctx->capt_host); + } + hep_gen_dtor(pvt->ctx); + rtpp_sbuf_dtor(pvt->sbp); + mod_free(pvt); + return; +} + +static void +rtpp_acct_rtcp_hep_do(struct rtpp_module_priv *pvt, struct rtpp_acct_rtcp *rarp) +{ + struct rc_info ri; + const struct sockaddr *src_addr, *dst_addr; + struct timeval rtimeval; + int rval; + + memset(&ri, '\0', sizeof(ri)); + + src_addr = sstosa(&(rarp->pkt->raddr)); + dst_addr = rarp->pkt->laddr; + ri.ip_proto = 17; /* UDP */ + ri.proto_type = 5; /* RTCP */ + + ri.ip_family = dst_addr->sa_family; + switch (ri.ip_family) { + case AF_INET: + ri.src.p4 = &(satosin(src_addr)->sin_addr); + ri.dst.p4 = &(satosin(dst_addr)->sin_addr); + break; + + case AF_INET6: + ri.src.p6 = &(satosin6(src_addr)->sin6_addr); + ri.dst.p6 = &(satosin6(dst_addr)->sin6_addr); + break; + + default: + abort(); + } + + ri.src_port = getport(src_addr); + ri.dst_port = rarp->pkt->lport; + dtime2timeval(rarp->pkt->rtime.wall, &rtimeval); + ri.time_sec = SEC(&rtimeval); + ri.time_usec = USEC(&rtimeval); + if (hep_gen_fill(pvt->ctx, &ri) < 0) { + mod_log(RTPP_LOG_ERR, "hep_gen_fill() failed"); + goto out; + } + + if (hep_gen_append(pvt->ctx, HEP_VID_GEN, HEP_TID_CID, rarp->call_id, + strlen(rarp->call_id)) < 0) { + mod_log(RTPP_LOG_ERR, "hep_gen_append() failed"); + goto out; + } + + rtpp_sbuf_reset(pvt->sbp); + rval = rtcp2json(pvt->sbp, rarp->pkt->data.buf, rarp->pkt->size); + if (rval < 0) { + mod_log(RTPP_LOG_ERR, "rtcp2json() failed: %d", rval); + goto out; + } + + rval = send_hep(pvt->ctx, &ri, pvt->sbp->bp, RS_ULEN(pvt->sbp)); + if (rval < 0) { + mod_log(RTPP_LOG_INFO, "send_hep() failed: %d", rval); + } + +out: + return; +} + +static struct rtpp_module_conf * +rtpp_acct_rtcp_hep_get_mconf(void) +{ + static struct hep_ctx hp; + + hp = default_ctx; + rtpp_arh_conf->conf_data = &hp; + + return (rtpp_arh_conf); +} diff --git a/pool/shard008/C/0129865_uuencode.c b/pool/shard008/C/0129865_uuencode.c new file mode 100644 index 0000000000000000000000000000000000000000..517f48d029b3a59d23455eab1d8979e0ccc85ed3 --- /dev/null +++ b/pool/shard008/C/0129865_uuencode.c @@ -0,0 +1,132 @@ +/* + * Copyright (C) 2007-2008 Sourcefire, Inc. + * + * Authors: Nigel Horne + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * 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. + */ + +static char const rcsid[] = "$Id: uuencode.c,v 1.8 2006/12/11 11:55:11 njh Exp $"; + +#include "clamav.h" + +#if HAVE_CONFIG_H +#include "clamav-config.h" +#endif + +#ifdef HAVE_UNISTD_H +#include +#endif + +#include +#include +#include +#ifdef HAVE_STRINGS_H +#include +#endif +#include "others.h" +#include "str.h" + +#include "mbox.h" +#include "uuencode.h" + +/* Maximum line length according to RFC821 */ +#define RFC2821LENGTH 1000 + +int +cli_uuencode(const char *dir, fmap_t *map) +{ + message *m; + char buffer[RFC2821LENGTH + 1]; + size_t at = 0; + + if(!fmap_gets(map, buffer, &at, sizeof(buffer) - 1)) { + /* empty message */ + return CL_CLEAN; + } + if(!isuuencodebegin(buffer)) { + cli_dbgmsg("Message is not in uuencoded format\n"); + return CL_EFORMAT; + } + + m = messageCreate(); + if(m == NULL) { + return CL_EMEM; + } + + cli_dbgmsg("found uuencode file\n"); + + if(uudecodeFile(m, buffer, dir, map, &at) < 0) { + messageDestroy(m); + cli_dbgmsg("Message is not in uuencoded format\n"); + return CL_EFORMAT; + } + messageDestroy(m); + + return CL_CLEAN; /* a lie - but it gets things going */ +} + +/* + * Save the uuencoded part of the file as it is read in since there's no need + * to include it in the parse tree. Saves memory and parse time. + * Return < 0 for failure + */ +int +uudecodeFile(message *m, const char *firstline, const char *dir, fmap_t *map, size_t *at) +{ + fileblob *fb; + char buffer[RFC2821LENGTH + 1]; + char *filename = cli_strtok(firstline, 2, " "); + + if(filename == NULL) + return -1; + + fb = fileblobCreate(); + if(fb == NULL) { + free(filename); + return -1; + } + + fileblobSetFilename(fb, dir, filename); + cli_dbgmsg("uudecode %s\n", filename); + free(filename); + + while(fmap_gets(map, buffer, at, sizeof(buffer) - 1)) { + unsigned char data[1024]; + const unsigned char *uptr; + size_t len; + + cli_chomp(buffer); + if(strcasecmp(buffer, "end") == 0) + break; + if(buffer[0] == '\0') + break; + + uptr = decodeLine(m, UUENCODE, buffer, data, sizeof(data)); + if(uptr == NULL) + break; + + len = (size_t)(uptr - data); + if((len > 62) || (len == 0)) + break; + + if(fileblobAddData(fb, data, len) < 0) + break; + } + + fileblobDestroy(fb); + + return 1; +} diff --git a/pool/shard008/C/0129866_astar.c b/pool/shard008/C/0129866_astar.c new file mode 100644 index 0000000000000000000000000000000000000000..25d004c2c51d19038f035352177bbdeef43c50d4 --- /dev/null +++ b/pool/shard008/C/0129866_astar.c @@ -0,0 +1,254 @@ +//////////////////////////////////////////////////// +// This file contains the A* pathfinding code +// +// all code by Thomas Grip +/////////////////////////////////////////////////// + + + +#include +#include +#include + +#include "../fiend.h" +#include "../grafik4.h" + +//max nodes on screen at ones. +#define MAX_SCREEN_NODES 40 + +//screen sixe for nodes. +#define NODE_SCREEN_H 480 +#define NODE_SCREEN_W 480 + + +typedef struct THE_NODE +{ + int num; + int cost; + + struct THE_NODE* parent; +}NODE; + + +static NODE *node[MAX_PATHNODE_NUM]; +int h_list[MAX_PATHNODE_NUM]; + +static int node_num=0; + +static int global_x; +static int global_y; + +static int global_goal_x; +static int global_goal_y; + + +//check if you can move from start to goal without hitting anything... +static int free_path(int start_x, int start_y, int goal_x,int goal_y,int w, int h, int check_player) +{ + int i; + + int x_add[5] = {0,-w/2+1,w/2-1,w/2-1,-w/2+1}; + int y_add[5] = {0,-h/2+1,-h/2+1,h/2-1,h/2-1}; + + for(i=0;i<5;i++) + { + if(!path_is_clear(start_x+x_add[i],start_y+y_add[i],0,goal_x,goal_y,1,check_player)) + return 0; + } + + return 1; +} + + +//make a new node +static int new_node(int index, int num, NODE *parent) +{ + int h; + int cost; + + NODE *temp_n; + + if(parent==NULL) + cost = distance(global_x, global_y, map->path_node[num].x,map->path_node[num].y); + else + cost = parent->cost + distance(map->path_node[num].x,map->path_node[num].y, map->path_node[parent->num].x,map->path_node[parent->num].y); + + h = cost + distance(map->path_node[num].x,map->path_node[num].y,global_goal_x, global_goal_y); + + if(h>=h_list[num]) return 0; + + node[index] = (NODE*) malloc(sizeof(NODE)); + + node[index]->num = num; + + if(parent==NULL) + { + node[index]->cost = cost; + node[index]->parent = NULL; + h_list[num] = h; + } + else + { + node[index]->cost = cost; + h_list[num] = h; + + while(parent->parent!=NULL) + { + temp_n = parent->parent; + parent = temp_n; + } + + temp_n = (NODE*) malloc(sizeof(NODE)); + + temp_n->cost =parent->cost; + temp_n->num =parent->num; + temp_n->parent = NULL; + + node[index]->parent = temp_n; + } + + return 1; +} + +//delete a node +static void delete_node(NODE *n) +{ + NODE* temp_n; + + + temp_n = n->parent; + free(n); + + while(temp_n!=NULL) + { + n = temp_n; + temp_n = n->parent; + free(n); + } +} + +//sort the nodes so that the lowest costing is first (node_index == node_num-1) +static void sort_node_list(void) +{ + int i; + int min_h=9999; + int best_node; + NODE * temp_n; + + if(node_num<2) return; + + for(i=0;inum]num]; + } + } + + temp_n = node[best_node]; + + node[best_node] = node[node_num-1]; + node[node_num-1] = temp_n; +} + + +//finds the x,y of the pathnode that is best to walk at if you want to get to goal. +//returns -1 if you can't get to the goal. +int find_best_xy(int start_x,int start_y, int goal_x,int goal_y,int w, int h, int *best_x, int *best_y,int check_player) +{ + int i; + + NODE *n; + + //init... + global_x = start_x; + global_y = start_y; + global_goal_x = goal_x; + global_goal_y = goal_y; + + for(i=0;inum_of_path_nodes;i++) + h_list[i] = 99999; + + //Check if you can walk straight to the goal + if(free_path(start_x, start_y,goal_x,goal_y,w,h,check_player)) + { + *best_x = goal_x; + *best_y = goal_y; + return 1; + } + + //check what nodes you can see and put em in node[] + for(i=0;inum_of_path_nodes;i++) + { + if(check_collision(start_x-240, start_y-240,480,480, map->path_node[i].x,map->path_node[i].y,2,2)) + if(free_path(start_x, start_y,map->path_node[i].x,map->path_node[i].y,w,h,check_player)) + { + new_node(node_num, i, NULL); + node_num++; + } + } + + //if we have no nodes in list exit... + if(node_num==0)return 0; + + //Sort the nodes... + sort_node_list(); + + while(1) + { + //if we have no nodes in list exit... + if(node_num==0)return 0; + + //set active node.. + n = node[node_num-1]; + node_num--; + + //check if you can get from the current node to the goal, if so quit. + if(free_path(map->path_node[n->num].x,map->path_node[n->num].y,goal_x, goal_y,w,h,check_player)) + { + //if the node has any parents then the parent node is the one we want! + if(n->parent==NULL) + { + *best_x = map->path_node[n->num].x; + *best_y = map->path_node[n->num].y; + } + else + { + *best_x = map->path_node[n->parent->num].x; + *best_y = map->path_node[n->parent->num].y; + } + + delete_node(n); + break; + } + + + //check wich nodes that you can get to from the current node. + for(i=0;inum_of_path_nodes;i++) + { + if(i != n->num) + if(check_collision(map->path_node[n->num].x-240, map->path_node[n->num].y-240,480,480, map->path_node[i].x,map->path_node[i].y,2,2)) + if(free_path(map->path_node[n->num].x, map->path_node[n->num].y,map->path_node[i].x,map->path_node[i].y,w,h,check_player)) + { + if(new_node(node_num, i, n)) + node_num++; + } + } + + delete_node(n); + + //Sort the nodes... + sort_node_list(); + + } + + //delete the nodes left + for(i=0;iPower = UNLBBPower; + GameStateRestore = StateRestore; + AddExState(&StateRegs, ~0, 0, 0); +} diff --git a/pool/shard008/C/0129869_clEnqueueCopyBufferToImage.c b/pool/shard008/C/0129869_clEnqueueCopyBufferToImage.c new file mode 100644 index 0000000000000000000000000000000000000000..55a6ab04702051b7552d3b3bc263d07101c67187 --- /dev/null +++ b/pool/shard008/C/0129869_clEnqueueCopyBufferToImage.c @@ -0,0 +1,66 @@ +#include "pocl_cl.h" +#include "pocl_image_util.h" + +extern CL_API_ENTRY cl_int CL_API_CALL +POname(clEnqueueCopyBufferToImage)(cl_command_queue command_queue, + cl_mem buffer, + cl_mem image, + size_t src_offset, + const size_t * dst_origin, /*[3]*/ + const size_t * region, /*[3]*/ + cl_uint num_events_in_wait_list, + const cl_event * event_wait_list, + cl_event * event ) CL_API_SUFFIX__VERSION_1_0 + { + if (region == NULL) + return CL_INVALID_VALUE; + + if (region[2] != 1) //3D image + POCL_ABORT_UNIMPLEMENTED(); + + if (event != NULL) + { + *event = (cl_event)malloc(sizeof(struct _cl_event)); + if (*event == NULL) + return CL_OUT_OF_HOST_MEMORY; + POCL_INIT_OBJECT(*event); + (*event)->queue = command_queue; + POname(clRetainCommandQueue) (command_queue); + (*event)->command_type = CL_COMMAND_COPY_BUFFER_TO_IMAGE; + POCL_UPDATE_EVENT_QUEUED; + POCL_UPDATE_EVENT_RUNNING; + } + + int dev_elem_size = sizeof(cl_float); + int dev_channels = 4; + + int host_elem_size; + int host_channels; + pocl_get_image_information (image, &host_channels, &host_elem_size); + + void* temp = malloc (image->size); + + cl_device_id device_id = command_queue->device; + + device_id->read + (device_id->data, + temp, + image->device_ptrs[device_id->dev_id], + image->size); + + cl_int ret_code = pocl_write_image + (image, + command_queue->device, + dst_origin, + region, + 0, + 0, + temp+src_offset); + + free(temp); + + POCL_UPDATE_EVENT_COMPLETE; + + return ret_code; + } +POsym(clEnqueueCopyBufferToImage) diff --git a/pool/shard008/C/0129884_shell.c b/pool/shard008/C/0129884_shell.c new file mode 100644 index 0000000000000000000000000000000000000000..d5aa921db6370fa9e1957e68921da934722348d2 --- /dev/null +++ b/pool/shard008/C/0129884_shell.c @@ -0,0 +1,44 @@ + +#include +#include + +#undef __FUNCT__ +#define __FUNCT__ "MatMultAdd_ShellPermon" +static PetscErrorCode MatMultAdd_ShellPermon(Mat A,Vec x,Vec y,Vec z) +{ + Mat_Shell *shell = (Mat_Shell*)A->data; + PetscErrorCode ierr; + + PetscFunctionBegin; + if (y == z) { + if (!shell->right_add_work) {ierr = VecDuplicate(z,&shell->right_add_work);CHKERRQ(ierr);} + ierr = MatMult(A,x,shell->right_add_work);CHKERRQ(ierr); + ierr = VecAXPY(shell->right_add_work,1.0,y);CHKERRQ(ierr); + ierr = VecCopy(shell->right_add_work,z);CHKERRQ(ierr); + } else { + ierr = MatMult(A,x,z);CHKERRQ(ierr); + ierr = VecAXPY(z,1.0,y);CHKERRQ(ierr); + } + PetscFunctionReturn(0); +} + +#undef __FUNCT__ +#define __FUNCT__ "MatCreateShellPermon" +PetscErrorCode MatCreateShellPermon(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt M,PetscInt N,void *ctx,Mat *A) +{ + PetscFunctionBegin; + TRY( MatCreateShell(comm,m,n,M,N,ctx,A) ); + TRY( MatShellSetOperation(*A,MATOP_MULT_ADD,(void(*)())MatMultAdd_ShellPermon) ); + PetscFunctionReturn(0); +} + + +#undef __FUNCT__ +#define __FUNCT__ "MatCreateDummy" +PetscErrorCode MatCreateDummy(MPI_Comm comm,PetscInt m,PetscInt n,PetscInt M,PetscInt N,void *ctx,Mat *A) +{ + PetscFunctionBegin; + TRY( MatCreateShell(comm,m,n,M,N,ctx,A) ); + TRY( PetscObjectChangeTypeName((PetscObject)*A,MATDUMMY) ); + PetscFunctionReturn(0); +} diff --git a/pool/shard008/C/0129885_event.c b/pool/shard008/C/0129885_event.c new file mode 100644 index 0000000000000000000000000000000000000000..941a28adc3650a3e11b2f21448747f9d280799c1 --- /dev/null +++ b/pool/shard008/C/0129885_event.c @@ -0,0 +1,186 @@ +/* + * The copyright in this software is being made available under the 2-clauses + * BSD License, included below. This software may be subject to other third + * party and contributor rights, including patent rights, and no such rights + * are granted under this license. + * + * Copyright (c) 2005, Herve Drolon, FreeImage Team + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS `AS IS' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include "opj_includes.h" + +/* ========================================================== +// Utility functions +// ==========================================================*/ + +#ifndef _WIN32 +static char* +i2a(unsigned i, char *a, unsigned r) { + if (i/r > 0) a = i2a(i/r,a,r); + *a = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[i%r]; + return a+1; +} + +/** + Transforms integer i into an ascii string and stores the result in a; + string is encoded in the base indicated by r. + @param i Number to be converted + @param a String result + @param r Base of value; must be in the range 2 - 36 + @return Returns a +*/ +static char * +_itoa(int i, char *a, int r) { + r = ((r < 2) || (r > 36)) ? 10 : r; + if(i < 0) { + *a = '-'; + *i2a(-i, a+1, r) = 0; + } + else *i2a(i, a, r) = 0; + return a; +} + +#endif /* !_WIN32 */ + +/* ----------------------------------------------------------------------- */ + +opj_event_mgr_t* OPJ_CALLCONV opj_set_event_mgr(opj_common_ptr cinfo, opj_event_mgr_t *event_mgr, void *context) { + if(cinfo) { + opj_event_mgr_t *previous = cinfo->event_mgr; + cinfo->event_mgr = event_mgr; + cinfo->client_data = context; + return previous; + } + + return NULL; +} + +bool opj_event_msg(opj_common_ptr cinfo, int event_type, const char *fmt, ...) { +#define MSG_SIZE 512 /* 512 bytes should be more than enough for a short message */ + opj_msg_callback msg_handler = NULL; + + opj_event_mgr_t *event_mgr = cinfo->event_mgr; + if(event_mgr != NULL) { + switch(event_type) { + case EVT_ERROR: + msg_handler = event_mgr->error_handler; + break; + case EVT_WARNING: + msg_handler = event_mgr->warning_handler; + break; + case EVT_INFO: + msg_handler = event_mgr->info_handler; + break; + default: + break; + } + if(msg_handler == NULL) { + return false; + } + } else { + return false; + } + + if ((fmt != NULL) && (event_mgr != NULL)) { + va_list arg; + int str_length, i, j; + char message[MSG_SIZE]; + memset(message, 0, MSG_SIZE); + /* initialize the optional parameter list */ + va_start(arg, fmt); + /* check the length of the format string */ + str_length = (strlen(fmt) > MSG_SIZE) ? MSG_SIZE : strlen(fmt); + /* parse the format string and put the result in 'message' */ + for (i = 0, j = 0; i < str_length; ++i) { + if (fmt[i] == '%') { + if (i + 1 < str_length) { + switch(tolower(fmt[i + 1])) { + case '%' : + message[j++] = '%'; + break; + case 'o' : /* octal numbers */ + { + char tmp[16]; + _itoa(va_arg(arg, int), tmp, 8); + strcat(message, tmp); + j += strlen(tmp); + ++i; + break; + } + case 'i' : /* decimal numbers */ + case 'd' : + { + char tmp[16]; + _itoa(va_arg(arg, int), tmp, 10); + strcat(message, tmp); + j += strlen(tmp); + ++i; + break; + } + case 'x' : /* hexadecimal numbers */ + { + char tmp[16]; + _itoa(va_arg(arg, int), tmp, 16); + strcat(message, tmp); + j += strlen(tmp); + ++i; + break; + } + case 's' : /* strings */ + { + char *tmp = va_arg(arg, char*); + strcat(message, tmp); + j += strlen(tmp); + ++i; + break; + } + case 'f' : /* floats */ + { + char tmp[16]; + double value = va_arg(arg, double); + sprintf(tmp, "%f", value); + strcat(message, tmp); + j += strlen(tmp); + ++i; + break; + } + }; + } else { + message[j++] = fmt[i]; + } + } else { + message[j++] = fmt[i]; + }; + } + /* deinitialize the optional parameter list */ + va_end(arg); + + /* output the message to the user program */ + msg_handler(message, cinfo->client_data); + } + + return true; +} + diff --git a/pool/shard008/C/0129886_dsync-mailbox.c b/pool/shard008/C/0129886_dsync-mailbox.c new file mode 100644 index 0000000000000000000000000000000000000000..e12d54c2640f177eefcba3562b6f79d59872e84b --- /dev/null +++ b/pool/shard008/C/0129886_dsync-mailbox.c @@ -0,0 +1,22 @@ +/* Copyright (c) 2013 Dovecot authors, see the included COPYING file */ + +#include "lib.h" +#include "istream.h" +#include "dsync-mailbox.h" + +void dsync_mailbox_attribute_dup(pool_t pool, + const struct dsync_mailbox_attribute *src, + struct dsync_mailbox_attribute *dest_r) +{ + dest_r->type = src->type; + dest_r->key = p_strdup(pool, src->key); + dest_r->value = p_strdup(pool, src->value); + if (src->value_stream != NULL) { + dest_r->value_stream = src->value_stream; + i_stream_ref(dest_r->value_stream); + } + + dest_r->deleted = src->deleted; + dest_r->last_change = src->last_change; + dest_r->modseq = src->modseq; +} diff --git a/pool/shard008/C/0129888_ext.c b/pool/shard008/C/0129888_ext.c new file mode 100644 index 0000000000000000000000000000000000000000..28d47da3404095fe22457d91ea8894127ad03b24 --- /dev/null +++ b/pool/shard008/C/0129888_ext.c @@ -0,0 +1,163 @@ +/* + * Copyright (c) 2012 Jon Mayo + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ +#include +#include +#include +#include +#include +#include "util.h" +#include "ext.h" +#include "logger.h" +#include "csv.h" + +struct ext_info { + char *content_type; + char *ext_match; + struct ext_info *next; +}; + +static struct ext_info *ext_head; +static char *default_content_type; + +/* finds an entry with the same pattern */ +static struct ext_info *find_entry(const char *match_pattern) +{ + struct ext_info *curr; + + for (curr = ext_head; curr; curr = curr->next) { + if (!strcmp(match_pattern, curr->ext_match)) + return curr; + } + return NULL; +} + +const char *ext_content_type(const char *path) +{ + const char *fn = util_basename(path); + struct ext_info *curr; + + for (curr = ext_head; curr; curr = curr->next) { + if (!fnmatch(curr->ext_match, fn, FNM_PATHNAME | FNM_NOESCAPE)) + return curr->content_type; + } + return default_content_type; /* not found */ +} + +/* create a new entry, or replace an entry that has an identical pattern */ +int ext_register(const char *match, const char *content_type) +{ + struct ext_info *ext; + + ext = find_entry(match); + if (!ext) { + ext = calloc(1, sizeof(*ext)); + if (!ext) { + perror(__func__); + return -1; + } + ext->next = ext_head; + ext_head = ext; + } + free(ext->content_type); + ext->content_type = strdup(content_type); + free(ext->ext_match); + ext->ext_match = strdup(match); + Debug("registered mime type %s (%s)\n", + ext->content_type, ext->ext_match); + return 0; +} + +void ext_default_content_type(const char *content_type) +{ + free(default_content_type); + default_content_type = strdup(content_type); +} + +struct ext_config_info { + char content_type[256]; + char pattern[256]; +}; + +static void on_row_end(void *user_ptr, unsigned row) +{ + struct ext_config_info *info = user_ptr; + + if (row == 0) + return; /* ignore first row */ + ext_register(info->pattern, info->content_type); + memset(&info, 0, sizeof(info)); +} + +static int on_data(void *user_ptr, unsigned row, unsigned col, + size_t len, const char *data) +{ + struct ext_config_info *info = user_ptr; + + assert(info != NULL); + if (row == 0) + return 0; /* ignore first row */ + switch (col) { + case 0: + /* content-type */ + snprintf(info->content_type, sizeof(info->content_type), "%.*s", + (int)len, data); + break; + case 1: + /* pattern */ + snprintf(info->pattern, sizeof(info->pattern), "%.*s", + (int)len, data); + break; + default: + return -1; + } + return 0; +} + +/* read a CSV file */ +int ext_config_load(const char *filename) +{ + FILE *f; + char buf[256]; + size_t len; + struct csv csv; + struct ext_config_info info; + + memset(&info, 0, sizeof(info)); + f = fopen(filename, "rb"); + if (!f) { + perror(filename); + return -1; + } + csv_init(&csv, &info, on_data, on_row_end); + do { + len = fread(buf, 1, sizeof(buf), f); + if (!len && ferror(f)) { + perror(filename); + return -1; + } + if (csv_push(&csv, len, buf)) + goto failure; + } while (!feof(f)); + + if (csv_eol(&csv)) + goto failure; + + fclose(f); + return 0; +failure: + fclose(f); + return -1; +} diff --git a/pool/shard008/C/0129890_test_uart_console.c b/pool/shard008/C/0129890_test_uart_console.c new file mode 100644 index 0000000000000000000000000000000000000000..dc1f59c57dbefce6997aa6bb4d93753905614dc5 --- /dev/null +++ b/pool/shard008/C/0129890_test_uart_console.c @@ -0,0 +1,141 @@ +/**************************************************************************** + * px4/sensors/test_uart_console.c + * + * Copyright (C) 2012 Lorenz Meier. All rights reserved. + * Authors: Lorenz Meier + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include +#include + +#include + +#include +#include +#include +#include +#include + +#include + +#include "tests.h" + +#include +#include +#include + +static void *receive_loop(void *arg) +{ + int uart_usb = open("/dev/ttyACM0", O_RDONLY | O_NOCTTY); + + while (1) { + char c; + read(uart_usb, &c, 1); + printf("%c", c); + fflush(stdout); + } + + return NULL; +} + +int test_uart_console(int argc, char *argv[]) +{ + /* assuming NuttShell is on UART1 (/dev/ttyS0) */ + // + int uart_usb = open("/dev/ttyACM0", O_WRONLY | O_NOCTTY); + + if (uart_usb < 0) { + printf("ERROR opening /dev/ttyACM0. Do you need to run sercon first? Aborting..\n"); + return uart_usb; + } + + uint8_t sample_uart_usb[] = {'S', 'A', 'M', 'P', 'L', 'E', ' ', '\n'}; + + pthread_t receive_thread; + + pthread_create(&receive_thread, NULL, receive_loop, NULL); + + //wait for threads to complete: + pthread_join(receive_thread, NULL); + + for (int i = 0; i < 30; i++) { + write(uart_usb, sample_uart_usb, sizeof(sample_uart_usb)); + printf("."); + fflush(stdout); + sleep(1); + } + +// uint64_t start_time = hrt_absolute_time(); +// +//// while (true) +// for (int i = 0; i < 1000; i++) +// { +// //write(uart_usb, sample_uart_usb, sizeof(sample_uart_usb)); +// int nread = 0; +// char c; +// do { +// nread = read(uart_usb, &c, 1); +// if (nread > 0) +// { +// printf("%c", c); +// } +// } while (nread > 0); +// +// do { +// nread = read(uart_console, &c, 1); +// if (nread > 0) +// { +// if (c == 0x03) +// { +// close(uart_usb); +// close(uart_console); +// exit(OK); +// } +// else +// { +// write(uart_usb, &c, 1); +// } +// } +// } while (nread > 0); +// usleep(10000); +// } +// +// int interval = hrt_absolute_time() - start_time; + + close(uart_usb); +// close(uart_console); + + return 0; +} diff --git a/pool/shard008/C/0129892_mcu_library.c b/pool/shard008/C/0129892_mcu_library.c new file mode 100644 index 0000000000000000000000000000000000000000..0d2a332d127f46ff8ae05d381fc388e072c24293 --- /dev/null +++ b/pool/shard008/C/0129892_mcu_library.c @@ -0,0 +1,204 @@ +/* +When you connect the camera to the serial2 you need to deactivate the Linux Console, +you can achieve that using this commands: + +systemctl stop serial-getty@ttyMFD2.service +dmesg -n 1 + +After you did that you can use the serial2 normally +You will also have to connect the GPIO48(mraa33) to the enable and use a 500Ohm resistor +as a pulldown +*/ +#include "mcu_api.h" +#include "mcu_errno.h" +#include +#include +#include +#include + +int x = 0; +unsigned char reset_camera[4] = {0x56, 0x00, 0x26, 0x00}; +unsigned char resolution[9] = {0x56, 0x00, 0x31, 0x05 , 0x04, 0x01, 0x00, 0x19, 0x11}; //Low Res 0x22, High Res 0x00, Medium Res 0x11 +unsigned char take_photo[5] = {0x56, 0x00, 0x36, 0x01, 0x00}; +unsigned char photo_size[5] = {0x56, 0x00, 0x34, 0x01, 0x00}; +unsigned char stop_camera[5] = {0x56, 0x00, 0x36, 0x01, 0x03}; + +unsigned char buf[12] = {0x00}; +unsigned char flush[8] = {0xFF}; +unsigned char photo_buffer[15000] = {0x00}; + +void flush_camera() +{ + while(!(flush[0]== 0x00 && flush[1]== 0x00 && flush[2]== 0x00 && flush[3]== 0x00 && flush[4]== 0x00 && flush[5]== 0x00 && flush[6]== 0x00 && flush[7]== 0x00)) + { + uart_read(2,flush+0, 1); + uart_read(2,flush+1, 1); + uart_read(2,flush+2, 1); + uart_read(2,flush+3, 1); + uart_read(2,flush+4, 1); + uart_read(2,flush+5, 1); + uart_read(2,flush+6, 1); + uart_read(2,flush+7, 1); + //debug_print(DBG_INFO, "Flush %x_%x_%x_%x_%x_%x_%x_%x\n",flush[0],flush[1],flush[2],flush[3],flush[4],flush[5],flush[6],flush[7]); + } +} +void mcu_main() +{ + //This pin will be used as EOE (Level Shifter Enable) + gpio_setup(33, 1); /* set GPIO48 (mraa33) as output */ + gpio_write(33, 0); /* Write 0 to GPIO48 (mraa33) */ + /* + Execute this commands on the ATOM before "before2" is printed on the terminal + + stty -F /dev/ttyMFD1 38400 + systemctl stop serial-getty@ttyMFD2.service + dmesg -n 1 + cat /dev/ttymcu1 + + */ + + + debug_print(DBG_INFO, "Before1\n"); + mcu_sleep(3050); + debug_print(DBG_INFO, "Before2\n"); + + gpio_write(33, 1);/* Write 1 to GPIO48 (mraa33) */ + uart_setup(2, 38400); + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //RESOLUTION + buf[0]=0x00; + while(!(buf[0]==0x76 && buf[2]==0x31)) + { + debug_print(DBG_INFO, "==================================\n"); + x = uart_write(2, resolution, 9); + x = uart_read(2,buf+0, 1); + x = uart_read(2,buf+1, 1); + x = uart_read(2,buf+2, 1); + x = uart_read(2,buf+3, 1); + x = uart_read(2,buf+4, 1); + debug_print(DBG_INFO, "After RESOLUTION: %x_%x\n", buf[0], buf[2]); + flush_camera(); + mcu_sleep(50); + } + + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //RESET + buf[0]=0x00; + while(!(buf[0]==0x76 && buf[2]==0x26)) + { + debug_print(DBG_INFO, "==================================\n"); + x = uart_write(2, reset_camera, 4); + x = uart_read(2,buf+0, 1); + x = uart_read(2,buf+1, 1); + x = uart_read(2,buf+2, 1); + x = uart_read(2,buf+3, 1); + debug_print(DBG_INFO, "After RESET: %x_%x\n", buf[0], buf[2]); + flush_camera(); + mcu_sleep(50); + } + mcu_sleep(250); + + + while(1) + { + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //TAKE_Photo + buf[0]=0x00; + while(!(buf[0]==0x76 && buf[2]==0x36)) + { + + x = uart_write(2, take_photo, 5);// + x = uart_read(2,buf+0, 1); + x = uart_read(2,buf+1, 1); + x = uart_read(2,buf+2, 1); + x = uart_read(2,buf+3, 1); + //debug_print(DBG_INFO, "==================================\n"); + //debug_print(DBG_INFO, "After TAKE Photo: %x_%x\n", buf[0], buf[2]); + flush_camera(); + //mcu_sleep(5); + } + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //READ_Size + buf[0]=0x00; + while(!(buf[0]==0x76 && buf[2]==0x34)) + { + x = uart_write(2, photo_size, 5); + x = uart_read(2,buf+0, 1); + x = uart_read(2,buf+1, 1); + x = uart_read(2,buf+2, 1); + x = uart_read(2,buf+3, 1); + x = uart_read(2,buf+4, 1); + x = uart_read(2,buf+5, 1); + x = uart_read(2,buf+6, 1); + x = uart_read(2,buf+7, 1); + x = uart_read(2,buf+8, 1); + //debug_print(DBG_INFO, "==================================\n"); + //debug_print(DBG_INFO, "After Read READ Size: %x_%x %x_%x\n", buf[0], buf[2], buf[7], buf[8]); + flush_camera(); + //mcu_sleep(5); + } + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + //READ_Photo + int fsizeH = (buf[7]<<8) + (buf[8]); + int total_read = fsizeH; + + //You have to ask for an 8 multiple size value + while( (total_read%8)!=0) + total_read+=2; + + int aloc=0; + unsigned char MH = 0x00; + unsigned char ML = 0x00; + unsigned char KH = (unsigned int)(total_read>>8); + unsigned char KL = (unsigned int)(total_read & 0xff); + /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + unsigned char jpeg[16] = {0x56, 0x00, 0x32, 0x0C, 0x00, 0x0A, 0x00, 0x00, MH, ML, 0x00, 0x00, KH, KL, 00, 00}; + uart_write(2, jpeg, 16); + + //Sync Bytes are 0x76 0x00 0x32 0x00 0x00 + uart_read(2,buf+0, 1); + uart_read(2,buf+1, 1); + uart_read(2,buf+2, 1); + uart_read(2,buf+3, 1); + uart_read(2,buf+4, 1); + + //Read the Total_read value but only the fsizeH characters correspond to the foto + while(aloc +#include + +int main() +{ + int i; + + i = 1; + + printf("Início\n"); + + while ( i <= 10 ) + { + int q = (int) pow( (double)i, 2.0 ); + int c = (int) pow( (double)i, 3.0 ); + + printf( "%4i", i ); + printf( " %4i", q ); + printf( " %4i", c ); + printf( "\n" ); + i = i + 1; + } + + printf("Fim\n"); + + return 0; +} diff --git a/pool/shard008/C/0129896_main.c b/pool/shard008/C/0129896_main.c new file mode 100644 index 0000000000000000000000000000000000000000..33ce34b09de1448aec2d587b6cc6f23b29a1a72b --- /dev/null +++ b/pool/shard008/C/0129896_main.c @@ -0,0 +1,48 @@ +/** + * @file main.c + * @copyright VCA Technology + * @~english + * @brief Implementation of @c main + */ + +#include +#include +#include +#include +#include "check_unit_test.h" +#include "unit_test.h" + +int main(const int argc, const char * const * const argv) { + // Determine what tests to run + const char * suite = NULL; + const char * const suite_arg = "--suite="; + const size_t suite_arg_size = strlen(suite_arg); + const char * test_case = NULL; + const char * const test_case_arg = "--test-case="; + const size_t test_case_arg_size = strlen(test_case_arg); + for (int i = 1; i < argc; ++i) { + if (0 == strncmp(suite_arg, argv[i], suite_arg_size) && (strlen(argv[i]) > suite_arg_size)) { + suite = &argv[i][suite_arg_size]; + } else if (0 == strncmp(test_case_arg, argv[i], test_case_arg_size) && (strlen(argv[i]) > test_case_arg_size)) { + test_case = &argv[i][test_case_arg_size]; + } else if (0 == strcmp("--help", argv[i])) { + printf("Usage: %s [options]\n" + " --suite=Suite Determines the suite to run\n" + " --test-case='Test Case' Determines the test case to run\n", + argv[0]); + exit(EXIT_SUCCESS); + } else { + fprintf(stderr, "Invalid argument: %s\n", argv[i]); + exit(EXIT_FAILURE); + } + } + + // Run up the tests + SRunner * const srunner = srunner_create(make_utility_suite()); +// srunner_add_suite(srunner, make_xyz_suite()); + srunner_run(srunner, suite, test_case, CK_NORMAL); + const int number_run = srunner_ntests_run(srunner); + const int number_failed = srunner_ntests_failed(srunner); + srunner_free(srunner); + return (number_failed == 0) && (number_run != 0) ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/pool/shard008/C/0129898_pmp.c b/pool/shard008/C/0129898_pmp.c new file mode 100644 index 0000000000000000000000000000000000000000..195a5757b623a6ceadc8d7d5e862a410c73fe6e1 --- /dev/null +++ b/pool/shard008/C/0129898_pmp.c @@ -0,0 +1,198 @@ +// See LICENSE for license details. + +// Test of PMP functionality. + +#include +#include +#include +#include "util.h" + +volatile int trap_expected; + +#define INLINE inline __attribute__((always_inline)) + +uintptr_t handle_trap(uintptr_t cause, uintptr_t epc, uintptr_t regs[32]) +{ + if (cause == CAUSE_ILLEGAL_INSTRUCTION) + exit(0); // no PMP support + + if (!trap_expected || cause != CAUSE_LOAD_ACCESS) + exit(1); + trap_expected = 0; + return epc + insn_len(epc); +} + +#define SCRATCH RISCV_PGSIZE +uintptr_t scratch[RISCV_PGSIZE / sizeof(uintptr_t)] __attribute__((aligned(RISCV_PGSIZE))); +uintptr_t l1pt[RISCV_PGSIZE / sizeof(uintptr_t)] __attribute__((aligned(RISCV_PGSIZE))); +uintptr_t l2pt[RISCV_PGSIZE / sizeof(uintptr_t)] __attribute__((aligned(RISCV_PGSIZE))); +#if __riscv_xlen == 64 +uintptr_t l3pt[RISCV_PGSIZE / sizeof(uintptr_t)] __attribute__((aligned(RISCV_PGSIZE))); +#else +#define l3pt l2pt +#endif + +static void init_pt() +{ + l1pt[0] = ((uintptr_t)l2pt >> RISCV_PGSHIFT << PTE_PPN_SHIFT) | PTE_V; + l3pt[SCRATCH / RISCV_PGSIZE] = ((uintptr_t)scratch >> RISCV_PGSHIFT << PTE_PPN_SHIFT) | PTE_A | PTE_D | PTE_V | PTE_R | PTE_W; +#if __riscv_xlen == 64 + l2pt[0] = ((uintptr_t)l3pt >> RISCV_PGSHIFT << PTE_PPN_SHIFT) | PTE_V; + uintptr_t vm_choice = SATP_MODE_SV39; +#else + uintptr_t vm_choice = SATP_MODE_SV32; +#endif + write_csr(sptbr, ((uintptr_t)l1pt >> RISCV_PGSHIFT) | + (vm_choice * (SATP_MODE & ~(SATP_MODE<<1)))); + write_csr(pmpcfg0, (PMP_NAPOT | PMP_R) << 16); + write_csr(pmpaddr2, -1); +} + +INLINE uintptr_t va2pa(uintptr_t va) +{ + if (va < SCRATCH || va >= SCRATCH + RISCV_PGSIZE) + exit(3); + return va - SCRATCH + (uintptr_t)scratch; +} + +#define GRANULE (1UL << PMP_SHIFT) + +typedef struct { + uintptr_t cfg; + uintptr_t a0; + uintptr_t a1; +} pmpcfg_t; + +INLINE int pmp_ok(pmpcfg_t p, uintptr_t addr, uintptr_t size) +{ + if ((p.cfg & PMP_A) == 0) + return 1; + + if ((p.cfg & PMP_A) != PMP_TOR) { + uintptr_t range = 1; + + if ((p.cfg & PMP_A) == PMP_NAPOT) { + range <<= 1; + for (uintptr_t i = 1; i; i <<= 1) { + if ((p.a1 & i) == 0) + break; + p.a1 &= ~i; + range <<= 1; + } + } + + p.a0 = p.a1; + p.a1 = p.a0 + range; + } + + p.a0 *= GRANULE; + p.a1 *= GRANULE; + addr = va2pa(addr); + + uintptr_t hits = 0; + for (uintptr_t i = 0; i < size; i += GRANULE) { + if (p.a0 <= addr + i && addr + i < p.a1) + hits += GRANULE; + } + + return hits == 0 || hits >= size; +} + +INLINE void test_one(uintptr_t addr, uintptr_t size) +{ + uintptr_t new_mstatus = (read_csr(mstatus) & ~MSTATUS_MPP) | (MSTATUS_MPP & (MSTATUS_MPP >> 1)) | MSTATUS_MPRV; + switch (size) { + case 1: asm volatile ("csrrw %0, mstatus, %0; lb x0, (%1); csrw mstatus, %0" : "+&r" (new_mstatus) : "r" (addr)); break; + case 2: asm volatile ("csrrw %0, mstatus, %0; lh x0, (%1); csrw mstatus, %0" : "+&r" (new_mstatus) : "r" (addr)); break; + case 4: asm volatile ("csrrw %0, mstatus, %0; lw x0, (%1); csrw mstatus, %0" : "+&r" (new_mstatus) : "r" (addr)); break; +#if __riscv_xlen >= 64 + case 8: asm volatile ("csrrw %0, mstatus, %0; ld x0, (%1); csrw mstatus, %0" : "+&r" (new_mstatus) : "r" (addr)); break; +#endif + default: __builtin_unreachable(); + } +} + +INLINE void test_all_sizes(pmpcfg_t p, uintptr_t addr) +{ + for (size_t size = 1; size <= sizeof(uintptr_t); size *= 2) { + if (addr & (size - 1)) + continue; + trap_expected = !pmp_ok(p, addr, size); + test_one(addr, size); + if (trap_expected) + exit(2); + } +} + +INLINE void test_range_once(pmpcfg_t p, uintptr_t base, uintptr_t range) +{ + for (uintptr_t addr = base; addr < base + range; addr += GRANULE) + test_all_sizes(p, addr); +} + +INLINE pmpcfg_t set_pmp(pmpcfg_t p) +{ + uintptr_t cfg0 = read_csr(pmpcfg0); + write_csr(pmpcfg0, cfg0 & ~0xff00); + write_csr(pmpaddr0, p.a0); + write_csr(pmpaddr1, p.a1); + write_csr(pmpcfg0, ((p.cfg << 8) & 0xff00) | (cfg0 & ~0xff00)); + asm volatile ("sfence.vma" ::: "memory"); + return p; +} + +INLINE pmpcfg_t set_pmp_range(uintptr_t base, uintptr_t range) +{ + pmpcfg_t p; + p.cfg = PMP_TOR | PMP_R; + p.a0 = base >> PMP_SHIFT; + p.a1 = (base + range) >> PMP_SHIFT; + return set_pmp(p); +} + +INLINE pmpcfg_t set_pmp_napot(uintptr_t base, uintptr_t range) +{ + pmpcfg_t p; + p.cfg = PMP_R | (range > GRANULE ? PMP_NAPOT : PMP_NA4); + p.a0 = 0; + p.a1 = (base + (range/2 - 1)) >> PMP_SHIFT; + return set_pmp(p); +} + +static void test_range(uintptr_t addr, uintptr_t range) +{ + pmpcfg_t p = set_pmp_range(va2pa(addr), range); + test_range_once(p, addr, range); + + if ((range & (range - 1)) == 0 && (addr & (range - 1)) == 0) { + p = set_pmp_napot(va2pa(addr), range); + test_range_once(p, addr, range); + } +} + +static void test_ranges(uintptr_t addr, uintptr_t size) +{ + for (uintptr_t range = GRANULE; range <= size; range += GRANULE) + test_range(addr, range); +} + +static void exhaustive_test(uintptr_t addr, uintptr_t size) +{ + for (uintptr_t base = addr; base < addr + size; base += GRANULE) + test_ranges(base, size - (base - addr)); +} + +int main() +{ + init_pt(); + + const int max_exhaustive = 32; + exhaustive_test(SCRATCH, max_exhaustive); + exhaustive_test(SCRATCH + RISCV_PGSIZE - max_exhaustive, max_exhaustive); + + test_range(SCRATCH, RISCV_PGSIZE); + test_range(SCRATCH, RISCV_PGSIZE / 2); + test_range(SCRATCH + RISCV_PGSIZE / 2, RISCV_PGSIZE / 2); + + return 0; +} diff --git a/pool/shard008/C/0129901_signal.c b/pool/shard008/C/0129901_signal.c new file mode 100644 index 0000000000000000000000000000000000000000..9b1b7c039ddf9c33ecf569c55b055b34de384ee3 --- /dev/null +++ b/pool/shard008/C/0129901_signal.c @@ -0,0 +1,262 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include +#include +#include +#include + +#include +#include +#include + +#include + +#ifdef CONFIG_CPU_HAS_FPU +#include +static int restore_fpu_state(struct sigcontext __user *sc) +{ + int err = 0; + struct user_fp user_fp; + + err = __copy_from_user(&user_fp, &sc->sc_user_fp, sizeof(user_fp)); + + restore_from_user_fp(&user_fp); + + return err; +} + +static int save_fpu_state(struct sigcontext __user *sc) +{ + struct user_fp user_fp; + + save_to_user_fp(&user_fp); + + return __copy_to_user(&sc->sc_user_fp, &user_fp, sizeof(user_fp)); +} +#else +#define restore_fpu_state(sigcontext) (0) +#define save_fpu_state(sigcontext) (0) +#endif + +struct rt_sigframe { + /* + * pad[3] is compatible with the same struct defined in + * gcc/libgcc/config/csky/linux-unwind.h + */ + int pad[3]; + struct siginfo info; + struct ucontext uc; +}; + +static long restore_sigcontext(struct pt_regs *regs, + struct sigcontext __user *sc) +{ + int err = 0; + + /* sc_pt_regs is structured the same as the start of pt_regs */ + err |= __copy_from_user(regs, &sc->sc_pt_regs, sizeof(struct pt_regs)); + + /* Restore the floating-point state. */ + err |= restore_fpu_state(sc); + + return err; +} + +SYSCALL_DEFINE0(rt_sigreturn) +{ + struct pt_regs *regs = current_pt_regs(); + struct rt_sigframe __user *frame; + sigset_t set; + + /* Always make any pending restarted system calls return -EINTR */ + current->restart_block.fn = do_no_restart_syscall; + + frame = (struct rt_sigframe __user *)regs->usp; + + if (!access_ok(frame, sizeof(*frame))) + goto badframe; + + if (__copy_from_user(&set, &frame->uc.uc_sigmask, sizeof(set))) + goto badframe; + + set_current_blocked(&set); + + if (restore_sigcontext(regs, &frame->uc.uc_mcontext)) + goto badframe; + + if (restore_altstack(&frame->uc.uc_stack)) + goto badframe; + + return regs->a0; + +badframe: + force_sig(SIGSEGV); + return 0; +} + +static int setup_sigcontext(struct rt_sigframe __user *frame, + struct pt_regs *regs) +{ + struct sigcontext __user *sc = &frame->uc.uc_mcontext; + int err = 0; + + err |= __copy_to_user(&sc->sc_pt_regs, regs, sizeof(struct pt_regs)); + err |= save_fpu_state(sc); + + return err; +} + +static inline void __user *get_sigframe(struct ksignal *ksig, + struct pt_regs *regs, size_t framesize) +{ + unsigned long sp; + /* Default to using normal stack */ + sp = regs->usp; + + /* + * If we are on the alternate signal stack and would overflow it, don't. + * Return an always-bogus address instead so we will die with SIGSEGV. + */ + if (on_sig_stack(sp) && !likely(on_sig_stack(sp - framesize))) + return (void __user __force *)(-1UL); + + /* This is the X/Open sanctioned signal stack switching. */ + sp = sigsp(sp, ksig) - framesize; + + /* Align the stack frame. */ + sp &= -8UL; + + return (void __user *)sp; +} + +static int +setup_rt_frame(struct ksignal *ksig, sigset_t *set, struct pt_regs *regs) +{ + struct rt_sigframe *frame; + int err = 0; + struct csky_vdso *vdso = current->mm->context.vdso; + + frame = get_sigframe(ksig, regs, sizeof(*frame)); + if (!access_ok(frame, sizeof(*frame))) + return -EFAULT; + + err |= copy_siginfo_to_user(&frame->info, &ksig->info); + + /* Create the ucontext. */ + err |= __put_user(0, &frame->uc.uc_flags); + err |= __put_user(NULL, &frame->uc.uc_link); + err |= __save_altstack(&frame->uc.uc_stack, regs->usp); + err |= setup_sigcontext(frame, regs); + err |= __copy_to_user(&frame->uc.uc_sigmask, set, sizeof(*set)); + if (err) + return -EFAULT; + + /* Set up to return from userspace. */ + regs->lr = (unsigned long)(vdso->rt_signal_retcode); + + /* + * Set up registers for signal handler. + * Registers that we don't modify keep the value they had from + * user-space at the time we took the signal. + * We always pass siginfo and mcontext, regardless of SA_SIGINFO, + * since some things rely on this (e.g. glibc's debug/segfault.c). + */ + regs->pc = (unsigned long)ksig->ka.sa.sa_handler; + regs->usp = (unsigned long)frame; + regs->a0 = ksig->sig; /* a0: signal number */ + regs->a1 = (unsigned long)(&(frame->info)); /* a1: siginfo pointer */ + regs->a2 = (unsigned long)(&(frame->uc)); /* a2: ucontext pointer */ + + return 0; +} + +static void handle_signal(struct ksignal *ksig, struct pt_regs *regs) +{ + sigset_t *oldset = sigmask_to_save(); + int ret; + + /* Are we from a system call? */ + if (in_syscall(regs)) { + /* Avoid additional syscall restarting via ret_from_exception */ + forget_syscall(regs); + + /* If so, check system call restarting.. */ + switch (regs->a0) { + case -ERESTART_RESTARTBLOCK: + case -ERESTARTNOHAND: + regs->a0 = -EINTR; + break; + + case -ERESTARTSYS: + if (!(ksig->ka.sa.sa_flags & SA_RESTART)) { + regs->a0 = -EINTR; + break; + } + /* fallthrough */ + case -ERESTARTNOINTR: + regs->a0 = regs->orig_a0; + regs->pc -= TRAP0_SIZE; + break; + } + } + + /* Set up the stack frame */ + ret = setup_rt_frame(ksig, oldset, regs); + + signal_setup_done(ret, ksig, 0); +} + +static void do_signal(struct pt_regs *regs) +{ + struct ksignal ksig; + + if (get_signal(&ksig)) { + /* Actually deliver the signal */ + handle_signal(&ksig, regs); + return; + } + + /* Did we come from a system call? */ + if (in_syscall(regs)) { + /* Avoid additional syscall restarting via ret_from_exception */ + forget_syscall(regs); + + /* Restart the system call - no handlers present */ + switch (regs->a0) { + case -ERESTARTNOHAND: + case -ERESTARTSYS: + case -ERESTARTNOINTR: + regs->a0 = regs->orig_a0; + regs->pc -= TRAP0_SIZE; + break; + case -ERESTART_RESTARTBLOCK: + regs->a0 = regs->orig_a0; + regs_syscallid(regs) = __NR_restart_syscall; + regs->pc -= TRAP0_SIZE; + break; + } + } + + /* + * If there is no signal to deliver, we just put the saved + * sigmask back. + */ + restore_saved_sigmask(); +} + +/* + * notification of userspace execution resumption + * - triggered by the _TIF_WORK_MASK flags + */ +asmlinkage void do_notify_resume(struct pt_regs *regs, + unsigned long thread_info_flags) +{ + /* Handle pending signal delivery */ + if (thread_info_flags & _TIF_SIGPENDING) + do_signal(regs); + + if (thread_info_flags & _TIF_NOTIFY_RESUME) { + clear_thread_flag(TIF_NOTIFY_RESUME); + tracehook_notify_resume(regs); + } +} diff --git a/pool/shard008/C/0129910_memleak_arm64.c b/pool/shard008/C/0129910_memleak_arm64.c new file mode 100644 index 0000000000000000000000000000000000000000..1ce62771f5e66e68d48ea3ccced25c3742257bc5 --- /dev/null +++ b/pool/shard008/C/0129910_memleak_arm64.c @@ -0,0 +1,120 @@ +/* Unicorn Emulator Engine */ +/* By Nguyen Anh Quynh, 2015 */ + +/* Sample code to demonstrate how to emulate ARM64 code */ + +// windows specific +#ifdef _MSC_VER +#include +#include +#define PRIx64 "llX" +#ifdef DYNLOAD +#include "unicorn_dynload.h" +#else // DYNLOAD +#include +#ifdef _WIN64 +#pragma comment(lib, "unicorn_staload64.lib") +#else // _WIN64 +#pragma comment(lib, "unicorn_staload.lib") +#endif // _WIN64 +#endif // DYNLOAD + +// posix specific +#else // _MSC_VER +#include +#endif // _MSC_VER + + +// code to be emulated +#define ARM_CODE "\xab\x01\x0f\x8b" // add x11, x13, x15 + +// memory address where emulation starts +#define ADDRESS 0x10000 + +static void hook_block(uc_engine *uc, uint64_t address, uint32_t size, void *user_data) +{ + printf(">>> Tracing basic block at 0x%"PRIx64 ", block size = 0x%x\n", address, size); +} + +static void hook_code(uc_engine *uc, uint64_t address, uint32_t size, void *user_data) +{ + printf(">>> Tracing instruction at 0x%"PRIx64 ", instruction size = 0x%x\n", address, size); +} + +static void test_arm64(void) +{ + uc_engine *uc; + uc_err err; + uc_hook trace1, trace2; + + int64_t x11 = 0x1234; // X11 register + int64_t x13 = 0x6789; // X13 register + int64_t x15 = 0x3333; // X15 register + + printf("Emulate ARM64 code\n"); + + // Initialize emulator in ARM mode + err = uc_open(UC_ARCH_ARM64, UC_MODE_ARM, &uc); + if (err) { + printf("Failed on uc_open() with error returned: %u (%s)\n", + err, uc_strerror(err)); + return; + } + + // map 2MB memory for this emulation + uc_mem_map(uc, ADDRESS, 2 * 1024 * 1024, UC_PROT_ALL); + + // write machine code to be emulated to memory + uc_mem_write(uc, ADDRESS, ARM_CODE, sizeof(ARM_CODE) - 1); + + // initialize machine registers + uc_reg_write(uc, UC_ARM64_REG_X11, &x11); + uc_reg_write(uc, UC_ARM64_REG_X13, &x13); + uc_reg_write(uc, UC_ARM64_REG_X15, &x15); + + // tracing all basic blocks with customized callback + uc_hook_add(uc, &trace1, UC_HOOK_BLOCK, hook_block, NULL, (uint64_t)1, (uint64_t)0); + + // tracing one instruction at ADDRESS with customized callback + uc_hook_add(uc, &trace2, UC_HOOK_CODE, hook_code, NULL, (uint64_t)ADDRESS, (uint64_t)ADDRESS); + + // emulate machine code in infinite time (last param = 0), or when + // finishing all the code. + err = uc_emu_start(uc, ADDRESS, ADDRESS + sizeof(ARM_CODE) -1, 0, 0); + if (err) { + printf("Failed on uc_emu_start() with error returned: %u\n", err); + } + + // now print out some registers + printf(">>> Emulation done. Below is the CPU context\n"); + + uc_reg_read(uc, UC_ARM64_REG_X11, &x11); + printf(">>> X11 = 0x%" PRIx64 "\n", x11); + + uc_close(uc); +} + +int main(int argc, char **argv, char **envp) +{ + // dynamically load shared library +#ifdef DYNLOAD + if (!uc_dyn_load(NULL, 0)) { + printf("Error dynamically loading shared library.\n"); + printf("Please check that unicorn.dll/unicorn.so is available as well as\n"); + printf("any other dependent dll/so files.\n"); + printf("The easiest way is to place them in the same directory as this app.\n"); + return 1; + } +#endif + + while(1) { + test_arm64(); + } + + // dynamically free shared library +#ifdef DYNLOAD + uc_dyn_free(); +#endif + + return 0; +} diff --git a/pool/shard008/C/0129912_stage_cache.c b/pool/shard008/C/0129912_stage_cache.c new file mode 100644 index 0000000000000000000000000000000000000000..28503aad3fc6e0ee4e6e191a571f35fae61dce27 --- /dev/null +++ b/pool/shard008/C/0129912_stage_cache.c @@ -0,0 +1,38 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2014 Google Inc. + * Copyright (C) 2015 Intel Corporation. + * + * 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; version 2 of the License. + * + * 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 St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include +#include + +struct ramstage_cache *ramstage_cache_location(long *size) +{ + /* + * The ramstage cache lives in the TSEG region. + * The top of ram is defined to be the TSEG base address. + */ + u32 offset = smm_region_size(); + offset -= CONFIG_IED_REGION_SIZE; + offset -= CONFIG_SMM_RESERVED_SIZE; + + *size = CONFIG_SMM_RESERVED_SIZE; + return (void *)(((u8 *)cbmem_top()) + offset); +} diff --git a/pool/shard008/C/0129915_eog-image-save-info.c b/pool/shard008/C/0129915_eog-image-save-info.c new file mode 100644 index 0000000000000000000000000000000000000000..e76105f5a4ce83db14eac6032cdcf502014a3705 --- /dev/null +++ b/pool/shard008/C/0129915_eog-image-save-info.c @@ -0,0 +1,147 @@ +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include "eog-image-save-info.h" +#include "eog-image-private.h" +#include "eog-pixbuf-util.h" +#include "eog-image.h" + +G_DEFINE_TYPE (EogImageSaveInfo, eog_image_save_info, G_TYPE_OBJECT) + +static void +eog_image_save_info_dispose (GObject *object) +{ + EogImageSaveInfo *info = EOG_IMAGE_SAVE_INFO (object); + + if (info->file != NULL) { + g_object_unref (info->file); + info->file = NULL; + } + + if (info->format != NULL) { + g_free (info->format); + info->format = NULL; + } + + G_OBJECT_CLASS (eog_image_save_info_parent_class)->dispose (object); +} + +static void +eog_image_save_info_init (EogImageSaveInfo *obj) +{ + +} + +static void +eog_image_save_info_class_init (EogImageSaveInfoClass *klass) +{ + GObjectClass *object_class = (GObjectClass*) klass; + + object_class->dispose = eog_image_save_info_dispose; +} + +/* is_local_uri: + * + * Checks if the URI points to a local file system. This tests simply + * if the URI scheme is 'file'. This function is used to ensure that + * we can write to the path-part of the URI with non-VFS aware + * filesystem calls. + */ +static gboolean +is_local_file (GFile *file) +{ + char *scheme; + gboolean ret; + + g_return_val_if_fail (file != NULL, FALSE); + + scheme = g_file_get_uri_scheme (file); + + ret = (g_ascii_strcasecmp (scheme, "file") == 0); + g_free (scheme); + return ret; +} + +static char* +get_save_file_type_by_file (GFile *file) +{ + GdkPixbufFormat *format; + char *type = NULL; + + format = eog_pixbuf_get_format (file); + if (format != NULL) { + type = gdk_pixbuf_format_get_name (format); + } + + return type; +} + +EogImageSaveInfo* +eog_image_save_info_new_from_image (EogImage *image) +{ + EogImageSaveInfo *info = NULL; + + g_return_val_if_fail (EOG_IS_IMAGE (image), NULL); + + info = g_object_new (EOG_TYPE_IMAGE_SAVE_INFO, NULL); + + info->file = eog_image_get_file (image); + info->format = g_strdup (image->priv->file_type); + info->exists = g_file_query_exists (info->file, NULL); + info->local = is_local_file (info->file); + info->has_metadata = eog_image_has_data (image, EOG_IMAGE_DATA_EXIF); + info->modified = eog_image_is_modified (image); + info->overwrite = FALSE; + + info->jpeg_quality = -1.0; + + return info; +} + +EogImageSaveInfo* +eog_image_save_info_new_from_uri (const char *txt_uri, GdkPixbufFormat *format) +{ + GFile *file; + EogImageSaveInfo *info; + + g_return_val_if_fail (txt_uri != NULL, NULL); + + file = g_file_new_for_uri (txt_uri); + + info = eog_image_save_info_new_from_file (file, format); + + g_object_unref (file); + + return info; +} + +EogImageSaveInfo* +eog_image_save_info_new_from_file (GFile *file, GdkPixbufFormat *format) +{ + EogImageSaveInfo *info; + + g_return_val_if_fail (file != NULL, NULL); + + info = g_object_new (EOG_TYPE_IMAGE_SAVE_INFO, NULL); + + info->file = g_object_ref (file); + if (format == NULL) { + info->format = get_save_file_type_by_file (info->file); + } + else { + info->format = gdk_pixbuf_format_get_name (format); + } + info->exists = g_file_query_exists (file, NULL); + info->local = is_local_file (file); + info->has_metadata = FALSE; + info->modified = FALSE; + info->overwrite = FALSE; + + info->jpeg_quality = -1.0; + + g_assert (info->format != NULL); + + return info; +} diff --git a/pool/shard008/C/0129931_ktti.c b/pool/shard008/C/0129931_ktti.c new file mode 100644 index 0000000000000000000000000000000000000000..fae8b211865fbd1b95d3ea778c0ce5fabbd2dca6 --- /dev/null +++ b/pool/shard008/C/0129931_ktti.c @@ -0,0 +1,117 @@ + + +#define KTTI_VERSION "1.0" + +#include +#include +#include +#include +#include +#include +#include + +#include "paride.h" + +#define j44(a,b) (((a>>4)&0x0f)|(b&0xf0)) + + + +static int cont_map[2] = { 0x10, 0x08 }; + +static void ktti_write_regr( PIA *pi, int cont, int regr, int val) + +{ int r; + + r = regr + cont_map[cont]; + + w0(r); w2(0xb); w2(0xa); w2(3); w2(6); + w0(val); w2(3); w0(0); w2(6); w2(0xb); +} + +static int ktti_read_regr( PIA *pi, int cont, int regr ) + +{ int a, b, r; + + r = regr + cont_map[cont]; + + w0(r); w2(0xb); w2(0xa); w2(9); w2(0xc); w2(9); + a = r1(); w2(0xc); b = r1(); w2(9); w2(0xc); w2(9); + return j44(a,b); + +} + +static void ktti_read_block( PIA *pi, char * buf, int count ) + +{ int k, a, b; + + for (k=0;ksaved_r0 = r0(); + pi->saved_r2 = r2(); + w2(0xb); w2(0xa); w0(0); w2(3); w2(6); +} + +static void ktti_disconnect ( PIA *pi ) + +{ w2(0xb); w2(0xa); w0(0xa0); w2(3); w2(4); + w0(pi->saved_r0); + w2(pi->saved_r2); +} + +static void ktti_log_adapter( PIA *pi, char * scratch, int verbose ) + +{ printk("%s: ktti %s, KT adapter at 0x%x, delay %d\n", + pi->device,KTTI_VERSION,pi->port,pi->delay); + +} + +static struct pi_protocol ktti = { + .owner = THIS_MODULE, + .name = "ktti", + .max_mode = 1, + .epp_first = 2, + .default_delay = 1, + .max_units = 1, + .write_regr = ktti_write_regr, + .read_regr = ktti_read_regr, + .write_block = ktti_write_block, + .read_block = ktti_read_block, + .connect = ktti_connect, + .disconnect = ktti_disconnect, + .log_adapter = ktti_log_adapter, +}; + +static int __init ktti_init(void) +{ + return paride_register(&ktti); +} + +static void __exit ktti_exit(void) +{ + paride_unregister(&ktti); +} + +MODULE_LICENSE("GPL"); +module_init(ktti_init) +module_exit(ktti_exit) diff --git a/pool/shard008/C/0129932_oracle.c b/pool/shard008/C/0129932_oracle.c new file mode 100644 index 0000000000000000000000000000000000000000..5c5cac2cf36bd36428979be64d28151421329475 --- /dev/null +++ b/pool/shard008/C/0129932_oracle.c @@ -0,0 +1,75 @@ +/* + * oracle.c + * + * Copyright (C) 2013 Remy Mudingay + * + * This module 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 module 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. + * If not, see . + * + */ + +#include "ndpi_protocol_ids.h" + +#define NDPI_CURRENT_PROTO NDPI_PROTOCOL_ORACLE + +#include "ndpi_api.h" + + +static void ndpi_int_oracle_add_connection(struct ndpi_detection_module_struct + *ndpi_struct, struct ndpi_flow_struct *flow) +{ + ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_ORACLE, NDPI_PROTOCOL_UNKNOWN, NDPI_CONFIDENCE_DPI); +} + +void ndpi_search_oracle(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) +{ + struct ndpi_packet_struct *packet = ndpi_get_packet_struct(ndpi_struct); + u_int16_t dport = 0, sport = 0; + + NDPI_LOG_DBG(ndpi_struct, "search ORACLE\n"); + + if(packet->tcp != NULL) { + sport = ntohs(packet->tcp->source), dport = ntohs(packet->tcp->dest); + NDPI_LOG_DBG2(ndpi_struct, "calculating ORACLE over tcp\n"); + /* Oracle Database 9g,10g,11g */ + if ((dport == 1521 || sport == 1521) + && (((packet->payload_packet_len >= 3 && packet->payload[0] == 0x07) && (packet->payload[1] == 0xff) && (packet->payload[2] == 0x00)) + || ((packet->payload_packet_len >= 232) && ((packet->payload[0] == 0x00) || (packet->payload[0] == 0x01)) + && (packet->payload[1] != 0x00) + && (packet->payload[2] == 0x00) + && (packet->payload[3] == 0x00)))) { + NDPI_LOG_INFO(ndpi_struct, "found oracle\n"); + ndpi_int_oracle_add_connection(ndpi_struct, flow); + } else if (packet->payload_packet_len == 213 && packet->payload[0] == 0x00 && + packet->payload[1] == 0xd5 && packet->payload[2] == 0x00 && + packet->payload[3] == 0x00 ) { + NDPI_LOG_INFO(ndpi_struct, "found oracle\n"); + ndpi_int_oracle_add_connection(ndpi_struct, flow); + } + } else { + NDPI_EXCLUDE_PROTO(ndpi_struct, flow); + } +} + + +void init_oracle_dissector(struct ndpi_detection_module_struct *ndpi_struct, u_int32_t *id, NDPI_PROTOCOL_BITMASK *detection_bitmask) +{ + ndpi_set_bitmask_protocol_detection("Oracle", ndpi_struct, detection_bitmask, *id, + NDPI_PROTOCOL_ORACLE, + ndpi_search_oracle, + NDPI_SELECTION_BITMASK_PROTOCOL_V4_V6_TCP_WITH_PAYLOAD_WITHOUT_RETRANSMISSION, + SAVE_DETECTION_BITMASK_AS_UNKNOWN, + ADD_TO_DETECTION_BITMASK); + + *id += 1; +} diff --git a/pool/shard008/C/0129939_mock_gtt.c b/pool/shard008/C/0129939_mock_gtt.c new file mode 100644 index 0000000000000000000000000000000000000000..5c7ae40bba634389187c6f56c9a0593c6604974d --- /dev/null +++ b/pool/shard008/C/0129939_mock_gtt.c @@ -0,0 +1,140 @@ +/* + * Copyright © 2016 Intel Corporation + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice (including the next + * paragraph) shall be included in all copies or substantial portions of the + * Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + */ + +#include "mock_gtt.h" + +static void mock_insert_page(struct i915_address_space *vm, + dma_addr_t addr, + u64 offset, + enum i915_cache_level level, + u32 flags) +{ +} + +static void mock_insert_entries(struct i915_address_space *vm, + struct i915_vma *vma, + enum i915_cache_level level, u32 flags) +{ +} + +static void mock_bind_ppgtt(struct i915_address_space *vm, + struct i915_vm_pt_stash *stash, + struct i915_vma *vma, + enum i915_cache_level cache_level, + u32 flags) +{ + GEM_BUG_ON(flags & I915_VMA_GLOBAL_BIND); + set_bit(I915_VMA_LOCAL_BIND_BIT, __i915_vma_flags(vma)); +} + +static void mock_unbind_ppgtt(struct i915_address_space *vm, + struct i915_vma *vma) +{ +} + +static void mock_cleanup(struct i915_address_space *vm) +{ +} + +static void mock_clear_range(struct i915_address_space *vm, + u64 start, u64 length) +{ +} + +struct i915_ppgtt *mock_ppgtt(struct drm_i915_private *i915, const char *name) +{ + struct i915_ppgtt *ppgtt; + + ppgtt = kzalloc(sizeof(*ppgtt), GFP_KERNEL); + if (!ppgtt) + return NULL; + + ppgtt->vm.gt = &i915->gt; + ppgtt->vm.i915 = i915; + ppgtt->vm.total = round_down(U64_MAX, PAGE_SIZE); + ppgtt->vm.file = ERR_PTR(-ENODEV); + ppgtt->vm.dma = i915->drm.dev; + + i915_address_space_init(&ppgtt->vm, VM_CLASS_PPGTT); + + ppgtt->vm.alloc_pt_dma = alloc_pt_dma; + + ppgtt->vm.clear_range = mock_clear_range; + ppgtt->vm.insert_page = mock_insert_page; + ppgtt->vm.insert_entries = mock_insert_entries; + ppgtt->vm.cleanup = mock_cleanup; + + ppgtt->vm.vma_ops.bind_vma = mock_bind_ppgtt; + ppgtt->vm.vma_ops.unbind_vma = mock_unbind_ppgtt; + ppgtt->vm.vma_ops.set_pages = ppgtt_set_pages; + ppgtt->vm.vma_ops.clear_pages = clear_pages; + + return ppgtt; +} + +static void mock_bind_ggtt(struct i915_address_space *vm, + struct i915_vm_pt_stash *stash, + struct i915_vma *vma, + enum i915_cache_level cache_level, + u32 flags) +{ +} + +static void mock_unbind_ggtt(struct i915_address_space *vm, + struct i915_vma *vma) +{ +} + +void mock_init_ggtt(struct drm_i915_private *i915, struct i915_ggtt *ggtt) +{ + memset(ggtt, 0, sizeof(*ggtt)); + + ggtt->vm.gt = &i915->gt; + ggtt->vm.i915 = i915; + ggtt->vm.is_ggtt = true; + + ggtt->gmadr = (struct resource) DEFINE_RES_MEM(0, 2048 * PAGE_SIZE); + ggtt->mappable_end = resource_size(&ggtt->gmadr); + ggtt->vm.total = 4096 * PAGE_SIZE; + + ggtt->vm.alloc_pt_dma = alloc_pt_dma; + + ggtt->vm.clear_range = mock_clear_range; + ggtt->vm.insert_page = mock_insert_page; + ggtt->vm.insert_entries = mock_insert_entries; + ggtt->vm.cleanup = mock_cleanup; + + ggtt->vm.vma_ops.bind_vma = mock_bind_ggtt; + ggtt->vm.vma_ops.unbind_vma = mock_unbind_ggtt; + ggtt->vm.vma_ops.set_pages = ggtt_set_pages; + ggtt->vm.vma_ops.clear_pages = clear_pages; + + i915_address_space_init(&ggtt->vm, VM_CLASS_GGTT); + i915->gt.ggtt = ggtt; +} + +void mock_fini_ggtt(struct i915_ggtt *ggtt) +{ + i915_address_space_fini(&ggtt->vm); +} diff --git a/pool/shard008/C/0129941_xsdl.c b/pool/shard008/C/0129941_xsdl.c new file mode 100644 index 0000000000000000000000000000000000000000..3dc69ae90588aeb4e64ae56921d6019b7fb45211 --- /dev/null +++ b/pool/shard008/C/0129941_xsdl.c @@ -0,0 +1,73 @@ +/* The MIT License (MIT) + * + * Copyright (c) 2015 Tomasz Kramkowski + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#include "xsdl.h" +#include +#include + +static SDL_Window *window; +static SDL_Renderer *renderer; +static SDL_Texture *screen; + +xsdl_colour_t *xsdl_buffer; +static unsigned bwidth, bheight; +static bool initialised = false; + +void xsdl_init(unsigned width, unsigned height, const char *title) +{ + if (initialised) + return; + initialised = true; + + SDL_Init(SDL_INIT_VIDEO); + atexit(xsdl_cleanup); + + window = SDL_CreateWindow(title, SDL_WINDOWPOS_UNDEFINED, + SDL_WINDOWPOS_UNDEFINED, width, height, 0); + renderer = SDL_CreateRenderer(window, -1, 0); + screen = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888, + SDL_TEXTUREACCESS_STREAMING, width, height); + xsdl_buffer = malloc(sizeof *xsdl_buffer * width * height); + + bwidth = width; + bheight = height; +} + +void xsdl_cleanup(void) +{ + if (!initialised) + return; + initialised = false; + + free(xsdl_buffer); + SDL_Quit(); +} + +void xsdl_draw(void) +{ + SDL_UpdateTexture(screen, NULL, xsdl_buffer, + bwidth * sizeof *xsdl_buffer); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, screen, NULL, NULL); + SDL_RenderPresent(renderer); +} diff --git a/pool/shard008/C/0129945_gpio.c b/pool/shard008/C/0129945_gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..2107b558437a2a9874854629bb44f2d582b40a72 --- /dev/null +++ b/pool/shard008/C/0129945_gpio.c @@ -0,0 +1,150 @@ +/* + * Copyright 2012 Red Hat Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * Authors: Ben Skeggs + */ +#include +#include +#include +#include + +u16 +dcb_gpio_table(struct nvkm_bios *bios, u8 *ver, u8 *hdr, u8 *cnt, u8 *len) +{ + u16 data = 0x0000; + u16 dcb = dcb_table(bios, ver, hdr, cnt, len); + if (dcb) { + if (*ver >= 0x30 && *hdr >= 0x0c) + data = nvbios_rd16(bios, dcb + 0x0a); + else + if (*ver >= 0x22 && nvbios_rd08(bios, dcb - 1) >= 0x13) + data = nvbios_rd16(bios, dcb - 0x0f); + + if (data) { + *ver = nvbios_rd08(bios, data + 0x00); + if (*ver < 0x30) { + *hdr = 3; + *cnt = nvbios_rd08(bios, data + 0x02); + *len = nvbios_rd08(bios, data + 0x01); + } else + if (*ver <= 0x41) { + *hdr = nvbios_rd08(bios, data + 0x01); + *cnt = nvbios_rd08(bios, data + 0x02); + *len = nvbios_rd08(bios, data + 0x03); + } else { + data = 0x0000; + } + } + } + return data; +} + +u16 +dcb_gpio_entry(struct nvkm_bios *bios, int idx, int ent, u8 *ver, u8 *len) +{ + u8 hdr, cnt, xver; /* use gpio version for xpio entry parsing */ + u16 gpio; + + if (!idx--) + gpio = dcb_gpio_table(bios, ver, &hdr, &cnt, len); + else + gpio = dcb_xpio_table(bios, idx, &xver, &hdr, &cnt, len); + + if (gpio && ent < cnt) + return gpio + hdr + (ent * *len); + + return 0x0000; +} + +u16 +dcb_gpio_parse(struct nvkm_bios *bios, int idx, int ent, u8 *ver, u8 *len, + struct dcb_gpio_func *gpio) +{ + u16 data = dcb_gpio_entry(bios, idx, ent, ver, len); + if (data) { + if (*ver < 0x40) { + u16 info = nvbios_rd16(bios, data); + *gpio = (struct dcb_gpio_func) { + .line = (info & 0x001f) >> 0, + .func = (info & 0x07e0) >> 5, + .log[0] = (info & 0x1800) >> 11, + .log[1] = (info & 0x6000) >> 13, + .param = !!(info & 0x8000), + }; + } else + if (*ver < 0x41) { + u32 info = nvbios_rd32(bios, data); + *gpio = (struct dcb_gpio_func) { + .line = (info & 0x0000001f) >> 0, + .func = (info & 0x0000ff00) >> 8, + .log[0] = (info & 0x18000000) >> 27, + .log[1] = (info & 0x60000000) >> 29, + .param = !!(info & 0x80000000), + }; + } else { + u32 info = nvbios_rd32(bios, data + 0); + u8 info1 = nvbios_rd32(bios, data + 4); + *gpio = (struct dcb_gpio_func) { + .line = (info & 0x0000003f) >> 0, + .func = (info & 0x0000ff00) >> 8, + .log[0] = (info1 & 0x30) >> 4, + .log[1] = (info1 & 0xc0) >> 6, + .param = !!(info & 0x80000000), + }; + } + } + + return data; +} + +u16 +dcb_gpio_match(struct nvkm_bios *bios, int idx, u8 func, u8 line, + u8 *ver, u8 *len, struct dcb_gpio_func *gpio) +{ + u8 hdr, cnt, i = 0; + u16 data; + + while ((data = dcb_gpio_parse(bios, idx, i++, ver, len, gpio))) { + if ((line == 0xff || line == gpio->line) && + (func == 0xff || func == gpio->func)) + return data; + } + + /* DCB 2.2, fixed TVDAC GPIO data */ + if ((data = dcb_table(bios, ver, &hdr, &cnt, len))) { + if (*ver >= 0x22 && *ver < 0x30 && func == DCB_GPIO_TVDAC0) { + u8 conf = nvbios_rd08(bios, data - 5); + u8 addr = nvbios_rd08(bios, data - 4); + if (conf & 0x01) { + *gpio = (struct dcb_gpio_func) { + .func = DCB_GPIO_TVDAC0, + .line = addr >> 4, + .log[0] = !!(conf & 0x02), + .log[1] = !(conf & 0x02), + }; + *ver = 0x00; + return data; + } + } + } + + return 0x0000; +} diff --git a/pool/shard008/C/0129946_4.c b/pool/shard008/C/0129946_4.c new file mode 100644 index 0000000000000000000000000000000000000000..072bb52e5c7bab8576066866d9524a97699fed07 --- /dev/null +++ b/pool/shard008/C/0129946_4.c @@ -0,0 +1,77 @@ +/* -*- linux-c -*- + * + * (C) Copyright IBM Corp. 2004, 2005 + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * Author(s): + * Carl McAdams + * Donald A. Barre + * + * Spec: HPI-B.01.01 + * Function: saHpiIdrAreaAdd + * Description: + * Call saHpiIdrAreaAdd() on a Resource which does not support IDRs. + * Expected return: SA_ERR_HPI_CAPABILITY. + * Line: P104-19:P104-20 + */ + +#include +#include "../include/inventory_test.h" + +/************************************************************************* + * + * Test a resource that does not support inventories. + * + *************************************************************************/ + +int Test_Resource(SaHpiSessionIdT sessionId, + SaHpiRptEntryT report, callback2_t func) +{ + SaErrorT status; + int retval = SAF_TEST_UNKNOWN; + SaHpiEntryIdT AreaId; + + if (!hasInventoryCapability(&report)) { + + // Call saHpiIdrAreaAdd() on a resource which does + // not support IDRs. + + status = saHpiIdrAreaAdd(sessionId, + report.ResourceId, + SAHPI_DEFAULT_INVENTORY_ID, + SAHPI_IDR_AREATYPE_PRODUCT_INFO, + &AreaId); + + if (status == SA_ERR_HPI_CAPABILITY) { + retval = SAF_TEST_PASS; + } else { + retval = SAF_TEST_FAIL; + e_print(saHpiIdrAreaAdd, SA_ERR_HPI_CAPABILITY, status); + } + } + + return retval; +} + +/************************************************************************* + * + * Main Program + * + *************************************************************************/ + +int main(int argc, char **argv) +{ + return process_all_domains(Test_Resource, NULL, NULL); +} diff --git a/pool/shard008/C/0129955_write_stdin.c b/pool/shard008/C/0129955_write_stdin.c new file mode 100644 index 0000000000000000000000000000000000000000..7ace53b679af229d250d1caa9333b939bf5c3761 --- /dev/null +++ b/pool/shard008/C/0129955_write_stdin.c @@ -0,0 +1,149 @@ +/* + * The Qubes OS Project, http://www.qubes-os.org + * + * Copyright (C) 2010 Rafal Wojtczuk + * + * 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. + * + */ + +#include +#include +#include +#include +#include +#include +#include "qrexec.h" +#include "buffer.h" +#include "glue.h" + +/* +There is buffered data in "buffer" for client id "client_id", and select() +reports that "fd" is writable. Write as much as possible to fd, if all sent, +notify the peer that this client's pipe is no longer full. +*/ +int flush_client_data(int fd, int client_id, struct buffer *buffer) +{ + int ret; + int len; + for (;;) { + len = buffer_len(buffer); + if (len > MAX_DATA_CHUNK) + len = MAX_DATA_CHUNK; + ret = write(fd, buffer_data(buffer), len); + if (ret == -1) { + if (errno != EAGAIN) { + return WRITE_STDIN_ERROR; + } else + return WRITE_STDIN_BUFFERED; + } + // we previously called buffer_remove(buffer, len) + // it will be wrong if we change MAX_DATA_CHUNK to something large + // as pipes writes are atomic only to PIPE_MAX limit + buffer_remove(buffer, ret); + len = buffer_len(buffer); + if (!len) { + struct server_header s_hdr; + s_hdr.type = MSG_XON; + s_hdr.client_id = client_id; + s_hdr.len = 0; + write_all_vchan_ext(&s_hdr, sizeof s_hdr); + return WRITE_STDIN_OK; + } + } + +} + +/* +Write "len" bytes from "data" to "fd". If not all written, buffer the rest +to "buffer", and notify the peer that the client "client_id" pipe is full via +MSG_XOFF message. +*/ +int write_stdin(int fd, int client_id, char *data, int len, + struct buffer *buffer) +{ + int ret; + int written = 0; + + if (buffer_len(buffer)) { + buffer_append(buffer, data, len); + return WRITE_STDIN_BUFFERED; + } + while (written < len) { + ret = write(fd, data + written, len - written); + if (ret == 0) { + perror("write_stdin: write returns 0 ???"); + exit(1); + } + if (ret == -1) { + struct server_header s_hdr; + + if (errno != EAGAIN) + return WRITE_STDIN_ERROR; + + buffer_append(buffer, data + written, + len - written); + + s_hdr.type = MSG_XOFF; + s_hdr.client_id = client_id; + s_hdr.len = 0; + write_all_vchan_ext(&s_hdr, sizeof s_hdr); + + return WRITE_STDIN_BUFFERED; + } + written += ret; + } + return WRITE_STDIN_OK; + +} + +void set_nonblock(int fd) +{ + int fl = fcntl(fd, F_GETFL, 0); + fcntl(fd, F_SETFL, fl | O_NONBLOCK); +} + +void set_block(int fd) +{ + int fl = fcntl(fd, F_GETFL, 0); + fcntl(fd, F_SETFL, fl & ~O_NONBLOCK); +} + +/* +Data feed process has exited, so we need to clear all control structures for +the client. However, if we have buffered data for the client (which is rare btw), +fire&forget a separate process to flush them. +*/ +int fork_and_flush_stdin(int fd, struct buffer *buffer) +{ + int i; + if (!buffer_len(buffer)) + return 0; + switch (fork()) { + case -1: + perror("fork"); + exit(1); + case 0: + break; + default: + return 1; + } + for (i = 0; i < MAX_FDS; i++) + if (i != fd && i != 2) + close(i); + set_block(fd); + write_all(fd, buffer_data(buffer), buffer_len(buffer)); + exit(0); +} diff --git a/pool/shard008/C/0129957_op_lvpatwrite.c b/pool/shard008/C/0129957_op_lvpatwrite.c new file mode 100644 index 0000000000000000000000000000000000000000..d16f29247126bcee7fb71c224fa314013c9ad8a8 --- /dev/null +++ b/pool/shard008/C/0129957_op_lvpatwrite.c @@ -0,0 +1,102 @@ +/**************************************************************** + * * + * Copyright 2001, 2003 Sanchez Computer Associates, Inc. * + * * + * This source code contains the intellectual property * + * of its copyright holder(s), and is made available * + * under a license. If you do not know the terms of * + * the license, please stop and do not read further. * + * * + ****************************************************************/ + +#include "mdef.h" + +#include "gtm_string.h" + +#include "error.h" +#include "mlkdef.h" +#include "zshow.h" +#include "compiler.h" +#include "gdsroot.h" +#include "gtm_facility.h" +#include "fileinfo.h" +#include "gdsbt.h" +#include "gdsfhead.h" +#include "zwrite.h" +#include +#include "op.h" +#include "mvalconv.h" +#include "gtm_maxstr.h" + +void op_lvpatwrite(va_alist) +va_dcl +{ + va_list var; + boolean_t flag, local_buff; + int4 count, arg1, arg2; + mval *mv; + zshow_out output, *out; + MAXSTR_BUFF_DECL(buff); + + VAR_START(var); + count = va_arg(var, int4); + arg1 = va_arg(var, int4); + local_buff = FALSE; + if (!arg1) + { + local_buff = TRUE; + MAXSTR_BUFF_INIT; + memset(&output, 0, sizeof(output)); + output.code = 'V'; + output.type = ZSHOW_DEVICE; + output.buff = &buff[0]; + output.ptr = output.buff; + out = &output; + } else + out = (zshow_out *) arg1; + count--; + arg1 = va_arg(var, int4); + lvzwr_init(TRUE, (mval *)arg1); + count--; + for (; count > 0; ) + { + mv = va_arg(var, mval *); count--; + switch ((flag = MV_FORCE_INT(mv))) + { + case ZWRITE_ASTERISK: /* caution fall through */ + lvzwr_arg(flag, (mval *)0, (mval *)0); + case ZWRITE_END: + lvzwr_fini(out,flag); + if (local_buff) + MAXSTR_BUFF_FINI; + return; + break; + case ZWRITE_ALL: + lvzwr_arg(flag, (mval *)0, (mval *)0); + break; + case ZWRITE_BOTH: + arg1 = va_arg(var, int4); + arg2 = va_arg(var, int4); + count -= 2; + lvzwr_arg(flag, (mval *)arg1, (mval *)arg2); + break; + case ZWRITE_UPPER: + arg1 = va_arg(var, int4); + count--; + lvzwr_arg(flag, (mval *)0, (mval *)arg1); + break; + case ZWRITE_VAL: + case ZWRITE_LOWER: + case ZWRITE_PATTERN: + arg1 = va_arg(var, int4); + count--; + lvzwr_arg(flag, (mval *)arg1, (mval *)0); + break; + default: + GTMASSERT; + break; + } + } + if (local_buff) + MAXSTR_BUFF_FINI; +} diff --git a/pool/shard008/C/0129958_ethphy.c b/pool/shard008/C/0129958_ethphy.c new file mode 100644 index 0000000000000000000000000000000000000000..a551cd36c3a647946b24971f251d70f8498a832d --- /dev/null +++ b/pool/shard008/C/0129958_ethphy.c @@ -0,0 +1,383 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) [2015] [Marco Russi] + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. +*/ + +/* + * This file ethphy.c represents the PHY layer source file + * of the UDP/IP stack. + * + * Author : Marco Russi + * + * Evolution of the file: + * 10/08/2015 - File created - Marco Russi + * +*/ + + +//TODO: manage RMII detection during MIIM interface initialisation + + +/* inclusion files */ +#include "p32mx795f512l.h" +#include "fw_common.h" + +#include "ethphy.h" +#include "extphy_regs.h" + + + +/* Local defines */ + +/* External PHY adress */ +#define UC_EXT_PHY_ADDRESS ((uint8)1) + +/* PHY required capabilities */ +#define PHY_REQUIRED_CPBL_MASK (BMSTAT_BASE10T_HDX_MASK | BMSTAT_BASE10T_FDX_MASK | BMSTAT_BASE100TX_HDX_MASK | BMSTAT_BASE100TX_FDX_MASK) + + +/* --- MIIM defines --- */ + +/* EMAC1MCFG register */ +#define MIIM_RESET_BIT_POS 15 +#define MIIM_CLKSEL_BIT_POS 2 + +/* EMAC1MIND register */ +#define MIIM_NOTVALID_BIT_POS 2 +#define MIIM_IS_BUSY_BIT_POS 0 + +/* EMAC1MADR register */ +#define MIIM_PHY_ADD_BIT_POS 8 +#define MIIM_REG_ADD_BIT_POS 0 + +/* EMAC1MCMD register */ +#define MIIM_SCAN_REG_BIT_POS 1 +#define MIIM_READ_REG_BIT_POS 0 + +/* EMAC1SUPP register */ +#define RESETRMII_BIT_POS 11 +#define SPEEDRMII_BIT_POS 8 + + + + +/* Local macros */ + +#define CHECK_MIIM_IS_BUSY() ((EMAC1MIND & (1 << MIIM_IS_BUSY_BIT_POS)) > 0) + + + + +/* Local functions prototypes */ +LOCAL void initMIIMInterface (void); +LOCAL uint16 readPHYRegister (uint8, uint8); +LOCAL void writePHYRegister (uint8, uint8, uint16); +LOCAL void scanPHYRegister (uint8, uint8); + + + + +/* Exported functions declaration */ + +/* Init Ethernet PHY module */ +EXPORTED boolean ETHPHY_Init(void) +{ + boolean bPHYValid = B_FALSE; + uint16 ui16RegisterData = US_NULL; + + /* init MIIM interface */ + initMIIMInterface(); + + /* read BMCON register default value */ + ui16RegisterData = readPHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_BMCON); /* maybe not needed */ + /* reset PHY */ + /* set RESET flag */ + ui16RegisterData |= BMCON_RESET_MASK; + /* write */ + writePHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_BMCON, ui16RegisterData); + /* ATTENTION: wait for this bit to self-clear itself - IMPLEMENT A TIMEOUT! */ + asm("nop"); + asm("nop"); + + /* try to write and read-back something to PHY */ +// ui16RegisterData = readPHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_BMCON); + ui16RegisterData = 0; + ui16RegisterData |= (BMCON_LOOPBACK_MASK | BMCON_ISOLATE_MASK); /* two flags */ + /* write */ + writePHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_BMCON, ui16RegisterData); + /* read-back */ + ui16RegisterData = readPHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_BMCON); + /* check both flags */ + if((ui16RegisterData & (BMCON_LOOPBACK_MASK | BMCON_ISOLATE_MASK)) == (BMCON_LOOPBACK_MASK | BMCON_ISOLATE_MASK)) + { + /* write success */ + bPHYValid = B_TRUE; + } + else + { + /* write fail */ + } + + /* clear flags previously tested */ + ui16RegisterData &= (~(BMCON_LOOPBACK_MASK | BMCON_ISOLATE_MASK)); + writePHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_BMCON, ui16RegisterData); + + /* if PHY is valid */ + if(B_TRUE == bPHYValid) + { + /* read BMSTAT register */ + ui16RegisterData = readPHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_BMSTAT); + /* check PHY required capabilities and Auto-negotiation ability */ + if(ui16RegisterData & (PHY_REQUIRED_CPBL_MASK | BMSTAT_AN_ABLE_MASK)) + { + /* PHY is still valid */ + } + else + { + /* PHY is not valid anymore */ + bPHYValid = B_FALSE; + } + } + + /* if PHY is valid */ + if(B_TRUE == bPHYValid) + { + /* configure MII/RMII */ + ui16RegisterData = readPHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_RMII_BYPASS); + /* ATTENTION: RMII is used at the moment - default by strap - Do not leave this as fixed */ + ui16RegisterData |= RMIIBYPASS_RMII_MODE_MASK; /* use RMII */ + ui16RegisterData &= (~RMIIBYPASS_RMII_REV1_0_MASK); /* use RMII 1.2 */ + //ui16RegisterData &= (~RMIIBYPASS_RMII_MODE_MASK); /* use MII */ + writePHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_RMII_BYPASS, ui16RegisterData); + + /* configure MDIX */ + ui16RegisterData = readPHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_PHY_CTRL); + /* enable MDIX Auto-negotiation */ + /* ATTENTION: Auto-negotiation is used at the moment - deafult by strap - Do not leave this as fixed */ + ui16RegisterData |= PHYCTRL_MDIX_EN_MASK; + writePHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_PHY_CTRL, ui16RegisterData); + + /* configure negotiation advertisement register */ + ui16RegisterData = readPHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_ANAD); + /* ATTENTION: Do not leave this as fixed */ + ui16RegisterData |= ANAD_PAUSE_MASK; /* PAUSE support for full duplex */ + ui16RegisterData |= ANAD_ASM_DIR_MASK; /* Asymmetric PAUSE support for full duplex */ + writePHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_ANAD, ui16RegisterData); + + /* read BMSTAT register */ + ui16RegisterData = readPHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_BMSTAT); + /* if autonegotiation ability is enabled */ + if((ui16RegisterData & BMSTAT_AN_ABLE_MASK) > US_NULL) + { + /* start autonegotiation */ + ui16RegisterData = readPHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_BMCON); + ui16RegisterData |= BMCON_AN_ENABLE_MASK; /* enable auto-negotiation */ + ui16RegisterData |= BMCON_AN_RESTART_MASK; /* restart auto-negotiation */ + writePHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_BMCON, ui16RegisterData); + + /* wait autonegotiation complete */ + do + { + /* read and check Auto-Negotiation Complete bit in BMSTAT register */ + ui16RegisterData = readPHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_BMSTAT); + } + while((ui16RegisterData & BMSTAT_AN_COMPLETE_MASK) == UL_NULL); + + + + +/* + { + uint16 reg; + reg = readPHYRegister(UC_EXT_PHY_ADDRESS,PHY_REG_BMCON); + reg = readPHYRegister(UC_EXT_PHY_ADDRESS,PHY_REG_BMSTAT); + reg = readPHYRegister(UC_EXT_PHY_ADDRESS,PHY_REG_PHYID1); + reg = readPHYRegister(UC_EXT_PHY_ADDRESS,PHY_REG_PHYID2); + reg = readPHYRegister(UC_EXT_PHY_ADDRESS,PHY_REG_ANAD); + reg = readPHYRegister(UC_EXT_PHY_ADDRESS,PHY_REG_ANLPAD); + reg = readPHYRegister(UC_EXT_PHY_ADDRESS,PHY_REG_ANEXP); + reg = readPHYRegister(UC_EXT_PHY_ADDRESS,PHY_REG_ANNPTR); + reg = readPHYRegister(UC_EXT_PHY_ADDRESS,PHY_REG_ANLPRNP); + } +*/ + + + + + + /* read ANEXP register */ + ui16RegisterData = readPHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_ANEXP); + /* read ANLPAR register */ + ui16RegisterData = readPHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_ANLPAD); + /* read ANLPAR next page register */ + ui16RegisterData = readPHYRegister(UC_EXT_PHY_ADDRESS, PHY_REG_ANLPADNP); + + asm("nop"); + + /* once the negotiation is completed get link partner capabilities from the PHY register ANLPAR */ + /* ATTENTION: not performed at the moment! */ + } + } + + return bPHYValid; +} + + + + +/* Local functions declaration */ + +/* initialise the MIIM interface */ +LOCAL void initMIIMInterface(void) +{ + /* detect alternate or default I/O configuration */ + /* FETHIO (DEVCFG3<25>) */ + /* not used here at the moment - set in main.c */ + + /* detect MII/RMII operation mode */ + /* FMIIEN (DEVCFG3<24>) */ + /* not used here at the moment - set in main.c */ + + /* initialise all pins used by the MAC PHY interface as digital */ + /* see main.c */ + + /* ATTENTION: do following reset instruction if RMII operation is selected */ + EMAC1SUPPSET = (1 << RESETRMII_BIT_POS); + asm("nop"); + asm("nop"); + asm("nop"); + EMAC1SUPPCLR = (1 << RESETRMII_BIT_POS); + + /* RMII is running in 100 Mbps */ + EMAC1SUPPSET = (1 << SPEEDRMII_BIT_POS); + + /* issue an MIIM block reset */ + EMAC1MCFGSET = (1 << MIIM_RESET_BIT_POS); + asm("nop"); + asm("nop"); + asm("nop"); + EMAC1MCFGCLR = (1 << MIIM_RESET_BIT_POS); + + /* select MIIM clock divider */ + EMAC1MCFGCLR = (0x0F << MIIM_CLKSEL_BIT_POS); + /* ATTENTION: this value should be calculated dinamically - clock set at 20 Mhz */ + EMAC1MCFGSET = (9 << MIIM_CLKSEL_BIT_POS); +} + + +LOCAL uint16 readPHYRegister(uint8 ui8PHYAddress, uint8 ui8RegAddress) +{ + uint16 ui16ReadData; + + /* poll MIIMBUSY flag */ + while(CHECK_MIIM_IS_BUSY()); + + /* set the PHY address */ + EMAC1MADRCLR = (0x1F << MIIM_PHY_ADD_BIT_POS); + EMAC1MADRSET = ((ui8PHYAddress & 0x1F) << MIIM_PHY_ADD_BIT_POS); + + /* set the register address */ + EMAC1MADRCLR = (0x1F << MIIM_REG_ADD_BIT_POS); + EMAC1MADRSET = ((ui8RegAddress & 0x1F) << MIIM_REG_ADD_BIT_POS); + + /* set read command */ + EMAC1MCMDSET = (1 << MIIM_READ_REG_BIT_POS); + + /* wait 3 SYSCLK cycles */ + asm("nop"); + asm("nop"); + asm("nop"); + + /* poll MIIMBUSY flag */ + while(CHECK_MIIM_IS_BUSY()); + + /* clear read command */ + EMAC1MCMDCLR = (1 << MIIM_READ_REG_BIT_POS); + + /* read 16-bit data */ + ui16ReadData = (EMAC1MRDD & 0x0000FFFF); + + return ui16ReadData; +} + + +LOCAL void writePHYRegister(uint8 ui8PHYAddress, uint8 ui8RegAddress, uint16 ui16DataToWrite) +{ + /* poll MIIMBUSY flag */ + while(CHECK_MIIM_IS_BUSY()); + + /* set the PHY address */ + EMAC1MADRCLR = (0x1F << MIIM_PHY_ADD_BIT_POS); + EMAC1MADRSET = ((ui8PHYAddress & 0x1F) << MIIM_PHY_ADD_BIT_POS); + + /* set the register address */ + EMAC1MADRCLR = (0x1F << MIIM_REG_ADD_BIT_POS); + EMAC1MADRSET = ((ui8RegAddress & 0x1F) << MIIM_REG_ADD_BIT_POS); + + /* set read command */ + EMAC1MWTD = (ui16DataToWrite & 0x0000FFFF); + + /* wait 3 SYSCLK cycles */ + asm("nop"); + asm("nop"); + asm("nop"); +} + + +LOCAL void scanPHYRegister(uint8 ui8PHYAddress, uint8 ui8RegAddress) +{ + uint16 ui16ReadData; + + /* poll MIIMBUSY flag */ + while(CHECK_MIIM_IS_BUSY()); + + /* set the PHY address */ + EMAC1MADRCLR = (0x1F << MIIM_PHY_ADD_BIT_POS); + EMAC1MADRSET = ((ui8PHYAddress & 0x1F) << MIIM_PHY_ADD_BIT_POS); + + /* set the register address */ + EMAC1MADRCLR = (0x1F << MIIM_REG_ADD_BIT_POS); + EMAC1MADRSET = ((ui8RegAddress & 0x1F) << MIIM_REG_ADD_BIT_POS); + + /* set scan command */ + EMAC1MCMDSET = (1 << MIIM_SCAN_REG_BIT_POS); + + /* wait 3 SYSCLK cycles */ + asm("nop"); + asm("nop"); + asm("nop"); + + /* poll NOT VALID flag */ + while((EMAC1MIND & (1 << MIIM_NOTVALID_BIT_POS)) == 1); + + /* read first 16-bit data */ + ui16ReadData = (EMAC1MRDD & 0x0000FFFF); + + //TODO: ...read other registers after frame time (no way to determine when register is updated) + + /* stop scan - clear scan command */ + EMAC1MCMDCLR = (1 << MIIM_SCAN_REG_BIT_POS); +} + + + + +/* End of files */ diff --git a/pool/shard008/C/0129960_exec_subtitle_export_script_export.c b/pool/shard008/C/0129960_exec_subtitle_export_script_export.c new file mode 100644 index 0000000000000000000000000000000000000000..cc35d1d627c3b24ca69ca6b6b0606f728104bf95 --- /dev/null +++ b/pool/shard008/C/0129960_exec_subtitle_export_script_export.c @@ -0,0 +1,105 @@ +/* libquvi + * Copyright (C) 2013 Toni Gundogdu + * + * This file is part of libquvi . + * + * This library is free software: you can redistribute it and/or + * modify it under the terms of the GNU Affero General Public + * License as published by the Free Software Foundation, either + * version 3 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General + * Public License along with this library. If not, see + * . + */ + +/* + * NOTE: The error messages produced in these functions are intended for + * developers. They would typically be seen when a new script is + * being developed or an old one is being maintained. + * + * These messages should be clear, indicating the actual error, + * minimizing the time spent on locating the problem in the script. + */ + +#include "config.h" + +#include +#include + +#include "quvi.h" +/* -- */ +#include "_quvi_s.h" +#include "_quvi_subtitle_export_s.h" +#include "_quvi_subtitle_s.h" +#include "_quvi_script_s.h" +/* -- */ +#include "misc/subtitle_export.h" +#include "lua/setfield.h" +#include "lua/chk.h" +#include "lua/def.h" + +static const gchar script_func[] = "export"; + +static QuviError _chk_result(lua_State *l, _quvi_subtitle_export_t qse, + const gchar *script_fpath) +{ + lua_pushnil(l); + while (lua_next(l, LI_KEY)) + { + l_chk_assign_s(l, SUES_DATA, qse->data, FALSE); + lua_pop(l, 1); + } + + if (qse->data->len ==0) + { + luaL_error(l, "%s: %s: must return `qargs.data'", + script_fpath, script_func); + } + lua_pop(l, 1); + return (QUVI_OK); +} + +QuviError l_exec_subtitle_export_script_export(gpointer p, GSList *sl) +{ + _quvi_subtitle_export_t qse; + _quvi_script_t qs; + lua_State *l; + + qse = (_quvi_subtitle_export_t) p; + l = qse->handle.quvi->handle.lua; + + qs = (_quvi_script_t) sl->data; + lua_getglobal(l, script_func); + + if (!lua_isfunction(l, -1)) + { + luaL_error(l, "%s: the function `%s' was not found", + qs->fpath->str, script_func); + } + + lua_newtable(l); + l_set_reg_userdata(l, USERDATA_QUVI_T, (gpointer) qse->handle.quvi); + l_setfield_s(l, SUES_INPUT_URL, qse->url.input->str, -1); + l_setfield_n(l, SUES_FROM_FORMAT, qse->format.from); + + if (lua_pcall(l, 1, 1, 0)) + { + g_string_assign(qse->handle.quvi->status.errmsg, lua_tostring(l, -1)); + return (QUVI_ERROR_SCRIPT); + } + + if (!lua_istable(l, -1)) + { + luaL_error(l, "%s: %s: must return a dictionary, this is " + "typically the `qargs'", qs->fpath->str, script_func); + } + return (_chk_result(l, qse, qs->fpath->str)); +} + +/* vim: set ts=2 sw=2 tw=72 expandtab: */ diff --git a/pool/shard008/C/0129962_pulse-source.c b/pool/shard008/C/0129962_pulse-source.c new file mode 100644 index 0000000000000000000000000000000000000000..acba18879b4d3f1f2692223236cad360adecaaf9 --- /dev/null +++ b/pool/shard008/C/0129962_pulse-source.c @@ -0,0 +1,286 @@ +/* + * Copyright (C) 2014 Michal Ratajsky + * + * 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 of the licence, 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. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + */ + +#include +#include +#include +#include +#include + +#include + +#include "pulse-connection.h" +#include "pulse-device.h" +#include "pulse-monitor.h" +#include "pulse-port.h" +#include "pulse-port-switch.h" +#include "pulse-stream.h" +#include "pulse-source.h" +#include "pulse-source-control.h" +#include "pulse-source-output.h" +#include "pulse-source-switch.h" + +struct _PulseSourcePrivate +{ + GHashTable *outputs; + GList *outputs_list; + PulsePortSwitch *pswitch; + GList *pswitch_list; + PulseSourceControl *control; +}; + +static void pulse_source_class_init (PulseSourceClass *klass); +static void pulse_source_init (PulseSource *source); +static void pulse_source_dispose (GObject *object); +static void pulse_source_finalize (GObject *object); + +G_DEFINE_TYPE (PulseSource, pulse_source, PULSE_TYPE_STREAM); + +static const GList *pulse_source_list_controls (MateMixerStream *mms); +static const GList *pulse_source_list_switches (MateMixerStream *mms); + +static void free_list_controls (PulseSource *source); + +static void +pulse_source_class_init (PulseSourceClass *klass) +{ + GObjectClass *object_class; + MateMixerStreamClass *stream_class; + + object_class = G_OBJECT_CLASS (klass); + object_class->dispose = pulse_source_dispose; + object_class->finalize = pulse_source_finalize; + + stream_class = MATE_MIXER_STREAM_CLASS (klass); + stream_class->list_controls = pulse_source_list_controls; + stream_class->list_switches = pulse_source_list_switches; + + g_type_class_add_private (klass, sizeof (PulseSourcePrivate)); +} + +static void +pulse_source_init (PulseSource *source) +{ + source->priv = G_TYPE_INSTANCE_GET_PRIVATE (source, + PULSE_TYPE_SOURCE, + PulseSourcePrivate); + + source->priv->outputs = g_hash_table_new_full (g_direct_hash, + g_direct_equal, + NULL, + g_object_unref); +} + +static void +pulse_source_dispose (GObject *object) +{ + PulseSource *source; + + source = PULSE_SOURCE (object); + + g_hash_table_remove_all (source->priv->outputs); + + g_clear_object (&source->priv->control); + g_clear_object (&source->priv->pswitch); + + free_list_controls (source); + + if (source->priv->pswitch_list != NULL) { + g_list_free (source->priv->pswitch_list); + source->priv->pswitch_list = NULL; + } + G_OBJECT_CLASS (pulse_source_parent_class)->dispose (object); +} + +static void +pulse_source_finalize (GObject *object) +{ + PulseSource *source; + + source = PULSE_SOURCE (object); + + g_hash_table_unref (source->priv->outputs); + + G_OBJECT_CLASS (pulse_source_parent_class)->finalize (object); +} + +PulseSource * +pulse_source_new (PulseConnection *connection, + const pa_source_info *info, + PulseDevice *device) +{ + PulseSource *source; + + g_return_val_if_fail (PULSE_IS_CONNECTION (connection), NULL); + g_return_val_if_fail (info != NULL, NULL); + + source = g_object_new (PULSE_TYPE_SOURCE, + "name", info->name, + "label", info->description, + "device", device, + "direction", MATE_MIXER_DIRECTION_INPUT, + "connection", connection, + "index", info->index, + NULL); + + source->priv->control = pulse_source_control_new (source, info); + + if (info->n_ports > 0) { + pa_source_port_info **ports = info->ports; + + /* Create the port switch */ + source->priv->pswitch = pulse_source_switch_new ("port", _("Connector"), source); + + while (*ports != NULL) { + pa_source_port_info *p = *ports++; + PulsePort *port; + const gchar *icon = NULL; + + /* A port may include an icon but in PulseAudio sink and source ports + * the property is not included, for this reason ports are also read from + * devices where the icons may be present */ + if (device != NULL) { + port = pulse_device_get_port (PULSE_DEVICE (device), p->name); + if (port != NULL) + icon = mate_mixer_switch_option_get_icon (MATE_MIXER_SWITCH_OPTION (port)); + } + + port = pulse_port_new (p->name, + p->description, + icon, + p->priority); + + pulse_port_switch_add_port (source->priv->pswitch, port); + + if (p == info->active_port) + pulse_port_switch_set_active_port (source->priv->pswitch, port); + } + source->priv->pswitch_list = g_list_prepend (NULL, source->priv->pswitch); + + g_debug ("Created port list for source %s", info->name); + } + + pulse_source_update (source, info); + + _mate_mixer_stream_set_default_control (MATE_MIXER_STREAM (source), + MATE_MIXER_STREAM_CONTROL (source->priv->control)); + return source; +} + +gboolean +pulse_source_add_output (PulseSource *source, const pa_source_output_info *info) +{ + PulseSourceOutput *output; + + /* This function is used for both creating and refreshing source outputs */ + output = g_hash_table_lookup (source->priv->outputs, GUINT_TO_POINTER (info->index)); + if (output == NULL) { + const gchar *name; + + output = pulse_source_output_new (source, info); + g_hash_table_insert (source->priv->outputs, + GUINT_TO_POINTER (info->index), + output); + + free_list_controls (source); + + name = mate_mixer_stream_control_get_name (MATE_MIXER_STREAM_CONTROL (output)); + g_signal_emit_by_name (G_OBJECT (source), + "control-added", + name); + return TRUE; + } + + pulse_source_output_update (output, info); + return FALSE; +} + +void +pulse_source_remove_output (PulseSource *source, guint32 index) +{ + PulseSourceOutput *output; + gchar *name; + + output = g_hash_table_lookup (source->priv->outputs, GUINT_TO_POINTER (index)); + if G_UNLIKELY (output == NULL) + return; + + name = g_strdup (mate_mixer_stream_control_get_name (MATE_MIXER_STREAM_CONTROL (output))); + + g_hash_table_remove (source->priv->outputs, GUINT_TO_POINTER (index)); + + free_list_controls (source); + g_signal_emit_by_name (G_OBJECT (source), + "control-removed", + name); + g_free (name); +} + +void +pulse_source_update (PulseSource *source, + const pa_source_info *info) +{ + g_return_if_fail (PULSE_IS_SOURCE (source)); + g_return_if_fail (info != NULL); + + /* The switch doesn't allow being unset, PulseAudio should always include + * the active port name if the are any ports available */ + if (info->active_port != NULL) + pulse_port_switch_set_active_port_by_name (source->priv->pswitch, + info->active_port->name); + + pulse_source_control_update (source->priv->control, info); +} + +static const GList * +pulse_source_list_controls (MateMixerStream *mms) +{ + PulseSource *source; + + g_return_val_if_fail (PULSE_IS_SOURCE (mms), NULL); + + source = PULSE_SOURCE (mms); + + if (source->priv->outputs_list == NULL) { + source->priv->outputs_list = g_hash_table_get_values (source->priv->outputs); + if (source->priv->outputs_list != NULL) + g_list_foreach (source->priv->outputs_list, (GFunc) g_object_ref, NULL); + + source->priv->outputs_list = g_list_prepend (source->priv->outputs_list, + g_object_ref (source->priv->control)); + } + return source->priv->outputs_list; +} + +static const GList * +pulse_source_list_switches (MateMixerStream *mms) +{ + g_return_val_if_fail (PULSE_IS_SOURCE (mms), NULL); + + return PULSE_SOURCE (mms)->priv->pswitch_list; +} + +static void +free_list_controls (PulseSource *source) +{ + if (source->priv->outputs_list == NULL) + return; + + g_list_free_full (source->priv->outputs_list, g_object_unref); + + source->priv->outputs_list = NULL; +} diff --git a/pool/shard008/C/0129965_CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memmove_08.c b/pool/shard008/C/0129965_CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memmove_08.c new file mode 100644 index 0000000000000000000000000000000000000000..ae024ed410917c8082593ec19d74539f3a00b434 --- /dev/null +++ b/pool/shard008/C/0129965_CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memmove_08.c @@ -0,0 +1,146 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memmove_08.c +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE193.label.xml +Template File: sources-sink-08.tmpl.c +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Allocate memory for a string, but do not allocate space for NULL terminator + * GoodSource: Allocate enough memory for a string and the NULL terminator + * Sink: memmove + * BadSink : Copy string to data using memmove() + * Flow Variant: 08 Control flow: if(staticReturnsTrue()) and if(staticReturnsFalse()) + * + * */ + +#include "std_testcase.h" + +#ifndef _WIN32 +#include +#endif + +/* MAINTENANCE NOTE: The length of this string should equal the 10 */ +#define SRC_STRING L"AAAAAAAAAA" + +/* The two function below always return the same value, so a tool + * should be able to identify that calls to the functions will always + * return a fixed value. + */ +static int staticReturnsTrue() +{ + return 1; +} + +static int staticReturnsFalse() +{ + return 0; +} + +#ifndef OMITBAD + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memmove_08_bad() +{ + wchar_t * data; + data = NULL; + if(staticReturnsTrue()) + { + /* FLAW: Did not leave space for a null terminator */ + data = (wchar_t *)malloc(10*sizeof(wchar_t)); + if (data == NULL) {exit(-1);} + } + { + wchar_t source[10+1] = SRC_STRING; + /* Copy length + 1 to include NUL terminator from source */ + /* POTENTIAL FLAW: data may not have enough space to hold source */ + memmove(data, source, (wcslen(source) + 1) * sizeof(wchar_t)); + printWLine(data); + free(data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the staticReturnsTrue() to staticReturnsFalse() */ +static void goodG2B1() +{ + wchar_t * data; + data = NULL; + if(staticReturnsFalse()) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Allocate space for a null terminator */ + data = (wchar_t *)malloc((10+1)*sizeof(wchar_t)); + if (data == NULL) {exit(-1);} + } + { + wchar_t source[10+1] = SRC_STRING; + /* Copy length + 1 to include NUL terminator from source */ + /* POTENTIAL FLAW: data may not have enough space to hold source */ + memmove(data, source, (wcslen(source) + 1) * sizeof(wchar_t)); + printWLine(data); + free(data); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + wchar_t * data; + data = NULL; + if(staticReturnsTrue()) + { + /* FIX: Allocate space for a null terminator */ + data = (wchar_t *)malloc((10+1)*sizeof(wchar_t)); + if (data == NULL) {exit(-1);} + } + { + wchar_t source[10+1] = SRC_STRING; + /* Copy length + 1 to include NUL terminator from source */ + /* POTENTIAL FLAW: data may not have enough space to hold source */ + memmove(data, source, (wcslen(source) + 1) * sizeof(wchar_t)); + printWLine(data); + free(data); + } +} + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memmove_08_good() +{ + goodG2B1(); + goodG2B2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memmove_08_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memmove_08_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard008/C/0129966_math-posting.c b/pool/shard008/C/0129966_math-posting.c new file mode 100644 index 0000000000000000000000000000000000000000..33dbdaf5dea27f349912d1341f2ef4632d3c24cd --- /dev/null +++ b/pool/shard008/C/0129966_math-posting.c @@ -0,0 +1,241 @@ +#include +#include +#include +#include "head.h" + +#define DISK_RD_BUF_BYTES (DISK_BLCK_SIZE * DISK_RD_BLOCKS) + +#define DISK_RD_BUF_ITEMS \ + (DISK_RD_BUF_BYTES / sizeof(struct math_posting_item)) + +#define DISK_RD_BUF_RMNDR \ + (DISK_RD_BUF_BYTES % sizeof(struct math_posting_item)) + +struct _math_posting { + struct subpath_ele *ele; + const char *fullpath; + FILE *fh_posting; + FILE *fh_pathinfo; + + /* read buffer */ + uint32_t buf_idx, buf_end; + struct math_posting_item buf[DISK_RD_BUF_ITEMS]; +}; + +static void print_cur_post_buf(struct _math_posting *po) +{ + uint32_t i; + struct math_posting_item *item; + printf("buf (idx=%u, end=%u): ", po->buf_idx, po->buf_end); + for (i = 0; i < po->buf_end; i++) { + item = po->buf + po->buf_idx; + printf("[%u]", i); + if (i == po->buf_idx) + printf("{doc%u,exp%u} ", item->doc_id, item->exp_id); + else + printf("(doc%u,exp%u) ", item->doc_id, item->exp_id); + } + printf("\n"); +} + +math_posting_t +math_posting_new_reader(struct subpath_ele *ele, const char *fullpath) +{ + struct _math_posting *po = + malloc(sizeof(struct _math_posting)); + + po->ele = ele; + po->fullpath = fullpath; + po->fh_posting = NULL; + po->fh_pathinfo = NULL; + po->buf_idx = 0; + po->buf_end = 0; + +#ifdef DEBUG_MATH_POSTING + printf("posting item size: %lu bytes.\n", + sizeof(struct math_posting_item)); + printf("DISK_RD_BUF_BYTES: %u\n", DISK_RD_BUF_BYTES); + printf("sizeof(math posting item): %lu\n", + sizeof(struct math_posting_item)); +#endif + + /* before compression is implemented, our posting item + * structure is a factor of DISK_BLCK_SIZE */ + assert(DISK_RD_BUF_RMNDR == 0); + + return po; +} + +struct subpath_ele *math_posting_get_ele(math_posting_t po_) +{ + struct _math_posting *po = (struct _math_posting*)po_; + return po->ele; +} + +const char *math_posting_get_pathstr(math_posting_t po_) +{ + struct _math_posting *po = (struct _math_posting*)po_; + return po->fullpath; +} + +void math_posting_free_reader(math_posting_t po_) +{ + free(po_); +} + +void math_posting_finish(math_posting_t po_) +{ + struct _math_posting *po = (struct _math_posting*)po_; + + if (po->fh_posting) + fclose(po->fh_posting); + + if (po->fh_pathinfo) + fclose(po->fh_pathinfo); +} + +static __inline size_t +rebuf(void *buf, FILE *fh, uint32_t *idx, uint32_t *end) +{ + size_t nread = fread(buf, sizeof(struct math_posting_item), + DISK_RD_BUF_ITEMS, fh); + *idx = 0; + *end = nread; + return nread; +} + +bool math_posting_start(math_posting_t po_) +{ + struct _math_posting *po = (struct _math_posting*)po_; + + char file_path[MAX_DIR_PATH_NAME_LEN]; + + sprintf(file_path, "%s/" MATH_POSTING_FNAME, po->fullpath); + po->fh_posting = fopen(file_path, "r"); + + sprintf(file_path, "%s/" PATH_INFO_FNAME, po->fullpath); + po->fh_pathinfo = fopen(file_path, "r"); + + if (NULL == po->fh_posting || NULL == po->fh_pathinfo) + return 0; + + /* start function is required to read the first item */ + rebuf(po->buf, po->fh_posting, &po->buf_idx, &po->buf_end); + + return 1; +} + +bool math_posting_next(math_posting_t po_) +{ + struct _math_posting *po = (struct _math_posting*)po_; + + po->buf_idx ++; /* one step forward */ + + do { + if (po->buf_idx < po->buf_end) + /* still in the buffer */ + return 1; + else + /* need one read to tell whether or not I can go further */ + rebuf(po->buf, po->fh_posting, &po->buf_idx, &po->buf_end); + + } while (po->buf_end != 0); + + /* buf_end equals zero: reached the end. */ + return 0; +} + +bool math_posting_jump(math_posting_t po_, uint64_t target) +{ + uint32_t rightmost; /* right most of the buffer */ + uint64_t *id64; + struct _math_posting *po = (struct _math_posting*)po_; + + do { + rightmost = po->buf_end - 1; + id64 = (uint64_t*)(po->buf + rightmost); + + if (po->buf_end == 0) { + return 0; /* no more to read, failed at finding target */ + } else if (target <= *id64) { + /* find that target is in this buffer */ + break; + } else if (po->buf_end != DISK_RD_BUF_ITEMS) { + /* cannot read again, we have examined entire file. */ + return 0; /* failed at finding target */ + } + + /* read into buffer */ + rebuf(po->buf, po->fh_posting, &po->buf_idx, &po->buf_end); + } while (1); + + /* go through the buffer to find the target */ + while (po->buf_idx < po->buf_end) { + id64 = (uint64_t*)(po->buf + po->buf_idx); + + if (*id64 < target) + po->buf_idx ++; /* step forward */ + else + break; /* we find an ID >= target */ + } + + return 1; +} + +struct math_posting_item* math_posting_current(math_posting_t po_) +{ + struct _math_posting *po = (struct _math_posting*)po_; + struct math_posting_item *item = po->buf + po->buf_idx; + // printf("math disk-item docID: %u\n", item->doc_id); + return item; +} + +struct math_pathinfo_pack* +math_posting_pathinfo(math_posting_t po_, uint32_t position) +{ + pathinfo_num_t i; + struct _math_posting *po = (struct _math_posting*)po_; + +#pragma pack(push, 1) + static struct { + struct math_pathinfo_pack head; + struct math_pathinfo info_arr[MAX_MATH_PATHS]; + } ret; +#pragma pack(pop) + + /* first go the specified file & position */ + if (-1 == fseek(po->fh_pathinfo, position, SEEK_SET)) + return NULL; + + if (1 == fread(&ret.head, sizeof(struct math_pathinfo_pack), + 1, po->fh_pathinfo)) { + + /* now, read all the path info items */ + for (i = 0; i < ret.head.n_paths; i++) { + if (1 != fread(ret.info_arr + i, sizeof(struct math_pathinfo), + 1, po->fh_pathinfo)) + return NULL; + } + } + + return (struct math_pathinfo_pack*)&ret; +} + +void math_posting_print_info(math_posting_t po_) +{ + uint32_t i; + struct subpath *sp; + const char *fullpath; + struct subpath_ele *ele; + + fullpath = math_posting_get_pathstr(po_); + ele = math_posting_get_ele(po_); + + printf("@%s ", fullpath); + printf("(duplicates: "); + for (i = 0; i <= ele->dup_cnt; i++) { + sp = ele->dup[i]; + printf("path#%u ", sp->path_id); + } + printf(")"); +} diff --git a/pool/shard008/C/0129968_config.c b/pool/shard008/C/0129968_config.c new file mode 100644 index 0000000000000000000000000000000000000000..15fec51734c4c9e83259cec2026e1385f1fa9f4f --- /dev/null +++ b/pool/shard008/C/0129968_config.c @@ -0,0 +1,197 @@ +#include +#include +#include +#include +#include +#include + +#include "spotifyd.h" +#include "config.h" +#include "helpers.h" + +char *socket_path = NULL; +char *username = NULL; +char *password = NULL; +char *port = NULL; +FILE *logfile = NULL; + +/* + * We only want to get these values + * once so they are set to NULL. The + * caller frees them. + */ + +char *get_socket_path() +{ + char *tmp = socket_path; + socket_path = NULL; + return tmp; +} + +char *get_port() +{ + char *tmp = port; + port = NULL; + return tmp; +} + +char *get_username() +{ + char *tmp = username; + username = NULL; + return tmp; +} + +char *get_password() +{ + char *tmp = password; + password = NULL; + return tmp; +} + +/* + * The following methods can be called multiple times. + */ + +FILE *get_logfile() +{ + return logfile; +} + + +bool have_port() +{ + return port != NULL; +} + +bool have_socket_path() +{ + return socket_path != NULL; +} + +char *trim_whitespace_front(char *str) +{ + /* + * remove leading whitespace. + */ + while(isspace(*str)) ++str; + return str; +} + +char *trim_whitespace_back(char *str) +{ + char *end = str + strlen(str) - 1; + while(isspace(*end)) --end; + *(end + 1) = '\0'; + + return str; +} + +char *trim_whitespace(char *str) +{ + return trim_whitespace_back(trim_whitespace_front(str)); +} + +bool read_config() +{ + char *config_file = malloc(sizeof(char) * (strlen(getenv("HOME")) + strlen("/.spotifyd.rc") + 1)); + if(config_file == NULL) + { + LOG_PRINT("Can't allocate memory. Quitting.\n"); + exit(1); + } + strcat(config_file, getenv("HOME")); + strcat(config_file, "/.spotifyd.rc"); + FILE *fp = fopen(config_file, "r"); + free(config_file); + char *line = NULL; + size_t n = 0; + + while(fp != NULL && -1 != getline(&line, &n, fp)) + { + if(!strncasecmp(line, "username", strlen("username"))) + { + char *tmp = trim_whitespace(line + strlen("username")); + username = malloc(sizeof(char) * (strlen(tmp) + 1)); + if(username == NULL) + { + LOG_PRINT("Can't allocate memory. Quitting.\n"); + exit(1); + } + strcpy(username, tmp); + } + else if(!strncasecmp(line, "password", strlen("password"))) + { + char *tmp = trim_whitespace(line + strlen("password")); + password = malloc(sizeof(char) * (strlen(tmp) + 1)); + if(password == NULL) + { + LOG_PRINT("Can't allocate memory. Quitting.\n"); + exit(1); + } + strcpy(password, tmp); + } + else if(!strncasecmp(line, "unix-socket", strlen("unix-socket"))) + { + char *tmp = trim_whitespace(line + strlen("unix-socket")); + socket_path = malloc(sizeof(char) * (strlen(tmp) + 1)); + if(socket_path == NULL) + { + LOG_PRINT("Can't allocate memory. Quitting.\n"); + exit(1); + } + strcpy(socket_path, tmp); + } + else if(!strncasecmp(line, "port", strlen("port"))) + { + char *tmp = trim_whitespace(line + strlen("port")); + port = malloc(sizeof(char) * (strlen(tmp) + 1)); + if(port == NULL) + { + LOG_PRINT("Can't allocate memory. Quitting.\n"); + exit(1); + } + strcpy(port, tmp); + } + else if(!strncasecmp(line, "log", strlen("log"))) + { + char *tmp = trim_whitespace(line + strlen("log")); + logfile = fopen(tmp, "w"); + } + free(line); + n = 0; + } + if(username == NULL && password != NULL) + { + LOG_PRINT("Couldn't read username.\n"); + exit(-1); + } + else if(username == NULL && password == NULL) + { + n = 0; + LOG_PRINT("Username: "); + if(getline(&username, &n, stdin) == -1) + { + LOG_PRINT("Couldn't read line.\n"); + exit(-1); + } + else + { + username = trim_whitespace_back(username); + } + if((password = getpass("Password: ")) == NULL) + { + LOG_PRINT("Couldn't password.\n"); + exit(-1); + } + } + else if(username != NULL && password == NULL) + { + if((password = getpass("Password: ")) == NULL) + { + LOG_PRINT("Couldn't password.\n"); + exit(-1); + } + } + return 1; +} diff --git a/pool/shard008/C/0129970_mptable.c b/pool/shard008/C/0129970_mptable.c new file mode 100644 index 0000000000000000000000000000000000000000..4e481f51b66cd4e45cd972298dbf0c33c1d5238c --- /dev/null +++ b/pool/shard008/C/0129970_mptable.c @@ -0,0 +1,164 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2012 Advanced Micro Devices, Inc. + * + * 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; version 2 of the License. + * + * 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 St, Fifth Floor, Boston, MA 02110-1301 USA + */ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void *smp_write_config_table(void *v) +{ + struct mp_config_table *mc; + int bus_isa; + u32 apicid_sb700; + u32 apicid_rd890; + device_t dev; + u32 dword; + + mc = (void *)(((char *)v) + SMP_FLOATING_TABLE_LEN); + mptable_init(mc, LOCAL_APIC_ADDR); + + smp_write_processors(mc); + mptable_write_buses(mc, NULL, &bus_isa); + + /* + * AGESA v5 Apply apic enumeration rules + * For systems with >= 16 APICs, put the IO-APICs at 0..n and + * put the local-APICs at m..z + * For systems with < 16 APICs, put the Local-APICs at 0..n and + * put the IO-APICs at (n + 1)..z + */ + if (CONFIG_MAX_CPUS >= 16) + apicid_sb700 = 0x0; + else + apicid_sb700 = CONFIG_MAX_CPUS + 1; + apicid_rd890 = apicid_sb700 + 1; + + dev = dev_find_slot(0, PCI_DEVFN(0x14, 0)); + if (dev) { + /* Set sb700 IOAPIC ID */ + dword = pci_read_config32(dev, 0x74) & 0xfffffff0; + smp_write_ioapic(mc, apicid_sb700, 0x20, dword); + + /* + * 00:12.0: PROG SATA : INT F + * 00:13.0: INTA USB_0 + * 00:13.1: INTB USB_1 + * 00:13.2: INTC USB_2 + * 00:13.3: INTD USB_3 + * 00:13.4: INTC USB_4 + * 00:13.5: INTD USB2 + * 00:14.1: INTA IDE + * 00:14.2: Prog HDA : INT E + * 00:14.5: INTB ACI + * 00:14.6: INTB MCI + */ + + /* Set RS5650 IOAPIC ID */ + dev = dev_find_slot(0, PCI_DEVFN(0, 0)); + if (dev) { + pci_write_config32(dev, 0xF8, 0x1); + dword = pci_read_config32(dev, 0xFC) & 0xfffffff0; + smp_write_ioapic(mc, apicid_rd890, 0x20, dword); + } + + } + + /* I/O Ints: Type Polarity Trigger Bus ID IRQ APIC ID PIN# */ +#define IO_LOCAL_INT(type, intr, apicid, pin) \ + smp_write_lintsrc(mc, (type), MP_IRQ_TRIGGER_EDGE | MP_IRQ_POLARITY_HIGH, bus_isa, (intr), (apicid), (pin)); + + mptable_add_isa_interrupts(mc, bus_isa, apicid_sb700, 0); + + /* PCI interrupts are level triggered, and are + * associated with a specific bus/device/function tuple. + */ +#define PCI_INT(bus, dev, int_sign, pin) \ + smp_write_intsrc(mc, mp_INT, MP_IRQ_TRIGGER_LEVEL|MP_IRQ_POLARITY_LOW, (bus), (((dev)<<2)|(int_sign)), apicid_sb700, (pin)) + + /* SMBUS */ + //PCI_INT(0x0, 0x14, 0x0, 0x10); //not generate interrupt, 3Ch hardcoded to 0 + + /* HD Audio */ + PCI_INT(0x0, 0x14, 0x2, 0x10); + + /* USB */ + /* OHCI0, OHCI1 hard-wired to 01h, corresponding to using INTA# */ + /* EHCI hard-wired to 02h, corresponding to using INTB# */ + /* USB1 */ + PCI_INT(0x0, 0x12, 0x0, 0x10); /* OHCI0 Port 0~2 */ + PCI_INT(0x0, 0x12, 0x1, 0x10); /* OHCI1 Port 3~5 */ + PCI_INT(0x0, 0x12, 0x2, 0x11); /* EHCI Port 0~5 */ + + /* USB2 */ + PCI_INT(0x0, 0x13, 0x0, 0x10); /* OHCI0 Port 6~8 */ + PCI_INT(0x0, 0x13, 0x1, 0x10); /* OHCI1 Port 9~11 */ + PCI_INT(0x0, 0x13, 0x2, 0x11); /* EHCI Port 6~11 */ + + /* USB3 EHCI hard-wired to 03h, corresponding to using INTC# */ + PCI_INT(0x0, 0x14, 0x5, 0x12); /* OHCI0 Port 12~13 */ + + /* SATA */ + PCI_INT(0x0, 0x11, 0x0, 0x16); //6, INTG + + /* PCI slots */ + dev = dev_find_slot(0, PCI_DEVFN(0x14, 4)); + if (dev && dev->enabled) { + u8 bus_pci = dev->link_list->secondary; + + /* PCI_SLOT 0. */ + PCI_INT(bus_pci, 0x5, 0x0, 0x14); + PCI_INT(bus_pci, 0x5, 0x1, 0x15); + PCI_INT(bus_pci, 0x5, 0x2, 0x16); + PCI_INT(bus_pci, 0x5, 0x3, 0x17); + + /* PCI_SLOT 1. */ + PCI_INT(bus_pci, 0x6, 0x0, 0x15); + PCI_INT(bus_pci, 0x6, 0x1, 0x16); + PCI_INT(bus_pci, 0x6, 0x2, 0x17); + PCI_INT(bus_pci, 0x6, 0x3, 0x14); + + /* PCI_SLOT 2. */ + PCI_INT(bus_pci, 0x7, 0x0, 0x16); + PCI_INT(bus_pci, 0x7, 0x1, 0x17); + PCI_INT(bus_pci, 0x7, 0x2, 0x14); + PCI_INT(bus_pci, 0x7, 0x3, 0x15); + } + + /*Local Ints: Type Polarity Trigger Bus ID IRQ APIC ID PIN# */ + IO_LOCAL_INT(mp_ExtINT, 0, MP_APIC_ALL, 0x0); + IO_LOCAL_INT(mp_NMI, 0, MP_APIC_ALL, 0x1); + /* There is no extension information... */ + + /* Compute the checksums */ + return mptable_finalize(mc); +} + +unsigned long write_smp_table(unsigned long addr) +{ + void *v; + v = smp_write_floating_table(addr, 0); + return (unsigned long)smp_write_config_table(v); +} diff --git a/pool/shard008/C/0129972_autcpu12.c b/pool/shard008/C/0129972_autcpu12.c new file mode 100644 index 0000000000000000000000000000000000000000..459d69ce0bf418c5aaabe46fbbcac29cd4451263 --- /dev/null +++ b/pool/shard008/C/0129972_autcpu12.c @@ -0,0 +1,255 @@ +/* + * drivers/mtd/autcpu12.c + * + * Copyright (c) 2002 Thomas Gleixner + * + * Derived from drivers/mtd/spia.c + * Copyright (C) 2000 Steven J. Hill (sjhill@realitydiluted.com) + * + * $Id: autcpu12.c,v 1.13 2003/07/11 15:12:29 dwmw2 Exp $ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * Overview: + * This is a device driver for the NAND flash device found on the + * autronix autcpu12 board, which is a SmartMediaCard. It supports + * 16MB, 32MB and 64MB cards. + * + * + * 02-12-2002 TG Cleanup of module params + * + * 02-20-2002 TG adjusted for different rd/wr adress support + * added support for read device ready/busy line + * added page_cache + * + * 10-06-2002 TG 128K card support added + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * MTD structure for AUTCPU12 board + */ +static struct mtd_info *autcpu12_mtd = NULL; + +/* + * Module stuff + */ +#if LINUX_VERSION_CODE < 0x20212 && defined(MODULE) +#define autcpu12_init init_module +#define autcpu12_cleanup cleanup_module +#endif + +static int autcpu12_io_base = CS89712_VIRT_BASE; +static int autcpu12_fio_pbase = AUTCPU12_PHYS_SMC; +static int autcpu12_fio_ctrl = AUTCPU12_SMC_SELECT_OFFSET; +static int autcpu12_pedr = AUTCPU12_SMC_PORT_OFFSET; +static int autcpu12_fio_base; + +#ifdef MODULE +MODULE_PARM(autcpu12_fio_pbase, "i"); +MODULE_PARM(autcpu12_fio_ctrl, "i"); +MODULE_PARM(autcpu12_pedr, "i"); + +__setup("autcpu12_fio_pbase=",autcpu12_fio_pbase); +__setup("autcpu12_fio_ctrl=",autcpu12_fio_ctrl); +__setup("autcpu12_pedr=",autcpu12_pedr); +#endif + +/* + * Define partitions for flash devices + */ +extern struct nand_oobinfo jffs2_oobinfo; + +static struct mtd_partition partition_info16k[] = { + { name: "AUTCPU12 flash partition 1", + offset: 0, + size: 8 * SZ_1M }, + { name: "AUTCPU12 flash partition 2", + offset: 8 * SZ_1M, + size: 8 * SZ_1M }, +}; + +static struct mtd_partition partition_info32k[] = { + { name: "AUTCPU12 flash partition 1", + offset: 0, + size: 8 * SZ_1M }, + { name: "AUTCPU12 flash partition 2", + offset: 8 * SZ_1M, + size: 24 * SZ_1M }, +}; + +static struct mtd_partition partition_info64k[] = { + { name: "AUTCPU12 flash partition 1", + offset: 0, + size: 16 * SZ_1M }, + { name: "AUTCPU12 flash partition 2", + offset: 16 * SZ_1M, + size: 48 * SZ_1M }, +}; + +static struct mtd_partition partition_info128k[] = { + { name: "AUTCPU12 flash partition 1", + offset: 0, + size: 16 * SZ_1M }, + { name: "AUTCPU12 flash partition 2", + offset: 16 * SZ_1M, + size: 112 * SZ_1M }, +}; + +#define NUM_PARTITIONS16K 2 +#define NUM_PARTITIONS32K 2 +#define NUM_PARTITIONS64K 2 +#define NUM_PARTITIONS128K 2 +/* + * hardware specific access to control-lines +*/ +static void autcpu12_hwcontrol(struct mtd_info *mtd, int cmd) +{ + + switch(cmd){ + + case NAND_CTL_SETCLE: (*(volatile unsigned char *) (autcpu12_io_base + autcpu12_pedr)) |= AUTCPU12_SMC_CLE; break; + case NAND_CTL_CLRCLE: (*(volatile unsigned char *) (autcpu12_io_base + autcpu12_pedr)) &= ~AUTCPU12_SMC_CLE; break; + + case NAND_CTL_SETALE: (*(volatile unsigned char *) (autcpu12_io_base + autcpu12_pedr)) |= AUTCPU12_SMC_ALE; break; + case NAND_CTL_CLRALE: (*(volatile unsigned char *) (autcpu12_io_base + autcpu12_pedr)) &= ~AUTCPU12_SMC_ALE; break; + + case NAND_CTL_SETNCE: (*(volatile unsigned char *) (autcpu12_fio_base + autcpu12_fio_ctrl)) = 0x01; break; + case NAND_CTL_CLRNCE: (*(volatile unsigned char *) (autcpu12_fio_base + autcpu12_fio_ctrl)) = 0x00; break; + } +} + +/* +* read device ready pin +*/ +int autcpu12_device_ready(struct mtd_info *mtd) +{ + + return ( (*(volatile unsigned char *) (autcpu12_io_base + autcpu12_pedr)) & AUTCPU12_SMC_RDY) ? 1 : 0; + +} +/* + * Main initialization routine + */ +int __init autcpu12_init (void) +{ + struct nand_chip *this; + int err = 0; + + /* Allocate memory for MTD device structure and private data */ + autcpu12_mtd = kmalloc (sizeof(struct mtd_info) + sizeof (struct nand_chip), + GFP_KERNEL); + if (!autcpu12_mtd) { + printk ("Unable to allocate AUTCPU12 NAND MTD device structure.\n"); + err = -ENOMEM; + goto out; + } + + /* map physical adress */ + autcpu12_fio_base=(unsigned long)ioremap(autcpu12_fio_pbase,SZ_1K); + if(!autcpu12_fio_base){ + printk("Ioremap autcpu12 SmartMedia Card failed\n"); + err = -EIO; + goto out_mtd; + } + + /* Get pointer to private data */ + this = (struct nand_chip *) (&autcpu12_mtd[1]); + + /* Initialize structures */ + memset((char *) autcpu12_mtd, 0, sizeof(struct mtd_info)); + memset((char *) this, 0, sizeof(struct nand_chip)); + + /* Link the private data with the MTD structure */ + autcpu12_mtd->priv = this; + + /* Set address of NAND IO lines */ + this->IO_ADDR_R = autcpu12_fio_base; + this->IO_ADDR_W = autcpu12_fio_base; + this->hwcontrol = autcpu12_hwcontrol; + this->dev_ready = autcpu12_device_ready; + /* 20 us command delay time */ + this->chip_delay = 20; + this->eccmode = NAND_ECC_SOFT; + + /* Scan to find existance of the device */ + if (nand_scan (autcpu12_mtd, 1)) { + err = -ENXIO; + goto out_ior; + } + + /* Allocate memory for internal data buffer */ + this->data_buf = kmalloc (sizeof(u_char) * (autcpu12_mtd->oobblock + autcpu12_mtd->oobsize), GFP_KERNEL); + if (!this->data_buf) { + printk ("Unable to allocate NAND data buffer for AUTCPU12.\n"); + err = -ENOMEM; + goto out_ior; + } + + /* Register the partitions */ + switch(autcpu12_mtd->size){ + case SZ_16M: add_mtd_partitions(autcpu12_mtd, partition_info16k, NUM_PARTITIONS16K); break; + case SZ_32M: add_mtd_partitions(autcpu12_mtd, partition_info32k, NUM_PARTITIONS32K); break; + case SZ_64M: add_mtd_partitions(autcpu12_mtd, partition_info64k, NUM_PARTITIONS64K); break; + case SZ_128M: add_mtd_partitions(autcpu12_mtd, partition_info128k, NUM_PARTITIONS128K); break; + default: { + printk ("Unsupported SmartMedia device\n"); + err = -ENXIO; + goto out_buf; + } + } + goto out; + +out_buf: + kfree (this->data_buf); +out_ior: + iounmap((void *)autcpu12_fio_base); +out_mtd: + kfree (autcpu12_mtd); +out: + return err; +} + +module_init(autcpu12_init); + +/* + * Clean up routine + */ +#ifdef MODULE +static void __exit autcpu12_cleanup (void) +{ + struct nand_chip *this = (struct nand_chip *) &autcpu12_mtd[1]; + + /* Unregister partitions */ + del_mtd_partitions(autcpu12_mtd); + + /* Unregister the device */ + del_mtd_device (autcpu12_mtd); + + /* Free internal data buffers */ + kfree (this->data_buf); + + /* unmap physical adress */ + iounmap((void *)autcpu12_fio_base); + + /* Free the MTD device structure */ + kfree (autcpu12_mtd); +} +module_exit(autcpu12_cleanup); +#endif + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Thomas Gleixner "); +MODULE_DESCRIPTION("Glue layer for SmartMediaCard on autronix autcpu12"); diff --git a/pool/shard008/C/0129973_helloneon.c b/pool/shard008/C/0129973_helloneon.c new file mode 100644 index 0000000000000000000000000000000000000000..c6551b48659965e5566037cadf0e5ce26f8fbd92 --- /dev/null +++ b/pool/shard008/C/0129973_helloneon.c @@ -0,0 +1,174 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * 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. + * + */ +#include +#include +#include +#include +#include + +#include +#include "helloneon-intrinsics.h" + +#define DEBUG 0 + +#if DEBUG +#include +# define D(x...) __android_log_print(ANDROID_LOG_INFO,"helloneon",x) +#else +# define D(...) do {} while (0) +#endif + +/* return current time in milliseconds */ +static double +now_ms(void) +{ + struct timespec res; + clock_gettime(CLOCK_REALTIME, &res); + return 1000.0*res.tv_sec + (double)res.tv_nsec/1e6; +} + + +/* this is a FIR filter implemented in C */ +static void +fir_filter_c(short *output, const short* input, const short* kernel, int width, int kernelSize) +{ + int offset = -kernelSize/2; + int nn; + for (nn = 0; nn < width; nn++) { + int sum = 0; + int mm; + for (mm = 0; mm < kernelSize; mm++) { + sum += kernel[mm]*input[nn+offset+mm]; + } + output[nn] = (short)((sum + 0x8000) >> 16); + } +} + +#define FIR_KERNEL_SIZE 32 +#define FIR_OUTPUT_SIZE 2560 +#define FIR_INPUT_SIZE (FIR_OUTPUT_SIZE + FIR_KERNEL_SIZE) +#define FIR_ITERATIONS 600 + +static const short fir_kernel[FIR_KERNEL_SIZE] = { + 0x10, 0x20, 0x40, 0x70, 0x8c, 0xa2, 0xce, 0xf0, 0xe9, 0xce, 0xa2, 0x8c, 070, 0x40, 0x20, 0x10, + 0x10, 0x20, 0x40, 0x70, 0x8c, 0xa2, 0xce, 0xf0, 0xe9, 0xce, 0xa2, 0x8c, 070, 0x40, 0x20, 0x10 }; + +static short fir_output[FIR_OUTPUT_SIZE]; +static short fir_input_0[FIR_INPUT_SIZE]; +static const short* fir_input = fir_input_0 + (FIR_KERNEL_SIZE/2); +static short fir_output_expected[FIR_OUTPUT_SIZE]; + +/* This is a trivial JNI example where we use a native method + * to return a new VM String. See the corresponding Java source + * file located at: + * + * apps/samples/hello-neon/project/src/com/example/neon/HelloNeon.java + */ +jstring +Java_com_example_helloneon_HelloNeon_stringFromJNI( JNIEnv* env, + jobject thiz ) +{ + char* str; + AndroidCpuFamily family; + uint64_t features; + char buffer[512]; + char tryNeon = 0; + double t0, t1, time_c, time_neon; + + /* setup FIR input - whatever */ + { + int nn; + for (nn = 0; nn < FIR_INPUT_SIZE; nn++) { + fir_input_0[nn] = (5*nn) & 255; + } + fir_filter_c(fir_output_expected, fir_input, fir_kernel, FIR_OUTPUT_SIZE, FIR_KERNEL_SIZE); + } + + /* Benchmark small FIR filter loop - C version */ + t0 = now_ms(); + { + int count = FIR_ITERATIONS; + for (; count > 0; count--) { + fir_filter_c(fir_output, fir_input, fir_kernel, FIR_OUTPUT_SIZE, FIR_KERNEL_SIZE); + } + } + t1 = now_ms(); + time_c = t1 - t0; + + asprintf(&str, "FIR Filter benchmark:\nC version : %g ms\n", time_c); + strlcpy(buffer, str, sizeof buffer); + free(str); + + strlcat(buffer, "Neon version : ", sizeof buffer); + + family = android_getCpuFamily(); + if ((family != ANDROID_CPU_FAMILY_ARM) && + (family != ANDROID_CPU_FAMILY_X86)) + { + strlcat(buffer, "Not an ARM and not an X86 CPU !\n", sizeof buffer); + goto EXIT; + } + + features = android_getCpuFeatures(); + if (((features & ANDROID_CPU_ARM_FEATURE_ARMv7) == 0) && + ((features & ANDROID_CPU_X86_FEATURE_SSSE3) == 0)) + { + strlcat(buffer, "Not an ARMv7 and not an X86 SSSE3 CPU !\n", sizeof buffer); + goto EXIT; + } + + /* HAVE_NEON is defined in CMakeLists.txt ! */ +#ifdef HAVE_NEON + if (((features & ANDROID_CPU_ARM_FEATURE_NEON) == 0) && + ((features & ANDROID_CPU_X86_FEATURE_SSSE3) == 0)) + { + strlcat(buffer, "CPU doesn't support NEON !\n", sizeof buffer); + goto EXIT; + } + + /* Benchmark small FIR filter loop - Neon version */ + t0 = now_ms(); + { + int count = FIR_ITERATIONS; + for (; count > 0; count--) { + fir_filter_neon_intrinsics(fir_output, fir_input, fir_kernel, FIR_OUTPUT_SIZE, FIR_KERNEL_SIZE); + } + } + t1 = now_ms(); + time_neon = t1 - t0; + asprintf(&str, "%g ms (x%g faster)\n", time_neon, time_c / (time_neon < 1e-6 ? 1. : time_neon)); + strlcat(buffer, str, sizeof buffer); + free(str); + + /* check the result, just in case */ + { + int nn, fails = 0; + for (nn = 0; nn < FIR_OUTPUT_SIZE; nn++) { + if (fir_output[nn] != fir_output_expected[nn]) { + if (++fails < 16) + D("neon[%d] = %d expected %d", nn, fir_output[nn], fir_output_expected[nn]); + } + } + D("%d fails\n", fails); + } +#else /* !HAVE_NEON */ + strlcat(buffer, "Program not compiled with ARMv7 support !\n", sizeof buffer); +#endif /* !HAVE_NEON */ +EXIT: + D("%s", buffer); + return (*env)->NewStringUTF(env, buffer); +} diff --git a/pool/shard008/C/0129974_test-getcwd-lgpl.c b/pool/shard008/C/0129974_test-getcwd-lgpl.c new file mode 100644 index 0000000000000000000000000000000000000000..56abcc2abc733de00b35706fa543cc663d0c12cf --- /dev/null +++ b/pool/shard008/C/0129974_test-getcwd-lgpl.c @@ -0,0 +1,102 @@ +/* Test of getcwd() function. + Copyright (C) 2009-2019 Free Software Foundation, Inc. + + 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 . */ + +#include + +#include + +#include "signature.h" +SIGNATURE_CHECK (getcwd, char *, (char *, size_t)); + +#include +#include +#include +#include + +#include "macros.h" + +int +main (int argc, char **argv) +{ + char *pwd1; + char *pwd2; + /* If the user provides an argument, attempt to chdir there first. */ + if (1 < argc) + { + if (chdir (argv[1]) == 0) + printf ("changed to directory %s\n", argv[1]); + } + + pwd1 = getcwd (NULL, 0); + ASSERT (pwd1 && *pwd1); + if (1 < argc) + printf ("cwd=%s\n", pwd1); + + /* Make sure the result is usable. */ + ASSERT (chdir (pwd1) == 0); + ASSERT (chdir (".//./.") == 0); + + /* Make sure that result is normalized. */ + pwd2 = getcwd (NULL, 0); + ASSERT (pwd2); + ASSERT (strcmp (pwd1, pwd2) == 0); + free (pwd2); + { + size_t len = strlen (pwd1); + ssize_t i = len - 10; + if (i < 1) + i = 1; + pwd2 = getcwd (NULL, len + 1); + ASSERT (pwd2); + free (pwd2); + pwd2 = malloc (len + 2); + for ( ; i <= len; i++) + { + char *tmp; + errno = 0; + ASSERT (getcwd (pwd2, i) == NULL); + ASSERT (errno == ERANGE); + /* Allow either glibc or BSD behavior, since POSIX allows both. */ + errno = 0; + tmp = getcwd (NULL, i); + if (tmp) + { + ASSERT (strcmp (pwd1, tmp) == 0); + free (tmp); + } + else + { + ASSERT (errno == ERANGE); + } + } + ASSERT (getcwd (pwd2, len + 1) == pwd2); + pwd2[len] = '/'; + pwd2[len + 1] = '\0'; + } + ASSERT (strstr (pwd2, "/./") == NULL); + ASSERT (strstr (pwd2, "/../") == NULL); + ASSERT (strstr (pwd2 + 1 + (pwd2[1] == '/'), "//") == NULL); + + /* Validate a POSIX requirement on size. */ + errno = 0; + ASSERT (getcwd(pwd2, 0) == NULL); + ASSERT (errno == EINVAL); + + free (pwd1); + free (pwd2); + + return 0; +} diff --git a/pool/shard008/C/0129975_metime.c b/pool/shard008/C/0129975_metime.c new file mode 100644 index 0000000000000000000000000000000000000000..ec7532a79f437ce3ddc8a2a5baf7b27ad5ffe938 --- /dev/null +++ b/pool/shard008/C/0129975_metime.c @@ -0,0 +1,95 @@ +/* + metime.c + + by Michael J. Fromberger + Copyright (C) 2000 Michael J. Fromberger, All Rights Reserved. + + Modular exponentiation timing test + + $Id: metime.c,v 1.1 2004/02/08 04:28:32 sting Exp $ + */ + +#include +#include +#include +#include +#include + +#include "mpi.h" +#include "mpprime.h" + +double clk_to_sec(clock_t start, clock_t stop); + +int main(int argc, char *argv[]) +{ + int ix, num, prec = 8; + unsigned int seed; + clock_t start, stop; + double sec; + + mp_int a, m, c; + + if(getenv("SEED") != NULL) + seed = abs(atoi(getenv("SEED"))); + else + seed = (unsigned int)time(NULL); + + if(argc < 2) { + fprintf(stderr, "Usage: %s []\n", argv[0]); + return 1; + } + + if((num = atoi(argv[1])) < 0) + num = -num; + + if(!num) { + fprintf(stderr, "%s: must perform at least 1 test\n", argv[0]); + return 1; + } + + if(argc > 2) { + if((prec = atoi(argv[2])) <= 0) + prec = 8; + else + prec = (prec + (MP_DIGIT_BIT - 1)) / MP_DIGIT_BIT; + + } + + printf("Modular exponentiation timing test\n" + "Precision: %d digits (%d bits)\n" + "# of tests: %d\n\n", prec, (int)(prec * MP_DIGIT_BIT), num); + + mp_init_size(&a, prec); + mp_init_size(&m, prec); + mp_init_size(&c, prec); + + srand(seed); + + start = clock(); + for(ix = 0; ix < num; ix++) { + mpp_random_size(&a, prec); + mpp_random_size(&c, prec); + mpp_random_size(&m, prec); + mp_exptmod(&a, &c, &m, &c); + } + stop = clock(); + + sec = clk_to_sec(start, stop); + + printf("Total: %.3f seconds\n", sec); + printf("Individual: %.3f seconds\n", sec / num); + + mp_clear(&c); + mp_clear(&a); + mp_clear(&m); + + return 0; +} + +double clk_to_sec(clock_t start, clock_t stop) +{ + return (double)(stop - start) / CLOCKS_PER_SEC; +} + +/*------------------------------------------------------------------------*/ +/* HERE THERE BE DRAGONS */ diff --git a/pool/shard008/C/0129984_vpd_calibration.c b/pool/shard008/C/0129984_vpd_calibration.c new file mode 100644 index 0000000000000000000000000000000000000000..ab862c808d7faa75110ec0ca12d8b32e6678e1b7 --- /dev/null +++ b/pool/shard008/C/0129984_vpd_calibration.c @@ -0,0 +1,202 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ + +#include +#include +#include +#include + +#include +#include + +/* + * This file provides functions looking in the VPD for WiFi calibration data, + * and if found, copying the calibration blobs into CBMEM. + * + * Per interface calibration data is stored in the VPD in opaque blobs. The + * keys of the blobs follow one of two possible patterns: + * "wifi_base64_calibration" or "wifi_calibration", where is the + * interface number. + * + * This function accommodates up to 4 interfaces. All calibration blobs found + * in the VPD are packed into a single CBMEM entry as describe by the + * structures below: + */ + +/* This structure describes a single calibration data blob */ +struct calibration_blob { + uint32_t blob_size; /* Total size. rounded up to fall on a 4 byte + boundary. */ + uint32_t key_size; /* Size of the name of this entry, \0 included. */ + uint32_t value_size; /* Size of the value of this entry */ + /* Zero terminated name(key) goes here, immediately followed by value */ +}; + +/* + * This is the structure of the CBMEM entry containing WiFi calibration blobs. + * It starts with the total size (header size included) followed by an + * arbitrary number of concatenated 4 byte aligned calibration blobs. + */ +struct calibration_entry { + uint32_t size; + struct calibration_blob entries[0]; /* A varialble size container. */ +}; + + +#define MAX_WIFI_INTERFACE_COUNT 4 + +/* + * Structure of the cache to keep information about calibration blobs present + * in the VPD, one cache entry per VPD blob. + * + * Maintaing the cache allows to scan the VPD once, determine the CBMEM entry + * memory requirements, then allocate as much room as necessary and fill it + * up. + */ +struct vpd_blob_cache_t { + /* The longest name template must fit with an extra character. */ + char key_name[40]; + void *value_pointer; + unsigned blob_size; + unsigned key_size; + unsigned value_size; +}; + +static const char * const templates[] = { + "wifi_base64_calibrationX", + "wifi_calibrationX" +}; + +/* + * Scan the VPD for WiFi calibration data, checking for all possible key names + * and caching discovered blobs. + * + * Return the sum of sizes of all blobs, as stored in CBMEM. + */ +static size_t fill_up_entries_cache(struct vpd_blob_cache_t *cache, + size_t max_entries, size_t *filled_entries) +{ + int i; + int cbmem_entry_size = 0; + size_t used_entries = 0; + + + for (i = 0; + (i < ARRAY_SIZE(templates)) && (used_entries < max_entries); + i++) { + int j; + const int index_location = strlen(templates[i]) - 1; + const int key_length = index_location + 2; + + if (key_length > sizeof(cache->key_name)) + continue; + + for (j = 0; j < MAX_WIFI_INTERFACE_COUNT; j++) { + const void *payload; + void *decoded_payload; + int payload_size; + size_t decoded_size; + + strcpy(cache->key_name, templates[i]); + cache->key_name[index_location] = j + '0'; + + payload = vpd_find(cache->key_name, &payload_size, VPD_RO_THEN_RW); + if (!payload) + continue; + + decoded_size = B64_DECODED_SIZE(payload_size); + decoded_payload = malloc(decoded_size); + if (!decoded_payload) { + printk(BIOS_ERR, + "%s: failed allocating %zd bytes\n", + __func__, decoded_size); + continue; + } + + decoded_size = b64_decode(payload, payload_size, + decoded_payload); + if (!decoded_size) { + free(decoded_payload); + printk(BIOS_ERR, "%s: failed decoding %s\n", + __func__, cache->key_name); + continue; + } + + cache->value_pointer = decoded_payload; + cache->key_size = key_length; + cache->value_size = decoded_size; + cache->blob_size = + ALIGN(sizeof(struct calibration_blob) + + cache->key_size + + cache->value_size, 4); + cbmem_entry_size += cache->blob_size; + + used_entries++; + if (used_entries == max_entries) + break; + + cache++; + } + } + + *filled_entries = used_entries; + return cbmem_entry_size; +} + +void cbmem_add_vpd_calibration_data(void) +{ + size_t cbmem_entry_size, filled_entries; + struct calibration_entry *cbmem_entry; + struct calibration_blob *cal_blob; + int i; + /* + * Allocate one more cache entry than max required, to make sure that + * the last entry can be identified by the key size of zero. + */ + struct vpd_blob_cache_t vpd_blob_cache[ARRAY_SIZE(templates) * + MAX_WIFI_INTERFACE_COUNT]; + + cbmem_entry_size = fill_up_entries_cache(vpd_blob_cache, + ARRAY_SIZE(vpd_blob_cache), + &filled_entries); + + if (!cbmem_entry_size) + return; /* No calibration data found in the VPD. */ + + cbmem_entry_size += sizeof(struct calibration_entry); + cbmem_entry = cbmem_add(CBMEM_ID_WIFI_CALIBRATION, cbmem_entry_size); + if (!cbmem_entry) { + printk(BIOS_ERR, "%s: no room in cbmem to add %zd bytes\n", + __func__, cbmem_entry_size); + return; + } + + cbmem_entry->size = cbmem_entry_size; + + /* Copy cached data into the CBMEM entry. */ + cal_blob = cbmem_entry->entries; + + for (i = 0; i < filled_entries; i++) { + /* Use this as a pointer to the current cache entry. */ + struct vpd_blob_cache_t *cache = vpd_blob_cache + i; + char *pointer; + + cal_blob->blob_size = cache->blob_size; + cal_blob->key_size = cache->key_size; + cal_blob->value_size = cache->value_size; + + /* copy the key */ + pointer = (char *)(cal_blob + 1); + memcpy(pointer, cache->key_name, cache->key_size); + + /* and the value */ + pointer += cache->key_size; + memcpy(pointer, cache->value_pointer, cache->value_size); + free(cache->value_pointer); + + printk(BIOS_INFO, "%s: added %s to CBMEM\n", + __func__, cache->key_name); + + cal_blob = (struct calibration_blob *) + ((char *)cal_blob + cal_blob->blob_size); + } +} diff --git a/pool/shard008/C/0129986_xilinx_axienet_mdio.c b/pool/shard008/C/0129986_xilinx_axienet_mdio.c new file mode 100644 index 0000000000000000000000000000000000000000..9c014cee34b29dec26a79a4a059be8f751a3a7ef --- /dev/null +++ b/pool/shard008/C/0129986_xilinx_axienet_mdio.c @@ -0,0 +1,297 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * MDIO bus driver for the Xilinx Axi Ethernet device + * + * Copyright (c) 2009 Secret Lab Technologies, Ltd. + * Copyright (c) 2010 - 2011 Michal Simek + * Copyright (c) 2010 - 2011 PetaLogix + * Copyright (c) 2019 SED Systems, a division of Calian Ltd. + * Copyright (c) 2010 - 2012 Xilinx, Inc. All rights reserved. + */ + +#include +#include +#include +#include +#include + +#include "xilinx_axienet.h" + +#define MAX_MDIO_FREQ 2500000 /* 2.5 MHz */ +#define DEFAULT_HOST_CLOCK 150000000 /* 150 MHz */ + +/* Wait till MDIO interface is ready to accept a new transaction.*/ +static int axienet_mdio_wait_until_ready(struct axienet_local *lp) +{ + u32 val; + + return readx_poll_timeout(axinet_ior_read_mcr, lp, + val, val & XAE_MDIO_MCR_READY_MASK, + 1, 20000); +} + +/* Enable the MDIO MDC. Called prior to a read/write operation */ +static void axienet_mdio_mdc_enable(struct axienet_local *lp) +{ + axienet_iow(lp, XAE_MDIO_MC_OFFSET, + ((u32)lp->mii_clk_div | XAE_MDIO_MC_MDIOEN_MASK)); +} + +/* Disable the MDIO MDC. Called after a read/write operation*/ +static void axienet_mdio_mdc_disable(struct axienet_local *lp) +{ + u32 mc_reg; + + mc_reg = axienet_ior(lp, XAE_MDIO_MC_OFFSET); + axienet_iow(lp, XAE_MDIO_MC_OFFSET, + (mc_reg & ~XAE_MDIO_MC_MDIOEN_MASK)); +} + +/** + * axienet_mdio_read - MDIO interface read function + * @bus: Pointer to mii bus structure + * @phy_id: Address of the PHY device + * @reg: PHY register to read + * + * Return: The register contents on success, -ETIMEDOUT on a timeout + * + * Reads the contents of the requested register from the requested PHY + * address by first writing the details into MCR register. After a while + * the register MRD is read to obtain the PHY register content. + */ +static int axienet_mdio_read(struct mii_bus *bus, int phy_id, int reg) +{ + u32 rc; + int ret; + struct axienet_local *lp = bus->priv; + + axienet_mdio_mdc_enable(lp); + + ret = axienet_mdio_wait_until_ready(lp); + if (ret < 0) { + axienet_mdio_mdc_disable(lp); + return ret; + } + + axienet_iow(lp, XAE_MDIO_MCR_OFFSET, + (((phy_id << XAE_MDIO_MCR_PHYAD_SHIFT) & + XAE_MDIO_MCR_PHYAD_MASK) | + ((reg << XAE_MDIO_MCR_REGAD_SHIFT) & + XAE_MDIO_MCR_REGAD_MASK) | + XAE_MDIO_MCR_INITIATE_MASK | + XAE_MDIO_MCR_OP_READ_MASK)); + + ret = axienet_mdio_wait_until_ready(lp); + if (ret < 0) { + axienet_mdio_mdc_disable(lp); + return ret; + } + + rc = axienet_ior(lp, XAE_MDIO_MRD_OFFSET) & 0x0000FFFF; + + dev_dbg(lp->dev, "axienet_mdio_read(phy_id=%i, reg=%x) == %x\n", + phy_id, reg, rc); + + axienet_mdio_mdc_disable(lp); + return rc; +} + +/** + * axienet_mdio_write - MDIO interface write function + * @bus: Pointer to mii bus structure + * @phy_id: Address of the PHY device + * @reg: PHY register to write to + * @val: Value to be written into the register + * + * Return: 0 on success, -ETIMEDOUT on a timeout + * + * Writes the value to the requested register by first writing the value + * into MWD register. The the MCR register is then appropriately setup + * to finish the write operation. + */ +static int axienet_mdio_write(struct mii_bus *bus, int phy_id, int reg, + u16 val) +{ + int ret; + struct axienet_local *lp = bus->priv; + + dev_dbg(lp->dev, "axienet_mdio_write(phy_id=%i, reg=%x, val=%x)\n", + phy_id, reg, val); + + axienet_mdio_mdc_enable(lp); + + ret = axienet_mdio_wait_until_ready(lp); + if (ret < 0) { + axienet_mdio_mdc_disable(lp); + return ret; + } + + axienet_iow(lp, XAE_MDIO_MWD_OFFSET, (u32) val); + axienet_iow(lp, XAE_MDIO_MCR_OFFSET, + (((phy_id << XAE_MDIO_MCR_PHYAD_SHIFT) & + XAE_MDIO_MCR_PHYAD_MASK) | + ((reg << XAE_MDIO_MCR_REGAD_SHIFT) & + XAE_MDIO_MCR_REGAD_MASK) | + XAE_MDIO_MCR_INITIATE_MASK | + XAE_MDIO_MCR_OP_WRITE_MASK)); + + ret = axienet_mdio_wait_until_ready(lp); + if (ret < 0) { + axienet_mdio_mdc_disable(lp); + return ret; + } + axienet_mdio_mdc_disable(lp); + return 0; +} + +/** + * axienet_mdio_enable - MDIO hardware setup function + * @lp: Pointer to axienet local data structure. + * + * Return: 0 on success, -ETIMEDOUT on a timeout. + * + * Sets up the MDIO interface by initializing the MDIO clock and enabling the + * MDIO interface in hardware. + **/ +int axienet_mdio_enable(struct axienet_local *lp) +{ + u32 host_clock; + + lp->mii_clk_div = 0; + + if (lp->clk) { + host_clock = clk_get_rate(lp->clk); + } else { + struct device_node *np1; + + /* Legacy fallback: detect CPU clock frequency and use as AXI + * bus clock frequency. This only works on certain platforms. + */ + np1 = of_find_node_by_name(NULL, "cpu"); + if (!np1) { + netdev_warn(lp->ndev, "Could not find CPU device node.\n"); + host_clock = DEFAULT_HOST_CLOCK; + } else { + int ret = of_property_read_u32(np1, "clock-frequency", + &host_clock); + if (ret) { + netdev_warn(lp->ndev, "CPU clock-frequency property not found.\n"); + host_clock = DEFAULT_HOST_CLOCK; + } + of_node_put(np1); + } + netdev_info(lp->ndev, "Setting assumed host clock to %u\n", + host_clock); + } + + /* clk_div can be calculated by deriving it from the equation: + * fMDIO = fHOST / ((1 + clk_div) * 2) + * + * Where fMDIO <= 2500000, so we get: + * fHOST / ((1 + clk_div) * 2) <= 2500000 + * + * Then we get: + * 1 / ((1 + clk_div) * 2) <= (2500000 / fHOST) + * + * Then we get: + * 1 / (1 + clk_div) <= ((2500000 * 2) / fHOST) + * + * Then we get: + * 1 / (1 + clk_div) <= (5000000 / fHOST) + * + * So: + * (1 + clk_div) >= (fHOST / 5000000) + * + * And finally: + * clk_div >= (fHOST / 5000000) - 1 + * + * fHOST can be read from the flattened device tree as property + * "clock-frequency" from the CPU + */ + + lp->mii_clk_div = (host_clock / (MAX_MDIO_FREQ * 2)) - 1; + /* If there is any remainder from the division of + * fHOST / (MAX_MDIO_FREQ * 2), then we need to add + * 1 to the clock divisor or we will surely be above 2.5 MHz + */ + if (host_clock % (MAX_MDIO_FREQ * 2)) + lp->mii_clk_div++; + + netdev_dbg(lp->ndev, + "Setting MDIO clock divisor to %u/%u Hz host clock.\n", + lp->mii_clk_div, host_clock); + + axienet_iow(lp, XAE_MDIO_MC_OFFSET, lp->mii_clk_div | XAE_MDIO_MC_MDIOEN_MASK); + + return axienet_mdio_wait_until_ready(lp); +} + +/** + * axienet_mdio_disable - MDIO hardware disable function + * @lp: Pointer to axienet local data structure. + * + * Disable the MDIO interface in hardware. + **/ +void axienet_mdio_disable(struct axienet_local *lp) +{ + axienet_iow(lp, XAE_MDIO_MC_OFFSET, 0); +} + +/** + * axienet_mdio_setup - MDIO setup function + * @lp: Pointer to axienet local data structure. + * + * Return: 0 on success, -ETIMEDOUT on a timeout, -ENOMEM when + * mdiobus_alloc (to allocate memory for mii bus structure) fails. + * + * Sets up the MDIO interface by initializing the MDIO clock. + * Register the MDIO interface. + **/ +int axienet_mdio_setup(struct axienet_local *lp) +{ + struct device_node *mdio_node; + struct mii_bus *bus; + int ret; + + ret = axienet_mdio_enable(lp); + if (ret < 0) + return ret; + + bus = mdiobus_alloc(); + if (!bus) + return -ENOMEM; + + snprintf(bus->id, MII_BUS_ID_SIZE, "axienet-%.8llx", + (unsigned long long)lp->regs_start); + + bus->priv = lp; + bus->name = "Xilinx Axi Ethernet MDIO"; + bus->read = axienet_mdio_read; + bus->write = axienet_mdio_write; + bus->parent = lp->dev; + lp->mii_bus = bus; + + mdio_node = of_get_child_by_name(lp->dev->of_node, "mdio"); + ret = of_mdiobus_register(bus, mdio_node); + of_node_put(mdio_node); + if (ret) { + mdiobus_free(bus); + lp->mii_bus = NULL; + return ret; + } + axienet_mdio_mdc_disable(lp); + return 0; +} + +/** + * axienet_mdio_teardown - MDIO remove function + * @lp: Pointer to axienet local data structure. + * + * Unregisters the MDIO and frees any associate memory for mii bus. + */ +void axienet_mdio_teardown(struct axienet_local *lp) +{ + mdiobus_unregister(lp->mii_bus); + mdiobus_free(lp->mii_bus); + lp->mii_bus = NULL; +} diff --git a/pool/shard008/C/0129990_hal_data.c b/pool/shard008/C/0129990_hal_data.c new file mode 100644 index 0000000000000000000000000000000000000000..e541eccc0ffa4b2c6b353306e85b0173ac5abac2 --- /dev/null +++ b/pool/shard008/C/0129990_hal_data.c @@ -0,0 +1,67 @@ +/* generated HAL source file - do not edit */ +#include "hal_data.h" +#if UART_ON_SCI_UART_CALLBACK_USED_g_uart +#if defined(__ICCARM__) +#define user_uart_callback_WEAK_ATTRIBUTE +#pragma weak user_uart_callback = user_uart_callback_internal +#elif defined(__GNUC__) +#define user_uart_callback_WEAK_ATTRIBUTE __attribute__ ((weak, alias("user_uart_callback_internal"))) +#endif +void user_uart_callback(uart_callback_args_t * p_args) user_uart_callback_WEAK_ATTRIBUTE; +#endif + +uart_ctrl_t g_uart_ctrl; + +/** UART extended configuration for UARTonSCI HAL driver */ +const uart_on_sci_cfg_t g_uart_cfg_extend = +{ .clk_src = SCI_CLK_SRC_INT, .baudclk_out = false, .rx_edge_start = true, .noisecancel_en = false, .p_extpin_ctrl = + (void *) NULL }; + +/** UART interface configuration */ +const uart_cfg_t g_uart_cfg = +{ .channel = 8, .baud_rate = 9600, .data_bits = UART_DATA_BITS_8, .parity = UART_PARITY_OFF, .stop_bits = + UART_STOP_BITS_1, + .ctsrts_en = false, .p_callback = user_uart_callback, .p_context = &g_uart, .p_extend = &g_uart_cfg_extend, +#define SYNERGY_NOT_DEFINED (1) +#if (SYNERGY_NOT_DEFINED == SYNERGY_NOT_DEFINED) + .p_transfer_tx = NULL, +#else + .p_transfer_tx = &SYNERGY_NOT_DEFINED, +#endif +#if (SYNERGY_NOT_DEFINED == SYNERGY_NOT_DEFINED) + .p_transfer_rx = NULL, +#else + .p_transfer_rx = &SYNERGY_NOT_DEFINED, +#endif +#undef SYNERGY_NOT_DEFINED + }; + +/* Instance structure to use this module. */ +const uart_instance_t g_uart = +{ .p_ctrl = &g_uart_ctrl, .p_cfg = &g_uart_cfg, .p_api = &g_uart_on_sci }; + +#if UART_ON_SCI_UART_CALLBACK_USED_g_uart +/*******************************************************************************************************************//** + * @brief This is a weak example callback function. It should be overridden by defining a user callback function + * with the prototype below. + * - void user_uart_callback(uart_callback_args_t * p_args) + * + * @param[in] p_args Callback arguments used to identify what caused the callback. + **********************************************************************************************************************/ +void user_uart_callback_internal(uart_callback_args_t * p_args); +void user_uart_callback_internal(uart_callback_args_t * p_args) +{ + /** Do nothing. */ + SSP_PARAMETER_NOT_USED(p_args); +} +#endif +const ioport_instance_t g_ioport = +{ .p_api = &g_ioport_on_ioport, .p_cfg = NULL }; +const elc_instance_t g_elc = +{ .p_api = &g_elc_on_elc, .p_cfg = NULL }; +const cgc_instance_t g_cgc = +{ .p_api = &g_cgc_on_cgc, .p_cfg = NULL }; +void g_hal_init(void) +{ + g_common_init (); +} diff --git a/pool/shard008/C/0129991_detect-engine-file.c b/pool/shard008/C/0129991_detect-engine-file.c new file mode 100644 index 0000000000000000000000000000000000000000..26a5239305f7816a643d7ff99bf1220e07aaf1ae --- /dev/null +++ b/pool/shard008/C/0129991_detect-engine-file.c @@ -0,0 +1,263 @@ +/* Copyright (C) 2007-2011 Open Information Security Foundation + * + * You can copy, redistribute or modify this Program under the terms of + * the GNU General Public License version 2 as published by the Free + * Software Foundation. + * + * 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 + * version 2 along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +/** + * \file + * + * \author Victor Julien + */ + +#include "suricata-common.h" + +#include "decode.h" + +#include "detect.h" +#include "detect-engine.h" +#include "detect-parse.h" +#include "detect-engine-state.h" + +#include "detect-filestore.h" + +#include "detect-engine-uri.h" +#include "detect-engine-hcbd.h" +#include "detect-engine-hrhd.h" +#include "detect-engine-hmd.h" +#include "detect-engine-hcd.h" +#include "detect-engine-hrud.h" +#include "detect-engine-dcepayload.h" +#include "detect-engine-file.h" + +#include "stream-tcp.h" +#include "stream-tcp-private.h" +#include "stream-tcp-reassemble.h" + +#include "app-layer-parser.h" +#include "app-layer-protos.h" +#include "app-layer-htp.h" +#include "app-layer-smb.h" +#include "app-layer-dcerpc-common.h" +#include "app-layer-dcerpc.h" +#include "app-layer-smtp.h" + +#include "util-unittest.h" +#include "util-unittest-helper.h" +#include "util-profiling.h" + + +/** + * \brief Inspect the file inspecting keywords. + * + * \param tv thread vars + * \param det_ctx detection engine thread ctx + * \param f flow + * \param s signature to inspect + * + * \retval 0 no match + * \retval 1 match + * \retval 2 can't match + * \retval 3 can't match filestore signature + */ +static int DetectFileInspect(ThreadVars *tv, DetectEngineThreadCtx *det_ctx, + Flow *f, const Signature *s, const SigMatchData *smd, + uint8_t flags, FileContainer *ffc) +{ + int r = 0; + int match = 0; + int store_r = 0; + + SCLogDebug("file inspection... %p", ffc); + + if (ffc != NULL) { + File *file = ffc->head; + for (; file != NULL; file = file->next) { + SCLogDebug("file"); + + if (file->state == FILE_STATE_NONE) { + SCLogDebug("file state FILE_STATE_NONE"); + continue; + } + + if (file->txid < det_ctx->tx_id) { + SCLogDebug("file->txid < det_ctx->tx_id == %"PRIu64" < %"PRIu64, file->txid, det_ctx->tx_id); + continue; + } + + if (file->txid > det_ctx->tx_id) { + SCLogDebug("file->txid > det_ctx->tx_id == %"PRIu64" > %"PRIu64, file->txid, det_ctx->tx_id); + break; + } + + if ((s->file_flags & FILE_SIG_NEED_FILENAME) && file->name == NULL) { + SCLogDebug("sig needs filename, but we don't have any"); + r = DETECT_ENGINE_INSPECT_SIG_NO_MATCH; + continue; + } + + uint64_t file_size = FileDataSize(file); + if ((s->file_flags & FILE_SIG_NEED_MAGIC) && file_size == 0) { + SCLogDebug("sig needs file content, but we don't have any"); + r = DETECT_ENGINE_INSPECT_SIG_NO_MATCH; + continue; + } + + if ((s->file_flags & FILE_SIG_NEED_FILECONTENT) && file_size == 0) { + SCLogDebug("sig needs file content, but we don't have any"); + r = DETECT_ENGINE_INSPECT_SIG_NO_MATCH; + continue; + } + + if ((s->file_flags & FILE_SIG_NEED_MD5) && (!(file->flags & FILE_MD5))) { + SCLogDebug("sig needs file md5, but we don't have any"); + r = DETECT_ENGINE_INSPECT_SIG_NO_MATCH; + continue; + } + + if ((s->file_flags & FILE_SIG_NEED_SHA1) && (!(file->flags & FILE_SHA1))) { + SCLogDebug("sig needs file sha1, but we don't have any"); + r = DETECT_ENGINE_INSPECT_SIG_NO_MATCH; + continue; + } + + if ((s->file_flags & FILE_SIG_NEED_SHA256) && (!(file->flags & FILE_SHA256))) { + SCLogDebug("sig needs file sha256, but we don't have any"); + r = DETECT_ENGINE_INSPECT_SIG_NO_MATCH; + continue; + } + + if ((s->file_flags & FILE_SIG_NEED_SIZE) && file->state < FILE_STATE_CLOSED) { + SCLogDebug("sig needs filesize, but state < FILE_STATE_CLOSED"); + r = DETECT_ENGINE_INSPECT_SIG_NO_MATCH; + continue; + } + + /* run the file match functions. */ + while (1) { + SCLogDebug("smd %p", smd); + + if (sigmatch_table[smd->type].FileMatch != NULL) { + KEYWORD_PROFILING_START; + match = sigmatch_table[smd->type]. + FileMatch(tv, det_ctx, f, flags, file, s, smd->ctx); + KEYWORD_PROFILING_END(det_ctx, smd->type, (match > 0)); + if (match == 0) { + r = DETECT_ENGINE_INSPECT_SIG_CANT_MATCH; + break; + } else if (smd->is_last) { + r = DETECT_ENGINE_INSPECT_SIG_MATCH; + break; + } + } + if (smd->is_last) + break; + smd++; + } + + /* continue inspection for other files as we may want to store + * those as well. We'll return 1 (match) regardless of their + * results though */ + if (r == DETECT_ENGINE_INSPECT_SIG_MATCH) + store_r = DETECT_ENGINE_INSPECT_SIG_MATCH; + + /* if this is a filestore sig, and the sig can't match + * return 3 so we can distinguish */ + if ((s->flags & SIG_FLAG_FILESTORE) && r == DETECT_ENGINE_INSPECT_SIG_CANT_MATCH) + r = DETECT_ENGINE_INSPECT_SIG_CANT_MATCH_FILESTORE; + + /* continue, this file may (or may not) be unable to match + * maybe we have more that can :) */ + } + } else { + /* if we have a filestore sm with a scope > file (so tx, ssn) we + * run it here */ + if (smd != NULL && smd->is_last && smd->type == DETECT_FILESTORE && + smd->ctx != NULL) + { + DetectFilestoreData *fd = (DetectFilestoreData *)smd->ctx; + if (fd->scope > FILESTORE_SCOPE_DEFAULT) { + KEYWORD_PROFILING_START; + match = sigmatch_table[smd->type]. + FileMatch(tv, det_ctx, f, flags, /* no file */NULL, s, smd->ctx); + KEYWORD_PROFILING_END(det_ctx, smd->type, (match > 0)); + + if (match == 1) { + r = DETECT_ENGINE_INSPECT_SIG_MATCH; + } + } + } + } + + if (r == DETECT_ENGINE_INSPECT_SIG_NO_MATCH && store_r == DETECT_ENGINE_INSPECT_SIG_MATCH) { + SCLogDebug("stored MATCH, current file NOMATCH"); + SCReturnInt(DETECT_ENGINE_INSPECT_SIG_MATCH_MORE_FILES); + } + + if (store_r == DETECT_ENGINE_INSPECT_SIG_MATCH) + r = DETECT_ENGINE_INSPECT_SIG_MATCH; + SCReturnInt(r); +} + +/** + * \brief Inspect the file inspecting keywords against the state + * + * \param tv thread vars + * \param det_ctx detection engine thread ctx + * \param f flow + * \param s signature to inspect + * \param alstate state + * \param flags direction flag + * + * \retval 0 no match + * \retval 1 match + * \retval 2 can't match + * \retval 3 can't match filestore signature + * + * \note flow is not locked at this time + */ +int DetectFileInspectGeneric(ThreadVars *tv, + DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, + const Signature *s, const SigMatchData *smd, + Flow *f, uint8_t flags, void *alstate, void *tx, uint64_t tx_id) +{ + SCEnter(); + + if (alstate == NULL) { + SCReturnInt(DETECT_ENGINE_INSPECT_SIG_NO_MATCH); + } + + const uint8_t direction = flags & (STREAM_TOSERVER|STREAM_TOCLIENT); + FileContainer *ffc = AppLayerParserGetFiles(f->proto, f->alproto, alstate, direction); + if (ffc == NULL || ffc->head == NULL) { + SCReturnInt(DETECT_ENGINE_INSPECT_SIG_NO_MATCH); + } + + int r = DETECT_ENGINE_INSPECT_SIG_NO_MATCH; + int match = DetectFileInspect(tv, det_ctx, f, s, smd, flags, ffc); + if (match == DETECT_ENGINE_INSPECT_SIG_MATCH) { + r = DETECT_ENGINE_INSPECT_SIG_MATCH; + } else if (match == DETECT_ENGINE_INSPECT_SIG_CANT_MATCH) { + SCLogDebug("sid %u can't match on this transaction", s->id); + r = DETECT_ENGINE_INSPECT_SIG_CANT_MATCH; + } else if (match == DETECT_ENGINE_INSPECT_SIG_CANT_MATCH_FILESTORE) { + SCLogDebug("sid %u can't match on this transaction (filestore sig)", s->id); + r = DETECT_ENGINE_INSPECT_SIG_CANT_MATCH_FILESTORE; + } else if (match == DETECT_ENGINE_INSPECT_SIG_MATCH_MORE_FILES) { + SCLogDebug("match with more files ahead"); + r = match; + } + + SCReturnInt(r); +} diff --git a/pool/shard008/C/0130002_web_example_01.c b/pool/shard008/C/0130002_web_example_01.c new file mode 100644 index 0000000000000000000000000000000000000000..fea19c18074085f864d184787bfb8104bcd0759a --- /dev/null +++ b/pool/shard008/C/0130002_web_example_01.c @@ -0,0 +1,49 @@ +/* + * gcc -o web_example_01 web_example_01.c `pkg-config --cflags --libs elementary ewebkit` -D_GNU_SOURCE + */ + +#define _GNU_SOURCE +#include +#ifdef HAVE_ELEMENTARY_WEB +#include +#endif + +#define URL "http://www.enlightenment.org" + +EAPI_MAIN int +elm_main(int argc, char *argv[]) +{ + Evas_Object *win, *web; + + /* The program will proceed only if Ewebkit library is available. */ + if (elm_need_web() == EINA_FALSE) + return -1; + + elm_policy_set(ELM_POLICY_QUIT, ELM_POLICY_QUIT_LAST_WINDOW_CLOSED); + + /* Window */ + win = elm_win_add(NULL, "Elementary Webkit Widget", ELM_WIN_BASIC); + elm_win_autodel_set(win, EINA_TRUE); + + /* Web */ + web = elm_web_add(win); + evas_object_size_hint_weight_set(web, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND); + elm_web_window_create_hook_set(web, NULL, NULL); + elm_win_resize_object_add(win, web); + elm_web_history_enabled_set(web, EINA_FALSE); + + if (!elm_web_url_set(web, URL)) + { + printf("URL NOT LOADED"); + return -1; + } + evas_object_show(web); + + evas_object_resize(win, 720, 600); + evas_object_show(win); + + elm_run(); + + return 0; +} +ELM_MAIN() diff --git a/pool/shard008/C/0130003_test_dec_conformance.c b/pool/shard008/C/0130003_test_dec_conformance.c new file mode 100644 index 0000000000000000000000000000000000000000..d8da75393231c089c0fa4a2773b4f50594886ee4 --- /dev/null +++ b/pool/shard008/C/0130003_test_dec_conformance.c @@ -0,0 +1,225 @@ +#include "fractaltest.h" +#include "md5.h" +#include "annexb.h" +#include "taah264dec.h" + +#include +#include + +// Disable warning to allow assert with descriptive text, eg FASSERT(!"foo") +#pragma diag_suppress 279 + +typedef struct +{ + md5_state_t * md5_state; + bool expect_no_errors; +} context; + +static void report_error_cb ( + void * ctx, + taa_h264_error_t level, + const char * error_file, + int error_line, + const char * msg) +{ + context * c = (context *) ctx; + if (c->expect_no_errors) + { + printf ("%s:%d %s\n", error_file, error_line, msg); + FASSERT (!"Should never see decoder error/warning in conformance tests"); + } +} + +static void report_frame_complete_cb ( + void * ctx, + const taa_h264_decoded_frame_t * frame) +{ + md5_state_t * state = ((context *) ctx)->md5_state; + + int i; + const uint8_t * y = frame->y; + const uint8_t * u = frame->u; + const uint8_t * v = frame->v; + const int stride = frame->stride; + const int cstride = frame->stride_chroma; + int rows = frame->height; + int cols = frame->width; + int crows = frame->height / 2; + int ccols = frame->width / 2; + + if (frame->crop_left || frame->crop_right || frame->crop_top || frame->crop_bottom) + { + rows = frame->height - frame->crop_top - frame->crop_bottom; + cols = frame->width - frame->crop_left - frame->crop_right; + crows = rows / 2; + ccols = cols / 2; + + y += stride * frame->crop_top; + u += cstride * frame->crop_top / 2; + v += cstride * frame->crop_top / 2; + + y += frame->crop_left; + u += frame->crop_left / 2; + v += frame->crop_left / 2; + } + + for (i = 0; i < rows; i++) + md5_append (state, &y[i * stride], cols); + + for (i = 0; i < crows; i++) + md5_append (state, &u[i * cstride], ccols); + + for (i = 0; i < crows; i++) + md5_append (state, &v[i * cstride], ccols); +} + + + +static void decode_file ( + FILE * file, + bool expect_no_errors, + char * md5, + int md5_maxlen) +{ + const int max_width = 1280; + const int max_height = 720; + taa_h264_dec_handle * decoder; + annexb_context annexb; + context cb_context; + + md5_state_t state; + md5_byte_t digest[16]; + + annexb_init (&annexb, file); + md5_init(&state); + + cb_context.md5_state = &state; + cb_context.expect_no_errors = expect_no_errors; + + taa_h264_dec_create_params cparams; + cparams.width = max_width; + cparams.height = max_height; + cparams.callbacks.context = &cb_context; + cparams.callbacks.report_error = report_error_cb; + cparams.callbacks.report_frame_complete = report_frame_complete_cb; + cparams.callbacks.received_sei_user_data = NULL; + cparams.callbacks.reference_ack = NULL; + + decoder = taa_h264_dec_create (&cparams); + + while (extract_nalu (&annexb)) + { + int happy; + int nalu_ok; + taa_h264_dec_exec_params eparams; + eparams.nalu_buffer = annexb.nalu_start; + eparams.nalu_size = annexb.nalu_size; + + nalu_ok = taa_h264_dec_execute (decoder, &eparams, &happy); + if (expect_no_errors) + { + FASSERT (nalu_ok); + FASSERT (happy); + } + } + + md5_finish (&state, digest); + FASSERT (md5_maxlen > 32); + for (int i = 0; i < 16; i++) + sprintf(&md5[i*2], "%02x", digest[i]); + + taa_h264_dec_destroy (decoder); + annexb_free (&annexb); +} + +typedef struct +{ + const char * filename; + const char * reference_md5; + bool expect_no_errors; +} test_file; + + +static void test_decoder_conformance (void) +{ + test_file test_cases[] = + { + /* Generate */ + {"AUD_MW_E.264", "e96fe5054de0329a8868d06003375cdb", true}, + {"BA1_FT_C.264", "4f2da01d1d1ae7b99bea3fe1fb9e8ef4", true}, + {"BA1_Sony_D.jsv", "114d1cf94a2fcaffda0cf1b49964bf3d", true}, + {"BA2_Sony_F.jsv", "124d28307b05702812a374cfc9aad615", true}, + {"BA_MW_D.264", "7d5d351ad061640294bf43a43150fbca", true}, + {"BAMQ1_JVC_C.264", "bad372deef52c08fc1e384ecd1a43137", true}, + {"BAMQ2_JVC_C.264", "e3f5d5b0774b55370745f2d04f009575", true}, + {"BANM_MW_D.264", "e637d38ed004df3540218e3d84b43e42", true}, + {"BASQP1_Sony_C.jsv", "9e9c06cfc882a3f618b6ad40811c1331", true}, + {"CI1_FT_B.264", "6832762976b6d48719bb6cb603acd988", true}, + {"CI_MW_D.264", "037becca5bc836b869aba825293d39a3", true}, + {"CVFC1_Sony_C.jsv", "9fdb17e17d332b5d9752362c9c7ff9b0", true}, + {"CVPCMNL1_SVA_C.264", "5c1fd0f68e875200711febf1d683e58f", true}, + {"CVPCMNL2_SVA_C.264", "af1f1dbe1dd6569cb02271f053217d88", true}, + {"FM1_BT_B.h264", "f21ad956409cfa237099f7ac28390614", false}, + {"FM1_FT_E.264", "bf2d60e2a0140368e087580a8565fc99", false}, + {"FM2_SVA_B.264", "bd0ed007d1cba3746073cb82974a1191", false}, + {"FM2_SVA_C.264", "2ca2331ff02689d0cc036935a7f0d4bf", false}, + {"HCBP1_HHI_A.264", "13022e7970d78f1de4aaf1f7bd0e440b", false}, + {"HCBP2_HHI_A.264", "6c689d1541f97dcc1a17f5bdb6569cf1", false}, + {"LS_SVA_D.264", "9c53be4b1dedcd4598d30293f01c7bfe", true}, + {"MIDR_MW_D.264", "d87bff88b2c5b96ccb291ef68a45bbc2", true}, + {"MPS_MW_A.264", "88bb5a513bd7f3cc8190c7c03688ab22", true}, + {"MR1_BT_A.h264", "6ea31a214aadd8bdc8e7d37195d91c81", true}, + {"MR1_MW_A.264", "8c03b4a5b27a6f594d917d6fee1d86e6", true}, + {"MR2_MW_A.264", "20e66bac06e537fb1d2fa949b28046cd", true}, + {"MR2_TANDBERG_E.264", "d154bf9264960fecc6d2cf72be4cf8cc", true}, + {"MR3_TANDBERG_B.264", "dd1091f75ac15d3ae70485295b0a116e", true}, + {"MR4_TANDBERG_C.264", "5f5f14beca549172487bb74c4d3ba8f9", false}, + {"MR5_TANDBERG_C.264", "5f5f14beca549172487bb74c4d3ba8f9", false}, + {"NL1_Sony_D.jsv", "d4bb8d980c1377ee45515763ae7989fd", true}, + {"NL2_Sony_H.jsv", "48d8380cdb7eff52116c1aaddbc583f5", true}, + {"NLMQ1_JVC_C.264", "5c4a2f6b39385805f480a3a4432873b2", true}, + {"NLMQ2_JVC_C.264", "90b70fbaa5ca679ec9bf5e011ddba8f9", true}, + {"NRF_MW_E.264", "a8635615b50c5a16decc555a3c6c81c8", true}, + {"SVA_BA1_B.264", "dab92aa2145ab44abab2beb2868dd326", true}, + {"SVA_BA2_D.264", "66130b14295574bf35b725a8eaded3ae", true}, + {"SVA_Base_B.264", "180dda3234bcbe57fc45587dac7d43fb", true}, + {"SVA_CL1_E.264", "5723a1518de9fadca7499c5ba34da7c4", true}, + {"SVA_FM1_E.264", "7f7eaf6107852b871a3894a950e3647e", true}, + {"SVA_NL1_B.264", "b5626983ac0877497fff9a4b10d2f1d4", true}, + {"SVA_NL2_E.264", "b47e932d436288013b8453d9a1d0f60d", true}, + {"UNOFFICIAL_C20_PADDING.264", "095078d34b5a9a080253c92a7dbe0b17", true}, + {"UNOFFICIAL_EX90_DISPOSABLE.264", "882b3b3935b9b696ad856bcad713226e", true}, + {"UNOFFICIAL_MXP3000.264", "95fc58311d25fa3d8729ad1ddae9d7a5", true}, + }; + + int n = sizeof(test_cases) / sizeof(test_cases[0]); + for (int i = 0; i < n; i++) + { + FILE * file; + char result_md5[32+1]; + test_file * test = &test_cases[i]; + + file = fopen (test->filename, "rb"); + if (!file) + perror (test->filename); + FASSERT(file != NULL); + + decode_file (file, test->expect_no_errors, result_md5, sizeof result_md5); + + // Ideally every sequence would be decoded perfectly, but it's not. + // A couple of features are not implemented, such as FMO and + // "encoding order != display order". Assert that decoding the sequences has + // the expected outcome, even if it means a different md5. + if (test->expect_no_errors) + FASSERT (strcmp (result_md5, test->reference_md5) == 0); + else + FASSERT (strcmp (result_md5, test->reference_md5) != 0); + + fclose (file); + } +} + +void test_dec_conformance (void) +{ + test_decoder_conformance (); +} diff --git a/pool/shard008/C/0130006_irq.c b/pool/shard008/C/0130006_irq.c new file mode 100644 index 0000000000000000000000000000000000000000..a1de501a27299bdd7856979e71baa4aa641e9a0a --- /dev/null +++ b/pool/shard008/C/0130006_irq.c @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * PCI IRQ handling code + * + * Copyright (c) 2008 James Bottomley + * Copyright (C) 2017 Christoph Hellwig. + */ + +#include +#include +#include +#include +#include + +static void pci_note_irq_problem(struct pci_dev *pdev, const char *reason) +{ + struct pci_dev *parent = to_pci_dev(pdev->dev.parent); + + pci_err(pdev, "Potentially misrouted IRQ (Bridge %s %04x:%04x)\n", + dev_name(&parent->dev), parent->vendor, parent->device); + pci_err(pdev, "%s\n", reason); + pci_err(pdev, "Please report to linux-kernel@vger.kernel.org\n"); + WARN_ON(1); +} + +/** + * pci_lost_interrupt - reports a lost PCI interrupt + * @pdev: device whose interrupt is lost + * + * The primary function of this routine is to report a lost interrupt + * in a standard way which users can recognise (instead of blaming the + * driver). + * + * Returns: + * a suggestion for fixing it (although the driver is not required to + * act on this). + */ +enum pci_lost_interrupt_reason pci_lost_interrupt(struct pci_dev *pdev) +{ + if (pdev->msi_enabled || pdev->msix_enabled) { + enum pci_lost_interrupt_reason ret; + + if (pdev->msix_enabled) { + pci_note_irq_problem(pdev, "MSIX routing failure"); + ret = PCI_LOST_IRQ_DISABLE_MSIX; + } else { + pci_note_irq_problem(pdev, "MSI routing failure"); + ret = PCI_LOST_IRQ_DISABLE_MSI; + } + return ret; + } +#ifdef CONFIG_ACPI + if (!(acpi_disabled || acpi_noirq)) { + pci_note_irq_problem(pdev, "Potential ACPI misrouting please reboot with acpi=noirq"); + /* currently no way to fix acpi on the fly */ + return PCI_LOST_IRQ_DISABLE_ACPI; + } +#endif + pci_note_irq_problem(pdev, "unknown cause (not MSI or ACPI)"); + return PCI_LOST_IRQ_NO_INFORMATION; +} +EXPORT_SYMBOL(pci_lost_interrupt); + +/** + * pci_request_irq - allocate an interrupt line for a PCI device + * @dev: PCI device to operate on + * @nr: device-relative interrupt vector index (0-based). + * @handler: Function to be called when the IRQ occurs. + * Primary handler for threaded interrupts. + * If NULL and thread_fn != NULL the default primary handler is + * installed. + * @thread_fn: Function called from the IRQ handler thread + * If NULL, no IRQ thread is created + * @dev_id: Cookie passed back to the handler function + * @fmt: Printf-like format string naming the handler + * + * This call allocates interrupt resources and enables the interrupt line and + * IRQ handling. From the point this call is made @handler and @thread_fn may + * be invoked. All interrupts requested using this function might be shared. + * + * @dev_id must not be NULL and must be globally unique. + */ +int pci_request_irq(struct pci_dev *dev, unsigned int nr, irq_handler_t handler, + irq_handler_t thread_fn, void *dev_id, const char *fmt, ...) +{ + va_list ap; + int ret; + char *devname; + unsigned long irqflags = IRQF_SHARED; + + if (!handler) + irqflags |= IRQF_ONESHOT; + + va_start(ap, fmt); + devname = kvasprintf(GFP_KERNEL, fmt, ap); + va_end(ap); + + ret = request_threaded_irq(pci_irq_vector(dev, nr), handler, thread_fn, + irqflags, devname, dev_id); + if (ret) + kfree(devname); + return ret; +} +EXPORT_SYMBOL(pci_request_irq); + +/** + * pci_free_irq - free an interrupt allocated with pci_request_irq + * @dev: PCI device to operate on + * @nr: device-relative interrupt vector index (0-based). + * @dev_id: Device identity to free + * + * Remove an interrupt handler. The handler is removed and if the interrupt + * line is no longer in use by any driver it is disabled. The caller must + * ensure the interrupt is disabled on the device before calling this function. + * The function does not return until any executing interrupts for this IRQ + * have completed. + * + * This function must not be called from interrupt context. + */ +void pci_free_irq(struct pci_dev *dev, unsigned int nr, void *dev_id) +{ + kfree(free_irq(pci_irq_vector(dev, nr), dev_id)); +} +EXPORT_SYMBOL(pci_free_irq); diff --git a/pool/shard008/C/0130008_procfs_note.c b/pool/shard008/C/0130008_procfs_note.c new file mode 100644 index 0000000000000000000000000000000000000000..2ad53939b038d67a28243c825425fcd7f7e83a4f --- /dev/null +++ b/pool/shard008/C/0130008_procfs_note.c @@ -0,0 +1,73 @@ +/* $OpenBSD: procfs_note.c,v 1.2 1996/06/21 12:49:55 mickey Exp $ */ +/* $NetBSD: procfs_note.c,v 1.8 1994/06/29 06:34:53 cgd Exp $ */ + +/* + * Copyright (c) 1993 Jan-Simon Pendry + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Jan-Simon Pendry. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)procfs_note.c 8.2 (Berkeley) 1/21/94 + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +int +procfs_donote(curp, p, pfs, uio) + struct proc *curp; + struct proc *p; + struct pfsnode *pfs; + struct uio *uio; +{ + int xlen; + int error; + char note[PROCFS_NOTELEN+1]; + + if (uio->uio_rw != UIO_WRITE) + return (EINVAL); + + xlen = PROCFS_NOTELEN; + error = vfs_getuserstr(uio, note, &xlen); + if (error) + return (error); + + /* send to process's notify function */ + return (EOPNOTSUPP); +} diff --git a/pool/shard008/C/0130009_light_cm36651.c b/pool/shard008/C/0130009_light_cm36651.c new file mode 100644 index 0000000000000000000000000000000000000000..6c9d84df5bca031abb0a634ae32c3ee947478049 --- /dev/null +++ b/pool/shard008/C/0130009_light_cm36651.c @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2012, Samsung Electronics Co. Ltd. All Rights Reserved. + * + * 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. + * + */ +#include "ssp.h" + +#define VENDOR "CAPELLA" +#define CHIP_ID "CM36651" + +/*************************************************************************/ +/* factory Sysfs */ +/*************************************************************************/ + +static ssize_t light_vendor_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + return sprintf(buf, "%s\n", VENDOR); +} + +static ssize_t light_name_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + return sprintf(buf, "%s\n", CHIP_ID); +} + +static ssize_t light_lux_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct ssp_data *data = dev_get_drvdata(dev); + + return sprintf(buf, "%u,%u,%u,%u\n", + data->buf[LIGHT_SENSOR].r, data->buf[LIGHT_SENSOR].g, + data->buf[LIGHT_SENSOR].b, data->buf[LIGHT_SENSOR].w); +} + +static ssize_t light_data_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + struct ssp_data *data = dev_get_drvdata(dev); + + return sprintf(buf, "%u,%u,%u,%u\n", + data->buf[LIGHT_SENSOR].r, data->buf[LIGHT_SENSOR].g, + data->buf[LIGHT_SENSOR].b, data->buf[LIGHT_SENSOR].w); +} + +static DEVICE_ATTR(vendor, S_IRUGO, light_vendor_show, NULL); +static DEVICE_ATTR(name, S_IRUGO, light_name_show, NULL); +static DEVICE_ATTR(lux, S_IRUGO, light_lux_show, NULL); +static DEVICE_ATTR(raw_data, S_IRUGO, light_data_show, NULL); + +static struct device_attribute *light_attrs[] = { + &dev_attr_vendor, + &dev_attr_name, + &dev_attr_lux, + &dev_attr_raw_data, + NULL, +}; + +void initialize_light_factorytest(struct ssp_data *data) +{ + struct device *light_device = NULL; + + sensors_register(light_device, data, light_attrs, "light_sensor"); +} diff --git a/pool/shard008/C/0130014_teli1.c b/pool/shard008/C/0130014_teli1.c new file mode 100644 index 0000000000000000000000000000000000000000..cb1f6e6b355653dcc076dacb12f417c9acd5d338 --- /dev/null +++ b/pool/shard008/C/0130014_teli1.c @@ -0,0 +1,57 @@ +/* + dlinked1.c + using head and tail pointers. + header files, ADT + memory on demand: malloc(), free() +*/ +#include +#include + +#include "listd.h" + + + + +/*--------------------------------------------------*/ +/*------------------- menu -------------------------*/ +int menu(){ + int r = 0; + + printf("1. add a node\n"); + printf("2. remove a node\n"); + printf("3. display\n"); + printf("4. search\n"); + printf("0. Quit\n"); + do{ + printf("type[1-2-3-4 or 0]"); + scanf("%d", &r); + } while(r < 0 || r > 4); + return r; +} +int main() +{ + node_t *p; + node_t *n1; + int i; + + i = menu(); + while(i){ + switch(i){ + case 1: n1 = get_node(); + add_node(&head, &tail, n1); + break; + case 2: remove_node(&head, &tail); + traverse(&head); + break; + case 3: traverse(&head);break; + case 4: n1 = get_search(); + p = search_node(&head,n1); + printf("search done"); + display_value(p->value); + default: exit(0); + } + i = menu(); + } + exit(0); +} + diff --git a/pool/shard008/C/0130022_handler_custom_error.c b/pool/shard008/C/0130022_handler_custom_error.c new file mode 100644 index 0000000000000000000000000000000000000000..815533994eb036e76008bf526345c70c0dba2a3d --- /dev/null +++ b/pool/shard008/C/0130022_handler_custom_error.c @@ -0,0 +1,96 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ + +/* Cherokee + * + * Authors: + * Alvaro Lopez Ortega + * + * Copyright (C) 2001-2014 Alvaro Lopez Ortega + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of version 2 of the GNU General Public + * License as published by the Free Software Foundation. + * + * 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. + */ + +#include "common-internal.h" +#include "handler_custom_error.h" +#include "connection-protected.h" +#include "util.h" + +PLUGIN_INFO_HANDLER_EASIEST_INIT (custom_error, http_all_methods); + + +static ret_t +props_free (cherokee_handler_custom_error_props_t *props) +{ + return cherokee_handler_props_free_base (HANDLER_PROPS(props)); +} + + +ret_t +cherokee_handler_custom_error_configure (cherokee_config_node_t *conf, + cherokee_server_t *srv, + cherokee_module_props_t **_props) +{ + ret_t ret; + int val; + cherokee_list_t *i; + cherokee_config_node_t *subconf; + cherokee_handler_custom_error_props_t *props; + + UNUSED(srv); + + if (*_props == NULL) { + CHEROKEE_NEW_STRUCT (n, handler_custom_error_props); + + cherokee_handler_props_init_base (HANDLER_PROPS(n), + MODULE_PROPS_FREE(props_free)); + + n->error_code = http_unset; + *_props = MODULE_PROPS(n); + } + + props = PROP_CUSTOM_ERROR(*_props); + + cherokee_config_node_foreach (i, conf) { + subconf = CONFIG_NODE(i); + if (equal_buf_str (&subconf->key, "error")) { + ret = cherokee_atoi (subconf->val.buf, &val); + if (ret != ret_ok) return ret; + props->error_code = val; + } + } + + /* Post checks + */ + if (props->error_code == http_unset) { + LOG_CRITICAL_S (CHEROKEE_ERROR_HANDLER_CUSTOM_ERROR_HTTP); + return ret_error; + } + + return ret_ok; +} + + +ret_t +cherokee_handler_custom_error_new (cherokee_handler_t **hdl, + void *cnt, + cherokee_module_props_t *props) +{ + UNUSED(hdl); + + CONN(cnt)->error_code = PROP_CUSTOM_ERROR(props)->error_code; + return ret_error; +} + + diff --git a/pool/shard008/C/0130028_files.c b/pool/shard008/C/0130028_files.c new file mode 100644 index 0000000000000000000000000000000000000000..513a0cb40e5b61c1bee93ae70d6c86b25026fa35 --- /dev/null +++ b/pool/shard008/C/0130028_files.c @@ -0,0 +1,82 @@ +/* Copyright (c) 2015 Bill Chatfield + * + * 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 (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 + * 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, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include /* snprintf */ +#include /* errno, ENOENT */ +#include +#include +#include +#include "strings.h" +#include "files.h" + +bool file_exists(const char *name) +{ + struct stat file_info; + return stat(name, &file_info) == 0 || errno != ENOENT; /* Don't second guess this. It is correct.*/ +} + +bool dir_exists(const char *name) +{ + struct stat file_info; + /* Don't second guess this. It is correct.*/ + return (stat(name, &file_info) == 0 && S_ISDIR(file_info.st_mode)) || errno != ENOENT; +} + +/** + * Searches dir_search_list for name. dir_search_list must be terminated by + * a NULL. + */ +bool find_dir(const char *dir_search_list[], const char *name, char result_dir[], size_t capacity) +{ + int i = 0; + bool found = false; + + while (!found && dir_search_list[i] != NULL) { + snprintf(result_dir, capacity, "%s/%s", dir_search_list[i], name); + if (dir_exists(result_dir)) { + found = true; + } + else { + i++; + } + } + return found; +} + +/** + * Gets the last component of a path. It returns an empty string if path + * ends with '/'. + */ +const char *get_short_name(const char *path) +{ + const char *p; + + p = path + strlen(path) - 1; + if (*p == '/') { + p = ""; + } + else { + p--; + while (*p != '/' && p > path) { + p--; + } + if (*p != '/') { + p = path; + } + } + return p; +} diff --git a/pool/shard008/C/0130032_sctp-client-dtls.c b/pool/shard008/C/0130032_sctp-client-dtls.c new file mode 100644 index 0000000000000000000000000000000000000000..f07051795f80d288312c8f9aa5d303f3afc59452 --- /dev/null +++ b/pool/shard008/C/0130032_sctp-client-dtls.c @@ -0,0 +1,125 @@ +/* sctp-client-dtls.c + * + * Copyright (C) 2006-2016 wolfSSL Inc. + * + * This file is part of wolfSSL. + * + * wolfSSL 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. + * + * wolfSSL 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-1335, USA + */ + + +/* sctp */ +#include +#include +#include +#include + +/* std */ +#include +#include +#include +#include + +/* wolfssl */ +#include +#include + + + +#define cacert "./certs/ca-cert.pem" + +static int err_sys(const char* msg) +{ + perror(msg); + exit(EXIT_FAILURE); +} + +int main() +{ + int sd = socket(PF_INET, SOCK_STREAM, IPPROTO_SCTP); + + if (sd < 0) + err_sys("sctp socket error"); + + struct sockaddr_in sa; + memset(&sa, 0, sizeof(sa)); + sa.sin_family = AF_INET; + sa.sin_addr.s_addr = inet_addr("127.0.0.1"); + sa.sin_port = htons(12345); + + int ret = connect(sd, (struct sockaddr*)&sa, sizeof(sa)); + if (ret < 0) + err_sys("sctp connect error"); + + const char* response = "hello there"; + char buffer[80]; + + WOLFSSL_CTX* ctx = wolfSSL_CTX_new(wolfDTLSv1_2_client_method()); + if (ctx == NULL) + err_sys("ctx new dtls client failed"); + + ret = wolfSSL_CTX_dtls_set_sctp(ctx); + if (ret != SSL_SUCCESS) + err_sys("set sctp mode failed"); + + ret = wolfSSL_CTX_load_verify_locations(ctx, cacert, NULL); + if (ret != SSL_SUCCESS) + err_sys("ca cert error"); + + WOLFSSL* ssl = wolfSSL_new(ctx); + if (ssl == NULL) + err_sys("ssl new dtls client failed"); + + wolfSSL_set_fd(ssl, sd); + + ret = wolfSSL_connect(ssl); + if (ret != SSL_SUCCESS) + err_sys("ssl connect failed"); + + printf("TLS version is %s\n", wolfSSL_get_version(ssl)); + printf("Cipher Suite is %s\n", + wolfSSL_CIPHER_get_name(wolfSSL_get_current_cipher(ssl))); + + wolfSSL_write(ssl, response, (int)strlen(response)); + int got = wolfSSL_read(ssl, buffer, sizeof(buffer)); + if (got > 0) { + buffer[got] = 0; + printf("server said: %s\n", buffer); + } + + unsigned char bigBuf[4096]; + unsigned int i; + + for (i = 0; i < (int)sizeof(bigBuf); i++) + bigBuf[i] = (unsigned char)(i & 0xFF); + wolfSSL_write(ssl, bigBuf, sizeof(bigBuf)); + memset(bigBuf, 0, sizeof(bigBuf)); + + wolfSSL_read(ssl, bigBuf, sizeof(bigBuf)); + for (i = 0; i < sizeof(bigBuf); i++) { + if (bigBuf[i] != (unsigned char)(i & 0xFF)) { + printf("big message check fail\n"); + break; + } + } + + wolfSSL_shutdown(ssl); + wolfSSL_free(ssl); + wolfSSL_CTX_free(ctx); + + close(sd); + + return 0; +} diff --git a/pool/shard008/C/0130033_lxqtbacklight_backend.c b/pool/shard008/C/0130033_lxqtbacklight_backend.c new file mode 100644 index 0000000000000000000000000000000000000000..e544a9e7c43b757fbbbdafdb61a3247c06fe3da6 --- /dev/null +++ b/pool/shard008/C/0130033_lxqtbacklight_backend.c @@ -0,0 +1,195 @@ +/* + * Copyright (C) 2016 P.L. Lucas + * + * 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. +*/ + +/******************************************************************************** + * This library uses Linux /sys/class/backlight files to read and change the + * backlight level. + * + * If screen backlight can be controlled, the Linux kernel will show inside + * /sys/class/backlight directory one or more directories. Each directory has + * got the following files: + * /sys/class/backlight/driver/max_brightness + * /sys/class/backlight/driver/actual_brightness + * /sys/class/backlight/driver/brightness + * /sys/class/backlight/driver/type + * + * The "max_brightness" file contains the maximum value that can be set to the + * backlight level. + * + * In "brightness" file you can write the value of backlight and the Linux + * kernel will set that value. + * + * You must read actual backlight level from "actual_brightness" file. Never + * read the backlight level from "brightness" file. + * + * The "type" file is the type of control and it can be: + * firmware + * platform + * raw + * The firmware control should be preferred to platform control. The platform + * control should be preferred to raw control. + * If there are several directories in /sys/class/backlight/, you should use + * the directory which its "type" file has got the "firmware" value. + * + * In order to write in /sys/class/backlight/driver/brightness file root + * permissions are needed. This library calls to a command line tool called + * "lxqtbacklight_backend". "lxqtbacklight_backend" has a policy in Polkit + * in order to write in /sys/class/backlight/driver/brightness file. + *******************************************************************************/ + +#include +#include +#include +#include +#include +#include + +#include "lxqtbacklight_backend.h" + +#define True 1 +#define False 0 + +static int read_backlight(char *driver); +static int read_max_backlight(char *driver); + +int lxqt_backlight_backend_get() +{ + char *driver = lxqt_backlight_backend_get_driver(); + if( driver == NULL ) { + fprintf(stderr, "Error: /sys/class/backlight is empty."); + return -1; + } + int value = read_backlight(driver); + free(driver); + return value; +} + +int lxqt_backlight_backend_get_max() +{ + char *driver = lxqt_backlight_backend_get_driver(); + if( driver == NULL ) { + fprintf(stderr, "Error: /sys/class/backlight is empty."); + return -1; + } + int value = read_max_backlight(driver); + free(driver); + return value; +} + +FILE *lxqt_backlight_backend_get_write_stream() +{ + FILE *stream = popen("pkexec lxqt-backlight_backend --stdin", "w"); + return stream; +} + +static int read_int(char *path) +{ + FILE *in = fopen(path, "r"); + if( in == NULL ) { + char buffer[1024]; + sprintf(buffer, "Couldn't open %s", path); + perror(buffer); + return -1; + } + int value; + int ok = fscanf(in, "%d", &value); + fclose(in); + if( ok == EOF ) { + value = 0; + } + return value; +} + +static int read_backlight(char *driver) +{ + char path[1024]; + sprintf(path, "/sys/class/backlight/%s/actual_brightness", driver); + return read_int(path); +} + +static int read_max_backlight(char *driver) +{ + char path[1024]; + sprintf(path, "/sys/class/backlight/%s/max_brightness", driver); + return read_int(path); +} + +typedef enum {FIRMWARE, PLATFORM, RAW, OTHER, N_BACKLIGHT} BackligthTypes; + +char *lxqt_backlight_backend_get_driver() +{ + DIR *dirp; + struct dirent *dp; + + char *drivers[N_BACKLIGHT]; + char *driver; + BackligthTypes n; + char path[1024], type[1024]; + + for(n=0;nd_name, ".") || !strcmp(dp->d_name, "..") ) + continue; + driver = dp->d_name; + sprintf(path, "/sys/class/backlight/%s/type", driver); + FILE *in = fopen(path, "r"); + if( in == NULL ) + continue; + int ok = fscanf(in, "%s", type); + fclose(in); + if( ok != EOF ) { + // firmware control should be preferred to platform control should be preferred to raw control. + if( ! strcmp("firmware", type) ) { + drivers[FIRMWARE] = strdup(driver); + break; + } else if( ! strcmp("platform", type) ) + drivers[PLATFORM] = strdup(driver); + else if( ! strcmp("raw", type) ) + drivers[RAW] = strdup(driver); + else // Only, firmware, platform and raw are defined, but... + drivers[OTHER] = strdup(driver); + } + } + } while (dp != NULL); + + closedir(dirp); + + if (errno != 0) + perror("Error reading directory"); + + driver = NULL; + for(n=0;n 2003 + * Copyright (C) James Peach 2006 + * + * 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 . + */ + +#include "replace.h" +#include +#include "lib/util/samba_util.h" +#include "lib/util_path.h" + +struct loadparm_substitution; +struct share_params; +#include "source3/param/param_proto.h" + +/** + * @brief Returns an absolute path to a file concatenating the provided + * @a rootpath and @a basename + * + * @param name Filename, relative to @a rootpath + * + * @retval Pointer to a string containing the full path. + **/ + +static char *xx_path(TALLOC_CTX *mem_ctx, + const char *name, + const char *rootpath) +{ + char *fname = NULL; + + fname = talloc_strdup(mem_ctx, rootpath); + if (!fname) { + return NULL; + } + trim_string(fname,"","/"); + + if (!directory_create_or_exist(fname, 0755)) { + return NULL; + } + + return talloc_asprintf_append(fname, "/%s", name); +} + +/** + * @brief Returns an absolute path to a file in the Samba lock directory. + * + * @param name File to find, relative to LOCKDIR. + * + * @retval Pointer to a talloc'ed string containing the full path. + **/ + +char *lock_path(TALLOC_CTX *mem_ctx, const char *name) +{ + return xx_path(mem_ctx, name, lp_lock_directory()); +} + +/** + * @brief Returns an absolute path to a file in the Samba state directory. + * + * @param name File to find, relative to STATEDIR. + * + * @retval Pointer to a talloc'ed string containing the full path. + **/ + +char *state_path(TALLOC_CTX *mem_ctx, const char *name) +{ + return xx_path(mem_ctx, name, lp_state_directory()); +} + +/** + * @brief Returns an absolute path to a file in the Samba cache directory. + * + * @param name File to find, relative to CACHEDIR. + * + * @retval Pointer to a talloc'ed string containing the full path. + **/ + +char *cache_path(TALLOC_CTX *mem_ctx, const char *name) +{ + return xx_path(mem_ctx, name, lp_cache_directory()); +} + +/** + * @brief Removes any invalid path components in an absolute POSIX path. + * + * @param ctx Talloc context to return string. + * + * @param abs_path Absolute path string to process. + * + * @retval Pointer to a talloc'ed string containing the absolute full path. + **/ + +char *canonicalize_absolute_path(TALLOC_CTX *ctx, const char *pathname_in) +{ + /* + * Note we use +2 here so if pathname_in=="" then we + * have space to return "/". + */ + char *pathname = talloc_array(ctx, char, strlen(pathname_in)+2); + const char *s = pathname_in; + char *p = pathname; + bool wrote_slash = false; + + if (pathname == NULL) { + return NULL; + } + + /* Always start with a '/'. */ + *p++ = '/'; + wrote_slash = true; + + while (*s) { + /* Deal with '/' or multiples of '/'. */ + if (s[0] == '/') { + while (s[0] == '/') { + /* Eat trailing '/' */ + s++; + } + /* Update target with one '/' */ + if (!wrote_slash) { + *p++ = '/'; + wrote_slash = true; + } + continue; + } + if (wrote_slash) { + /* Deal with "./" or ".\0" */ + if (s[0] == '.' && + (s[1] == '/' || s[1] == '\0')) { + /* Eat the dot. */ + s++; + while (s[0] == '/') { + /* Eat any trailing '/' */ + s++; + } + /* Don't write anything to target. */ + /* wrote_slash is still true. */ + continue; + } + /* Deal with "../" or "..\0" */ + if (s[0] == '.' && s[1] == '.' && + (s[2] == '/' || s[2] == '\0')) { + /* Eat the dot dot. */ + s += 2; + while (s[0] == '/') { + /* Eat any trailing '/' */ + s++; + } + /* + * As wrote_slash is true, we go back + * one character to point p at the slash + * we just saw. + */ + if (p > pathname) { + p--; + } + /* + * Now go back to the slash + * before the one that p currently points to. + */ + while (p > pathname) { + p--; + if (p[0] == '/') { + break; + } + } + /* + * Step forward one to leave the + * last written '/' alone. + */ + p++; + + /* Don't write anything to target. */ + /* wrote_slash is still true. */ + continue; + } + } + /* Non-separator character, just copy. */ + *p++ = *s++; + wrote_slash = false; + } + if (wrote_slash) { + /* + * We finished on a '/'. + * Remove the trailing '/', but not if it's + * the sole character in the path. + */ + if (p > pathname + 1) { + p--; + } + } + /* Terminate and we're done ! */ + *p++ = '\0'; + return pathname; +} diff --git a/pool/shard008/C/0130043_Inst_Mem_ts_isim_beh.exe_main.c b/pool/shard008/C/0130043_Inst_Mem_ts_isim_beh.exe_main.c new file mode 100644 index 0000000000000000000000000000000000000000..f7e379fb6fd857c65455356758829b5321ec953a --- /dev/null +++ b/pool/shard008/C/0130043_Inst_Mem_ts_isim_beh.exe_main.c @@ -0,0 +1,58 @@ +/**********************************************************************/ +/* ____ ____ */ +/* / /\/ / */ +/* /___/ \ / */ +/* \ \ \/ */ +/* \ \ Copyright (c) 2003-2009 Xilinx, Inc. */ +/* / / All Right Reserved. */ +/* /---/ /\ */ +/* \ \ / \ */ +/* \___\/\___\ */ +/***********************************************************************/ + +#include "xsi.h" + +struct XSI_INFO xsi_info; + +char *IEEE_P_2592010699; +char *STD_STANDARD; +char *IEEE_P_3499444699; +char *IEEE_P_3620187407; +char *STD_TEXTIO; +char *IEEE_P_3564397177; + + +int main(int argc, char **argv) +{ + xsi_init_design(argc, argv); + xsi_register_info(&xsi_info); + + xsi_register_min_prec_unit(-12); + ieee_p_2592010699_init(); + ieee_p_3499444699_init(); + ieee_p_3620187407_init(); + work_a_3319326315_3212880686_init(); + std_textio_init(); + ieee_p_3564397177_init(); + xilinxcorelib_a_1203745346_2959432447_init(); + xilinxcorelib_a_1677950190_1709443946_init(); + xilinxcorelib_a_2866867632_0543512595_init(); + xilinxcorelib_a_4066303846_3212880686_init(); + work_a_3219856015_3777409210_init(); + work_a_1056326260_1181938964_init(); + work_a_0980737152_2372691052_init(); + + + xsi_register_tops("work_a_0980737152_2372691052"); + + IEEE_P_2592010699 = xsi_get_engine_memory("ieee_p_2592010699"); + xsi_register_ieee_std_logic_1164(IEEE_P_2592010699); + STD_STANDARD = xsi_get_engine_memory("std_standard"); + IEEE_P_3499444699 = xsi_get_engine_memory("ieee_p_3499444699"); + IEEE_P_3620187407 = xsi_get_engine_memory("ieee_p_3620187407"); + STD_TEXTIO = xsi_get_engine_memory("std_textio"); + IEEE_P_3564397177 = xsi_get_engine_memory("ieee_p_3564397177"); + + return xsi_run_simulation(argc, argv); + +} diff --git a/pool/shard008/C/0130044_py_select.c b/pool/shard008/C/0130044_py_select.c new file mode 100644 index 0000000000000000000000000000000000000000..8b588baacd5fa5f3890524cd17a84c7d31d19315 --- /dev/null +++ b/pool/shard008/C/0130044_py_select.c @@ -0,0 +1,144 @@ +/* + * This file is part of the OpenMV project. + * Copyright (c) 2013/2014 Ibrahim Abdelkader + * This work is licensed under the MIT license, see the file LICENSE for details. + * + * Select Python module. + * + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define min(a,b) \ + ({ __typeof__ (a) _a = (a); \ + __typeof__ (b) _b = (b); \ + _a < _b ? _a : _b; }) + +#define max(a,b) \ + ({ __typeof__ (a) _a = (a); \ + __typeof__ (b) _b = (b); \ + _a > _b ? _a : _b; }) + +// select helper functions +static void set_fds(int *nfds, mp_obj_t *fdlist, uint fdlist_len, fd_set *fdset) +{ + FD_ZERO(fdset); + + /* add sockets to fd set*/ + for (int i=0; ifd, fdset); + + if (s->fd > (*nfds)) { + *nfds = s->fd; + } + } +} + +static void get_fds(mp_obj_t *fdlist, uint fdlist_len, mp_obj_t *fdlist_out, fd_set *fdset) +{ + for (int i=0; ifd, fdset)) { + socket_t *socket_obj = m_new_obj_with_finaliser(socket_t); + socket_obj->base.type = (mp_obj_t)&socket_type; + socket_obj->fd = s->fd; + mp_obj_list_append(fdlist_out, socket_obj); + } + } +} + +static mp_obj_t py_select(uint n_args, const mp_obj_t *args) +{ + int nfds=0; //highest-numbered fd plus 1 + timeval tv={0}; + fd_set rfds, wfds, xfds; + + mp_obj_t *rlist, *wlist, *xlist; + uint rlist_len, wlist_len, xlist_len; + + /* read args */ + mp_obj_get_array(args[0], &rlist_len, &rlist); + mp_obj_get_array(args[1], &wlist_len, &wlist); + mp_obj_get_array(args[2], &xlist_len, &xlist); + + if (n_args == 4) { + float timeout = mp_obj_get_float(args[3]); + tv.tv_sec = (int)timeout; + tv.tv_usec = (timeout-(int)timeout)*1000*1000; + } + + // add fds to their respective sets + set_fds(&nfds, rlist, rlist_len, &rfds); + set_fds(&nfds, wlist, wlist_len, &wfds); + set_fds(&nfds, xlist, xlist_len, &xfds); + + // call select + nfds = select(nfds+1, &rfds, &wfds, &xfds, &tv); + + // if any of the read sockets is closed, we add it to the read fd set, + // a subsequent call to recv() returns 0. This behavior is consistent with BSD. + for (int i=0; ifd)) { + FD_SET(s->fd, &rfds); + nfds = max(nfds, s->fd); + } + } + + // return value; a tuple of 3 lists + mp_obj_t fds[3] = { + mp_obj_new_list(0, NULL), + mp_obj_new_list(0, NULL), + mp_obj_new_list(0, NULL) + }; + + // On success, select() returns the number of file descriptors contained + // in the three returned descriptor sets which may be zero if the timeout + // expires before anything interesting happens, -1 is returned on error. + if (nfds == -1) { // select failed + nlr_raise(mp_obj_new_exception_msg(&mp_type_OSError, "select failed")); + } else if (nfds) { // an fd is ready + get_fds(rlist, rlist_len, fds[0], &rfds); + get_fds(wlist, wlist_len, fds[1], &wfds); + get_fds(xlist, xlist_len, fds[2], &xfds); + } // select timedout + + return mp_obj_new_tuple(3, fds); +} + +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(py_select_obj, 3, 4, py_select); +// select module +static const mp_map_elem_t module_globals_dict_table[] = { + { MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_select) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_select), (mp_obj_t)&py_select_obj }, +}; + +static MP_DEFINE_CONST_DICT(module_globals_dict, module_globals_dict_table); + +const mp_obj_module_t select_module = { + .base = { &mp_type_module }, + .name = MP_QSTR_select, + .globals = (mp_obj_dict_t*)&module_globals_dict, +}; + +const mp_obj_module_t *py_select_init() +{ + return &select_module; +} + + + diff --git a/pool/shard008/C/0130049_zfs.c b/pool/shard008/C/0130049_zfs.c new file mode 100644 index 0000000000000000000000000000000000000000..384ac4c9396cc288c5169aaac2210f49321849fd --- /dev/null +++ b/pool/shard008/C/0130049_zfs.c @@ -0,0 +1,170 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * + * ZFS filesystem porting to Uboot by + * Jorgen Lundman + * + * zfsfs support + * made from existing GRUB Sources by Sun, GNU and others. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(CONFIG_CMD_USB) && defined(CONFIG_USB_STORAGE) +#include +#endif + +#if !CONFIG_IS_ENABLED(DOS_PARTITION) && !CONFIG_IS_ENABLED(EFI_PARTITION) +#error DOS or EFI partition support must be selected +#endif + +#define DOS_PART_MAGIC_OFFSET 0x1fe +#define DOS_FS_TYPE_OFFSET 0x36 +#define DOS_FS32_TYPE_OFFSET 0x52 + +static int do_zfs_load(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) +{ + char *filename = NULL; + int dev; + int part; + ulong addr = 0; + disk_partition_t info; + struct blk_desc *dev_desc; + char buf[12]; + unsigned long count; + const char *addr_str; + struct zfs_file zfile; + struct device_s vdev; + + if (argc < 3) + return CMD_RET_USAGE; + + count = 0; + addr = simple_strtoul(argv[3], NULL, 16); + filename = env_get("bootfile"); + switch (argc) { + case 3: + addr_str = env_get("loadaddr"); + if (addr_str != NULL) + addr = simple_strtoul(addr_str, NULL, 16); + else + addr = CONFIG_SYS_LOAD_ADDR; + + break; + case 4: + break; + case 5: + filename = argv[4]; + break; + case 6: + filename = argv[4]; + count = simple_strtoul(argv[5], NULL, 16); + break; + + default: + return cmd_usage(cmdtp); + } + + if (!filename) { + puts("** No boot file defined **\n"); + return 1; + } + + part = blk_get_device_part_str(argv[1], argv[2], &dev_desc, &info, 1); + if (part < 0) + return 1; + + dev = dev_desc->devnum; + printf("Loading file \"%s\" from %s device %d%c%c\n", + filename, argv[1], dev, + part ? ':' : ' ', part ? part + '0' : ' '); + + zfs_set_blk_dev(dev_desc, &info); + vdev.part_length = info.size; + + memset(&zfile, 0, sizeof(zfile)); + zfile.device = &vdev; + if (zfs_open(&zfile, filename)) { + printf("** File not found %s **\n", filename); + return 1; + } + + if ((count < zfile.size) && (count != 0)) + zfile.size = (uint64_t)count; + + if (zfs_read(&zfile, (char *)addr, zfile.size) != zfile.size) { + printf("** Unable to read \"%s\" from %s %d:%d **\n", + filename, argv[1], dev, part); + zfs_close(&zfile); + return 1; + } + + zfs_close(&zfile); + + /* Loading ok, update default load address */ + load_addr = addr; + + printf("%llu bytes read\n", zfile.size); + env_set_hex("filesize", zfile.size); + + return 0; +} + + +int zfs_print(const char *entry, const struct zfs_dirhook_info *data) +{ + printf("%s %s\n", + data->dir ? " " : " ", + entry); + return 0; /* 0 continue, 1 stop */ +} + + + +static int do_zfs_ls(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[]) +{ + const char *filename = "/"; + int part; + struct blk_desc *dev_desc; + disk_partition_t info; + struct device_s vdev; + + if (argc < 2) + return cmd_usage(cmdtp); + + if (argc == 4) + filename = argv[3]; + + part = blk_get_device_part_str(argv[1], argv[2], &dev_desc, &info, 1); + if (part < 0) + return 1; + + zfs_set_blk_dev(dev_desc, &info); + vdev.part_length = info.size; + + zfs_ls(&vdev, filename, + zfs_print); + + return 0; +} + + +U_BOOT_CMD(zfsls, 4, 1, do_zfs_ls, + "list files in a directory (default /)", + " [directory]\n" + " - list files from 'dev' on 'interface' in a '/DATASET/@/$dir/'"); + +U_BOOT_CMD(zfsload, 6, 0, do_zfs_load, + "load binary file from a ZFS filesystem", + " [addr] [filename] [bytes]\n" + " - load binary file '/DATASET/@/$dir/$file' from 'dev' on 'interface'\n" + " to address 'addr' from ZFS filesystem"); diff --git a/pool/shard008/C/0130052_pm_uc3c.c b/pool/shard008/C/0130052_pm_uc3c.c new file mode 100644 index 0000000000000000000000000000000000000000..14794fa056e6da966ca8e8c43aa92159b3cd0922 --- /dev/null +++ b/pool/shard008/C/0130052_pm_uc3c.c @@ -0,0 +1,279 @@ +/***************************************************************************** + * + * \file + * + * \brief Power Manager(PM) driver interface. + * + * Copyright (c) 2014 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * \asf_license_stop + * + *****************************************************************************/ + /** + * Support and FAQ: visit Atmel Support + */ + +#include "pm_uc3c.h" + +#ifndef AVR32_PM_VERSION_RESETVALUE + #error Cannot use this software module with the current device. +#else + #if AVR32_PM_VERSION_RESETVALUE < 0x400 + #error Cannot use this software module with the current device + #endif +#endif + +/*! \name PM Writable Bit-Field Registers + */ +//! @{ + +typedef union +{ + unsigned long cfdctrl; + avr32_pm_cfdctrl_t CFDCTRL; +} u_avr32_pm_cfdctrl_t; + +typedef union +{ + unsigned long cpusel; + avr32_pm_cpusel_t CPUSEL; +} u_avr32_pm_cpusel_t; + +typedef union +{ + unsigned long pbasel; + avr32_pm_pbasel_t PBASEL; +} u_avr32_pm_pbasel_t; + +typedef union +{ + unsigned long pbbsel; + avr32_pm_pbbsel_t PBBSEL; +} u_avr32_pm_pbbsel_t; + +typedef union +{ + unsigned long pbcsel; + avr32_pm_pbcsel_t PBCSEL; +} u_avr32_pm_pbcsel_t; + +//! @} + + +/** + ** Clock Functions + **/ + +long pm_set_mclk_source(pm_clk_src_t src) +{ + // Unlock the write-protected MCCTRL register + AVR32_ENTER_CRITICAL_REGION( ); + PM_UNLOCK(AVR32_PM_MCCTRL); + AVR32_PM.mcctrl = src; + AVR32_LEAVE_CRITICAL_REGION( ); + + return PASS; +} + +long pm_config_mainclk_safety(bool cfd, bool final) +{ + u_avr32_pm_cfdctrl_t u_avr32_pm_cfdctrl = {AVR32_PM.cfdctrl}; + + // Check if the CFDCTRL register is read-only. + if(AVR32_PM.cfdctrl & AVR32_PM_CFDCTRL_SFV_MASK) + return -1; + + // Unlock the write-protected CFDCTRL register + AVR32_ENTER_CRITICAL_REGION( ); + // Modify + u_avr32_pm_cfdctrl.CFDCTRL.cfden = cfd; + u_avr32_pm_cfdctrl.CFDCTRL.sfv = final; + // Write back + PM_UNLOCK(AVR32_PM_CFDCTRL); + AVR32_PM.cfdctrl = u_avr32_pm_cfdctrl.cfdctrl; + AVR32_LEAVE_CRITICAL_REGION( ); + + return PASS; +} + +long pm_set_clk_domain_div(pm_clk_domain_t clock_domain, pm_divratio_t divratio) +{ + u_avr32_pm_cpusel_t u_avr32_pm_cpusel = {AVR32_PM.cpusel}; + +//# Implementation note: the CPUSEL and PBASEL and PBBSEL registers all have the +//# same structure. + +//# Implementation note: the ckSEL registers are contiguous and memory-mapped in +//# that order: CPUSEL, HSBSEL, PBASEL, PBBSEL. + +#ifdef AVR32SFW_INPUT_CHECK + // Check the divratio + if((divratio > PM_CPUSEL_DIVRATIO_MAX)||(divratio < 0)) + return -1; +#endif + + // ckSEL must not be written while SR.CKRDY is 0. + if(!(AVR32_PM.sr & AVR32_PM_SR_CKRDY_MASK)) + return -1; + + // Modify + u_avr32_pm_cpusel.CPUSEL.cpudiv= 1; + u_avr32_pm_cpusel.CPUSEL.cpusel = divratio; + AVR32_ENTER_CRITICAL_REGION( ); + // Unlock the write-protected ckSEL register + PM_UNLOCK(AVR32_PM_CPUSEL + clock_domain*sizeof(avr32_pm_cpusel_t)); + // Update + *(&(AVR32_PM.cpusel) + clock_domain)= u_avr32_pm_cpusel.cpusel; + AVR32_LEAVE_CRITICAL_REGION( ); + + return PASS; +} + +long pm_disable_clk_domain_div(pm_clk_domain_t clock_domain) +{ + u_avr32_pm_cpusel_t u_avr32_pm_cpusel = {AVR32_PM.cpusel}; + +//# Implementation note: the CPUSEL and PBASEL and PBBSEL and PBCSEL registers all have the +//# same structure. + +//# Implementation note: the ckSEL registers are contiguous and memory-mapped in +//# that order: CPUSEL, HSBSEL, PBASEL, PBBSEL, PBCSEL. + + // ckSEL must not be written while SR.CKRDY is 0. + if(!(AVR32_PM.sr & AVR32_PM_SR_CKRDY_MASK)) + return -1; + + // Modify + u_avr32_pm_cpusel.CPUSEL.cpudiv= DISABLE; + AVR32_ENTER_CRITICAL_REGION( ); + // Unlock the write-protected ckSEL register + PM_UNLOCK(AVR32_PM_CPUSEL + clock_domain*sizeof(avr32_pm_cpusel_t)); + // Update + *(&(AVR32_PM.cpusel) + clock_domain)= u_avr32_pm_cpusel.cpusel; + AVR32_LEAVE_CRITICAL_REGION( ); + + return PASS; +} + +long pm_wait_for_clk_ready(void) +{ + unsigned int timeout = PM_POLL_TIMEOUT; + while (!(AVR32_PM.sr & AVR32_PM_SR_CKRDY_MASK)) + { + if(--timeout == 0) + return -1; + } + return PASS; +} + + + +/** + ** Module Functions + **/ + +long pm_enable_module(unsigned long module) +{ + unsigned long domain = module>>5; +//# Implementation note: the ckMASK registers are contiguous and memory-mapped +//# in that order: CPUMASK, HSBMASK, PBAMASK, PBBMASK. + unsigned long *regptr = (unsigned long*)(&(AVR32_PM.cpumask) + domain); + unsigned long regvalue; + + + // Read + regvalue = *regptr; + // Modify + regvalue |= (1<<(module%32)); + AVR32_ENTER_CRITICAL_REGION( ); + // Unlock the write-protected ckMASK register + PM_UNLOCK(AVR32_PM_CPUMASK + domain*sizeof(avr32_pm_cpumask_t)); + // Write + *regptr = regvalue; + AVR32_LEAVE_CRITICAL_REGION( ); + + return PASS; +} + +long pm_disable_module(unsigned long module) +{ + unsigned long domain = module>>5; +//# Implementation note: the ckMASK registers are contiguous and memory-mapped +//# in that order: CPUMASK, HSBMASK, PBAMASK, PBBMASK. + volatile unsigned long *regptr = (volatile unsigned long*)(&(AVR32_PM.cpumask) + domain); + unsigned long regvalue; + + + // Read + regvalue = *regptr; + // Modify + regvalue &= ~(1<<(module%32)); + AVR32_ENTER_CRITICAL_REGION( ); + // Unlock the write-protected ckMASK register + PM_UNLOCK(AVR32_PM_CPUMASK + domain*sizeof(avr32_pm_cpumask_t)); + // Write + *regptr = regvalue; + AVR32_LEAVE_CRITICAL_REGION( ); + + return PASS; +} + + + +/** + ** Sleep Functions + **/ +// Implemented as inline in pm_uc3c.h + + + +/** + ** Reset Functions + **/ +// Implemented as inline in pm_uc3c.h + + + +/** + ** Interrupt Functions + **/ +// Implemented as inline in pm_uc3c.h + + + +/** + ** Misc Functions + **/ +// Implemented as inline in pm_uc3c.h diff --git a/pool/shard008/C/0130053_os_fsync.c b/pool/shard008/C/0130053_os_fsync.c new file mode 100644 index 0000000000000000000000000000000000000000..377d7ff345bd4554545b44fedd93610df5dc3441 --- /dev/null +++ b/pool/shard008/C/0130053_os_fsync.c @@ -0,0 +1,104 @@ +/*- + * See the file LICENSE for redistribution information. + * + * Copyright (c) 1997, 2015 Oracle and/or its affiliates. All rights reserved. + * + * $Id$ + */ + +#include "db_config.h" + +#include "db_int.h" + +#ifdef HAVE_VXWORKS +#include "ioLib.h" + +#define fsync(fd) __vx_fsync(fd) + +int +__vx_fsync(fd) + int fd; +{ + int ret; + + /* + * The results of ioctl are driver dependent. Some will return the + * number of bytes sync'ed. Only if it returns 'ERROR' should we + * flag it. + */ + if ((ret = ioctl(fd, FIOSYNC, 0)) != ERROR) + return (0); + return (ret); +} +#endif + +#ifdef __hp3000s900 +#define fsync(fd) __mpe_fsync(fd) + +int +__mpe_fsync(fd) + int fd; +{ + extern FCONTROL(short, short, void *); + + FCONTROL(_MPE_FILENO(fd), 2, NULL); /* Flush the buffers */ + FCONTROL(_MPE_FILENO(fd), 6, NULL); /* Write the EOF */ + return (0); +} +#endif + +/* + * __os_fsync -- + * Flush a file descriptor. + * + * PUBLIC: int __os_fsync __P((ENV *, DB_FH *)); + */ +int +__os_fsync(env, fhp) + ENV *env; + DB_FH *fhp; +{ + DB_ENV *dbenv; + int ret; + + dbenv = env == NULL ? NULL : env->dbenv; + + DB_ASSERT(env, F_ISSET(fhp, DB_FH_OPENED) && fhp->fd != -1); + + /* + * Do nothing if the file descriptor has been marked as not requiring + * any sync to disk. + */ + if (F_ISSET(fhp, DB_FH_NOSYNC)) + return (0); + + if (dbenv != NULL && FLD_ISSET(dbenv->verbose, DB_VERB_FILEOPS_ALL)) + __db_msg(env, DB_STR_A("0150", "fileops: flush %s", "%s"), + fhp->name); + + if (DB_GLOBAL(j_fsync) != NULL) + ret = DB_GLOBAL(j_fsync)(fhp->fd); + else { +#if defined(F_FULLFSYNC) + RETRY_CHK((fcntl(fhp->fd, F_FULLFSYNC, 0)), ret); + /* + * On OS X, F_FULLSYNC only works on HFS+, so we need to fall + * back to regular fsync on other filesystems. + */ + if (ret == ENOTSUP) + RETRY_CHK((fsync(fhp->fd)), ret); +#elif defined(HAVE_QNX) + ret = __qnx_fsync(fhp); +#elif defined(HAVE_FDATASYNC) + RETRY_CHK((fdatasync(fhp->fd)), ret); +#else + RETRY_CHK((fsync(fhp->fd)), ret); +#endif + } + + if (ret != 0) { + __db_syserr(env, ret, DB_STR("0151", "fsync")); + ret = __os_posix_err(ret); + } + return (ret); +} diff --git a/pool/shard008/C/0130057_scopy_to_ucol.c b/pool/shard008/C/0130057_scopy_to_ucol.c new file mode 100644 index 0000000000000000000000000000000000000000..99de9898ef46ea1837822f2cc0760ad8f3c4cdac --- /dev/null +++ b/pool/shard008/C/0130057_scopy_to_ucol.c @@ -0,0 +1,105 @@ + + +/* + * -- SuperLU routine (version 2.0) -- + * Univ. of California Berkeley, Xerox Palo Alto Research Center, + * and Lawrence Berkeley National Lab. + * November 15, 1997 + * + */ +/* + Copyright (c) 1994 by Xerox Corporation. All rights reserved. + + THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY + EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK. + + Permission is hereby granted to use or copy this program for any + purpose, provided the above notices are retained on all copies. + Permission to modify the code and to distribute modified code is + granted, provided the above notices are retained, and a notice that + the code was modified is included with the above copyright notice. +*/ + +#include "ssp_defs.h" +#include "util.h" + +int +scopy_to_ucol( + int jcol, /* in */ + int nseg, /* in */ + int *segrep, /* in */ + int *repfnz, /* in */ + int *perm_r, /* in */ + float *dense, /* modified - reset to zero on return */ + GlobalLU_t *Glu /* modified */ + ) +{ +/* + * Gather from SPA dense[*] to global ucol[*]. + */ + int ksub, krep, ksupno; + int i, k, kfnz, segsze; + int fsupc, isub, irow; + int jsupno, nextu; + int new_next, mem_error; + int *xsup, *supno; + int *lsub, *xlsub; + float *ucol; + int *usub, *xusub; + int nzumax; + + float zero = 0.0; + + xsup = Glu->xsup; + supno = Glu->supno; + lsub = Glu->lsub; + xlsub = Glu->xlsub; + ucol = Glu->ucol; + usub = Glu->usub; + xusub = Glu->xusub; + nzumax = Glu->nzumax; + + jsupno = supno[jcol]; + nextu = xusub[jcol]; + k = nseg - 1; + for (ksub = 0; ksub < nseg; ksub++) { + krep = segrep[k--]; + ksupno = supno[krep]; + + if ( ksupno != jsupno ) { /* Should go into ucol[] */ + kfnz = repfnz[krep]; + if ( kfnz != EMPTY ) { /* Nonzero U-segment */ + + fsupc = xsup[ksupno]; + isub = xlsub[fsupc] + kfnz - fsupc; + segsze = krep - kfnz + 1; + + new_next = nextu + segsze; + while ( new_next > nzumax ) { + if (mem_error = sLUMemXpand(jcol, nextu, UCOL, &nzumax, Glu)) + return (mem_error); + ucol = Glu->ucol; + if (mem_error = sLUMemXpand(jcol, nextu, USUB, &nzumax, Glu)) + return (mem_error); + usub = Glu->usub; + lsub = Glu->lsub; + } + + for (i = 0; i < segsze; i++) { + irow = lsub[isub]; + usub[nextu] = perm_r[irow]; + ucol[nextu] = dense[irow]; + dense[irow] = zero; + nextu++; + isub++; + } + + } + + } + + } /* for each segment... */ + + xusub[jcol + 1] = nextu; /* Close U[*,jcol] */ + return 0; +} diff --git a/pool/shard008/C/0130065_gpaste-ui-history-action.c b/pool/shard008/C/0130065_gpaste-ui-history-action.c new file mode 100644 index 0000000000000000000000000000000000000000..439fc04e57ba04e230b4448b17edeaf60cf07992 --- /dev/null +++ b/pool/shard008/C/0130065_gpaste-ui-history-action.c @@ -0,0 +1,143 @@ +/* + * This file is part of GPaste. + * + * Copyright (c) 2010-2018, Marc-Antoine Perennou + */ + +#include +#include + +typedef struct +{ + GPasteClient *client; + GPasteSettings *settings; + GPasteUiHistoryActions *actions; + + GtkWindow *rootwin; + + gchar *history; +} GPasteUiHistoryActionPrivate; + +G_PASTE_DEFINE_ABSTRACT_TYPE_WITH_PRIVATE (UiHistoryAction, ui_history_action, GTK_TYPE_BUTTON) + +/** + * g_paste_ui_history_action_set_history: + * @self: a #GPasteUiHistoryAction instance + * @history: the history to delete + * + * Set the history to delete + */ +G_PASTE_VISIBLE void +g_paste_ui_history_action_set_history (GPasteUiHistoryAction *self, + const gchar *history) +{ + g_return_if_fail (_G_PASTE_IS_UI_HISTORY_ACTION (self)); + + GPasteUiHistoryActionPrivate *priv = g_paste_ui_history_action_get_instance_private (G_PASTE_UI_HISTORY_ACTION (self)); + + g_free (priv->history); + priv->history = g_strdup (history); +} + +static gboolean +g_paste_ui_history_action_button_press_event (GtkWidget *widget, + GdkEventButton *event G_GNUC_UNUSED) +{ + GPasteUiHistoryAction *self = G_PASTE_UI_HISTORY_ACTION (widget); + GPasteUiHistoryActionClass *klass = G_PASTE_UI_HISTORY_ACTION_GET_CLASS (self); + const GPasteUiHistoryActionPrivate *priv = _g_paste_ui_history_action_get_instance_private (self); + gboolean ret; + + if (priv->history && klass->activate) + ret = klass->activate (self, priv->client, priv->settings, priv->rootwin, priv->history); + else + ret = GTK_WIDGET_CLASS (g_paste_ui_history_action_parent_class)->button_press_event (widget, event); + + g_paste_ui_history_actions_set_relative_to (priv->actions, NULL); + + return ret; +} + +static void +g_paste_ui_history_action_dispose (GObject *object) +{ + GPasteUiHistoryActionPrivate *priv = g_paste_ui_history_action_get_instance_private (G_PASTE_UI_HISTORY_ACTION (object)); + + g_clear_object (&priv->client); + g_clear_object (&priv->settings); + + G_OBJECT_CLASS (g_paste_ui_history_action_parent_class)->dispose (object); +} + +static void +g_paste_ui_history_action_finalize (GObject *object) +{ + const GPasteUiHistoryActionPrivate *priv = _g_paste_ui_history_action_get_instance_private (G_PASTE_UI_HISTORY_ACTION (object)); + + g_free (priv->history); + + G_OBJECT_CLASS (g_paste_ui_history_action_parent_class)->finalize (object); +} + +static void +g_paste_ui_history_action_class_init (GPasteUiHistoryActionClass *klass) +{ + GObjectClass *object_class = G_OBJECT_CLASS (klass); + + object_class->dispose = g_paste_ui_history_action_dispose; + object_class->finalize = g_paste_ui_history_action_finalize; + + GTK_WIDGET_CLASS (klass)->button_press_event = g_paste_ui_history_action_button_press_event; +} + +static void +g_paste_ui_history_action_init (GPasteUiHistoryAction *self) +{ + GtkWidget *button = GTK_WIDGET (self); + + gtk_widget_set_margin_start (button, 5); + gtk_widget_set_margin_end (button, 5); +} + +/** + * g_paste_ui_history_action_new: + * @type: the type of the subclass to instantiate + * @client: a #GPasteClient + * @settings: a #GPasteSettings + * @actions: a #GPasteUiHistoryActions + * @rootwin: the main #GtkWindow + * + * Create a new instance of #GPasteUiHistoryAction + * + * Returns: a newly allocated #GPasteUiHistoryAction + * free it with g_object_unref + */ +G_PASTE_VISIBLE GtkWidget * +g_paste_ui_history_action_new (GType type, + GPasteClient *client, + GPasteSettings *settings, + GtkWidget *actions, + GtkWindow *rootwin, + const gchar *label) +{ + g_return_val_if_fail (g_type_is_a (type, G_PASTE_TYPE_UI_HISTORY_ACTION), NULL); + g_return_val_if_fail (_G_PASTE_IS_CLIENT (client), NULL); + g_return_val_if_fail (_G_PASTE_IS_SETTINGS (settings), NULL); + g_return_val_if_fail (_G_PASTE_IS_UI_HISTORY_ACTIONS (actions), NULL); + g_return_val_if_fail (GTK_IS_WINDOW (rootwin), NULL); + + GtkWidget *self = gtk_widget_new (type, + "width-request", 200, + "height-request", 30, + NULL); + GPasteUiHistoryActionPrivate *priv = g_paste_ui_history_action_get_instance_private (G_PASTE_UI_HISTORY_ACTION (self)); + + priv->client = g_object_ref (client); + priv->settings = g_object_ref (settings); + priv->actions = G_PASTE_UI_HISTORY_ACTIONS (actions); + priv->rootwin = rootwin; + + gtk_button_set_label (GTK_BUTTON (self), label); + + return self; +} diff --git a/pool/shard008/C/0130072_DETOUR1027.c b/pool/shard008/C/0130072_DETOUR1027.c new file mode 100644 index 0000000000000000000000000000000000000000..e753c05d4e1a9291ff92256a58044dbc3f7db30d --- /dev/null +++ b/pool/shard008/C/0130072_DETOUR1027.c @@ -0,0 +1,59 @@ +/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo + * This benchmark is part of SWSC */ + +#include +#include +#include +#include + +atomic_int vars[2]; +atomic_int atom_0_r3_1; +atomic_int atom_1_r3_0; + +void *t0(void *arg){ +label_1:; + atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); + int v2_r3 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v3_r4 = v2_r3 ^ v2_r3; + int v4_r4 = v3_r4 + 1; + atomic_store_explicit(&vars[1], v4_r4, memory_order_seq_cst); + atomic_store_explicit(&vars[1], 2, memory_order_seq_cst); + int v13 = (v2_r3 == 1); + atomic_store_explicit(&atom_0_r3_1, v13, memory_order_seq_cst); + return NULL; +} + +void *t1(void *arg){ +label_2:; + atomic_store_explicit(&vars[1], 3, memory_order_seq_cst); + + int v6_r3 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v14 = (v6_r3 == 0); + atomic_store_explicit(&atom_1_r3_0, v14, memory_order_seq_cst); + return NULL; +} + +int main(int argc, char *argv[]){ + pthread_t thr0; + pthread_t thr1; + + atomic_init(&vars[0], 0); + atomic_init(&vars[1], 0); + atomic_init(&atom_0_r3_1, 0); + atomic_init(&atom_1_r3_0, 0); + + pthread_create(&thr0, NULL, t0, NULL); + pthread_create(&thr1, NULL, t1, NULL); + + pthread_join(thr0, NULL); + pthread_join(thr1, NULL); + + int v7 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v8 = (v7 == 3); + int v9 = atomic_load_explicit(&atom_0_r3_1, memory_order_seq_cst); + int v10 = atomic_load_explicit(&atom_1_r3_0, memory_order_seq_cst); + int v11_conj = v9 & v10; + int v12_conj = v8 & v11_conj; + if (v12_conj == 1) assert(0); + return 0; +} diff --git a/pool/shard008/C/0130073_bn_sqr.c b/pool/shard008/C/0130073_bn_sqr.c new file mode 100644 index 0000000000000000000000000000000000000000..0c1c14785cbd2f781799824344c76684f9663bcb --- /dev/null +++ b/pool/shard008/C/0130073_bn_sqr.c @@ -0,0 +1,296 @@ +#include "bn.h" + +#ifndef WITH_LIBCRYPTO +//FIXME Not checked on threadsafety yet; after checking please remove this line +/* crypto/bn/bn_sqr.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The license and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution license + * [including the GNU Public License.] + */ + +#include +#include +#include "bn_lcl.h" +#include "openssl_mods.h" + +/* r must not be a */ +/* I've just gone over this and it is now %20 faster on x86 - eay - 27 Jun 96 */ +int BN_sqr(BIGNUM *r, BIGNUM *a, BN_CTX *ctx) +{ + int max, al; + int ret = 0; + BIGNUM *tmp, *rr; + +#ifdef BN_COUNT + printf("BN_sqr %d * %d\n", a->top, a->top); +#endif + bn_check_top(a); + + al = a->top; + if(al <= 0) + { + r->top = 0; + return (1); + } + + BN_CTX_start(ctx); + rr = (a != r) ? r : BN_CTX_get(ctx); + tmp = BN_CTX_get(ctx); + if(tmp == NULL) { goto err; } + + max = (al + al); + if(bn_wexpand(rr, max + 1) == NULL) { goto err; } + + r->neg = 0; + if(al == 4) + { +#ifndef BN_SQR_COMBA + BN_ULONG t[8]; + bn_sqr_normal(rr->d, a->d, 4, t); +#else + bn_sqr_comba4(rr->d, a->d); +#endif + } + else if(al == 8) + { +#ifndef BN_SQR_COMBA + BN_ULONG t[16]; + bn_sqr_normal(rr->d, a->d, 8, t); +#else + bn_sqr_comba8(rr->d, a->d); +#endif + } + else + { +#if defined(BN_RECURSION) + if(al < BN_SQR_RECURSIVE_SIZE_NORMAL) + { + BN_ULONG t[BN_SQR_RECURSIVE_SIZE_NORMAL * 2]; + bn_sqr_normal(rr->d, a->d, al, t); + } + else + { + int j, k; + + j = BN_num_bits_word((BN_ULONG)al); + j = 1 << (j - 1); + k = j + j; + if(al == j) + { + if(bn_wexpand(a, k * 2) == NULL) { goto err; } + if(bn_wexpand(tmp, k * 2) == NULL) { goto err; } + bn_sqr_recursive(rr->d, a->d, al, tmp->d); + } + else + { + if(bn_wexpand(tmp, max) == NULL) { goto err; } + bn_sqr_normal(rr->d, a->d, al, tmp->d); + } + } +#else + if(bn_wexpand(tmp, max) == NULL) { goto err; } + bn_sqr_normal(rr->d, a->d, al, tmp->d); +#endif + } + + rr->top = max; + if((max > 0) && (rr->d[max - 1] == 0)) { rr->top--; } + if(rr != r) { BN_copy(r, rr); } + ret = 1; +err: + BN_CTX_end(ctx); + return (ret); +} + +/* tmp must have 2*n words */ +void bn_sqr_normal(BN_ULONG *r, BN_ULONG *a, int n, BN_ULONG *tmp) +{ + int i, j, max; + BN_ULONG *ap, *rp; + + max = n * 2; + ap = a; + rp = r; + rp[0] = rp[max - 1] = 0; + rp++; + j = n; + + if(--j > 0) + { + ap++; + rp[j] = bn_mul_words(rp, ap, j, ap[-1]); + rp += 2; + } + + for(i = n - 2; i > 0; i--) + { + j--; + ap++; + rp[j] = bn_mul_add_words(rp, ap, j, ap[-1]); + rp += 2; + } + + bn_add_words(r, r, r, max); + + /* There will not be a carry */ + + bn_sqr_words(tmp, a, n); + + bn_add_words(r, r, tmp, max); +} + +#ifdef BN_RECURSION +/* r is 2*n words in size, + * a and b are both n words in size. (There's not actually a 'b' here ...) + * n must be a power of 2. + * We multiply and return the result. + * t must be 2*n words in size + * We calculate + * a[0]*b[0] + * a[0]*b[0]+a[1]*b[1]+(a[0]-a[1])*(b[1]-b[0]) + * a[1]*b[1] + */ +void bn_sqr_recursive(BN_ULONG *r, BN_ULONG *a, int n2, BN_ULONG *t) +{ + int n = n2 / 2; + int zero, c1; + BN_ULONG ln, lo, *p; + +#ifdef BN_COUNT + printf(" bn_sqr_recursive %d * %d\n", n2, n2); +#endif + if(n2 == 4) + { +#ifndef BN_SQR_COMBA + bn_sqr_normal(r, a, 4, t); +#else + bn_sqr_comba4(r, a); +#endif + return; + } + else if(n2 == 8) + { +#ifndef BN_SQR_COMBA + bn_sqr_normal(r, a, 8, t); +#else + bn_sqr_comba8(r, a); +#endif + return; + } + if(n2 < BN_SQR_RECURSIVE_SIZE_NORMAL) + { + bn_sqr_normal(r, a, n2, t); + return; + } + /* r=(a[0]-a[1])*(a[1]-a[0]) */ + c1 = bn_cmp_words(a, &(a[n]), n); + zero = 0; + if(c1 > 0) + { bn_sub_words(t, a, &(a[n]), n); } + else if(c1 < 0) + { bn_sub_words(t, &(a[n]), a, n); } + else + { zero = 1; } + + /* The result will always be negative unless it is zero */ + p = &(t[n2 * 2]); + + if(!zero) + { bn_sqr_recursive(&(t[n2]), t, n, p); } + else + { memset(&(t[n2]), 0, n2 * sizeof(BN_ULONG)); } + bn_sqr_recursive(r, a, n, p); + bn_sqr_recursive(&(r[n2]), &(a[n]), n, p); + + /* t[32] holds (a[0]-a[1])*(a[1]-a[0]), it is negative or zero + * r[10] holds (a[0]*b[0]) + * r[32] holds (b[1]*b[1]) + */ + + c1 = (int)(bn_add_words(t, r, &(r[n2]), n2)); + + /* t[32] is negative */ + c1 -= (int)(bn_sub_words(&(t[n2]), t, &(t[n2]), n2)); + + /* t[32] holds (a[0]-a[1])*(a[1]-a[0])+(a[0]*a[0])+(a[1]*a[1]) + * r[10] holds (a[0]*a[0]) + * r[32] holds (a[1]*a[1]) + * c1 holds the carry bits + */ + c1 += (int)(bn_add_words(&(r[n]), &(r[n]), &(t[n2]), n2)); + if(c1) + { + p = &(r[n + n2]); + lo = *p; + ln = (lo + c1)&BN_MASK2; + *p = ln; + + /* The overflow will stop before we over write + * words we should not overwrite */ + if(ln < (BN_ULONG)c1) + { + do + { + p++; + lo = *p; + ln = (lo + 1)&BN_MASK2; + *p = ln; + } + while(ln == 0); + } + } +} +#endif +#endif diff --git a/pool/shard008/C/0130075_serial_fifo.c b/pool/shard008/C/0130075_serial_fifo.c new file mode 100644 index 0000000000000000000000000000000000000000..e5a61791218e31c3b476201e026ca020dde5f0e7 --- /dev/null +++ b/pool/shard008/C/0130075_serial_fifo.c @@ -0,0 +1,132 @@ +/** \file serial_fifo.c + * + * \brief Implements FIFO buffers for I/O streams. + * + * Each FIFO buffer is intended to be used in a producer-consumer process, + * with the producer existing in a non-IRH (Interrupt Request Handler) context + * and the consumer existing in an IRH context, or vice versa. Synchronisation + * is handled using critical sections. + * The functions in this file don't actually interface with any + * communications hardware. The interface of circular buffers to hardware + * must be handled elsewhere. + * + * This file is licensed as described by the file LICENCE. + */ + +#include +#include +#include "pic32_system.h" +#include "serial_fifo.h" +#include "usb_callbacks.h" // for usbFatalError() + +/** Clear and initialise contents of circular buffer. + * \param buffer The circular buffer to initialise and clear. + * \param storage Storage array for buffer contents. This must be large enough + * to store the number of bytes specified by size. + * \param size Size, in bytes, of the storage array. + */ +void initCircularBuffer(volatile CircularBuffer *buffer, volatile uint8_t *storage, uint32_t size) +{ + memset((void *)storage, 0xff, size); // just to be sure + memset((void *)storage, 0, size); + buffer->next = 0; + buffer->remaining = 0; + buffer->size = size; + buffer->storage = storage; +} + +/** Check whether a circular buffer is empty. + * \param buffer The circular buffer to check. + * \return Non-zero if it is empty, zero if it is non-empty. + */ +int isCircularBufferEmpty(volatile CircularBuffer *buffer) +{ + return buffer->remaining == 0; +} + +/** Check whether a circular buffer is full. + * \param buffer The circular buffer to check. + * \return Non-zero if it is full, zero if it is not full. + */ +int isCircularBufferFull(volatile CircularBuffer *buffer) +{ + return buffer->remaining == buffer->size; +} + +/** Obtain the remaining space (in number of bytes) in a circular buffer. + * It should be safe to call circularBufferWrite() the number of times + * specified by the return value. + * \param buffer The circular buffer to check. + * \return The number of bytes of space remaining in the circular buffer. + */ +uint32_t circularBufferSpaceRemaining(volatile CircularBuffer *buffer) +{ + // No need to put this in a critical section since (outside of init), + // nothing else touches size. + return buffer->size - buffer->remaining; +} + +/** Read a byte from a circular buffer. This will block until a byte is + * read. + * \param buffer The circular buffer to read from. + * \param is_irq Pass a non-zero value if calling this from an interrupt + * request handler, otherwise pass zero. + * \return The byte that was read from the buffer. + */ +uint8_t circularBufferRead(volatile CircularBuffer *buffer, int is_irq) +{ + uint32_t status; + uint8_t r; + + while(isCircularBufferEmpty(buffer)) + { + if (is_irq) + { + // Interrupt service handlers should never try to read from an + // empty buffer, since they will end up blocking the producer + // and causing a deadlock. + usbFatalError(); + return 0; + } + enterIdleMode(); + } + + status = disableInterrupts(); + r = buffer->storage[buffer->next]; + buffer->remaining--; + buffer->next = (buffer->next + 1) & (buffer->size - 1); + restoreInterrupts(status); + return r; +} + +/** Write a byte to a circular buffer. If the buffer is full, this will block + * until the buffer is not full. + * \param buffer The circular buffer to write to. + * \param data The byte to write to the buffer. + * \param is_irq Pass a non-zero value if calling this from an interrupt + * request handler, otherwise pass zero. + */ +void circularBufferWrite(volatile CircularBuffer *buffer, uint8_t data, int is_irq) +{ + uint32_t status; + uint32_t index; + + while (isCircularBufferFull(buffer)) + { + // Buffer is full. + if (is_irq) + { + // In interrupt handler; cannot block, because that will block + // the consumer and cause a deadlock. + usbFatalError(); + return; + } + enterIdleMode(); + } + + status = disableInterrupts(); + index = (buffer->next + buffer->remaining) & (buffer->size - 1); + buffer->storage[index] = data; + buffer->remaining++; + restoreInterrupts(status); +} diff --git a/pool/shard008/C/0130076_act_pedit.c b/pool/shard008/C/0130076_act_pedit.c new file mode 100644 index 0000000000000000000000000000000000000000..c655df2baff71d4e8f8192e685ee4fbec29384e4 --- /dev/null +++ b/pool/shard008/C/0130076_act_pedit.c @@ -0,0 +1,267 @@ +/* + * net/sched/pedit.c Generic packet editor + * + * 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. + * + * Authors: Jamal Hadi Salim (2002-4) + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define PEDIT_TAB_MASK 15 +static struct tcf_common *tcf_pedit_ht[PEDIT_TAB_MASK + 1]; +static u32 pedit_idx_gen; +static DEFINE_RWLOCK(pedit_lock); + +static struct tcf_hashinfo pedit_hash_info = { + .htab = tcf_pedit_ht, + .hmask = PEDIT_TAB_MASK, + .lock = &pedit_lock, +}; + +static const struct nla_policy pedit_policy[TCA_PEDIT_MAX + 1] = { + [TCA_PEDIT_PARMS] = { .len = sizeof(struct tc_pedit) }, +}; + +static int tcf_pedit_init(struct net *net, struct nlattr *nla, + struct nlattr *est, struct tc_action *a, + int ovr, int bind) +{ + struct nlattr *tb[TCA_PEDIT_MAX + 1]; + struct tc_pedit *parm; + int ret = 0, err; + struct tcf_pedit *p; + struct tcf_common *pc; + struct tc_pedit_key *keys = NULL; + int ksize; + + if (nla == NULL) + return -EINVAL; + + err = nla_parse_nested(tb, TCA_PEDIT_MAX, nla, pedit_policy); + if (err < 0) + return err; + + if (tb[TCA_PEDIT_PARMS] == NULL) + return -EINVAL; + parm = nla_data(tb[TCA_PEDIT_PARMS]); + ksize = parm->nkeys * sizeof(struct tc_pedit_key); + if (nla_len(tb[TCA_PEDIT_PARMS]) < sizeof(*parm) + ksize) + return -EINVAL; + + pc = tcf_hash_check(parm->index, a, bind, &pedit_hash_info); + if (!pc) { + if (!parm->nkeys) + return -EINVAL; + pc = tcf_hash_create(parm->index, est, a, sizeof(*p), bind, + &pedit_idx_gen, &pedit_hash_info); + if (IS_ERR(pc)) + return PTR_ERR(pc); + p = to_pedit(pc); + keys = kmalloc(ksize, GFP_KERNEL); + if (keys == NULL) { + if (est) + gen_kill_estimator(&pc->tcfc_bstats, + &pc->tcfc_rate_est); + kfree_rcu(pc, tcfc_rcu); + return -ENOMEM; + } + ret = ACT_P_CREATED; + } else { + p = to_pedit(pc); + if (!ovr) { + tcf_hash_release(pc, bind, &pedit_hash_info); + return -EEXIST; + } + if (p->tcfp_nkeys && p->tcfp_nkeys != parm->nkeys) { + keys = kmalloc(ksize, GFP_KERNEL); + if (keys == NULL) + return -ENOMEM; + } + } + + spin_lock_bh(&p->tcf_lock); + p->tcfp_flags = parm->flags; + p->tcf_action = parm->action; + if (keys) { + kfree(p->tcfp_keys); + p->tcfp_keys = keys; + p->tcfp_nkeys = parm->nkeys; + } + memcpy(p->tcfp_keys, parm->keys, ksize); + spin_unlock_bh(&p->tcf_lock); + if (ret == ACT_P_CREATED) + tcf_hash_insert(pc, &pedit_hash_info); + return ret; +} + +static int tcf_pedit_cleanup(struct tc_action *a, int bind) +{ + struct tcf_pedit *p = rtnl_dereference(a->priv); + + if (p) { + struct tc_pedit_key *keys = p->tcfp_keys; + if (tcf_hash_release(&p->common, bind, &pedit_hash_info)) { + kfree(keys); + return 1; + } + } + return 0; +} + +static int tcf_pedit(struct sk_buff *skb, const struct tc_action *a, + struct tcf_result *res) +{ + struct tcf_pedit *p = rcu_dereference_bh(a->priv); + int i, munged = 0; + unsigned int off; + + if (skb_unclone(skb, GFP_ATOMIC)) + return p->tcf_action; + + off = skb_network_offset(skb); + + spin_lock(&p->tcf_lock); + + p->tcf_tm.lastuse = jiffies; + + if (p->tcfp_nkeys > 0) { + struct tc_pedit_key *tkey = p->tcfp_keys; + + for (i = p->tcfp_nkeys; i > 0; i--, tkey++) { + u32 *ptr, _data; + int offset = tkey->off; + + if (tkey->offmask) { + char *d, _d; + + d = skb_header_pointer(skb, off + tkey->at, 1, + &_d); + if (!d) + goto bad; + offset += (*d & tkey->offmask) >> tkey->shift; + } + + if (offset % 4) { + pr_info("tc filter pedit" + " offset must be on 32 bit boundaries\n"); + goto bad; + } + if (offset > 0 && offset > skb->len) { + pr_info("tc filter pedit" + " offset %d can't exceed pkt length %d\n", + offset, skb->len); + goto bad; + } + + ptr = skb_header_pointer(skb, off + offset, 4, &_data); + if (!ptr) + goto bad; + /* just do it, baby */ + *ptr = ((*ptr & tkey->mask) ^ tkey->val); + if (ptr == &_data) + skb_store_bits(skb, off + offset, ptr, 4); + munged++; + } + + if (munged) + skb->tc_verd = SET_TC_MUNGED(skb->tc_verd); + goto done; + } else + WARN(1, "pedit BUG: index %d\n", p->tcf_index); + +bad: + p->tcf_qstats.overlimits++; +done: + bstats_update(&p->tcf_bstats, skb); + spin_unlock(&p->tcf_lock); + return p->tcf_action; +} + +static int tcf_pedit_dump(struct sk_buff *skb, struct tc_action *a, + int bind, int ref) +{ + unsigned char *b = skb_tail_pointer(skb); + struct tcf_pedit *p = rtnl_dereference(a->priv); + struct tc_pedit *opt; + struct tcf_t t; + int s; + + s = sizeof(*opt) + p->tcfp_nkeys * sizeof(struct tc_pedit_key); + + /* netlink spinlocks held above us - must use ATOMIC */ + opt = kzalloc(s, GFP_ATOMIC); + if (unlikely(!opt)) + return -ENOBUFS; + + memcpy(opt->keys, p->tcfp_keys, + p->tcfp_nkeys * sizeof(struct tc_pedit_key)); + opt->index = p->tcf_index; + opt->nkeys = p->tcfp_nkeys; + opt->flags = p->tcfp_flags; + opt->action = p->tcf_action; + opt->refcnt = p->tcf_refcnt - ref; + opt->bindcnt = p->tcf_bindcnt - bind; + + if (nla_put(skb, TCA_PEDIT_PARMS, s, opt)) + goto nla_put_failure; + t.install = jiffies_to_clock_t(jiffies - p->tcf_tm.install); + t.lastuse = jiffies_to_clock_t(jiffies - p->tcf_tm.lastuse); + t.expires = jiffies_to_clock_t(p->tcf_tm.expires); + if (nla_put(skb, TCA_PEDIT_TM, sizeof(t), &t)) + goto nla_put_failure; + kfree(opt); + return skb->len; + +nla_put_failure: + nlmsg_trim(skb, b); + kfree(opt); + return -1; +} + +static struct tc_action_ops act_pedit_ops = { + .kind = "pedit", + .hinfo = &pedit_hash_info, + .type = TCA_ACT_PEDIT, + .capab = TCA_CAP_NONE, + .owner = THIS_MODULE, + .act = tcf_pedit, + .dump = tcf_pedit_dump, + .cleanup = tcf_pedit_cleanup, + .lookup = tcf_hash_search, + .init = tcf_pedit_init, + .walk = tcf_generic_walker +}; + +MODULE_AUTHOR("Jamal Hadi Salim(2002-4)"); +MODULE_DESCRIPTION("Generic Packet Editor actions"); +MODULE_LICENSE("GPL"); + +static int __init pedit_init_module(void) +{ + return tcf_register_action(&act_pedit_ops); +} + +static void __exit pedit_cleanup_module(void) +{ + tcf_unregister_action(&act_pedit_ops); +} + +module_init(pedit_init_module); +module_exit(pedit_cleanup_module); + diff --git a/pool/shard008/C/0130078_blowfish.c b/pool/shard008/C/0130078_blowfish.c new file mode 100644 index 0000000000000000000000000000000000000000..59ec2a6979ba8085606b199a80981ee08e02d2f1 --- /dev/null +++ b/pool/shard008/C/0130078_blowfish.c @@ -0,0 +1,84 @@ +/* + * gcc -Wl,-soname,_ecblowfish -fPIC -shared -o _ecblowfish.so blowfish.c -lssl + */ + +#include +#include + +#define n2l(c,l) (l =((unsigned long)(*((c)++)))<<24L, \ + l|=((unsigned long)(*((c)++)))<<16L, \ + l|=((unsigned long)(*((c)++)))<< 8L, \ + l|=((unsigned long)(*((c)++)))) + +#define l2n(l,c) (*((c)++)=(unsigned char)(((l)>>24L)&0xff), \ + *((c)++)=(unsigned char)(((l)>>16L)&0xff), \ + *((c)++)=(unsigned char)(((l)>> 8L)&0xff), \ + *((c)++)=(unsigned char)(((l) )&0xff)) + +void bfencrypt(unsigned char *keydata, int keydatalen, const unsigned char *in, unsigned char *out, unsigned int inlen); +static void cfb64_encrypt(const unsigned char* in, unsigned char* out, long length, BF_KEY* schedule, unsigned char* ivec, int *num, int encrypt); + +/** + * + * + * @param in + * @param out + * @param length + * @param schedule + * @param ivec + * @param num + * @param encrypt + */ + +static void cfb64_encrypt(const unsigned char* in, unsigned char* out, long length, + BF_KEY* schedule, + unsigned char* ivec, + int *num, + int encrypt) +{ + register BF_LONG v0,v1,t; + register int n= *num; + register long l=length; + BF_LONG ti[2]; + unsigned char *iv,c,cc; + + iv=(unsigned char *)ivec; + while (l--) + { + if (n == 0) + { + n2l(iv,v0); ti[0]=v0; + n2l(iv,v1); ti[1]=v1; + BF_encrypt((BF_LONG*)ti,schedule); + iv=(unsigned char *)ivec; + t=ti[0]; l2n(t,iv); + t=ti[1]; l2n(t,iv); + iv=(unsigned char *)ivec; + } + c= *(in++)^iv[n]; + *(out++)=c; + iv[n]=c; + n=(n+1)&0x07; + } + v0=v1=ti[0]=ti[1]=t=c=cc=0; + *num=n; +} + +/** + * + * @param keydata + * @param keydatalen + * @param in + * @param out + * @param inlen + */ + +void bfencrypt(unsigned char *keydata, int keydatalen, const unsigned char *in, unsigned char *out, unsigned int inlen) { + BF_KEY key; + unsigned char ivec[32]; + int num=0; + /** set up for encryption **/ + BF_set_key(&key, keydatalen, keydata); + memset(ivec, '\0', 32); + cfb64_encrypt(in, out, inlen, &key, ivec, &num, BF_ENCRYPT); +} diff --git a/pool/shard008/C/0130079_main_databinder.c b/pool/shard008/C/0130079_main_databinder.c new file mode 100644 index 0000000000000000000000000000000000000000..60d31f3a8ef6c31ed50cfe3f4824b32aa0d3a252 --- /dev/null +++ b/pool/shard008/C/0130079_main_databinder.c @@ -0,0 +1,170 @@ +/* + * Copyright (C) 2007-2018 Siemens AG + * + * 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 . + */ + +/******************************************************************* + * + * @author Daniel.Peintner.EXT@siemens.com + * @version 0.9.4 + * @contact Richard.Kuntschke@siemens.com + * + *

Code generated by EXIdizer

+ *

Schema: V2G_CI_MsgDef.xsd

+ * + * + ********************************************************************/ + + + +/******************************************************************* + * + *

Sample program to illustrate how to read an EXI stream and + * directly write it again to an output

+ * + *

e.g., in.exi out.exi

+ ********************************************************************/ + +#include +#include +#include + +/* schema-dependent */ +#include "iso1EXIDatatypes.h" +#if DEPLOY_ISO1_CODEC == SUPPORT_YES +#include "iso1EXIDatatypesEncoder.h" +#include "iso1EXIDatatypesDecoder.h" +#endif /* DEPLOY_ISO1_CODEC == SUPPORT_YES */ +#include "iso2EXIDatatypes.h" +#if DEPLOY_ISO2_CODEC == SUPPORT_YES +#include "iso2EXIDatatypesEncoder.h" +#include "iso2EXIDatatypesDecoder.h" +#endif /* DEPLOY_ISO2_CODEC == SUPPORT_YES */ + +#include "ByteStream.h" + +/** EXI Debug mode */ +#define EXI_DEBUG 0 + +#define BUFFER_SIZE 4096 +uint8_t bufferIn[BUFFER_SIZE]; +uint8_t bufferOut[BUFFER_SIZE]; + + +#if EXI_DEBUG == 1 +# define DEBUG_PRINTF(x) printf x +#else +# define DEBUG_PRINTF(x) do {} while (0) +#endif + + +int main_databinder(int argc, char *argv[]) { + +#if DEPLOY_ISO1_CODEC == SUPPORT_YES + struct iso1EXIDocument exi1Doc; +#endif /* DEPLOY_ISO1_CODEC == SUPPORT_YES */ +#if DEPLOY_ISO2_CODEC == SUPPORT_YES + struct iso2EXIDocument exi2Doc; +#endif /* DEPLOY_ISO2_CODEC == SUPPORT_YES */ + int errn = 0; + + bitstream_t iStream, oStream; + +#if EXI_STREAM == BYTE_ARRAY + size_t posDecode; + size_t posEncode; +#endif /* EXI_STREAM == BYTE_ARRAY */ + + +#if EXI_DEBUG == 1 + /* The Eclipse console has buffering problems on Windows e.g, Debug mode */ + setvbuf(stdout, NULL, _IONBF, 0); + setvbuf(stderr, NULL, _IONBF, 0); +#endif /*EXI_DEBUG*/ + + if (argc != 3) { + printf("Usage: %s exiInput exiOutput\n", argv[0]); + return -1; + } + +#if EXI_STREAM == BYTE_ARRAY + /* input pos */ + posDecode = 0; + /* parse EXI stream to internal byte structures */ + errn = readBytesFromFile(argv[1], bufferIn, BUFFER_SIZE, &posDecode); + if (errn != 0) { + printf("Problems while reading file into buffer, err==%d\n", errn); + return errn; + } + posDecode = 0; /* reset position */ +#endif /* EXI_STREAM == BYTE_ARRAY */ + + /* setup input stream */ +#if EXI_STREAM == BYTE_ARRAY + iStream.size = BUFFER_SIZE; + iStream.data = bufferIn; + iStream.pos = &posDecode; +#endif /* EXI_STREAM == BYTE_ARRAY */ + + iStream.buffer = 0; + iStream.capacity = 0; + + + printf("Start decoding EXI stream to databinding layer \n"); +#if DEPLOY_ISO1_CODEC == SUPPORT_YES + errn = decode_iso1ExiDocument(&iStream, &exi1Doc); +#endif /* DEPLOY_ISO1_CODEC == SUPPORT_YES */ +#if DEPLOY_ISO2_CODEC == SUPPORT_YES + errn = decode_iso2ExiDocument(&iStream, &exi2Doc); +#endif /* DEPLOY_ISO2_CODEC == SUPPORT_YES */ + if (errn != 0) { + printf("Problems while decoding EXI stream, err==%d\n", errn); + return errn; + } + +#if EXI_STREAM == BYTE_ARRAY + /* setup output stream */ + posEncode = 0; + oStream.size = BUFFER_SIZE; + oStream.data = bufferOut; + oStream.pos = &posEncode; +#endif + + oStream.buffer = 0; + oStream.capacity = 8; + + printf("Start encoding databinding layer to EXI \n"); +#if DEPLOY_ISO1_CODEC == SUPPORT_YES + errn = encode_iso1ExiDocument(&oStream, &exi1Doc); +#endif /* DEPLOY_ISO1_CODEC == SUPPORT_YES */ +#if DEPLOY_ISO2_CODEC == SUPPORT_YES + errn = encode_iso2ExiDocument(&oStream, &exi2Doc); +#endif /* DEPLOY_ISO2_CODEC == SUPPORT_YES */ + if (errn != 0) { + printf("Problems while encoding databinding layer, err==%d\n", errn); + return errn; + } + + printf("EXI roundtrip done with success\n"); +#if EXI_STREAM == BYTE_ARRAY + /* write to file */ + writeBytesToFile(oStream.data, posEncode, argv[2]); +#endif + + + return errn; +} + + diff --git a/pool/shard008/C/0130087_pwrbutton_management.c b/pool/shard008/C/0130087_pwrbutton_management.c new file mode 100644 index 0000000000000000000000000000000000000000..b19f46b6fa024e5193be18ca6f73568234485782 --- /dev/null +++ b/pool/shard008/C/0130087_pwrbutton_management.c @@ -0,0 +1,229 @@ +/* + * Power Button management + * Copyright 2013 Seco S.r.l. + * + * Author: Matrco Sandrelli + * Maintainers: + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * Add in board platform definition the following function to create exported device + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define INPUT_DEV_NAME "Embedded Controller" +#define PWR_BUTTON_NAME "power_button" +#define INPUT_POWER_NAME INPUT_DEV_NAME " - " PWR_BUTTON_NAME +#define MAX_LEN_NAME 32 +#define DELAY_TIME 500 +#define HALT_TIME 4000 + +struct event_dev { + unsigned short int id; + struct input_dev *input; + char name[MAX_LEN_NAME]; +}; + +struct pwrb_control { + struct event_dev *events; + int irq; + unsigned long irq_flags; + unsigned long pwrb_gpio; + unsigned long halt_gpio; + char *phys; + struct delayed_work pwbd_event_work; + struct workqueue_struct *pwbd_wq; + long msecs; +}; + +/* + * Manage Power Button event + * + */ +static void pwbd_pressure_event_worker(struct work_struct *work) +{ + /* Report power button event */ + struct pwrb_control *wm = container_of(work, struct pwrb_control, pwbd_event_work.work); + + if (gpio_get_value(wm->pwrb_gpio) && ((jiffies_to_msecs(jiffies) - wm->msecs) < HALT_TIME) ) { + /* Shutdown the system calling dpwrevn */ + input_report_key (wm->events->input, KEY_POWER, 1); + input_sync (wm->events->input); + input_report_key (wm->events->input, KEY_POWER, 0); + input_sync (wm->events->input); + wm->msecs = 0; + enable_irq(wm->irq); + } else { + + if((jiffies_to_msecs(jiffies) - wm->msecs) > HALT_TIME) { + /* Shutdown the system brutally */ + printk(KERN_INFO"%s: halt the system!",__FUNCTION__); + gpio_request(wm->halt_gpio,"HALT"); + gpio_direction_output(wm->halt_gpio, 1); + mdelay(1); + gpio_set_value(wm->halt_gpio, 0); + queue_delayed_work(wm->pwbd_wq, &wm->pwbd_event_work,msecs_to_jiffies(DELAY_TIME)); + + } else + queue_delayed_work(wm->pwbd_wq, &wm->pwbd_event_work,msecs_to_jiffies(DELAY_TIME)); + } + + return; +} + +/* + * Catch Power Button Event + * + */ +static irqreturn_t pwrb_irq_handler (int irq, void *dev_id) { + + struct pwrb_control *pwbd = ((struct pwrb_control *) dev_id); + printk (KERN_INFO "event name: %s\n", pwbd->events->input->name); + disable_irq_nosync (pwbd->irq); + if (!delayed_work_pending(&pwbd->pwbd_event_work)){ + pwbd->msecs = jiffies_to_msecs(jiffies); + queue_delayed_work(pwbd->pwbd_wq, &pwbd->pwbd_event_work, msecs_to_jiffies(DELAY_TIME)); + } + + return IRQ_HANDLED; +} + + + +/* + * Probing the driver + * + */ +static int __devinit pwrb_probe(struct platform_device *pdev) +{ + int err, ret; + struct pwrb_control *pwrb_data; + struct imx_seco_pwrb_platform_data *pdata = (struct imx_seco_pwrb_platform_data *)pdev->dev.platform_data; + + if (!pdata) { + dev_err(&pdev->dev, "platform data is required!\n"); + return -EINVAL; + } + printk("pwrb probing..."); + + pwrb_data = kzalloc (sizeof (struct pwrb_control), GFP_KERNEL); + + if (!pwrb_data) { + err = -ENOMEM; + goto err_pwrb; + } + + pwrb_data->events = kzalloc (sizeof (struct event_dev), GFP_KERNEL); + if (!pwrb_data->events) { + err = -ENOMEM; + goto err_pwrb; + } + + pwrb_data->events->input = input_allocate_device(); + if (!pwrb_data->events->input) { + err = -ENOMEM; + goto err_pwrb; + } + + pwrb_data->phys = kzalloc (sizeof (char) * 32, GFP_KERNEL); + snprintf(pwrb_data->phys, sizeof(char) * 32, + "%s/input%d", dev_name(&pdev->dev), 0); + + pwrb_data->events->input->name = INPUT_POWER_NAME; + pwrb_data->events->input->phys = pwrb_data->phys; + pwrb_data->events->input->dev.parent = &pdev->dev; + + pwrb_data->events->input->evbit[0] = BIT_MASK(EV_KEY); + set_bit (KEY_POWER, pwrb_data->events->input->keybit); + + err = input_register_device (pwrb_data->events->input); + if (err) { + printk ("pwrb: No input assigned"); + err = -EINVAL; + goto err_pwrb; + } + + pwrb_data->irq = gpio_to_irq(pdata->pwrb_gpio); + pwrb_data->irq_flags = pdata->irq_flags; + pwrb_data->pwrb_gpio = pdata->pwrb_gpio; + pwrb_data->halt_gpio = pdata->halt_gpio; + ret = request_irq (pwrb_data->irq, pwrb_irq_handler, + pwrb_data->irq_flags, "pwrb_irq", pwrb_data); + + if (ret) { + printk ("pwrb error %d: IRQ not acquired", ret); + err = -EIO; + goto err_free_irq; + } + + pwrb_data->pwbd_wq = create_singlethread_workqueue("pwbd_work"); + if(!pwrb_data->pwbd_wq){ + printk ("pwrb error %d: Work not allocated", ret); + err = -EINVAL; + goto err_free_irq; + } + INIT_DELAYED_WORK(&pwrb_data->pwbd_event_work, pwbd_pressure_event_worker); + pwrb_data->msecs = 0; + printk("done\n"); + + return 0; +err_pwrb: + printk("Errors pwrb\n"); + return -1; +err_free_irq: + printk("pwrb: freeing irq"); + free_irq (pwrb_data->irq, pwrb_data); + return -1; + +} + +static int __devexit pwrb_remove(struct platform_device *pdev) +{ + printk("pwrb: clean memory"); + return 0; +} + +static struct platform_driver pwrb_driver = { + .driver = { + .name = "imx_seco_pwrb", + }, + .probe = pwrb_probe, + .remove = __devexit_p(pwrb_remove), +}; + +static int __init pwrb_init(void) +{ + return platform_driver_register(&pwrb_driver); +} + +static void __exit pwrb_exit(void) +{ + platform_driver_unregister(&pwrb_driver); + +} + +module_init(pwrb_init); +module_exit(pwrb_exit); + +MODULE_AUTHOR("MS SECO, Inc."); +MODULE_DESCRIPTION("Power Button Management Driver"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard008/C/0130090_vlc-video-plugin.c b/pool/shard008/C/0130090_vlc-video-plugin.c new file mode 100644 index 0000000000000000000000000000000000000000..e37439c1f01597141809738f0150a61cb0d0a47e --- /dev/null +++ b/pool/shard008/C/0130090_vlc-video-plugin.c @@ -0,0 +1,211 @@ +#ifdef _WIN32 +#include +#endif + +#include +#include "vlc-video-plugin.h" + +OBS_DECLARE_MODULE() +OBS_MODULE_USE_DEFAULT_LOCALE("vlc-video", "en-US") + +/* libvlc core */ +LIBVLC_NEW libvlc_new_; +LIBVLC_RELEASE libvlc_release_; +LIBVLC_CLOCK libvlc_clock_; +LIBVLC_EVENT_ATTACH libvlc_event_attach_; + +/* libvlc media */ +LIBVLC_MEDIA_NEW_PATH libvlc_media_new_path_; +LIBVLC_MEDIA_NEW_LOCATION libvlc_media_new_location_; +LIBVLC_MEDIA_ADD_OPTION libvlc_media_add_option_; +LIBVLC_MEDIA_RELEASE libvlc_media_release_; +LIBVLC_MEDIA_RELEASE libvlc_media_retain_; + +/* libvlc media player */ +LIBVLC_MEDIA_PLAYER_NEW libvlc_media_player_new_; +LIBVLC_MEDIA_PLAYER_NEW_FROM_MEDIA libvlc_media_player_new_from_media_; +LIBVLC_MEDIA_PLAYER_RELEASE libvlc_media_player_release_; +LIBVLC_VIDEO_SET_CALLBACKS libvlc_video_set_callbacks_; +LIBVLC_VIDEO_SET_FORMAT_CALLBACKS libvlc_video_set_format_callbacks_; +LIBVLC_AUDIO_SET_CALLBACKS libvlc_audio_set_callbacks_; +LIBVLC_AUDIO_SET_FORMAT_CALLBACKS libvlc_audio_set_format_callbacks_; +LIBVLC_MEDIA_PLAYER_PLAY libvlc_media_player_play_; +LIBVLC_MEDIA_PLAYER_STOP libvlc_media_player_stop_; +LIBVLC_MEDIA_PLAYER_GET_TIME libvlc_media_player_get_time_; +LIBVLC_VIDEO_GET_SIZE libvlc_video_get_size_; +LIBVLC_MEDIA_PLAYER_EVENT_MANAGER libvlc_media_player_event_manager_; +LIBVLC_VIDEO_SET_DEINTERLACE libvlc_video_set_deinterlace_; + +/* libvlc media list */ +LIBVLC_MEDIA_LIST_NEW libvlc_media_list_new_; +LIBVLC_MEDIA_LIST_RELEASE libvlc_media_list_release_; +LIBVLC_MEDIA_LIST_ADD_MEDIA libvlc_media_list_add_media_; +LIBVLC_MEDIA_LIST_LOCK libvlc_media_list_lock_; +LIBVLC_MEDIA_LIST_UNLOCK libvlc_media_list_unlock_; +LIBVLC_MEDIA_LIST_EVENT_MANAGER libvlc_media_list_event_manager_; + +/* libvlc media list player */ +LIBVLC_MEDIA_LIST_PLAYER_NEW libvlc_media_list_player_new_; +LIBVLC_MEDIA_LIST_PLAYER_RELEASE libvlc_media_list_player_release_; +LIBVLC_MEDIA_LIST_PLAYER_PLAY libvlc_media_list_player_play_; +LIBVLC_MEDIA_LIST_PLAYER_PAUSE libvlc_media_list_player_pause_; +LIBVLC_MEDIA_LIST_PLAYER_STOP libvlc_media_list_player_stop_; +LIBVLC_MEDIA_LIST_PLAYER_SET_MEDIA_PLAYER libvlc_media_list_player_set_media_player_; +LIBVLC_MEDIA_LIST_PLAYER_SET_MEDIA_LIST libvlc_media_list_player_set_media_list_; +LIBVLC_MEDIA_LIST_PLAYER_EVENT_MANAGER libvlc_media_list_player_event_manager_; +LIBVLC_MEDIA_LIST_PLAYER_SET_PLAYBACK_MODE libvlc_media_list_player_set_playback_mode_; +LIBVLC_MEDIA_LIST_PLAYER_NEXT libvlc_media_list_player_next_; +LIBVLC_MEDIA_LIST_PLAYER_PREVIOUS libvlc_media_list_player_previous_; + +void *libvlc_module = NULL; +libvlc_instance_t *libvlc = NULL; +uint64_t time_start = 0; + +static bool load_vlc_funcs(void) +{ +#define LOAD_VLC_FUNC(func) \ + do { \ + func ## _ = os_dlsym(libvlc_module, #func); \ + if (!func ## _) { \ + blog(LOG_WARNING, "Could not func VLC function %s, " \ + "VLC loading failed", #func); \ + return false; \ + } \ + } while (false) + + /* libvlc core */ + LOAD_VLC_FUNC(libvlc_new); + LOAD_VLC_FUNC(libvlc_release); + LOAD_VLC_FUNC(libvlc_clock); + LOAD_VLC_FUNC(libvlc_event_attach); + + /* libvlc media */ + LOAD_VLC_FUNC(libvlc_media_new_path); + LOAD_VLC_FUNC(libvlc_media_new_location); + LOAD_VLC_FUNC(libvlc_media_add_option); + LOAD_VLC_FUNC(libvlc_media_release); + LOAD_VLC_FUNC(libvlc_media_retain); + + /* libvlc media player */ + LOAD_VLC_FUNC(libvlc_media_player_new); + LOAD_VLC_FUNC(libvlc_media_player_new_from_media); + LOAD_VLC_FUNC(libvlc_media_player_release); + LOAD_VLC_FUNC(libvlc_video_set_callbacks); + LOAD_VLC_FUNC(libvlc_video_set_format_callbacks); + LOAD_VLC_FUNC(libvlc_audio_set_callbacks); + LOAD_VLC_FUNC(libvlc_audio_set_format_callbacks); + LOAD_VLC_FUNC(libvlc_media_player_play); + LOAD_VLC_FUNC(libvlc_media_player_stop); + LOAD_VLC_FUNC(libvlc_media_player_get_time); + LOAD_VLC_FUNC(libvlc_video_get_size); + LOAD_VLC_FUNC(libvlc_media_player_event_manager); + LOAD_VLC_FUNC(libvlc_video_set_deinterlace); + + /* libvlc media list */ + LOAD_VLC_FUNC(libvlc_media_list_new); + LOAD_VLC_FUNC(libvlc_media_list_release); + LOAD_VLC_FUNC(libvlc_media_list_add_media); + LOAD_VLC_FUNC(libvlc_media_list_lock); + LOAD_VLC_FUNC(libvlc_media_list_unlock); + LOAD_VLC_FUNC(libvlc_media_list_event_manager); + + /* libvlc media list player */ + LOAD_VLC_FUNC(libvlc_media_list_player_new); + LOAD_VLC_FUNC(libvlc_media_list_player_release); + LOAD_VLC_FUNC(libvlc_media_list_player_play); + LOAD_VLC_FUNC(libvlc_media_list_player_pause); + LOAD_VLC_FUNC(libvlc_media_list_player_stop); + LOAD_VLC_FUNC(libvlc_media_list_player_set_media_player); + LOAD_VLC_FUNC(libvlc_media_list_player_set_media_list); + LOAD_VLC_FUNC(libvlc_media_list_player_event_manager); + LOAD_VLC_FUNC(libvlc_media_list_player_set_playback_mode); + LOAD_VLC_FUNC(libvlc_media_list_player_next); + LOAD_VLC_FUNC(libvlc_media_list_player_previous); + return true; +} + +static bool load_libvlc_module(void) +{ +#ifdef _WIN32 + char *path_utf8 = NULL; + wchar_t path[1024]; + LSTATUS status; + DWORD size; + HKEY key; + + memset(path, 0, 1024 * sizeof(wchar_t)); + + status = RegOpenKeyW(HKEY_LOCAL_MACHINE, + L"SOFTWARE\\VideoLAN\\VLC", + &key); + if (status != ERROR_SUCCESS) + return false; + + size = 1024; + status = RegQueryValueExW(key, L"InstallDir", NULL, NULL, + (LPBYTE)path, &size); + if (status == ERROR_SUCCESS) { + wcscat(path, L"\\libvlc.dll"); + os_wcs_to_utf8_ptr(path, 0, &path_utf8); + libvlc_module = os_dlopen(path_utf8); + bfree(path_utf8); + } + + RegCloseKey(key); +#else + +#ifdef __APPLE__ +#define LIBVLC_DIR "/Applications/VLC.app/Contents/MacOS/" +#define LIBVLC_FILE LIBVLC_DIR "lib/libvlc.5.dylib" + setenv("VLC_PLUGIN_PATH", LIBVLC_DIR "plugins", false); +#else +#define LIBVLC_FILE "libvlc.so.5" +#endif + libvlc_module = os_dlopen(LIBVLC_FILE); + +#endif + + return libvlc_module != NULL; +} + +extern struct obs_source_info vlc_source_info; + +bool load_libvlc(void) +{ + if (libvlc) + return true; + + libvlc = libvlc_new_(0, 0); + if (!libvlc) { + blog(LOG_INFO, "Couldn't create libvlc instance"); + return false; + } + + time_start = (uint64_t)libvlc_clock_() * 1000ULL; + return true; +} + +bool obs_module_load(void) +{ + if (!load_libvlc_module()) { + blog(LOG_INFO, "Couldn't find VLC installation, VLC video " + "source disabled"); + return true; + } + + if (!load_vlc_funcs()) + return true; + + blog(LOG_INFO, "VLC found, VLC video source enabled"); + + obs_register_source(&vlc_source_info); + return true; +} + +void obs_module_unload(void) +{ + if (libvlc) + libvlc_release_(libvlc); + if (libvlc_module) + os_dlclose(libvlc_module); +} diff --git a/pool/shard008/C/0130091_EdbSupportFile.c b/pool/shard008/C/0130091_EdbSupportFile.c new file mode 100644 index 0000000000000000000000000000000000000000..2d817f98e673902ec77483a50c619a6a282d57b8 --- /dev/null +++ b/pool/shard008/C/0130091_EdbSupportFile.c @@ -0,0 +1,390 @@ +/** @file + +Copyright (c) 2007, Intel Corporation. All rights reserved.
+This program and the accompanying materials +are licensed and made available under the terms and conditions of the BSD License +which accompanies this distribution. The full text of the license may be found at +http://opensource.org/licenses/bsd-license.php + +THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. + + +**/ + +#include "Edb.h" + +/** + Read a file. + + @param Vol - File System Volume + @param FileName - The file to be read. + @param BufferSize - The file buffer size + @param Buffer - The file buffer + + @retval EFI_SUCCESS - read file successfully + @retval EFI_NOT_FOUND - file not found + +**/ +EFI_STATUS +EFIAPI +ReadFileFromVol ( + IN EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Vol, + IN CHAR16 *FileName, + OUT UINTN *BufferSize, + OUT VOID **Buffer + ) +{ + EFI_STATUS Status; + EFI_FILE_HANDLE RootDir; + EFI_FILE_HANDLE Handle; + UINTN FileInfoSize; + EFI_FILE_INFO *FileInfo; + UINTN TempBufferSize; + VOID *TempBuffer; + + // + // Open the root directory + // + Status = Vol->OpenVolume (Vol, &RootDir); + if (EFI_ERROR (Status)) { + return Status; + } + + // + // Open the file + // + Status = RootDir->Open ( + RootDir, + &Handle, + FileName, + EFI_FILE_MODE_READ, + 0 + ); + if (EFI_ERROR (Status)) { + RootDir->Close (RootDir); + return Status; + } + + RootDir->Close (RootDir); + + // + // Get the file information + // + FileInfoSize = sizeof(EFI_FILE_INFO) + 1024; + + FileInfo = AllocateZeroPool (FileInfoSize); + if (FileInfo == NULL) { + Handle->Close (Handle); + return Status; + } + + Status = Handle->GetInfo ( + Handle, + &gEfiFileInfoGuid, + &FileInfoSize, + FileInfo + ); + if (EFI_ERROR (Status)) { + Handle->Close (Handle); + gBS->FreePool (FileInfo); + return Status; + } + + // + // Allocate buffer for the file data. The last CHAR16 is for L'\0' + // + TempBufferSize = (UINTN) FileInfo->FileSize + sizeof(CHAR16); + TempBuffer = AllocateZeroPool (TempBufferSize); + if (TempBuffer == NULL) { + Handle->Close (Handle); + gBS->FreePool (FileInfo); + return Status; + } + + gBS->FreePool (FileInfo); + + // + // Read the file data to the buffer + // + Status = Handle->Read ( + Handle, + &TempBufferSize, + TempBuffer + ); + if (EFI_ERROR (Status)) { + Handle->Close (Handle); + gBS->FreePool (TempBuffer); + return Status; + } + + Handle->Close (Handle); + + *BufferSize = TempBufferSize; + *Buffer = TempBuffer; + return EFI_SUCCESS; +} + +/** + + Read a file. + If ScanFs is FLASE, it will use DebuggerPrivate->Vol as default Fs. + If ScanFs is TRUE, it will scan all FS and check the file. + If there is only one file match the name, it will be read. + If there is more than one file match the name, it will return Error. + + @param DebuggerPrivate - EBC Debugger private data structure + @param FileName - The file to be read. + @param BufferSize - The file buffer size + @param Buffer - The file buffer + @param ScanFs - Need Scan all FS + + @retval EFI_SUCCESS - read file successfully + @retval EFI_NOT_FOUND - file not found + @retval EFI_NO_MAPPING - there is duplicated files found + +**/ +EFI_STATUS +EFIAPI +ReadFileToBuffer ( + IN EFI_DEBUGGER_PRIVATE_DATA *DebuggerPrivate, + IN CHAR16 *FileName, + OUT UINTN *BufferSize, + OUT VOID **Buffer, + IN BOOLEAN ScanFs + ) +{ + EFI_STATUS Status; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Vol; + UINTN TempBufferSize; + VOID *TempBuffer; + UINTN NoHandles; + EFI_HANDLE *HandleBuffer; + UINTN Index; + + // + // Check parameters + // + if ((FileName == NULL) || (Buffer == NULL)) { + return EFI_INVALID_PARAMETER; + } + + // + // not scan fs + // + if (!ScanFs) { + if (DebuggerPrivate->Vol == NULL) { + return EFI_INVALID_PARAMETER; + } + // + // Read file directly from Vol + // + return ReadFileFromVol (DebuggerPrivate->Vol, FileName, BufferSize, Buffer); + } + + // + // need scan fs + // + + // + // Get all Vol handle + // + Status = gBS->LocateHandleBuffer ( + ByProtocol, + &gEfiSimpleFileSystemProtocolGuid, + NULL, + &NoHandles, + &HandleBuffer + ); + if (EFI_ERROR (Status) && (NoHandles == 0)) { + return EFI_NOT_FOUND; + } + + // + // Walk through each Vol + // + DebuggerPrivate->Vol = NULL; + *BufferSize = 0; + *Buffer = NULL; + for (Index = 0; Index < NoHandles; Index++) { + Status = gBS->HandleProtocol ( + HandleBuffer[Index], + &gEfiSimpleFileSystemProtocolGuid, + (VOID**) &Vol + ); + if (EFI_ERROR(Status)) { + continue; + } + + Status = ReadFileFromVol (Vol, FileName, &TempBufferSize, &TempBuffer); + if (!EFI_ERROR (Status)) { + // + // Read file OK, check duplication + // + if (DebuggerPrivate->Vol != NULL) { + // + // Find the duplicated file + // + gBS->FreePool (TempBuffer); + gBS->FreePool (*Buffer); + EDBPrint (L"Duplicated FileName found!\n"); + return EFI_NO_MAPPING; + } else { + // + // Record value + // + DebuggerPrivate->Vol = Vol; + *BufferSize = TempBufferSize; + *Buffer = TempBuffer; + } + } + } + + // + // Scan Fs done + // + if (DebuggerPrivate->Vol == NULL) { + return EFI_NOT_FOUND; + } + + // + // Done + // + return EFI_SUCCESS; +} + +/** + + Get file name under this dir with index + + @param DebuggerPrivate - EBC Debugger private data structure + @param DirName - The dir to be read. + @param FileName - The file name pattern under this dir + @param Index - The file index under this dir + + @return File Name which match the pattern and index. + +**/ +CHAR16 * +EFIAPI +GetFileNameUnderDir ( + IN EFI_DEBUGGER_PRIVATE_DATA *DebuggerPrivate, + IN CHAR16 *DirName, + IN CHAR16 *FileName, + IN OUT UINTN *Index + ) +{ + EFI_STATUS Status; + EFI_FILE_HANDLE RootDir; + EFI_FILE_HANDLE Handle; + UINTN FileInfoSize; + EFI_FILE_INFO *FileInfo; + EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *Vol; + VOID *TempName; + UINTN FileIndex; + + if (DebuggerPrivate->Vol == NULL) { + Status = gBS->LocateProtocol ( + &gEfiSimpleFileSystemProtocolGuid, + NULL, + (VOID**) &DebuggerPrivate->Vol + ); + if (EFI_ERROR(Status)) { + return NULL; + } + } + Vol = DebuggerPrivate->Vol; + + // + // Open the root directory + // + Status = Vol->OpenVolume (Vol, &RootDir); + if (EFI_ERROR (Status)) { + return NULL; + } + + // + // Open the file + // + Status = RootDir->Open ( + RootDir, + &Handle, + DirName, + EFI_FILE_MODE_READ, + EFI_FILE_DIRECTORY + ); + if (EFI_ERROR (Status)) { + RootDir->Close (RootDir); + return NULL; + } + RootDir->Close (RootDir); + + // + // Set Dir Position + // + Status = Handle->SetPosition (Handle, 0); + if (EFI_ERROR (Status)) { + Handle->Close (Handle); + return NULL; + } + + // + // Get the file information + // + FileInfoSize = sizeof(EFI_FILE_INFO) + 1024; + + FileInfo = AllocateZeroPool (FileInfoSize); + if (FileInfo == NULL) { + Handle->Close (Handle); + return NULL; + } + + // + // Walk through each file in the directory + // + FileIndex = 0; + TempName = NULL; + while (TRUE) { + // + // Read a file entry + // + FileInfoSize = sizeof(EFI_FILE_INFO) + 1024; + + Status = Handle->Read ( + Handle, + &FileInfoSize, + FileInfo + ); + if (EFI_ERROR (Status) || (FileInfoSize == 0)) { + break; + } + + if ((FileInfo->Attribute & EFI_FILE_DIRECTORY) == 0) { + // + // This is a file + // + + // + // Only deal with the EFI key file + // + if (!StrEndWith (FileInfo->FileName, FileName)) { + continue; + } + + if (FileIndex == *Index) { + TempName = StrDuplicate (FileInfo->FileName); + *Index = *Index + 1; + break; + } + FileIndex ++; + } + } + + // + // Free resources + // + gBS->FreePool (FileInfo); + Handle->Close (Handle); + + return TempName; +} diff --git a/pool/shard008/C/0130092_tsc2101.c b/pool/shard008/C/0130092_tsc2101.c new file mode 100644 index 0000000000000000000000000000000000000000..f676d0468e595c0da09e6974cdd2b36ec243ad1d --- /dev/null +++ b/pool/shard008/C/0130092_tsc2101.c @@ -0,0 +1,123 @@ +/** + * EIA-FR - Embedded Systems 2 laboratory + * + * Abstract: TSC2101 - Touch Screen Controller + * Author: Daniel Gachet / Florian Nicoulaud + * Date: 12.02.2014 + */ + +#include "tsc2101.h" +#include "cspi.h" + +/* ADC */ +#define TSC2101_P1_ADC_PSTCM (1 << 15) +#define TSC2101_P1_ADC_ADST (1 << 14) +#define TSC2101_P1_ADC_ADCSM(x) (((x) & 0xf) << 10) +#define TSC2101_P1_ADC_RESOL(x) (((x) & 0x3) << 8) +#define TSC2101_P1_ADC_ADAVG(x) (((x) & 0x3) << 6) +#define TSC2101_P1_ADC_ADCR(x) (((x) & 0x3) << 4) +#define TSC2101_P1_ADC_PVSTC(x) (((x) & 0x7) << 1) +#define TSC2101_P1_ADC_AVGFS (1 << 0) + +/* RESET CONTROL */ +#define TSC2101_P1_RESET_RSALL (0xbb00) + +/* REFERENCE CONTROL */ +#define TSC2101_P1_REF_VREFM (1 << 4) +#define TSC2101_P1_REF_RPWUDL(x) (((x) & 0x3) << 2) +#define TSC2101_P1_REF_RPWDN (1 << 1) +#define TSC2101_P1_REF_IREFV (1 << 0) + +/* CONFIGURATION CONTROL */ +#define TSC2101_P1_CONF_SWPDTD (1 << 6) +#define TSC2101_P1_CONF_PRECTM(x) (((x) & 0x7) << 3) +#define TSC2101_P1_CONF_RPWUDL(x) (((x) & 0x7) << 0) + +/* MEASUREMENT CONFIGURATION */ +#define TSC2101_P1_MEASU_TSCAN (1 << 15) +#define TSC2101_P1_MEASU_A1CONF (1 << 14) +#define TSC2101_P1_MEASU_A2CONF (1 << 13) +#define TSC2101_P1_MEASU_ATEMES (1 << 12) +#define TSC2101_P1_MEASU_AA1MES (1 << 11) +#define TSC2101_P1_MEASU_AA2MES (1 << 10) +#define TSC2101_P1_MEASU_IGPIO1 (1 << 9) +#define TSC2101_P1_MEASU_THMFXL (1 << 8) +#define TSC2101_P1_MEASU_THMNFL (1 << 7) +#define TSC2101_P1_MEASU_EXTRES (1 << 2) + +/* PROGRAMMABLE DELAY */ +#define TSC2101_P1_DELAY_NTSPDELE (1 << 15) +#define TSC2101_P1_DELAY_NTSPDINTV(x) (((x) & 0x7) << 12) +#define TSC2101_P1_DELAY_TSPDELEN (1 << 11) +#define TSC2101_P1_DELAY_TSPDINTV(x) (((x) & 0x7) << 8) +#define TSC2101_P1_DELAY_CLKSEL (1 << 7) +#define TSC2101_P1_DELAY_CLKDIV(x) (((x) & 0x7f) << 0) + +struct cspi_ctrl spi2; + + +void tsc2101_init() +{ + /* initialize the spi interface */ + spi2 = cspi_init(SPI2, SS0, 8000, 16); + + /* Reset the TSC2101 */ + uint32_t data = TSC2101_P1_RESET_RSALL; + uint32_t c = (1 << 11) + (4 << 5); + spi2.write (&spi2, c, data); + + /* Configure touchscreen scan */ + data = TSC2101_P1_ADC_PSTCM | TSC2101_P1_ADC_ADCSM(2) + | TSC2101_P1_ADC_ADAVG(1) | TSC2101_P1_ADC_RESOL(2) + | TSC2101_P1_ADC_ADCR(3) | TSC2101_P1_ADC_PVSTC(3); + + c = (1 << 11) + (0 << 5); + spi2.write (&spi2, c, data); + + /* Status Register */ + data = 0; + c = (1 << 11) + (1 << 5); + spi2.write (&spi2, c, data); + + /* Buffer Register */ + data = 0; + c = (1 << 11) + (2 << 5); + spi2.write (&spi2, c, data); + + /* Reference Control */ + data = TSC2101_P1_REF_RPWUDL(1) | TSC2101_P1_REF_RPWDN; + c = (1 << 11) + (3 << 5); + spi2.write (&spi2, c, data); + + /* Configuration Control */ + data = TSC2101_P1_CONF_PRECTM(0); + c = (1 << 11) + (5 << 5); + spi2.write (&spi2, c, data); + + /* Measurement Control */ + data = TSC2101_P1_MEASU_TSCAN | TSC2101_P1_MEASU_ATEMES; + c = (1 << 11) + (12 << 5); + spi2.write (&spi2, c, data); + + /* Programmable Delay */ + data = TSC2101_P1_DELAY_CLKDIV(0) | TSC2101_P1_DELAY_TSPDINTV(2) + | TSC2101_P1_DELAY_TSPDELEN; + c = (1 << 11) + (13 << 5); + spi2.write (&spi2, c, data); +} + + +struct tsc2101_position tsc2101_read_position() +{ + uint32_t d[3]; + uint32_t c = 0x8000 + (0 << 11) + (0 << 5); + spi2.read(&spi2, c, d, 3); + + struct tsc2101_position page = { + .x = d[0], + .y = d[1], + .z = d[2], + }; + + return page; +} diff --git a/pool/shard008/C/0130093_softlockup.c b/pool/shard008/C/0130093_softlockup.c new file mode 100644 index 0000000000000000000000000000000000000000..0131e296ffb416435f7c54a935657c624a09d0c5 --- /dev/null +++ b/pool/shard008/C/0130093_softlockup.c @@ -0,0 +1,197 @@ +/* + * Detect Soft Lockups + * + * started by Ingo Molnar, Copyright (C) 2005, 2006 Red Hat, Inc. + * + * this code detects soft lockups: incidents in where on a CPU + * the kernel does not reschedule for 10 seconds or more. + */ +#include +#include +#include +#include +#include +#include +#include + +static DEFINE_SPINLOCK(print_lock); + +static DEFINE_PER_CPU(unsigned long, touch_timestamp); +static DEFINE_PER_CPU(unsigned long, print_timestamp); +static DEFINE_PER_CPU(struct task_struct *, watchdog_task); + +static int did_panic = 0; + +static int +softlock_panic(struct notifier_block *this, unsigned long event, void *ptr) +{ + did_panic = 1; + + return NOTIFY_DONE; +} + +static struct notifier_block panic_block = { + .notifier_call = softlock_panic, +}; + +/* + * Returns seconds, approximately. We don't need nanosecond + * resolution, and we don't need to waste time with a big divide when + * 2^30ns == 1.074s. + */ +static unsigned long get_timestamp(void) +{ + return sched_clock() >> 30; /* 2^30 ~= 10^9 */ +} + +void touch_softlockup_watchdog(void) +{ + __raw_get_cpu_var(touch_timestamp) = get_timestamp(); +} +EXPORT_SYMBOL(touch_softlockup_watchdog); + +void touch_all_softlockup_watchdogs(void) +{ + int cpu; + + /* Cause each CPU to re-update its timestamp rather than complain */ + for_each_online_cpu(cpu) + per_cpu(touch_timestamp, cpu) = 0; +} +EXPORT_SYMBOL(touch_all_softlockup_watchdogs); + +/* + * This callback runs from the timer interrupt, and checks + * whether the watchdog thread has hung or not: + */ +void softlockup_tick(void) +{ + int this_cpu = smp_processor_id(); + unsigned long touch_timestamp = per_cpu(touch_timestamp, this_cpu); + unsigned long print_timestamp; + unsigned long now; + + if (touch_timestamp == 0) { + touch_softlockup_watchdog(); + return; + } + + print_timestamp = per_cpu(print_timestamp, this_cpu); + + /* report at most once a second */ + if (print_timestamp < (touch_timestamp + 1) || + did_panic || + !per_cpu(watchdog_task, this_cpu)) + return; + + /* do not print during early bootup: */ + if (unlikely(system_state != SYSTEM_RUNNING)) { + touch_softlockup_watchdog(); + return; + } + + now = get_timestamp(); + + /* Wake up the high-prio watchdog task every second: */ + if (now > (touch_timestamp + 1)) + wake_up_process(per_cpu(watchdog_task, this_cpu)); + + /* Warn about unreasonable 10+ seconds delays: */ + if (now > (touch_timestamp + 10)) { + per_cpu(print_timestamp, this_cpu) = touch_timestamp; + + spin_lock(&print_lock); + printk(KERN_ERR "BUG: soft lockup detected on CPU#%d!\n", + this_cpu); + dump_stack(); + spin_unlock(&print_lock); + } +} + +/* + * The watchdog thread - runs every second and touches the timestamp. + */ +static int watchdog(void * __bind_cpu) +{ + struct sched_param param = { .sched_priority = MAX_RT_PRIO-1 }; + + sched_setscheduler(current, SCHED_FIFO, ¶m); + current->flags |= PF_NOFREEZE; + + /* initialize timestamp */ + touch_softlockup_watchdog(); + + /* + * Run briefly once per second to reset the softlockup timestamp. + * If this gets delayed for more than 10 seconds then the + * debug-printout triggers in softlockup_tick(). + */ + while (!kthread_should_stop()) { + set_current_state(TASK_INTERRUPTIBLE); + touch_softlockup_watchdog(); + schedule(); + } + + return 0; +} + +/* + * Create/destroy watchdog threads as CPUs come and go: + */ +static int __cpuinit +cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu) +{ + int hotcpu = (unsigned long)hcpu; + struct task_struct *p; + + switch (action) { + case CPU_UP_PREPARE: + case CPU_UP_PREPARE_FROZEN: + BUG_ON(per_cpu(watchdog_task, hotcpu)); + p = kthread_create(watchdog, hcpu, "watchdog/%d", hotcpu); + if (IS_ERR(p)) { + printk("watchdog for %i failed\n", hotcpu); + return NOTIFY_BAD; + } + per_cpu(touch_timestamp, hotcpu) = 0; + per_cpu(watchdog_task, hotcpu) = p; + kthread_bind(p, hotcpu); + break; + case CPU_ONLINE: + case CPU_ONLINE_FROZEN: + wake_up_process(per_cpu(watchdog_task, hotcpu)); + break; +#ifdef CONFIG_HOTPLUG_CPU + case CPU_UP_CANCELED: + case CPU_UP_CANCELED_FROZEN: + if (!per_cpu(watchdog_task, hotcpu)) + break; + /* Unbind so it can run. Fall thru. */ + kthread_bind(per_cpu(watchdog_task, hotcpu), + any_online_cpu(cpu_online_map)); + case CPU_DEAD: + case CPU_DEAD_FROZEN: + p = per_cpu(watchdog_task, hotcpu); + per_cpu(watchdog_task, hotcpu) = NULL; + kthread_stop(p); + break; +#endif /* CONFIG_HOTPLUG_CPU */ + } + return NOTIFY_OK; +} + +static struct notifier_block __cpuinitdata cpu_nfb = { + .notifier_call = cpu_callback +}; + +__init void spawn_softlockup_task(void) +{ + void *cpu = (void *)(long)smp_processor_id(); + int err = cpu_callback(&cpu_nfb, CPU_UP_PREPARE, cpu); + + BUG_ON(err == NOTIFY_BAD); + cpu_callback(&cpu_nfb, CPU_ONLINE, cpu); + register_cpu_notifier(&cpu_nfb); + + atomic_notifier_chain_register(&panic_notifier_list, &panic_block); +} diff --git a/pool/shard008/C/0130095_bfnmerge.c b/pool/shard008/C/0130095_bfnmerge.c new file mode 100644 index 0000000000000000000000000000000000000000..c9c5c37c8667a213893224c26a56d8e60f075134 --- /dev/null +++ b/pool/shard008/C/0130095_bfnmerge.c @@ -0,0 +1,141 @@ +#include +#include + +int main(int argc, char *argv[]) +{ + unsigned char *charbuf, *map; + + FILE *fd, *ofd; + char *buf; + int s, e; + int i, j; + int w, h, wl; + + charbuf=malloc(65536*128); + map=malloc(65536/8); + memset(map, 0, 65536/8); + + w=8; + h=16; + wl=0; + + for(i=2; i>8)&0xff, ofd); + fputc(e&0xff, ofd); + fputc((e>>8)&0xff, ofd); + fwrite(charbuf+(s*((w*h)/8)), e-s+1, ((w*h)/8), ofd); + } + s=0; + e=0; + } + } + if(s || e) + { +// printf("%d-%d ", s, e); + + fputc(s&0xff, ofd); + fputc((s>>8)&0xff, ofd); + fputc(e&0xff, ofd); + fputc((e>>8)&0xff, ofd); + fwrite(charbuf+(s*((w*h)/8)), e-s+1, ((w*h)/8), ofd); + } + + //special end of font marker... + fputc(0, ofd); + fputc(0, ofd); + fputc(0, ofd); + fputc(0, ofd); + +// fwrite(outbuf, 256*16, 256*8*3, ofd); + + return(0); +} diff --git a/pool/shard008/C/0130097_block.c b/pool/shard008/C/0130097_block.c new file mode 100644 index 0000000000000000000000000000000000000000..9db9f605b2427430b81eadc8898745712404227c --- /dev/null +++ b/pool/shard008/C/0130097_block.c @@ -0,0 +1,248 @@ +/* Created By: Virgil Dupras + * Created On: 2010-01-30 + * Copyright 2014 Hardcoded Software (http://www.hardcoded.net) + * + * This software is licensed under the "BSD" License as described in the + * "LICENSE" file, which should be included with this package. The terms are + * also available at http://www.hardcoded.net/licenses/bsd_license + */ + +#include "common.h" + +/* avgdiff/maxdiff has been called with empty lists */ +static PyObject *NoBlocksError; +/* avgdiff/maxdiff has been called with 2 block lists of different size. */ +static PyObject *DifferentBlockCountError; + +/* Returns a 3 sized tuple containing the mean color of 'image'. + * image: a PIL image or crop. + */ +static PyObject *getblock(PyObject *image) { + int i, totr, totg, totb; + Py_ssize_t pixel_count; + PyObject *ppixels; + + totr = totg = totb = 0; + ppixels = PyObject_CallMethod(image, "getdata", NULL); + if (ppixels == NULL) { + return NULL; + } + + pixel_count = PySequence_Length(ppixels); + for (i = 0; i < pixel_count; i++) { + PyObject *ppixel, *pr, *pg, *pb; + int r, g, b; + + ppixel = PySequence_ITEM(ppixels, i); + pr = PySequence_ITEM(ppixel, 0); + pg = PySequence_ITEM(ppixel, 1); + pb = PySequence_ITEM(ppixel, 2); + Py_DECREF(ppixel); + r = PyLong_AsLong(pr); + g = PyLong_AsLong(pg); + b = PyLong_AsLong(pb); + Py_DECREF(pr); + Py_DECREF(pg); + Py_DECREF(pb); + + totr += r; + totg += g; + totb += b; + } + + Py_DECREF(ppixels); + + if (pixel_count) { + totr /= pixel_count; + totg /= pixel_count; + totb /= pixel_count; + } + + return inttuple(3, totr, totg, totb); +} + +/* Returns the difference between the first block and the second. + * It returns an absolute sum of the 3 differences (RGB). + */ +static int diff(PyObject *first, PyObject *second) { + int r1, g1, b1, r2, b2, g2; + PyObject *pr, *pg, *pb; + pr = PySequence_ITEM(first, 0); + pg = PySequence_ITEM(first, 1); + pb = PySequence_ITEM(first, 2); + r1 = PyLong_AsLong(pr); + g1 = PyLong_AsLong(pg); + b1 = PyLong_AsLong(pb); + Py_DECREF(pr); + Py_DECREF(pg); + Py_DECREF(pb); + + pr = PySequence_ITEM(second, 0); + pg = PySequence_ITEM(second, 1); + pb = PySequence_ITEM(second, 2); + r2 = PyLong_AsLong(pr); + g2 = PyLong_AsLong(pg); + b2 = PyLong_AsLong(pb); + Py_DECREF(pr); + Py_DECREF(pg); + Py_DECREF(pb); + + return abs(r1 - r2) + abs(g1 - g2) + abs(b1 - b2); +} + +PyDoc_STRVAR(block_getblocks2_doc, + "Returns a list of blocks (3 sized tuples).\n\ +\n\ +image: A PIL image to base the blocks on.\n\ +block_count_per_side: This integer determine the number of blocks the function will return.\n\ +If it is 10, for example, 100 blocks will be returns (10 width, 10 height). The blocks will not\n\ +necessarely cover square areas. The area covered by each block will be proportional to the image\n\ +itself.\n"); + +static PyObject *block_getblocks2(PyObject *self, PyObject *args) { + int block_count_per_side, width, height, block_width, block_height, ih; + PyObject *image; + PyObject *pimage_size, *pwidth, *pheight; + PyObject *result; + + if (!PyArg_ParseTuple(args, "Oi", &image, &block_count_per_side)) { + return NULL; + } + + pimage_size = PyObject_GetAttrString(image, "size"); + pwidth = PySequence_ITEM(pimage_size, 0); + pheight = PySequence_ITEM(pimage_size, 1); + width = PyLong_AsLong(pwidth); + height = PyLong_AsLong(pheight); + Py_DECREF(pimage_size); + Py_DECREF(pwidth); + Py_DECREF(pheight); + + if (!(width && height)) { + return PyList_New(0); + } + + block_width = max(width / block_count_per_side, 1); + block_height = max(height / block_count_per_side, 1); + + result = PyList_New((Py_ssize_t)block_count_per_side * block_count_per_side); + if (result == NULL) { + return NULL; + } + + for (ih = 0; ih < block_count_per_side; ih++) { + int top, bottom, iw; + top = min(ih * block_height, height - block_height); + bottom = top + block_height; + for (iw = 0; iw < block_count_per_side; iw++) { + int left, right; + PyObject *pbox; + PyObject *pmethodname; + PyObject *pcrop; + PyObject *pblock; + + left = min(iw * block_width, width - block_width); + right = left + block_width; + pbox = inttuple(4, left, top, right, bottom); + pmethodname = PyUnicode_FromString("crop"); + pcrop = PyObject_CallMethodObjArgs(image, pmethodname, pbox, NULL); + Py_DECREF(pmethodname); + Py_DECREF(pbox); + if (pcrop == NULL) { + Py_DECREF(result); + return NULL; + } + pblock = getblock(pcrop); + Py_DECREF(pcrop); + if (pblock == NULL) { + Py_DECREF(result); + return NULL; + } + PyList_SET_ITEM(result, ih * block_count_per_side + iw, pblock); + } + } + + return result; +} + +PyDoc_STRVAR(block_avgdiff_doc, + "Returns the average diff between first blocks and seconds.\n\ +\n\ +If the result surpasses limit, limit + 1 is returned, except if less than min_iterations\n\ +iterations have been made in the blocks.\n"); + +static PyObject *block_avgdiff(PyObject *self, PyObject *args) { + PyObject *first, *second; + int limit, min_iterations; + Py_ssize_t count; + int sum, i, result; + + if (!PyArg_ParseTuple(args, "OOii", &first, &second, &limit, + &min_iterations)) { + return NULL; + } + + count = PySequence_Length(first); + if (count != PySequence_Length(second)) { + PyErr_SetString(DifferentBlockCountError, ""); + return NULL; + } + if (!count) { + PyErr_SetString(NoBlocksError, ""); + return NULL; + } + + sum = 0; + for (i = 0; i < count; i++) { + int iteration_count; + PyObject *item1, *item2; + + iteration_count = i + 1; + item1 = PySequence_ITEM(first, i); + item2 = PySequence_ITEM(second, i); + sum += diff(item1, item2); + Py_DECREF(item1); + Py_DECREF(item2); + if ((sum > limit * iteration_count) && + (iteration_count >= min_iterations)) { + return PyLong_FromLong(limit + 1); + } + } + + result = sum / count; + if (!result && sum) { + result = 1; + } + return PyLong_FromLong(result); +} + +static PyMethodDef BlockMethods[] = { + {"getblocks2", block_getblocks2, METH_VARARGS, block_getblocks2_doc}, + {"avgdiff", block_avgdiff, METH_VARARGS, block_avgdiff_doc}, + {NULL, NULL, 0, NULL} /* Sentinel */ +}; + +static struct PyModuleDef BlockDef = {PyModuleDef_HEAD_INIT, + "_block", + NULL, + -1, + BlockMethods, + NULL, + NULL, + NULL, + NULL}; + +PyObject *PyInit__block(void) { + PyObject *m = PyModule_Create(&BlockDef); + if (m == NULL) { + return NULL; + } + + NoBlocksError = PyErr_NewException("_block.NoBlocksError", NULL, NULL); + PyModule_AddObject(m, "NoBlocksError", NoBlocksError); + DifferentBlockCountError = + PyErr_NewException("_block.DifferentBlockCountError", NULL, NULL); + PyModule_AddObject(m, "DifferentBlockCountError", DifferentBlockCountError); + + return m; +} \ No newline at end of file diff --git a/pool/shard008/C/0130098_sys_spu_wrapper.c b/pool/shard008/C/0130098_sys_spu_wrapper.c new file mode 100644 index 0000000000000000000000000000000000000000..4a2bb83621dc523ede3f79418c2eea92910c17d8 --- /dev/null +++ b/pool/shard008/C/0130098_sys_spu_wrapper.c @@ -0,0 +1,30 @@ +#include +#include +#include +#include +#include + +s32 sysSpuImageOpenELF(sysSpuImage* image, const char* path) +{ + s32 ret = -1; + FILE *fd = NULL; + size_t fsize = 0; + void *data = NULL; + + fd = fopen(path, "rb"); + if(fd != NULL) { + fseek(fd,0,SEEK_END); + fsize = ftell(fd); + fseek(fd,0,SEEK_SET); + + data = malloc(fsize); + if(data != NULL) { + fread(data,1,fsize,fd); + ret = sysSpuImageImport(image,data,SPU_IMAGE_PROTECT); + free(data); + } + fclose(fd); + } + + return ret; +} diff --git a/pool/shard008/C/0130099_api.c b/pool/shard008/C/0130099_api.c new file mode 100644 index 0000000000000000000000000000000000000000..9ea441781520244c00e52ffaf5a4d5215044fc7d --- /dev/null +++ b/pool/shard008/C/0130099_api.c @@ -0,0 +1,241 @@ +/* + * This file is part of the libsigrok project. + * + * Copyright (C) 2012 Bert Vermeulen + * + * 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 . + */ + +#include +#include "libsigrok.h" +#include "libsigrok-internal.h" +#include "protocol.h" +#include +#include +#include +#include +#include + +/* The Colead SL-5868P uses this. */ +#define SERIALCOMM "2400/8n1" + +static const uint32_t scanopts[] = { + SR_CONF_CONN, + SR_CONF_SERIALCOMM, +}; + +static const uint32_t devopts[] = { + SR_CONF_SOUNDLEVELMETER, + SR_CONF_CONTINUOUS, + SR_CONF_LIMIT_SAMPLES | SR_CONF_SET, + SR_CONF_LIMIT_MSEC | SR_CONF_SET, +}; + +SR_PRIV struct sr_dev_driver colead_slm_driver_info; +static struct sr_dev_driver *di = &colead_slm_driver_info; + +static int init(struct sr_context *sr_ctx) +{ + return std_init(sr_ctx, di, LOG_PREFIX); +} + +static GSList *scan(GSList *options) +{ + struct drv_context *drvc; + struct dev_context *devc; + struct sr_dev_inst *sdi; + struct sr_config *src; + struct sr_channel *ch; + GSList *devices, *l; + const char *conn, *serialcomm; + + drvc = di->priv; + drvc->instances = NULL; + + devices = NULL; + + conn = serialcomm = NULL; + for (l = options; l; l = l->next) { + src = l->data; + switch (src->key) { + case SR_CONF_CONN: + conn = g_variant_get_string(src->data, NULL); + break; + case SR_CONF_SERIALCOMM: + serialcomm = g_variant_get_string(src->data, NULL); + break; + } + } + if (!conn) + return NULL; + if (!serialcomm) + serialcomm = SERIALCOMM; + + if (!(sdi = sr_dev_inst_new(SR_ST_INACTIVE, "Colead", + "SL-5868P", NULL))) + return NULL; + + if (!(devc = g_try_malloc0(sizeof(struct dev_context)))) { + sr_dbg("Device context malloc failed."); + return NULL; + } + + if (!(sdi->conn = sr_serial_dev_inst_new(conn, serialcomm))) + return NULL; + + sdi->inst_type = SR_INST_SERIAL; + sdi->priv = devc; + sdi->driver = di; + if (!(ch = sr_channel_new(0, SR_CHANNEL_ANALOG, TRUE, "P1"))) + return NULL; + sdi->channels = g_slist_append(sdi->channels, ch); + drvc->instances = g_slist_append(drvc->instances, sdi); + devices = g_slist_append(devices, sdi); + + return devices; +} + +static GSList *dev_list(void) +{ + return ((struct drv_context *)(di->priv))->instances; +} + +static int dev_open(struct sr_dev_inst *sdi) +{ + struct sr_serial_dev_inst *serial; + + serial = sdi->conn; + if (serial_open(serial, SERIAL_RDWR) != SR_OK) + return SR_ERR; + + sdi->status = SR_ST_ACTIVE; + + return SR_OK; +} + +static int cleanup(void) +{ + return std_dev_clear(di, NULL); +} + +static int config_set(uint32_t key, GVariant *data, const struct sr_dev_inst *sdi, + const struct sr_channel_group *cg) +{ + struct dev_context *devc; + + (void)cg; + + if (sdi->status != SR_ST_ACTIVE) + return SR_ERR_DEV_CLOSED; + + if (!(devc = sdi->priv)) { + sr_err("sdi->priv was NULL."); + return SR_ERR_BUG; + } + + switch (key) { + case SR_CONF_LIMIT_MSEC: + /* TODO: not yet implemented */ + if (g_variant_get_uint64(data) == 0) { + sr_err("LIMIT_MSEC can't be 0."); + return SR_ERR; + } + devc->limit_msec = g_variant_get_uint64(data);; + sr_dbg("Setting time limit to %" PRIu64 "ms.", + devc->limit_msec); + break; + case SR_CONF_LIMIT_SAMPLES: + devc->limit_samples = g_variant_get_uint64(data); + sr_dbg("Setting sample limit to %" PRIu64 ".", + devc->limit_samples); + break; + default: + return SR_ERR_NA; + } + + return SR_OK; +} + +static int config_list(uint32_t key, GVariant **data, const struct sr_dev_inst *sdi, + const struct sr_channel_group *cg) +{ + (void)sdi; + (void)cg; + + switch (key) { + case SR_CONF_SCAN_OPTIONS: + *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32, + scanopts, ARRAY_SIZE(scanopts), sizeof(uint32_t)); + break; + case SR_CONF_DEVICE_OPTIONS: + *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32, + devopts, ARRAY_SIZE(devopts), sizeof(uint32_t)); + break; + default: + return SR_ERR_NA; + } + + return SR_OK; +} + +static int dev_acquisition_start(const struct sr_dev_inst *sdi, void *cb_data) +{ + struct dev_context *devc; + struct sr_serial_dev_inst *serial; + + if (sdi->status != SR_ST_ACTIVE) + return SR_ERR_DEV_CLOSED; + + if (!(devc = sdi->priv)) { + sr_err("sdi->priv was NULL."); + return SR_ERR_BUG; + } + + devc->cb_data = cb_data; + + /* Send header packet to the session bus. */ + std_session_send_df_header(cb_data, LOG_PREFIX); + + /* Poll every 150ms, or whenever some data comes in. */ + serial = sdi->conn; + serial_source_add(sdi->session, serial, G_IO_IN, 150, + colead_slm_receive_data, (void *)sdi); + + return SR_OK; +} + +static int dev_acquisition_stop(struct sr_dev_inst *sdi, void *cb_data) +{ + return std_serial_dev_acquisition_stop(sdi, cb_data, std_serial_dev_close, + sdi->conn, LOG_PREFIX); +} + +SR_PRIV struct sr_dev_driver colead_slm_driver_info = { + .name = "colead-slm", + .longname = "Colead SLM", + .api_version = 1, + .init = init, + .cleanup = cleanup, + .scan = scan, + .dev_list = dev_list, + .dev_clear = NULL, + .config_get = NULL, + .config_set = config_set, + .config_list = config_list, + .dev_open = dev_open, + .dev_close = std_serial_dev_close, + .dev_acquisition_start = dev_acquisition_start, + .dev_acquisition_stop = dev_acquisition_stop, + .priv = NULL, +}; diff --git a/pool/shard008/C/0130105_timerthr.c b/pool/shard008/C/0130105_timerthr.c new file mode 100644 index 0000000000000000000000000000000000000000..0d57d6501326796e056927e6ee84d305859688f6 --- /dev/null +++ b/pool/shard008/C/0130105_timerthr.c @@ -0,0 +1,146 @@ +/* $Id$ */ +/* + * %ISC_START_LICENSE% + * --------------------------------------------------------------------- + * Copyright 2006-2018, Pittsburgh Supercomputing Center + * All rights reserved. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the + * above copyright notice and this permission notice appear in all + * copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL + * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE + * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL + * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR + * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + * -------------------------------------------------------------------- + * %END_LICENSE% + */ + +#include +#include +#include + +#include + +#include "pfl/atomic.h" +#include "pfl/cdefs.h" +#include "pfl/opstats.h" +#include "pfl/lockedlist.h" +#include "pfl/thread.h" +#include "pfl/time.h" +#include "pfl/waitq.h" + +/* + * Logic for recomputing instantaneous and weighted averages for opstats. + * The theory is, under normal operation, the number of opstats will be + * constant; so unless CPU is scarce, the opstats will be calculated at + * the same time, thus avoiding syscalls to get clock time used to + * measure rates. + */ +void +pfl_opstimerthr_main(struct psc_thread *thr) +{ + struct psc_waitq dummy = PSC_WAITQ_INIT("opstats"); + struct pfl_opstat *opst; + struct timespec ts; + double alpha = .25; + int64_t len, curr; + int i; + +#if HAVE_PTHREAD_SETSCHEDPRIO + pthread_setschedprio(thr->pscthr_pthread, + sched_get_priority_max(SCHED_RR)); +#endif + + PFL_GETTIMESPEC(&ts); + ts.tv_nsec = 0; + + while (pscthr_run(thr)) { + ts.tv_sec++; + psc_waitq_waitabs(&dummy, NULL, &ts); + + spinlock(&pfl_opstats_lock); + DYNARRAY_FOREACH(opst, i, &pfl_opstats) { + + /* update last second rate */ + curr = psc_atomic64_read(&opst->opst_lifetime); + len = curr - opst->opst_last; + if (len < 0) + len = -len; + opst->opst_intv = len; + + /* compute time weighted average */ + opst->opst_avg = alpha * len + (1 - alpha) * + opst->opst_avg; + if (opst->opst_avg > opst->opst_max) + opst->opst_max = opst->opst_avg; + opst->opst_last = curr; + } + freelock(&pfl_opstats_lock); + } +} + +void +pfl_rusagethr_main(struct psc_thread *thr) +{ + struct psc_waitq dummy = PSC_WAITQ_INIT("rusage"); + struct rusage ru, lastru; + struct timespec ts; + long pgsz; + +#if HAVE_PTHREAD_SETSCHEDPRIO + pthread_setschedprio(thr->pscthr_pthread, + sched_get_priority_max(SCHED_RR)); +#endif + + memset(&lastru, 0, sizeof(lastru)); + PFL_GETTIMESPEC(&ts); + pgsz = sysconf(_SC_PAGESIZE); + + while (pscthr_run(thr)) { + ts.tv_sec++; + psc_waitq_waitabs(&dummy, NULL, &ts); + + getrusage(RUSAGE_SELF, &ru); + +#define RUSAGE_FIELD_MULT(name, suffix, mult) \ + OPSTAT_ADD("rusage." #name suffix, \ + (mult) * (ru.ru_##name - lastru.ru_##name)) +#define RUSAGE_FIELD2_MULT(name, suffix, mult) \ + OPSTAT2_ADD("rusage." #name suffix, \ + (mult) * (ru.ru_##name - lastru.ru_##name)) +#define RUSAGE_FIELD(name) RUSAGE_FIELD_MULT(name, "", 1) +#define RUSAGE_FIELD2(name) RUSAGE_FIELD2_MULT(name, "", 1) + + RUSAGE_FIELD2(maxrss); + RUSAGE_FIELD2(ixrss); + RUSAGE_FIELD2(idrss); + RUSAGE_FIELD2(isrss); + RUSAGE_FIELD(minflt); + RUSAGE_FIELD2_MULT(minflt, "_sz", pgsz); + RUSAGE_FIELD(majflt); + RUSAGE_FIELD2_MULT(majflt, "_sz", pgsz); + RUSAGE_FIELD(nswap); + RUSAGE_FIELD(inblock); + RUSAGE_FIELD(oublock); + RUSAGE_FIELD(msgsnd); + RUSAGE_FIELD(msgrcv); + RUSAGE_FIELD(nsignals); + RUSAGE_FIELD(nvcsw); + RUSAGE_FIELD(nivcsw); + + lastru = ru; + } +} + +void +pfl_opstimerthr_spawn(int thrtype, const char *name) +{ + pscthr_init(thrtype, pfl_opstimerthr_main, 0, name); +} diff --git a/pool/shard008/C/0130107_ps2_ass.c b/pool/shard008/C/0130107_ps2_ass.c new file mode 100644 index 0000000000000000000000000000000000000000..33271d7ab7066ec154bb90046046a02a28a4e8f8 --- /dev/null +++ b/pool/shard008/C/0130107_ps2_ass.c @@ -0,0 +1,92 @@ +#include "meta.h" +#include "../util.h" + +/* SVS (from Dai Senryaku VII - Exceed) */ + +VGMSTREAM * init_vgmstream_ps2_ass(STREAMFILE *streamFile) { + VGMSTREAM * vgmstream = NULL; + char filename[260]; + off_t start_offset; + uint8_t testBuffer[0x10]; + off_t loopStart = 0; + off_t loopEnd = 0; + off_t readOffset = 0; + size_t fileLength; + int loop_flag; + int channel_count; + + /* check extension, case insensitive */ + streamFile->get_name(streamFile,filename,sizeof(filename)); + if (strcasecmp("ass",filename_extension(filename))) goto fail; + + /* check header */ + if (read_32bitBE(0x00,streamFile) != 0x02000000) /* "0x02000000" */ + goto fail; + + loop_flag = 1; + channel_count = 2; + + /* build the VGMSTREAM */ + vgmstream = allocate_vgmstream(channel_count,loop_flag); + if (!vgmstream) goto fail; + + /* fill in the vital statistics */ + start_offset = 0x800; + vgmstream->channels = channel_count; + vgmstream->sample_rate = read_32bitLE(0x04,streamFile); + vgmstream->coding_type = coding_PSX; + vgmstream->num_samples = (read_32bitLE(0x08,streamFile)*2)*28/16/channel_count; + + fileLength = get_streamfile_size(streamFile); + + do { + + readOffset+=(off_t)read_streamfile(testBuffer,readOffset,0x10,streamFile); + /* Loop Start */ + if(testBuffer[0x01]==0x06) { + if(loopStart == 0) loopStart = readOffset-0x10; + /* break; */ + } + /* Loop End */ + if(testBuffer[0x01]==0x03) { + if(loopEnd == 0) loopEnd = readOffset-0x10; + /* break; */ + } + } while (streamFile->get_offset(streamFile)<(int32_t)fileLength); + + if(loopStart == 0) { + loop_flag = 0; + vgmstream->num_samples = read_32bitLE(0x4,streamFile)*28/16/channel_count; + } else { + loop_flag = 1; + vgmstream->loop_start_sample = (loopStart-start_offset)*28/16/channel_count; + vgmstream->loop_end_sample = (loopEnd-start_offset)*28/16/channel_count; + } + + vgmstream->layout_type = layout_interleave; + vgmstream->interleave_block_size = read_32bitLE(0x0C,streamFile); + vgmstream->meta_type = meta_PS2_ASS; + + /* open the file for reading */ + { + int i; + STREAMFILE * file; + file = streamFile->open(streamFile,filename,STREAMFILE_DEFAULT_BUFFER_SIZE); + if (!file) goto fail; + for (i=0;ich[i].streamfile = file; + + vgmstream->ch[i].channel_start_offset= + vgmstream->ch[i].offset=start_offset+ + vgmstream->interleave_block_size*i; + + } + } + + return vgmstream; + + /* clean up anything we may have opened */ +fail: + if (vgmstream) close_vgmstream(vgmstream); + return NULL; +} diff --git a/pool/shard008/C/0130109_hw3d.c b/pool/shard008/C/0130109_hw3d.c new file mode 100644 index 0000000000000000000000000000000000000000..1d6b3583109786d1723edf2a2e5fabef44b9fbfd --- /dev/null +++ b/pool/shard008/C/0130109_hw3d.c @@ -0,0 +1,222 @@ +/* arch/arm/mach-msm/hw3d.c + * + * Register/Interrupt access for userspace 3D library. + * + * Copyright (C) 2007 Google, Inc. + * Author: Brian Swetland + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * 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. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static DEFINE_SPINLOCK(hw3d_lock); +static DECLARE_WAIT_QUEUE_HEAD(hw3d_queue); +static int hw3d_pending; +static int hw3d_disabled; + +static struct clk *grp_clk; +static struct clk *imem_clk; +DECLARE_MUTEX(hw3d_sem); +static unsigned int hw3d_granted; +static struct file *hw3d_granted_file; + +static irqreturn_t hw3d_irq_handler(int irq, void *data) +{ + unsigned long flags; + + spin_lock_irqsave(&hw3d_lock, flags); + if (!hw3d_disabled) { + disable_irq(INT_GRAPHICS); + hw3d_disabled = 1; + } + hw3d_pending = 1; + spin_unlock_irqrestore(&hw3d_lock, flags); + + wake_up(&hw3d_queue); + + return IRQ_HANDLED; +} + +static void hw3d_disable_interrupt(void) +{ + unsigned long flags; + spin_lock_irqsave(&hw3d_lock, flags); + if (!hw3d_disabled) { + disable_irq(INT_GRAPHICS); + hw3d_disabled = 1; + } + spin_unlock_irqrestore(&hw3d_lock, flags); +} + +static long hw3d_wait_for_interrupt(void) +{ + unsigned long flags; + int ret; + + for (;;) { + spin_lock_irqsave(&hw3d_lock, flags); + if (hw3d_pending) { + hw3d_pending = 0; + spin_unlock_irqrestore(&hw3d_lock, flags); + return 0; + } + if (hw3d_disabled) { + hw3d_disabled = 0; + enable_irq(INT_GRAPHICS); + } + spin_unlock_irqrestore(&hw3d_lock, flags); + + ret = wait_event_interruptible(hw3d_queue, hw3d_pending); + if (ret < 0) { + hw3d_disable_interrupt(); + return ret; + } + } + + return 0; +} + +#define MAGIC_REVOKE_NUMBER 0xdeadbeef +#define MAGIC_REVOKE_ADDR 0x10000 +#define HW3D_REGS_LEN 0x100000 + +static long hw3d_revoke_gpu(struct file *file) +{ + int ret = 0; + unsigned long user_start, user_len; + struct pmem_region region = {.offset = 0x0, .len = HW3D_REGS_LEN}; + + down(&hw3d_sem); + if (!hw3d_granted) { + goto end; + } + /* revoke the pmem region completely */ + if ((ret = pmem_remap(®ion, file, PMEM_UNMAP))) + goto end; + get_pmem_user_addr(file, &user_start, &user_len); + /* write the magic revoke code into the regs */ + if (MAGIC_REVOKE_ADDR > user_len) { + ret = -1; + goto end; + } + put_user(MAGIC_REVOKE_NUMBER, + (unsigned long __user *)(user_start + MAGIC_REVOKE_ADDR)); + /* reset the gpu */ + clk_disable(grp_clk); + clk_disable(imem_clk); + hw3d_granted = 0; +end: + up(&hw3d_sem); + return ret; +} + +static long hw3d_grant_gpu(struct file *file) +{ + int ret = 0; + struct pmem_region region = {.offset = 0x0, .len = HW3D_REGS_LEN}; + + down(&hw3d_sem); + if (hw3d_granted) { + ret = -1; + goto end; + } + /* map the registers */ + if ((ret = pmem_remap(®ion, file, PMEM_MAP))) + goto end; + clk_enable(grp_clk); + clk_enable(imem_clk); + hw3d_granted = 1; + hw3d_granted_file = file; +end: + up(&hw3d_sem); + return ret; +} + +static int hw3d_release(struct inode *inode, struct file *file) +{ + down(&hw3d_sem); + /* if the gpu is in use, and its inuse by the file that was released */ + if (hw3d_granted && (file == hw3d_granted_file)) { + clk_disable(grp_clk); + clk_disable(imem_clk); + hw3d_granted = 0; + hw3d_granted_file = NULL; + } + up(&hw3d_sem); + return 0; +} + +static long hw3d_ioctl(struct file *file, unsigned int cmd, unsigned long arg) +{ + switch (cmd) { + case HW3D_REVOKE_GPU: + return hw3d_revoke_gpu(file); + break; + case HW3D_GRANT_GPU: + return hw3d_grant_gpu(file); + break; + case HW3D_WAIT_FOR_INTERRUPT: + return hw3d_wait_for_interrupt(); + break; + default: + return -EINVAL; + } + return 0; +} + +static struct android_pmem_platform_data pmem_data = { + .name = "hw3d", + .start = 0xA0000000, + .size = 0x100000, + .no_allocator = 1, + .cached = 0, +}; + +static int __init hw3d_init(void) +{ + int ret; + + grp_clk = clk_get(NULL, "grp_clk"); + if (IS_ERR(grp_clk)) + return PTR_ERR(grp_clk); + + imem_clk = clk_get(NULL, "imem_clk"); + if (IS_ERR(imem_clk)) { + clk_put(grp_clk); + return PTR_ERR(imem_clk); + } + ret = request_irq(INT_GRAPHICS, hw3d_irq_handler, + IRQF_TRIGGER_HIGH, "hw3d", 0); + if (ret) { + clk_put(grp_clk); + clk_put(imem_clk); + return ret; + } + hw3d_disable_interrupt(); + hw3d_granted = 0; + + return pmem_setup(&pmem_data, hw3d_ioctl, hw3d_release); +} + +device_initcall(hw3d_init); diff --git a/pool/shard008/C/0130110_lift.c b/pool/shard008/C/0130110_lift.c new file mode 100644 index 0000000000000000000000000000000000000000..5c99f4ed475c8378bdf9a9df398f7d066e88b5a3 --- /dev/null +++ b/pool/shard008/C/0130110_lift.c @@ -0,0 +1,243 @@ +#include "Error-utils.h" +#include + +/* note that the function below is copied from another lifting + * library. This kind of duplication can be avoided when apigen + * for C will support modular generation of API's. + */ +static PERR_LexStrCon ERR_makeLexStrCon(const char* str) +{ + int len = strlen(str); + int i; + PERR_LexStrCharChars list = PERR_makeLexStrCharCharsEmpty(); + + for (i = len - 1; i >= 0; i--) { + PERR_LexStrChar ch; + + switch(str[i]) { + case '\n': + ch = PERR_makeLexStrCharNewline(); + break; + case '\t': + ch = PERR_makeLexStrCharTab(); + break; + case '"': + ch = PERR_makeLexStrCharQuote(); + break; + case '\\': + ch = PERR_makeLexStrCharBackslash(); + break; + default: + if (isprint((int) str[i])) { + ch = PERR_makeLexStrCharNormal(str[i]); + } + else { + int value = str[i]; + int a, b, c; + + c = value % 10; + value /= 10; + b = value % 10; + value /= 10; + a = value; + + ch = PERR_makeLexStrCharDecimal(a,b,c); + } + } + + list = PERR_makeLexStrCharCharsMany(ch, list); + } + + + return PERR_makeLexStrConDefault(list); +} + +static PERR_StrCon ERR_liftStrCon(const char *str) +{ + return PERR_makeStrConLexToCf(ERR_makeLexStrCon(str)); +} + +/*{{{ static PERR_NatCon ERR_liftNatCon(int natcon) */ + +static PERR_NatCon ERR_liftNatCon(int natcon) +{ + static char string[1024]; + sprintf(string, "%d", natcon); + return PERR_makeNatConLexToCf(PERR_makeLexNatConDigits(string)); +} + +/*}}} */ + +/*{{{ PERR_Area ERR_liftArea(ERR_Area area) */ + +PERR_Area ERR_liftArea(ERR_Area area) +{ + int beginLine; + int beginColumn; + int endLine; + int endColumn; + int offset; + int length; + PERR_NatCon pBeginLine; + PERR_NatCon pBeginColumn; + PERR_NatCon pEndLine; + PERR_NatCon pEndColumn; + PERR_NatCon pOffset; + PERR_NatCon pLength; + PERR_OptLayout e; + + beginLine = ERR_getAreaBeginLine(area); + beginColumn = ERR_getAreaBeginColumn(area); + endLine = ERR_getAreaEndLine(area); + endColumn = ERR_getAreaEndColumn(area); + offset = ERR_getAreaOffset(area); + length = ERR_getAreaLength(area); + + pBeginLine = ERR_liftNatCon(beginLine); + pBeginColumn = ERR_liftNatCon(beginColumn); + pEndLine = ERR_liftNatCon(endLine); + pEndColumn = ERR_liftNatCon(endColumn); + pOffset = ERR_liftNatCon(offset); + pLength = ERR_liftNatCon(length); + e = PERR_makeOptLayoutAbsent(); + + return PERR_makeAreaArea(e,e, + pBeginLine, + e,e, + pBeginColumn, + e,e, + pEndLine, + e,e, + pEndColumn, + e,e, + pOffset, + e,e, + pLength, + e); +} + +/*}}} */ +/*{{{ PERR_Location ERR_liftLocation(ERR_Location location) */ + +PERR_Location ERR_liftLocation(ERR_Location location) +{ + char *filename = ERR_getLocationFilename(location); + PERR_StrCon pFilename = ERR_liftStrCon(filename); + PERR_OptLayout e = PERR_makeOptLayoutAbsent(); + + if (ERR_isLocationAreaInFile(location)) { + ERR_Area area = ERR_getLocationArea(location); + PERR_Area pArea = ERR_liftArea(area); + + return PERR_makeLocationAreaInFile(e, e, pFilename, e, e, pArea, e); + } + + return PERR_makeLocationFile(e, e, pFilename, e); +} + +/*}}} */ +/*{{{ PERR_Subject ERR_liftSubject(ERR_Subject subject) */ + +PERR_Subject ERR_liftSubject(ERR_Subject subject) +{ + char *description = ERR_getSubjectDescription(subject); + PERR_StrCon pDescription = ERR_liftStrCon(description); + PERR_OptLayout e = PERR_makeOptLayoutAbsent(); + + if (ERR_isSubjectLocalized(subject)) { + ERR_Location location = ERR_getSubjectLocation(subject); + PERR_Location pLocation = ERR_liftLocation(location); + return PERR_makeSubjectLocalized(e, e, pDescription, e, e, pLocation, e); + } + + return PERR_makeSubjectSubject(e, e, pDescription, e); +} + +/*}}} */ +/*{{{ PERR_SubjectList ERR_liftSubjects(ERR_SubjectList subjects) */ + +PERR_SubjectList ERR_liftSubjects(ERR_SubjectList subjects) +{ + PERR_SubjectList pSubjects = PERR_makeSubjectListEmpty(); + PERR_OptLayout e = PERR_makeOptLayoutAbsent(); + + while (!ERR_isSubjectListEmpty(subjects)) { + ERR_Subject cur = ERR_getSubjectListHead(subjects); + PERR_Subject pCur = ERR_liftSubject(cur); + pSubjects = PERR_makeSubjectListMany(pCur, e, e, pSubjects); + subjects = ERR_getSubjectListTail(subjects); + } + + return pSubjects; +} + +/*}}} */ +/*{{{ PERR_Error ERR_liftError(ERR_Error error) */ + +PERR_Error ERR_liftError(ERR_Error error) +{ + char *description = ERR_getErrorDescription(error); + PERR_StrCon pDescription = ERR_liftStrCon(description); + ERR_SubjectList subjects = ERR_getErrorList(error); + PERR_SubjectList pSubjects = ERR_liftSubjects(subjects); + PERR_OptLayout e = PERR_makeOptLayoutAbsent(); + + if (ERR_isErrorInfo(error)) { + return PERR_makeErrorInfo(e, e, pDescription, e, e, e, pSubjects, e, e); + } + else if (ERR_isErrorWarning(error)) { + return PERR_makeErrorWarning(e, e, pDescription, e, e, e, pSubjects, e, e); + } + else if (ERR_isErrorError(error)) { + return PERR_makeErrorError(e, e, pDescription, e, e, e, pSubjects, e, e); + } + else if (ERR_isErrorFatal(error)) { + return PERR_makeErrorFatal(e, e, pDescription, e, e, e, pSubjects, e, e); + } + + ATerror("unknown error type: %t\n", error); + return NULL; +} + +/*}}} */ + +/*{{{ static PERR_ErrorList ERR_liftErrorList(ERR_ErrorList errors) */ + +static PERR_ErrorList ERR_liftErrorList(ERR_ErrorList errors) +{ + PERR_OptLayout e = PERR_makeOptLayoutAbsent(); + PERR_ErrorList result = PERR_makeErrorListEmpty(); + + for (;!ERR_isErrorListEmpty(errors); errors = ERR_getErrorListTail(errors)) { + ERR_Error head = ERR_getErrorListHead(errors); + PERR_Error pHead = ERR_liftError(head); + + result = PERR_makeErrorListMany(pHead, e, e, result); + } + + return PERR_reverseErrorList(result); +} + +/*}}} */ +/*{{{ PERR_Summary ERR_liftSummary(ERR_Summary summary) */ + +PERR_Summary ERR_liftSummary(ERR_Summary summary) +{ + PERR_OptLayout e = PERR_makeOptLayoutAbsent(); + const char *producer = ERR_getSummaryProducer(summary); + const char *id = ERR_getSummaryId(summary); + ERR_ErrorList errors = ERR_getSummaryList(summary); + PERR_StrCon pProducer = ERR_liftStrCon(producer); + PERR_StrCon pId = ERR_liftStrCon(id); + PERR_ErrorList pErrors = ERR_liftErrorList(errors); + + return PERR_makeSummarySummary(e, e, + pProducer, + e, e, + pId, + e, e, e, + pErrors, + e, e); +} + +/*}}} */ diff --git a/pool/shard008/C/0130115_4-1.c b/pool/shard008/C/0130115_4-1.c new file mode 100644 index 0000000000000000000000000000000000000000..2b5912930107f1ce106d86f9faa8b8e2ed154834 --- /dev/null +++ b/pool/shard008/C/0130115_4-1.c @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2004, Bull S.A.. All rights reserved. + * Created by: Sebastien Decugis + + * This program is free software; you can redistribute it and/or modify it + * under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it would be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write the Free Software Foundation, Inc., 59 + * Temple Place - Suite 330, Boston MA 02111-1307, USA. + + * This sample test aims to check the following assertion: + * + * The parent process ID of the child is the process ID of the parent (caller of fork()) + + * The steps are: + * -> create a child + * -> check its parent process ID is the PID of its parent. + + * The test fails if the IDs differ. + + */ + + /* We are testing conformance to IEEE Std 1003.1, 2003 Edition */ + #define _POSIX_C_SOURCE 200112L + +/********************************************************************************************/ +/****************************** standard includes *****************************************/ +/********************************************************************************************/ + #include + #include + #include + #include + #include + #include + + #include + #include + +/********************************************************************************************/ +/****************************** Test framework *****************************************/ +/********************************************************************************************/ + #include "../testfrmw/testfrmw.h" + #include "../testfrmw/testfrmw.c" + /* This header is responsible for defining the following macros: + * UNRESOLVED(ret, descr); + * where descr is a description of the error and ret is an int (error code for example) + * FAILED(descr); + * where descr is a short text saying why the test has failed. + * PASSED(); + * No parameter. + * + * Both three macros shall terminate the calling process. + * The testcase shall not terminate in any other maneer. + * + * The other file defines the functions + * void output_init() + * void output(char * string, ...) + * + * Those may be used to output information. + */ + +/********************************************************************************************/ +/********************************** Configuration ******************************************/ +/********************************************************************************************/ +#ifndef VERBOSE +#define VERBOSE 1 +#endif + +/********************************************************************************************/ +/*********************************** Test case *****************************************/ +/********************************************************************************************/ + +/* The main test function. */ +int main(int argc, char * argv[]) +{ + int status; + pid_t child, ctl; + + /* Initialize output */ + output_init(); + + /* Get parent process ID */ + ctl = getpid(); + + /* Create the child */ + child = fork(); + if (child == -1) { UNRESOLVED(errno, "Failed to fork"); } + + /* child */ + if (child == 0) + { + /* Check the parent process ID */ + if (ctl != getppid()) + { + FAILED("The parent process ID is not the PID of the parent"); + } + + /* We're done */ + exit(PTS_PASS); + } + + /* Parent joins the child */ + ctl = waitpid(child, &status, 0); + if (ctl != child) { UNRESOLVED(errno, "Waitpid returned the wrong PID"); } + if ((!WIFEXITED(status)) || (WEXITSTATUS(status) != PTS_PASS)) + { + UNRESOLVED(status, "Child exited abnormally"); + } + + /* Test passed */ + #if VERBOSE > 0 + output("Test passed\n"); + #endif + + PASSED; +} \ No newline at end of file diff --git a/pool/shard008/C/0130116_read.c b/pool/shard008/C/0130116_read.c new file mode 100644 index 0000000000000000000000000000000000000000..feaa76918a9b04f6a16f1c5a6c67a27f292113d9 --- /dev/null +++ b/pool/shard008/C/0130116_read.c @@ -0,0 +1,38 @@ +/**************************************************************************/ +/* */ +/* OCaml */ +/* */ +/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ +/* */ +/* Copyright 1996 Institut National de Recherche en Informatique et */ +/* en Automatique. */ +/* */ +/* All rights reserved. This file is distributed under the terms of */ +/* the GNU Lesser General Public License version 2.1, with the */ +/* special exception on linking described in the file LICENSE. */ +/* */ +/**************************************************************************/ + +#include +#include +#include +#include +#include "unixsupport.h" + +CAMLprim value unix_read(value fd, value buf, value ofs, value len) +{ + long numbytes; + int ret; + char iobuf[UNIX_BUFFER_SIZE]; + + Begin_root (buf); + numbytes = Long_val(len); + if (numbytes > UNIX_BUFFER_SIZE) numbytes = UNIX_BUFFER_SIZE; + enter_blocking_section(); + ret = read(Int_val(fd), iobuf, (int) numbytes); + leave_blocking_section(); + if (ret == -1) uerror("read", Nothing); + memmove (&Byte(buf, Long_val(ofs)), iobuf, ret); + End_roots(); + return Val_int(ret); +} diff --git a/pool/shard008/C/0130118_chpass_c.c b/pool/shard008/C/0130118_chpass_c.c new file mode 100644 index 0000000000000000000000000000000000000000..13f2f82ce7d2a19c5c39ceced89ba8baa10acaf1 --- /dev/null +++ b/pool/shard008/C/0130118_chpass_c.c @@ -0,0 +1,130 @@ +/* $NetBSD: chpass_c.c,v 1.1.1.2 2014/04/24 12:45:48 pettai Exp $ */ + +/* + * Copyright (c) 1997-2000, 2005-2006 Kungliga Tekniska Högskolan + * (Royal Institute of Technology, Stockholm, Sweden). + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include "kadm5_locl.h" + +__RCSID("NetBSD"); + +kadm5_ret_t +kadm5_c_chpass_principal(void *server_handle, + krb5_principal princ, + const char *password) +{ + kadm5_client_context *context = server_handle; + kadm5_ret_t ret; + krb5_storage *sp; + unsigned char buf[1024]; + int32_t tmp; + krb5_data reply; + + ret = _kadm5_connect(server_handle); + if(ret) + return ret; + + sp = krb5_storage_from_mem(buf, sizeof(buf)); + if (sp == NULL) { + krb5_clear_error_message(context->context); + return ENOMEM; + } + krb5_store_int32(sp, kadm_chpass); + krb5_store_principal(sp, princ); + krb5_store_string(sp, password); + ret = _kadm5_client_send(context, sp); + krb5_storage_free(sp); + if (ret) + return ret; + ret = _kadm5_client_recv(context, &reply); + if(ret) + return ret; + sp = krb5_storage_from_data (&reply); + if (sp == NULL) { + krb5_clear_error_message(context->context); + krb5_data_free (&reply); + return ENOMEM; + } + krb5_ret_int32(sp, &tmp); + krb5_clear_error_message(context->context); + krb5_storage_free(sp); + krb5_data_free (&reply); + return tmp; +} + +kadm5_ret_t +kadm5_c_chpass_principal_with_key(void *server_handle, + krb5_principal princ, + int n_key_data, + krb5_key_data *key_data) +{ + kadm5_client_context *context = server_handle; + kadm5_ret_t ret; + krb5_storage *sp; + unsigned char buf[1024]; + int32_t tmp; + krb5_data reply; + int i; + + ret = _kadm5_connect(server_handle); + if(ret) + return ret; + + sp = krb5_storage_from_mem(buf, sizeof(buf)); + if (sp == NULL) { + krb5_clear_error_message(context->context); + return ENOMEM; + } + krb5_store_int32(sp, kadm_chpass_with_key); + krb5_store_principal(sp, princ); + krb5_store_int32(sp, n_key_data); + for (i = 0; i < n_key_data; ++i) + kadm5_store_key_data (sp, &key_data[i]); + ret = _kadm5_client_send(context, sp); + krb5_storage_free(sp); + if (ret) + return ret; + ret = _kadm5_client_recv(context, &reply); + if(ret) + return ret; + sp = krb5_storage_from_data (&reply); + if (sp == NULL) { + krb5_clear_error_message(context->context); + krb5_data_free (&reply); + return ENOMEM; + } + krb5_ret_int32(sp, &tmp); + krb5_clear_error_message(context->context); + krb5_storage_free(sp); + krb5_data_free (&reply); + return tmp; +} diff --git a/pool/shard008/C/0130119_stmmac_mdio.c b/pool/shard008/C/0130119_stmmac_mdio.c new file mode 100644 index 0000000000000000000000000000000000000000..da4a1042523a633e5781f86df7ffe4e123c09910 --- /dev/null +++ b/pool/shard008/C/0130119_stmmac_mdio.c @@ -0,0 +1,249 @@ +/******************************************************************************* + STMMAC Ethernet Driver -- MDIO bus implementation + Provides Bus interface for MII registers + + Copyright (C) 2007-2009 STMicroelectronics Ltd + + This program is free software; you can redistribute it and/or modify it + under the terms and conditions of the GNU General Public License, + version 2, as published by the Free Software Foundation. + + This program is distributed in the hope 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 St - Fifth Floor, Boston, MA 02110-1301 USA. + + The full GNU General Public License is included in this distribution in + the file called "COPYING". + + Author: Carl Shaw + Maintainer: Giuseppe Cavallaro +*******************************************************************************/ + +#include +#include +#include +#include + +#include "stmmac.h" + +#define MII_BUSY 0x00000001 +#define MII_WRITE 0x00000002 + +/** + * stmmac_mdio_read + * @bus: points to the mii_bus structure + * @phyaddr: MII addr reg bits 15-11 + * @phyreg: MII addr reg bits 10-6 + * Description: it reads data from the MII register from within the phy device. + * For the 7111 GMAC, we must set the bit 0 in the MII address register while + * accessing the PHY registers. + * Fortunately, it seems this has no drawback for the 7109 MAC. + */ +static int stmmac_mdio_read(struct mii_bus *bus, int phyaddr, int phyreg) +{ + struct net_device *ndev = bus->priv; + struct stmmac_priv *priv = netdev_priv(ndev); + unsigned int mii_address = priv->hw->mii.addr; + unsigned int mii_data = priv->hw->mii.data; + + int data; + u16 regValue = (((phyaddr << 11) & (0x0000F800)) | + ((phyreg << 6) & (0x000007C0))); + regValue |= MII_BUSY | ((priv->plat->clk_csr & 7) << 2); + + do {} while (((readl(priv->ioaddr + mii_address)) & MII_BUSY) == 1); + writel(regValue, priv->ioaddr + mii_address); + do {} while (((readl(priv->ioaddr + mii_address)) & MII_BUSY) == 1); + + /* Read the data from the MII data register */ + data = (int)readl(priv->ioaddr + mii_data); + + return data; +} + +/** + * stmmac_mdio_write + * @bus: points to the mii_bus structure + * @phyaddr: MII addr reg bits 15-11 + * @phyreg: MII addr reg bits 10-6 + * @phydata: phy data + * Description: it writes the data into the MII register from within the device. + */ +static int stmmac_mdio_write(struct mii_bus *bus, int phyaddr, int phyreg, + u16 phydata) +{ + struct net_device *ndev = bus->priv; + struct stmmac_priv *priv = netdev_priv(ndev); + unsigned int mii_address = priv->hw->mii.addr; + unsigned int mii_data = priv->hw->mii.data; + + u16 value = + (((phyaddr << 11) & (0x0000F800)) | ((phyreg << 6) & (0x000007C0))) + | MII_WRITE; + + value |= MII_BUSY | ((priv->plat->clk_csr & 7) << 2); + + + /* Wait until any existing MII operation is complete */ + do {} while (((readl(priv->ioaddr + mii_address)) & MII_BUSY) == 1); + + /* Set the MII address register to write */ + writel(phydata, priv->ioaddr + mii_data); + writel(value, priv->ioaddr + mii_address); + + /* Wait until any existing MII operation is complete */ + do {} while (((readl(priv->ioaddr + mii_address)) & MII_BUSY) == 1); + + return 0; +} + +/** + * stmmac_mdio_reset + * @bus: points to the mii_bus structure + * Description: reset the MII bus + */ +static int stmmac_mdio_reset(struct mii_bus *bus) +{ +#if defined(CONFIG_STMMAC_PLATFORM) + struct net_device *ndev = bus->priv; + struct stmmac_priv *priv = netdev_priv(ndev); + unsigned int mii_address = priv->hw->mii.addr; + + if (priv->plat->mdio_bus_data->phy_reset) { + pr_debug("stmmac_mdio_reset: calling phy_reset\n"); + priv->plat->mdio_bus_data->phy_reset(priv->plat->bsp_priv); + } + + /* This is a workaround for problems with the STE101P PHY. + * It doesn't complete its reset until at least one clock cycle + * on MDC, so perform a dummy mdio read. + */ + writel(0, priv->ioaddr + mii_address); +#endif + return 0; +} + +/** + * stmmac_mdio_register + * @ndev: net device structure + * Description: it registers the MII bus + */ +int stmmac_mdio_register(struct net_device *ndev) +{ + int err = 0; + struct mii_bus *new_bus; + int *irqlist; + struct stmmac_priv *priv = netdev_priv(ndev); + struct stmmac_mdio_bus_data *mdio_bus_data = priv->plat->mdio_bus_data; + int addr, found; + + if (!mdio_bus_data) + return 0; + + new_bus = mdiobus_alloc(); + if (new_bus == NULL) + return -ENOMEM; + + if (mdio_bus_data->irqs) + irqlist = mdio_bus_data->irqs; + else + irqlist = priv->mii_irq; + + new_bus->name = "STMMAC MII Bus"; + new_bus->read = &stmmac_mdio_read; + new_bus->write = &stmmac_mdio_write; + new_bus->reset = &stmmac_mdio_reset; + snprintf(new_bus->id, MII_BUS_ID_SIZE, "%s-%x", + new_bus->name, mdio_bus_data->bus_id); + new_bus->priv = ndev; + new_bus->irq = irqlist; + new_bus->phy_mask = mdio_bus_data->phy_mask; + new_bus->parent = priv->device; + err = mdiobus_register(new_bus); + if (err != 0) { + pr_err("%s: Cannot register as MDIO bus\n", new_bus->name); + goto bus_register_fail; + } + + priv->mii = new_bus; + + found = 0; + for (addr = 0; addr < PHY_MAX_ADDR; addr++) { + struct phy_device *phydev = new_bus->phy_map[addr]; + if (phydev) { + int act = 0; + char irq_num[4]; + char *irq_str; + + /* + * If an IRQ was provided to be assigned after + * the bus probe, do it here. + */ + if ((mdio_bus_data->irqs == NULL) && + (mdio_bus_data->probed_phy_irq > 0)) { + irqlist[addr] = mdio_bus_data->probed_phy_irq; + phydev->irq = mdio_bus_data->probed_phy_irq; + } + + /* + * If we're going to bind the MAC to this PHY bus, + * and no PHY number was provided to the MAC, + * use the one probed here. + */ + if ((priv->plat->bus_id == mdio_bus_data->bus_id) && + (priv->plat->phy_addr == -1)) + priv->plat->phy_addr = addr; + + act = (priv->plat->bus_id == mdio_bus_data->bus_id) && + (priv->plat->phy_addr == addr); + switch (phydev->irq) { + case PHY_POLL: + irq_str = "POLL"; + break; + case PHY_IGNORE_INTERRUPT: + irq_str = "IGNORE"; + break; + default: + sprintf(irq_num, "%d", phydev->irq); + irq_str = irq_num; + break; + } + pr_info("%s: PHY ID %08x at %d IRQ %s (%s)%s\n", + ndev->name, phydev->phy_id, addr, + irq_str, dev_name(&phydev->dev), + act ? " active" : ""); + found = 1; + } + } + + if (!found) + pr_warning("%s: No PHY found\n", ndev->name); + + return 0; + +bus_register_fail: + mdiobus_free(new_bus); + return err; +} + +/** + * stmmac_mdio_unregister + * @ndev: net device structure + * Description: it unregisters the MII bus + */ +int stmmac_mdio_unregister(struct net_device *ndev) +{ + struct stmmac_priv *priv = netdev_priv(ndev); + + mdiobus_unregister(priv->mii); + priv->mii->priv = NULL; + mdiobus_free(priv->mii); + priv->mii = NULL; + + return 0; +} diff --git a/pool/shard008/C/0130121_hmac.c b/pool/shard008/C/0130121_hmac.c new file mode 100644 index 0000000000000000000000000000000000000000..169a7091c97d4b2afa3d80daf3c6aaae77eaebc4 --- /dev/null +++ b/pool/shard008/C/0130121_hmac.c @@ -0,0 +1,113 @@ +/* + * hmac.c - Libteredo HMAC tests + */ + +/*********************************************************************** + * Copyright © 2005-2006 Rémi Denis-Courmont. * + * This program is free software; you can redistribute and/or modify * + * it under the terms of the GNU General Public License as published * + * by the Free Software Foundation; 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, you can get it from: * + * http://www.gnu.org/copyleft/gpl.html * + ***********************************************************************/ + +#ifdef HAVE_CONFIG_H +# include +#endif + +#undef NDEBUG +#include +#include +#include +#include + +#include /* for Mac OS X */ +#include +#include +#include /* sleep () */ +#include /* fd_set */ + +#include "teredo.h" +#include "tunnel.h" +#include "security.h" + +static const uint32_t stamp = 0x12345678; + +static int test_ping (void) +{ + struct in6_addr src, dst; + uint8_t hmac[LIBTEREDO_HMAC_LEN]; + + memcpy (&src, "\x20\x01\x00\x00\x8a\xc3\x9d\xdd" + "\x80\x00\xf2\x27\x75\x3c\x67\x74", 16); + memcpy (&dst, "\x20\x02\xc0\x00\x02\x42\x12\x42" + "\x13\x43\x14\x44\x15\x45\x16\x46", 16); + teredo_get_pinghash (stamp, &src, &dst, hmac); + if (teredo_verify_pinghash (stamp, &src, &dst, hmac)) + return 1; + + /* retry after first run */ + teredo_get_pinghash (stamp, &dst, &src, hmac); + if (teredo_verify_pinghash (stamp, &dst, &src, hmac)) + return 1; + if (teredo_verify_pinghash (stamp, &src, &dst, hmac) == 0) + /* mixed addresses : should fail */ + return 1; + + for (unsigned i = 0; i < sizeof (hmac); i++) + { + hmac[i] ^= 0x40; + if (teredo_verify_pinghash (stamp, &dst, &src, hmac) == 0) + /* altered hash : should fail */ + return 1; + hmac[i] ^= 0x40; + } + + for (unsigned delay = 0; delay < 30; delay++) + /* should still be valid after <30 seconds */ + if (teredo_verify_pinghash (stamp + delay, &dst, &src, hmac)) + return 1; + + /* should no longer be valid after 30 seconds, or in the past */ + if ((teredo_verify_pinghash (stamp + 30, &dst, &src, hmac) == 0) + || (teredo_verify_pinghash (stamp + 31, &dst, &src, hmac) == 0) + || (teredo_verify_pinghash (stamp - 1, &dst, &src, hmac) == 0)) + return 1; + + return 0; +} + + +static int test_rs (void) +{ + uint8_t nonce[LIBTEREDO_NONCE_LEN], buf[LIBTEREDO_NONCE_LEN]; + uint32_t ipv4 = htonl (0xc0000234); + uint16_t port = htons (12345); + + teredo_get_nonce (stamp, ipv4, port, nonce); + teredo_get_nonce (stamp, ipv4, port, buf); + + if (memcmp (buf, nonce, LIBTEREDO_NONCE_LEN)) + return 1; + + return 0; +} + + +int main (void) +{ + assert (teredo_init_HMAC () == 0); + assert (test_ping () == 0); + assert (test_rs () == 0); + + teredo_deinit_HMAC (); + return 0; +} diff --git a/pool/shard008/C/0130122_benchmark-cipher.c b/pool/shard008/C/0130122_benchmark-cipher.c new file mode 100644 index 0000000000000000000000000000000000000000..61ec5e248ab91e7c9591c98991bdff65536c0219 --- /dev/null +++ b/pool/shard008/C/0130122_benchmark-cipher.c @@ -0,0 +1,224 @@ +/* + * Copyright (C) 2009-2012 Free Software Foundation, Inc. + * + * This file is part of GnuTLS. + * + * GnuTLS 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. + * + * GnuTLS 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 + * . + * + * Written by Nikos Mavrogiannopoulos . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "benchmark.h" + +static unsigned char data[64 * 1024]; + + +static void tls_log_func(int level, const char *str) +{ + fprintf(stderr, "|<%d>| %s", level, str); +} + +static void cipher_mac_bench(int algo, int mac_algo, int size) +{ + int ret; + gnutls_cipher_hd_t ctx; + gnutls_hmac_hd_t mac_ctx; + void *_key, *_iv; + gnutls_datum_t key, iv; + int ivsize = gnutls_cipher_get_iv_size(algo); + int keysize = gnutls_cipher_get_key_size(algo); + int step = size * 1024; + struct benchmark_st st; + + _key = malloc(keysize); + if (_key == NULL) + return; + memset(_key, 0xf0, keysize); + + _iv = malloc(ivsize); + if (_iv == NULL) + return; + memset(_iv, 0xf0, ivsize); + + iv.data = _iv; + iv.size = ivsize; + + key.data = _key; + key.size = keysize; + + printf("%16s-%s ", gnutls_cipher_get_name(algo), + gnutls_mac_get_name(mac_algo)); + fflush(stdout); + + start_benchmark(&st); + + ret = gnutls_hmac_init(&mac_ctx, mac_algo, key.data, key.size); + if (ret < 0) { + fprintf(stderr, "error: %s\n", gnutls_strerror(ret)); + goto leave; + } + + ret = gnutls_cipher_init(&ctx, algo, &key, &iv); + if (ret < 0) { + fprintf(stderr, "error: %s\n", gnutls_strerror(ret)); + goto leave; + } + + gnutls_hmac(mac_ctx, data, 1024); + + do { + gnutls_hmac(mac_ctx, data, step); + gnutls_cipher_encrypt2(ctx, data, step, data, step + 64); + st.size += step; + } + while (benchmark_must_finish == 0); + + gnutls_cipher_deinit(ctx); + gnutls_hmac_deinit(mac_ctx, NULL); + + stop_benchmark(&st, NULL, 1); + + leave: + free(_key); + free(_iv); +} + + +static void cipher_bench(int algo, int size, int aead) +{ + int ret; + gnutls_cipher_hd_t ctx; + void *_key, *_iv; + gnutls_datum_t key, iv; + int ivsize = gnutls_cipher_get_iv_size(algo); + int keysize = gnutls_cipher_get_key_size(algo); + int step = size * 1024; + struct benchmark_st st; + + _key = malloc(keysize); + if (_key == NULL) + return; + memset(_key, 0xf0, keysize); + + _iv = malloc(ivsize); + if (_iv == NULL) + return; + memset(_iv, 0xf0, ivsize); + + iv.data = _iv; + if (aead) + iv.size = 12; + else + iv.size = ivsize; + + key.data = _key; + key.size = keysize; + + printf("%16s ", gnutls_cipher_get_name(algo)); + fflush(stdout); + + start_benchmark(&st); + + ret = gnutls_cipher_init(&ctx, algo, &key, &iv); + if (ret < 0) { + fprintf(stderr, "error: %s\n", gnutls_strerror(ret)); + goto leave; + } + + if (aead) + gnutls_cipher_add_auth(ctx, data, 1024); + + do { + gnutls_cipher_encrypt2(ctx, data, step, data, step + 64); + st.size += step; + } + while (benchmark_must_finish == 0); + + gnutls_cipher_deinit(ctx); + + stop_benchmark(&st, NULL, 1); + + leave: + free(_key); + free(_iv); +} + +static void mac_bench(int algo, int size) +{ + void *_key; + int blocksize = gnutls_hmac_get_len(algo); + int step = size * 1024; + struct benchmark_st st; + + _key = malloc(blocksize); + if (_key == NULL) + return; + memset(_key, 0xf0, blocksize); + + printf("%16s ", gnutls_mac_get_name(algo)); + fflush(stdout); + + start_benchmark(&st); + + do { + gnutls_hmac_fast(algo, _key, blocksize, data, step, _key); + st.size += step; + } + while (benchmark_must_finish == 0); + + stop_benchmark(&st, NULL, 1); + + free(_key); +} + +void benchmark_cipher(int debug_level) +{ + int size = 16; + gnutls_global_set_log_function(tls_log_func); + gnutls_global_set_log_level(debug_level); + + gnutls_rnd(GNUTLS_RND_NONCE, data, sizeof(data)); + + printf("Checking cipher-MAC combinations, payload size: %u\n", size * 1024); + cipher_mac_bench(GNUTLS_CIPHER_SALSA20_256, GNUTLS_MAC_SHA1, size); + cipher_mac_bench(GNUTLS_CIPHER_AES_128_CBC, GNUTLS_MAC_SHA1, size); + cipher_mac_bench(GNUTLS_CIPHER_AES_128_CBC, GNUTLS_MAC_SHA256, + size); + cipher_bench(GNUTLS_CIPHER_AES_128_GCM, size, 1); + + printf("\nChecking MAC algorithms, payload size: %u\n", size * 1024); + mac_bench(GNUTLS_MAC_SHA1, size); + mac_bench(GNUTLS_MAC_SHA256, size); + mac_bench(GNUTLS_MAC_SHA512, size); + + printf("\nChecking ciphers, payload size: %u\n", size * 1024); + cipher_bench(GNUTLS_CIPHER_3DES_CBC, size, 0); + + cipher_bench(GNUTLS_CIPHER_AES_128_CBC, size, 0); + + cipher_bench(GNUTLS_CIPHER_ARCFOUR, size, 0); + + cipher_bench(GNUTLS_CIPHER_SALSA20_256, size, 0); + + gnutls_global_deinit(); +} diff --git a/pool/shard008/C/0130130_linReg.c b/pool/shard008/C/0130130_linReg.c new file mode 100644 index 0000000000000000000000000000000000000000..96fe1e6051abc2cce64c846052976819ae91ed8e --- /dev/null +++ b/pool/shard008/C/0130130_linReg.c @@ -0,0 +1,135 @@ +// Samuel Havron +// https://www.github.com/samuelhavron +// MIT License + +#include +#include +#include +#include "linReg.h" + +// Fixed point arithmetic +#define SCALE (1 << 16) // 2^16 +#define DESCALE(x) (double) x / SCALE + +void check_mem(int *x, int *y) { + if(x == NULL || y == NULL) { + printf("ERROR: Memory allocation failed\n"); + exit(1); + } +} + +DataSet load_data(FILE *inputFile) { + DataSet data; + data.x = malloc(sizeof(int)); + data.y = malloc(sizeof(int)); + data.n = 0; + check_mem(data.x, data.y); + + double a, b; + while (!feof(inputFile)) { + int dataPoints = fscanf(inputFile, "%lf %lf", &a, &b); + + if (dataPoints != 2) { + if (dataPoints < 0 && feof(inputFile)) { + break; + } else { + fprintf(stderr, "ERROR: Input does not match file format. Check input file.\n"); + printf("File format exception found at Line %d in file.\n", data.n + 1); + exit(1); + } + } + + // Update count and resize arrays + data.n += 1; + data.x = realloc(data.x, sizeof(int) * data.n); + data.y = realloc(data.y, sizeof(int) * data.n); + check_mem(data.x, data.y); + + data.x[data.n - 1] = a*SCALE; // -1 for index + data.y[data.n - 1] = b*SCALE; // -1 for index + } + + printf("Loading %d data points ...\n", data.n); + return data; +} + +LinRegResult linear_regression(DataSet theData) { + + LinRegResult result; + int n = theData.n; // number of data points + double sumx = DESCALE(sum(theData.x, n)); // sum of x + double sumxx = DESCALE(dotProd(theData.x, theData.x, n)); // sum of each x squared + double sumy = DESCALE(sum(theData.y, n)); // sum of y + double sumyy = DESCALE(dotProd(theData.y, theData.y, n)); // sum of each y squared + double sumxy = DESCALE(dotProd(theData.x, theData.y, n)); // sum of each x * y + + double m, b, r; + // Compute least-squares best fit straight line + m = (n * sumxy - sumx * sumy) / (n * sumxx - sqr(sumx)); // slope + b = (sumy * sumxx - (sumx * sumxy)) / (n * sumxx - sqr(sumx)); // y-intercept + r = (sumxy - sumx * sumy / n) / sqrt((sumxx - sqr(sumx) / n) * (sumyy - sqr(sumy)/ n)); // correlation + + result.m = m * SCALE; + result.b = b * SCALE; + result.r = r * SCALE; + return result; +} + +int main(int argc, char *argv[]) { + printf("Linear Regression\n"); + printf("=================\n\n"); + + // Check for a filename + if (argc == 2) { + FILE *input = fopen(argv[1], "r"); + + if (input == NULL) { + perror(argv[1]); + exit(1); + + } else { + DataSet theData = load_data(input); + fclose(input); + + LinRegResult linReg = linear_regression(theData); + clean(theData); + printf("\nSlope \tm = %15.6e\n", DESCALE(linReg.m)); // print slope + printf("y-intercept\tb = %15.6e\n", DESCALE(linReg.b)); // print y-intercept + printf("Correlation\tr = %15.6e\n", DESCALE(linReg.r)); // print correlation + } + + } else { + printf("ERROR: Must enter filename after ./linReg\n"); + + } + return 0; +} + +int sqr(int x) { + return x * x; +} + +int dotProd(int *a, int *b, int n) { + double dotProd = 0; + int result = 0; + int i; + for (i = 0; i < n; i++) { + dotProd += DESCALE(a[i]) * DESCALE(b[i]); + } + result = dotProd * SCALE; + return result; +} + +int sum(int *a, int n) { + int sum = 0; + int i; + for (i = 0; i < n; i++) { + sum += a[i]; + } + return sum; +} + +void clean(DataSet data) { + free(data.x); + free(data.y); +} diff --git a/pool/shard008/C/0130132_gsimpath.c b/pool/shard008/C/0130132_gsimpath.c new file mode 100644 index 0000000000000000000000000000000000000000..2752c5d5379385fdca4b4b6ac2ab45ad6b3f16a0 --- /dev/null +++ b/pool/shard008/C/0130132_gsimpath.c @@ -0,0 +1,188 @@ +/* Copyright (C) 1989, 1992 Aladdin Enterprises. All rights reserved. + + This file is part of GNU Ghostscript. + + GNU Ghostscript is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY. No author or distributor accepts responsibility to + anyone for the consequences of using it or for whether it serves any + particular purpose or works at all, unless he says so in writing. Refer to + the GNU General Public License for full details. + + Everyone is granted permission to copy, modify and redistribute GNU + Ghostscript, but only under the conditions described in the GNU General + Public License. A copy of this license is supposed to have been given to + you along with GNU Ghostscript so you can know your rights and + responsibilities. It should be in a file named COPYING. Among other + things, the copyright notice and this notice must be preserved on all + copies. + + Aladdin Enterprises is not affiliated with the Free Software Foundation or + the GNU Project. GNU Ghostscript, as distributed by Aladdin Enterprises, + does not depend on any other GNU software. +*/ + +/* gsimpath.c */ +/* Image to outline conversion for Ghostscript library */ +#include "gx.h" +#include "gserrors.h" +#include "gsmatrix.h" +#include "gsstate.h" +#include "gspath.h" + +/* Define the state of the conversion process. */ +typedef struct { + /* The following are set at the beginning of the conversion. */ + gs_state *pgs; + const byte *data; /* image data */ + int width, height, raster; + /* The following are updated dynamically. */ + int dx, dy; /* X/Y increment of current run */ + int count; /* # of steps in current run */ +} status; + +/* Define the scaling for the path tracer. */ +/* It must be even. */ +#define outline_scale 4 +/* Define the length of the short strokes for turning corners. */ +#define step 1 + +/* Forward declarations */ +private int near get_pixel(P3(const status *, int, int)); +private int near trace_from(P4(status *, int, int, int)); +private int near add_dxdy(P4(status *, int, int, int)); +#define add_deltas(s, dx, dy, n)\ + if ( (code = add_dxdy(s, dx, dy, n)) < 0 ) return code +/* Append an outline derived from an image to the current path. */ +int +gs_imagepath(gs_state *pgs, int width, int height, const byte *data) +{ status stat; + status *out = &stat; + int code, x, y; + /* Initialize the state. */ + stat.pgs = pgs; + stat.data = data; + stat.width = width; + stat.height = height; + stat.raster = (width + 7) / 8; + /* Trace the cells to form an outline. The trace goes in clockwise */ + /* order, always starting by going west along a bottom edge. */ + for ( y = height - 1; y >= 0; y-- ) + for ( x = width - 1; x >= 0; x-- ) + { if ( get_pixel(out, x, y) && !get_pixel(out, x, y - 1) && + (!get_pixel(out, x + 1, y) || get_pixel(out, x + 1, y - 1)) && + !trace_from(out, x, y, 1) + ) + { /* Found a starting point */ + stat.count = 0; + stat.dx = stat.dy = 0; + if ( (code = trace_from(out, x, y, 0)) < 0 ) + return code; + add_deltas(out, 0, 0, 1); /* force out last segment */ + if ( (code = gs_closepath(pgs)) < 0 ) + return code; + } + } + return 0; +} + +/* Get a pixel from the data. Return 0 if outside the image. */ +private int near +get_pixel(register const status *out, int x, int y) +{ if ( x < 0 || x >= out->width || y < 0 || y >= out->height ) + return 0; + return (out->data[y * out->raster + (x >> 3)] >> (~x & 7)) & 1; +} + +/* Trace a path. If detect is true, don't draw, just return 1 if we ever */ +/* encounter a starting point whose x,y follows that of the initial point */ +/* in x-then-y scan order; if detect is false, actually draw the outline. */ +private int near +trace_from(register status *out, int x0, int y0, int detect) +{ int x = x0, y = y0; + int dx = -1, dy = 0; /* initially going west */ + int part = 0; /* how far along edge we are; */ + /* initialized only to pacify gcc */ + int code; + if ( !detect ) + { part = (get_pixel(out, x + 1, y - 1) ? + outline_scale - step : step); + code = gs_moveto(out->pgs, + x + 1 - part / (float)outline_scale, + (float)y); + if ( code < 0 ) return code; + } + while ( 1 ) + { /* Relative to the current direction, */ + /* -dy,dx is at +90 degrees (counter-clockwise); */ + /* tx,ty is at +45 degrees; */ + /* ty,-tx is at -45 degrees (clockwise); */ + /* dy,-dx is at -90 degrees. */ + int tx = dx - dy, ty = dy + dx; + if ( get_pixel(out, x + tx, y + ty) ) + { /* Cell at 45 degrees is full, */ + /* go counter-clockwise. */ + if ( !detect ) + { /* If this is a 90 degree corner set at a */ + /* 45 degree angle, avoid backtracking. */ + if ( out->dx == ty && out->dy == -tx ) + { +#define half_scale (outline_scale / 2 - step) + out->count -= half_scale; + add_deltas(out, tx, ty, outline_scale / 2); +#undef half_scale + } + else + { add_deltas(out, dx, dy, step - part); + add_deltas(out, tx, ty, outline_scale - step); + } + part = outline_scale - step; + } + x += tx, y += ty; + dx = -dy, dy += tx; + } + else if ( !get_pixel(out, x + dx, y + dy) ) + { /* Cell straight ahead is empty, go clockwise. */ + if ( !detect ) + { add_deltas(out, dx, dy, outline_scale - step - part); + add_deltas(out, ty, -tx, step); + part = step; + } + dx = dy, dy -= ty; + } + else + { /* Neither of the above, go in same direction. */ + if ( !detect ) + { add_deltas(out, dx, dy, outline_scale); + } + x += dx, y += dy; + } + if ( dx == -step && dy == 0 && !(tx == -step && ty == -step) ) + { /* We just turned a corner and are going west, */ + /* so the previous pixel is a starting point pixel. */ + if ( x == x0 && y == y0 ) return 0; + if ( detect && (y > y0 || (y == y0 && x > x0)) ) + return 1; + } + } +} + +/* Add a (dx, dy) pair to the path being formed. */ +/* Accumulate successive segments in the same direction. */ +private int near +add_dxdy(register status *out, int dx, int dy, int count) +{ if ( count != 0 ) + { if ( dx == out->dx && dy == out->dy ) + out->count += count; + else + { if ( out->count != 0 ) + { int code = gs_rlineto(out->pgs, + out->dx * out->count / (float)outline_scale, + out->dy * out->count / (float)outline_scale); + if ( code < 0 ) return code; + } + out->dx = dx, out->dy = dy; + out->count = count; + } + } + return 0; +} diff --git a/pool/shard008/C/0130137_program.c b/pool/shard008/C/0130137_program.c new file mode 100644 index 0000000000000000000000000000000000000000..2dfb4645632f36508b09704046ef1c135eb3c6d9 --- /dev/null +++ b/pool/shard008/C/0130137_program.c @@ -0,0 +1,20 @@ +#include +#include "data-formats.h" +#include "synthesizer.h" + +int main() { + StereoSample32 sample; + StereoSample32 *sample_pointer; + + double audio = 0; + + for (int t = 0; t < 1000000; t++) { + audio = play(t, 440); + sample.left_channel = audio; + sample.right_channel = audio; + sample_pointer = &sample; + fwrite(sample_pointer, 1, sizeof(sample), stdout); + } + + return 0; +} diff --git a/pool/shard008/C/0130142_CWE401_Memory_Leak__twoIntsStruct_calloc_41.c b/pool/shard008/C/0130142_CWE401_Memory_Leak__twoIntsStruct_calloc_41.c new file mode 100644 index 0000000000000000000000000000000000000000..ca5d7822f90c27844707a88e73ed2e70de05d4da --- /dev/null +++ b/pool/shard008/C/0130142_CWE401_Memory_Leak__twoIntsStruct_calloc_41.c @@ -0,0 +1,119 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE401_Memory_Leak__twoIntsStruct_calloc_41.c +Label Definition File: CWE401_Memory_Leak.c.label.xml +Template File: sources-sinks-41.tmpl.c +*/ +/* + * @description + * CWE: 401 Memory Leak + * BadSource: calloc Allocate data using calloc() + * GoodSource: Allocate data on the stack + * Sinks: + * GoodSink: call free() on data + * BadSink : no deallocation of data + * Flow Variant: 41 Data flow: data passed as an argument from one function to another in the same source file + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +static void badSink(twoIntsStruct * data) +{ + /* POTENTIAL FLAW: No deallocation */ + ; /* empty statement needed for some flow variants */ +} + +void CWE401_Memory_Leak__twoIntsStruct_calloc_41_bad() +{ + twoIntsStruct * data; + data = NULL; + /* POTENTIAL FLAW: Allocate memory on the heap */ + data = (twoIntsStruct *)calloc(100, sizeof(twoIntsStruct)); + /* Initialize and make use of data */ + data[0].intOne = 0; + data[0].intTwo = 0; + printStructLine(&data[0]); + badSink(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2BSink(twoIntsStruct * data) +{ + /* POTENTIAL FLAW: No deallocation */ + ; /* empty statement needed for some flow variants */ +} + +static void goodG2B() +{ + twoIntsStruct * data; + data = NULL; + /* FIX: Use memory allocated on the stack with ALLOCA */ + data = (twoIntsStruct *)ALLOCA(100*sizeof(twoIntsStruct)); + /* Initialize and make use of data */ + data[0].intOne = 0; + data[0].intTwo = 0; + printStructLine(&data[0]); + goodG2BSink(data); +} + +/* goodB2G uses the BadSource with the GoodSink */ +static void goodB2GSink(twoIntsStruct * data) +{ + /* FIX: Deallocate memory */ + free(data); +} + +static void goodB2G() +{ + twoIntsStruct * data; + data = NULL; + /* POTENTIAL FLAW: Allocate memory on the heap */ + data = (twoIntsStruct *)calloc(100, sizeof(twoIntsStruct)); + /* Initialize and make use of data */ + data[0].intOne = 0; + data[0].intTwo = 0; + printStructLine(&data[0]); + goodB2GSink(data); +} + +void CWE401_Memory_Leak__twoIntsStruct_calloc_41_good() +{ + goodB2G(); + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE401_Memory_Leak__twoIntsStruct_calloc_41_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE401_Memory_Leak__twoIntsStruct_calloc_41_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard008/C/0130143_linux_mouse.c b/pool/shard008/C/0130143_linux_mouse.c new file mode 100644 index 0000000000000000000000000000000000000000..d00a7de6705c0ed9d49ee9aca0f20082c9ca68b2 --- /dev/null +++ b/pool/shard008/C/0130143_linux_mouse.c @@ -0,0 +1,25 @@ +// linux_mouse.c + +static int +mouse_x11_grab(Display* display, Window window) +{ + int grab_status = XGrabPointer(display, window, True, None, GrabModeAsync, GrabModeAsync, + window, None, CurrentTime); + + return (grab_status == Success); +} + +static void +mouse_x11_ungrab(Display* display) +{ + XUngrabPointer(display, CurrentTime); +} + +static void +mouse_x11_set_cursor(Display* display, Cursor cursor) +{ + Window window = DefaultRootWindow(display); + XDefineCursor(display, window, cursor); +} + + diff --git a/pool/shard008/C/0130145_evergreen_dma.c b/pool/shard008/C/0130145_evergreen_dma.c new file mode 100644 index 0000000000000000000000000000000000000000..afaba388c36dec2fcd6cd5b986a9ab4d70406385 --- /dev/null +++ b/pool/shard008/C/0130145_evergreen_dma.c @@ -0,0 +1,184 @@ +/* + * Copyright 2010 Advanced Micro Devices, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + * OTHER DEALINGS IN THE SOFTWARE. + * + * Authors: Alex Deucher + */ +#include +#include "radeon.h" +#include "radeon_asic.h" +#include "evergreend.h" + +u32 evergreen_gpu_check_soft_reset(struct radeon_device *rdev); + +/** + * evergreen_dma_fence_ring_emit - emit a fence on the DMA ring + * + * @rdev: radeon_device pointer + * @fence: radeon fence object + * + * Add a DMA fence packet to the ring to write + * the fence seq number and DMA trap packet to generate + * an interrupt if needed (evergreen-SI). + */ +void evergreen_dma_fence_ring_emit(struct radeon_device *rdev, + struct radeon_fence *fence) +{ + struct radeon_ring *ring = &rdev->ring[fence->ring]; + u64 addr = rdev->fence_drv[fence->ring].gpu_addr; + /* write the fence */ + radeon_ring_write(ring, DMA_PACKET(DMA_PACKET_FENCE, 0, 0)); + radeon_ring_write(ring, addr & 0xfffffffc); + radeon_ring_write(ring, (upper_32_bits(addr) & 0xff)); + radeon_ring_write(ring, fence->seq); + /* generate an interrupt */ + radeon_ring_write(ring, DMA_PACKET(DMA_PACKET_TRAP, 0, 0)); + /* flush HDP */ + radeon_ring_write(ring, DMA_PACKET(DMA_PACKET_SRBM_WRITE, 0, 0)); + radeon_ring_write(ring, (0xf << 16) | (HDP_MEM_COHERENCY_FLUSH_CNTL >> 2)); + radeon_ring_write(ring, 1); +} + +/** + * evergreen_dma_ring_ib_execute - schedule an IB on the DMA engine + * + * @rdev: radeon_device pointer + * @ib: IB object to schedule + * + * Schedule an IB in the DMA ring (evergreen). + */ +void evergreen_dma_ring_ib_execute(struct radeon_device *rdev, + struct radeon_ib *ib) +{ + struct radeon_ring *ring = &rdev->ring[ib->ring]; + + if (rdev->wb.enabled) { + u32 next_rptr = ring->wptr + 4; + while ((next_rptr & 7) != 5) + next_rptr++; + next_rptr += 3; + radeon_ring_write(ring, DMA_PACKET(DMA_PACKET_WRITE, 0, 1)); + radeon_ring_write(ring, ring->next_rptr_gpu_addr & 0xfffffffc); + radeon_ring_write(ring, upper_32_bits(ring->next_rptr_gpu_addr) & 0xff); + radeon_ring_write(ring, next_rptr); + } + + /* The indirect buffer packet must end on an 8 DW boundary in the DMA ring. + * Pad as necessary with NOPs. + */ + while ((ring->wptr & 7) != 5) + radeon_ring_write(ring, DMA_PACKET(DMA_PACKET_NOP, 0, 0)); + radeon_ring_write(ring, DMA_PACKET(DMA_PACKET_INDIRECT_BUFFER, 0, 0)); + radeon_ring_write(ring, (ib->gpu_addr & 0xFFFFFFE0)); + radeon_ring_write(ring, (ib->length_dw << 12) | (upper_32_bits(ib->gpu_addr) & 0xFF)); + +} + +/** + * evergreen_copy_dma - copy pages using the DMA engine + * + * @rdev: radeon_device pointer + * @src_offset: src GPU address + * @dst_offset: dst GPU address + * @num_gpu_pages: number of GPU pages to xfer + * @fence: radeon fence object + * + * Copy GPU paging using the DMA engine (evergreen-cayman). + * Used by the radeon ttm implementation to move pages if + * registered as the asic copy callback. + */ +int evergreen_copy_dma(struct radeon_device *rdev, + uint64_t src_offset, uint64_t dst_offset, + unsigned num_gpu_pages, + struct radeon_fence **fence) +{ + struct radeon_semaphore *sem = NULL; + int ring_index = rdev->asic->copy.dma_ring_index; + struct radeon_ring *ring = &rdev->ring[ring_index]; + u32 size_in_dw, cur_size_in_dw; + int i, num_loops; + int r = 0; + + r = radeon_semaphore_create(rdev, &sem); + if (r) { + DRM_ERROR("radeon: moving bo (%d).\n", r); + return r; + } + + size_in_dw = (num_gpu_pages << RADEON_GPU_PAGE_SHIFT) / 4; + num_loops = DIV_ROUND_UP(size_in_dw, 0xfffff); + r = radeon_ring_lock(rdev, ring, num_loops * 5 + 11); + if (r) { + DRM_ERROR("radeon: moving bo (%d).\n", r); + radeon_semaphore_free(rdev, &sem, NULL); + return r; + } + + radeon_semaphore_sync_to(sem, *fence); + radeon_semaphore_sync_rings(rdev, sem, ring->idx); + + for (i = 0; i < num_loops; i++) { + cur_size_in_dw = size_in_dw; + if (cur_size_in_dw > 0xFFFFF) + cur_size_in_dw = 0xFFFFF; + size_in_dw -= cur_size_in_dw; + radeon_ring_write(ring, DMA_PACKET(DMA_PACKET_COPY, 0, cur_size_in_dw)); + radeon_ring_write(ring, dst_offset & 0xfffffffc); + radeon_ring_write(ring, src_offset & 0xfffffffc); + radeon_ring_write(ring, upper_32_bits(dst_offset) & 0xff); + radeon_ring_write(ring, upper_32_bits(src_offset) & 0xff); + src_offset += cur_size_in_dw * 4; + dst_offset += cur_size_in_dw * 4; + } + + r = radeon_fence_emit(rdev, fence, ring->idx); + if (r) { + radeon_ring_unlock_undo(rdev, ring); + radeon_semaphore_free(rdev, &sem, NULL); + return r; + } + + radeon_ring_unlock_commit(rdev, ring, false); + radeon_semaphore_free(rdev, &sem, *fence); + + return r; +} + +/** + * evergreen_dma_is_lockup - Check if the DMA engine is locked up + * + * @rdev: radeon_device pointer + * @ring: radeon_ring structure holding ring information + * + * Check if the async DMA engine is locked up. + * Returns true if the engine appears to be locked up, false if not. + */ +bool evergreen_dma_is_lockup(struct radeon_device *rdev, struct radeon_ring *ring) +{ + u32 reset_mask = evergreen_gpu_check_soft_reset(rdev); + + if (!(reset_mask & RADEON_RESET_DMA)) { + radeon_ring_lockup_update(rdev, ring); + return false; + } + return radeon_ring_test_lockup(rdev, ring); +} + + diff --git a/pool/shard008/C/0130146_fdd_mtr.c b/pool/shard008/C/0130146_fdd_mtr.c new file mode 100644 index 0000000000000000000000000000000000000000..24b82be57826eddb782445aa279a13974e46ecd6 --- /dev/null +++ b/pool/shard008/C/0130146_fdd_mtr.c @@ -0,0 +1,195 @@ +#include "compiler.h" +#include "soundmng.h" +#include "pccore.h" +#include "fdd_mtr.h" +#if defined(SUPPORT_SWSEEKSND) +#include "sound/pcmmix.h" +#include "fdd_mtr.res" +#endif + + +#if defined(SUPPORT_SWSEEKSND) + +static struct { + UINT enable; + struct { + PMIXHDR hdr; + PMIXTRK trk[2]; + } snd; +} mtrsnd; + +void fddmtrsnd_initialize(UINT rate) { + + ZeroMemory(&mtrsnd, sizeof(mtrsnd)); + if (np2cfg.MOTORVOL) { + mtrsnd.enable = 1; + mtrsnd.snd.hdr.enable = 3; + pcmmix_regist(&mtrsnd.snd.trk[0].data, + (void *)fddseek, sizeof(fddseek), rate); + mtrsnd.snd.trk[0].flag = PMIXFLAG_L | PMIXFLAG_R | PMIXFLAG_LOOP; + mtrsnd.snd.trk[0].volume = (np2cfg.MOTORVOL << 12) / 100; + pcmmix_regist(&mtrsnd.snd.trk[1].data, + (void *)fddseek1, sizeof(fddseek1), rate); + mtrsnd.snd.trk[1].flag = PMIXFLAG_L | PMIXFLAG_R; + mtrsnd.snd.trk[1].volume = (np2cfg.MOTORVOL << 12) / 100; + } +} + +void fddmtrsnd_bind(void) { + + if (mtrsnd.enable) { + sound_streamregist(&mtrsnd.snd, (SOUNDCB)pcmmix_getpcm); + } +} + +void fddmtrsnd_deinitialize(void) { + + int i; + void *ptr; + + for (i=0; i<2; i++) { + ptr = mtrsnd.snd.trk[i].data.sample; + mtrsnd.snd.trk[i].data.sample = NULL; + if (ptr) { + _MFREE(ptr); + } + } +} + +static void fddmtrsnd_play(UINT num, BOOL play) { + + PMIXTRK *trk; + + if ((mtrsnd.enable) && (num < 2)) { + sound_sync(); + trk = mtrsnd.snd.trk + num; + if (play) { + if (trk->data.sample) { + trk->pcm = trk->data.sample; + trk->remain = trk->data.samples; + mtrsnd.snd.hdr.playing |= (1 << num); + } + } + else { + mtrsnd.snd.hdr.playing &= ~(1 << num); + } + } +} +#endif + + +// ---- + +enum { + MOVE1TCK_MS = 15, + MOVEMOTOR1_MS = 25, + DISK1ROL_MS = 166 +}; + + _FDDMTR fddmtr; + +static void fddmtr_event(void) { + + switch(fddmtr.curevent) { + case 100: +#if defined(SUPPORT_SWSEEKSND) + fddmtrsnd_play(0, FALSE); +#else + soundmng_pcmstop(SOUND_PCMSEEK); +#endif + fddmtr.curevent = 0; + break; + + default: + fddmtr.curevent = 0; + break; + } +} + +void fddmtr_initialize(void) { + +#if defined(SUPPORT_SWSEEKSND) + fddmtrsnd_play(0, FALSE); +#else + soundmng_pcmstop(SOUND_PCMSEEK); +#endif + ZeroMemory(&fddmtr, sizeof(fddmtr)); + FillMemory(fddmtr.head, sizeof(fddmtr.head), 42); +} + +void fddmtr_callback(UINT nowtime) { + + if ((fddmtr.curevent) && (nowtime >= fddmtr.nextevent)) { + fddmtr_event(); + } +} + +void fdbiosout(NEVENTITEM item) { + + fddmtr.busy = 0; + (void)item; +} + +void fddmtr_seek(REG8 drv, REG8 c, UINT size) { + + int regmove; + SINT32 waitcnt; + + drv &= 3; + regmove = c - fddmtr.head[drv]; + fddmtr.head[drv] = c; + + if (!np2cfg.MOTOR) { + if (size) { + fddmtr.busy = 1; + nevent_set(NEVENT_FDBIOSBUSY, size * pccore.multiple, + fdbiosout, NEVENT_ABSOLUTE); + } + return; + } + + waitcnt = (size * DISK1ROL_MS) / (1024 * 8); + if (regmove < 0) { + regmove = 0 - regmove; + } + if (regmove == 1) { + if (fddmtr.curevent < 80) { + fddmtr_event(); +#if defined(SUPPORT_SWSEEKSND) + fddmtrsnd_play(1, TRUE); +#else + soundmng_pcmplay(SOUND_PCMSEEK1, FALSE); +#endif + fddmtr.curevent = 80; + fddmtr.nextevent = GETTICK() + MOVEMOTOR1_MS; + } + } + else if (regmove) { + if (fddmtr.curevent < 100) { + fddmtr_event(); +#if defined(SUPPORT_SWSEEKSND) + fddmtrsnd_play(0, TRUE); +#else + soundmng_pcmplay(SOUND_PCMSEEK, TRUE); +#endif + fddmtr.curevent = 100; + fddmtr.nextevent = GETTICK() + (regmove * MOVE1TCK_MS); + } + if (regmove >= 32) { + waitcnt += DISK1ROL_MS; + } + } + if (waitcnt) { + fddmtr.busy = 1; + nevent_setbyms(NEVENT_FDBIOSBUSY, + waitcnt, fdbiosout, NEVENT_ABSOLUTE); + } + (void)drv; +} + +void fddmtr_reset(void) { + + fddmtr.busy = 0; + nevent_reset(NEVENT_FDBIOSBUSY); +} + diff --git a/pool/shard008/C/0130150_sun-bwtwo.c b/pool/shard008/C/0130150_sun-bwtwo.c new file mode 100644 index 0000000000000000000000000000000000000000..abfbc72e5fa59eb3a88423f8a93fe4c77004b691 --- /dev/null +++ b/pool/shard008/C/0130150_sun-bwtwo.c @@ -0,0 +1,379 @@ +/* $Id: sun-bwtwo.c,v 1.6 2009/11/08 17:03:58 fredette Exp $ */ + +/* machine/sun/sun-bwtwo.c - Sun bwtwo emulation: */ + +/* + * Copyright (c) 2003, 2004, 2006 Matt Fredette + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by Matt Fredette. + * 4. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +_TME_RCSID("$Id: sun-bwtwo.c,v 1.6 2009/11/08 17:03:58 fredette Exp $"); + +/* includes: */ +#include +#include +#include +#include "sun-fb.h" + +/* macros: */ + +/* bwtwo types: */ +#define TME_SUNBW2_TYPE_NULL (0) +#define TME_SUNBW2_TYPE_MULTIBUS (1) +#define TME_SUNBW2_TYPE_OLD_ONBOARD (2) +#define TME_SUNBW2_TYPE_ONBOARD (3) +#define TME_SUNBW2_TYPE_P4 (4) +#define TME_SUNBW2_TYPE_SBUS (5) + +/* register offsets and sizes: */ +#define TME_SUNBW2_REG_CSR_MULTIBUS (0x81800) +#define TME_SUNBW2_REG_CSR_OLD_ONBOARD (0x20000) +#define TME_SUNBW2_SIZ_CSR (0x00002) +#define TME_SUNBW2_SIZ_CSR_PAGE (0x00800) + +/* the bits in the Multibus and old-onboard Control/Status register: */ +#define TME_SUNBW2_CSR_ENABLE_VIDEO (0x8000) /* enable video */ +#define TME_SUNBW2_CSR_ENABLE_COPY (0x4000) /* enable copy mode */ +#define TME_SUNBW2_CSR_ENABLE_INT (0x2000) /* interrupt enable */ +#define TME_SUNBW2_CSR_INT_ACTIVE (0x1000) /* interrupt is active */ +#define TME_SUNBW2_CSR_JUMPER_B (0x0800) /* jumper B */ +#define TME_SUNBW2_CSR_JUMPER_A (0x0400) /* jumper A */ +#define TME_SUNBW2_CSR_JUMPER_COLOR (0x0200) /* jumper color */ +#define TME_SUNBW2_CSR_JUMPER_HIRES (0x0100) /* jumper hires */ +#define TME_SUNBW2_CSR_COPYBASE_MASK (0x007E) /* copybase mask */ + +#if 0 +#define TME_SUNBW2_DEBUG +#endif + +/* structures: */ + +/* the card: */ +struct tme_sunbw2 { + + /* our generic Sun framebuffer: */ + struct tme_sunfb tme_sunbw2_sunfb; +#define tme_sunbw2_mutex tme_sunbw2_sunfb.tme_sunfb_mutex +#define tme_sunbw2_bus_subregion_memory tme_sunbw2_sunfb.tme_sunfb_bus_subregion_memory +#define tme_sunbw2_bus_subregion_regs tme_sunbw2_sunfb.tme_sunfb_bus_subregion_regs +#define tme_sunbw2_csr_address tme_sunbw2_bus_subregion_regs.tme_bus_subregion_address_first + + /* the type of the bwtwo: */ + tme_uint32_t tme_sunbw2_type; + + /* our csr: */ + tme_uint16_t tme_sunbw2_csr; +}; + +#ifdef TME_SUNBW2_DEBUG +#define TME_SUNBW2_LO_WIDTH (1152) +#define TME_SUNBW2_LO_HEIGHT (900) +static int +_tme_sunbw2_update_debug(struct tme_fb_connection *conn_fb) +{ + struct tme_sunbw2 *sunbw2; + static int y = -1; + static int x; + unsigned long pixel; + unsigned int pixel_byte; + tme_uint8_t pixel_bit; + int box, box_y, box_x; + + sunbw2 = conn_fb->tme_fb_connection.tme_connection_element->tme_element_private; + + for (box = 0; box < 2; box++) { + if (y < 0) { + y = 16; + x = 0; + continue; + } + for (box_y = 0; box_y < 2; box_y++) { + for (box_x = 0; box_x < 2; box_x++) { + pixel = (((y + box_y) + * TME_SUNBW2_LO_WIDTH) + + x + + box_x); + pixel_byte = (pixel / 8); + pixel_bit = (0x80 >> (pixel % 8)); + sunbw2->tme_sunbw2_fb_memory[pixel_byte] ^= pixel_bit; + } + } + if (box == 0) { + x += 2; + if (x == TME_SUNBW2_LO_WIDTH) { + x = 0; + y += 2; + if (y == TME_SUNBW2_LO_HEIGHT) { + y = 0; + } + } + } + } + + return (TME_OK); +} +#undef TME_SUNBW2_LO_WIDTH +#undef TME_SUNBW2_LO_HEIGHT +#endif /* TME_SUNBW2_DEBUG */ + +/* the sunbw2 CSR bus cycle handler: */ +static int +_tme_sunbw2_bus_cycle_csr(void *_sunbw2, struct tme_bus_cycle *cycle_init) +{ + struct tme_sunbw2 *sunbw2; + tme_uint16_t csr_old, csr_new; + tme_bus_addr32_t undecoded; + + /* recover our data structure: */ + sunbw2 = (struct tme_sunbw2 *) _sunbw2; + + /* lock the mutex: */ + tme_mutex_lock(&sunbw2->tme_sunbw2_mutex); + + /* get the old CSR value: */ + csr_old = tme_betoh_u16(sunbw2->tme_sunbw2_csr); + + /* the entire 2KB (one page's) worth of addresses at + tme_sunbw2_csr_address are all decoded (or, rather, not decoded) + as the CSR: */ + undecoded + = (cycle_init->tme_bus_cycle_address + & (TME_SUNBW2_SIZ_CSR_PAGE - sizeof(sunbw2->tme_sunbw2_csr))); + cycle_init->tme_bus_cycle_address + -= undecoded; + + /* run the cycle: */ + assert (cycle_init->tme_bus_cycle_address + >= sunbw2->tme_sunbw2_csr_address); + tme_bus_cycle_xfer_memory(cycle_init, + (((tme_uint8_t *) &sunbw2->tme_sunbw2_csr) + - sunbw2->tme_sunbw2_csr_address), + (sunbw2->tme_sunbw2_csr_address + + sizeof(sunbw2->tme_sunbw2_csr) + - 1)); + cycle_init->tme_bus_cycle_address + += undecoded; + + /* get the new CSR value: */ + csr_new = tme_betoh_u16(sunbw2->tme_sunbw2_csr); + + /* put back the unchanging bits: */ + csr_new + = ((csr_new + & ~(TME_SUNBW2_CSR_INT_ACTIVE + | TME_SUNBW2_CSR_JUMPER_B + | TME_SUNBW2_CSR_JUMPER_A + | TME_SUNBW2_CSR_JUMPER_COLOR + | TME_SUNBW2_CSR_JUMPER_HIRES)) + | (csr_old + & (TME_SUNBW2_CSR_INT_ACTIVE + | TME_SUNBW2_CSR_JUMPER_B + | TME_SUNBW2_CSR_JUMPER_A + | TME_SUNBW2_CSR_JUMPER_COLOR + | TME_SUNBW2_CSR_JUMPER_HIRES))); + + /* we do not support these bits: */ + if (csr_new + & (TME_SUNBW2_CSR_ENABLE_COPY + | TME_SUNBW2_CSR_ENABLE_INT)) { + abort(); + } + + /* set the new CSR value: */ + sunbw2->tme_sunbw2_csr = tme_htobe_u16(csr_new); + + /* unlock the mutex: */ + tme_mutex_unlock(&sunbw2->tme_sunbw2_mutex); + + /* no faults: */ + return (TME_OK); +} + +/* this sets the bwtwo type: */ +static const char * +_tme_sunbw2_type_set(struct tme_sunfb *sunfb, const char *bw2_type_string) +{ + struct tme_sunbw2 *sunbw2; + tme_uint32_t bw2_type; + + /* recover our data structure: */ + sunbw2 = (struct tme_sunbw2 *) sunfb; + + /* see if this is a good type: */ + bw2_type = TME_SUNBW2_TYPE_NULL; + if (TME_ARG_IS(bw2_type_string, "multibus")) { + bw2_type = TME_SUNBW2_TYPE_MULTIBUS; + } + else if (TME_ARG_IS(bw2_type_string, "old-onboard")) { + bw2_type = TME_SUNBW2_TYPE_OLD_ONBOARD; + } + else if (TME_ARG_IS(bw2_type_string, "onboard")) { + bw2_type = TME_SUNBW2_TYPE_ONBOARD; + } + else if (TME_ARG_IS(bw2_type_string, "P4")) { + bw2_type = TME_SUNBW2_TYPE_P4; + } + else if (TME_ARG_IS(bw2_type_string, "sbus")) { + bw2_type = TME_SUNBW2_TYPE_SBUS; + } + + /* set the new type: */ + sunbw2->tme_sunbw2_type = bw2_type; + + /* assume the (relative) bus address of the first byte of displayed + framebuffer memory is zero: */ + sunbw2->tme_sunbw2_bus_subregion_memory.tme_bus_subregion_address_first = 0; + + /* assume that we can use the unspecified interrupt: */ + sunfb->tme_sunfb_bus_signal_int = TME_BUS_SIGNAL_INT_UNSPEC; + + /* dispatch on the new type: */ + switch (bw2_type) { + + /* if this was a bad type, return a string of types: */ + default: assert(FALSE); + case TME_SUNBW2_TYPE_NULL: + return ("multibus | old-onboard | onboard | P4 | sbus"); + + case TME_SUNBW2_TYPE_MULTIBUS: + case TME_SUNBW2_TYPE_OLD_ONBOARD: + + /* set the addresses of the CSR bus subregion: */ + sunbw2->tme_sunbw2_csr_address + = (bw2_type == TME_SUNBW2_TYPE_MULTIBUS + ? TME_SUNBW2_REG_CSR_MULTIBUS + : TME_SUNBW2_REG_CSR_OLD_ONBOARD); + sunbw2->tme_sunbw2_bus_subregion_regs.tme_bus_subregion_address_last + = (sunbw2->tme_sunbw2_csr_address + + TME_SUNBW2_SIZ_CSR_PAGE + - 1); + + /* set the CSR bus cycle handler: */ + sunfb->tme_sunfb_bus_handler_regs = _tme_sunbw2_bus_cycle_csr; + + /* the original Multibus bwtwo and onboard bwtwo only support + 1152x900 and 1024x1024: */ + sunfb->tme_sunfb_size + = (TME_SUNFB_SIZE_1152_900 + | TME_SUNFB_SIZE_1024_1024); + break; + + case TME_SUNBW2_TYPE_ONBOARD: + + /* the onboard bwtwo doesn't have any CSR: */ + sunfb->tme_sunfb_bus_handler_regs = NULL; + + /* the sizes supported by a CSR-less bwtwo appear to depend on the + actual model; we assume the user knows what he is doing: */ + sunfb->tme_sunfb_size = (TME_SUNFB_SIZE_NULL - 1); + break; + + case TME_SUNBW2_TYPE_P4: + + /* set our initial P4 register: */ + sunfb->tme_sunfb_p4 = tme_htobe_u32(TME_SUNFB_P4_ID_BWTWO); + + /* set the P4 register bus cycle handler: */ + sunfb->tme_sunfb_bus_handler_regs = tme_sunfb_bus_cycle_p4; + + /* we support the default P4 framebuffer sizes: */ + sunfb->tme_sunfb_size = 0; + + /* the framebuffer memory begins at a fixed offset after the P4 register: */ + sunbw2->tme_sunbw2_bus_subregion_memory.tme_bus_subregion_address_first + = TME_SUNFB_P4_OFFSET_BITMAP; + + break; + + case TME_SUNBW2_TYPE_SBUS: + + /* set the S4 register bus cycle handler: */ + sunfb->tme_sunfb_bus_handler_regs = tme_sunfb_bus_cycle_s4; + + /* we support the default S4 framebuffer sizes: */ + sunfb->tme_sunfb_size = 0; + + /* we use the default S4 memory address: */ + sunbw2->tme_sunbw2_bus_subregion_memory.tme_bus_subregion_address_first = 0; + + /* the SBus bwtwo uses priority seven interrupts: */ + sunfb->tme_sunfb_bus_signal_int = TME_BUS_SIGNAL_INT(7); + + break; + } + + /* success: */ + return (NULL); +} + +/* the new sun bwtwo function: */ +int +tme_sun_bwtwo(struct tme_element *element, const char * const *args, char **_output) +{ + struct tme_sunbw2 *sunbw2; + int rc; + + /* start the sunbw2 structure: */ + sunbw2 = tme_new0(struct tme_sunbw2, 1); + sunbw2->tme_sunbw2_sunfb.tme_sunfb_element = element; + + /* initialize the sunfb structure: */ + sunbw2->tme_sunbw2_sunfb.tme_sunfb_class = TME_FB_XLAT_CLASS_MONOCHROME; + sunbw2->tme_sunbw2_sunfb.tme_sunfb_depth = 1; + sunbw2->tme_sunbw2_sunfb.tme_sunfb_type_set = _tme_sunbw2_type_set; + + /* if the generic initialization fails: */ + rc = tme_sunfb_new(&sunbw2->tme_sunbw2_sunfb, args, _output); + if (rc) { + + /* free the sunfb structure and return the error: */ + tme_free(sunbw2); + return (rc); + } + + /* dispatch on the bwtwo type: */ + switch (sunbw2->tme_sunbw2_type) { + default: break; + case TME_SUNBW2_TYPE_MULTIBUS: + case TME_SUNBW2_TYPE_OLD_ONBOARD: + + /* set our initial CSR: */ + sunbw2->tme_sunbw2_csr + = tme_htobe_u16(TME_SUNBW2_CSR_ENABLE_VIDEO + | (sunbw2->tme_sunbw2_sunfb.tme_sunfb_size == TME_SUNFB_SIZE_1024_1024 + ? TME_SUNBW2_CSR_JUMPER_HIRES + : 0)); + + break; + } + + return (TME_OK); +} + diff --git a/pool/shard008/C/0130154_ffopensg.c b/pool/shard008/C/0130154_ffopensg.c new file mode 100644 index 0000000000000000000000000000000000000000..e6feaadbcc4a599beadda951c85d96a92ff19648 --- /dev/null +++ b/pool/shard008/C/0130154_ffopensg.c @@ -0,0 +1,117 @@ +/* + + Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved. + + This program is free software; you can redistribute it and/or modify it + under the terms of version 2.1 of the GNU Lesser General Public License + as published by the Free Software Foundation. + + This program is distributed in the hope that it would be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + + Further, this software is distributed without any warranty that it is + free of the rightful claim of any third person regarding infringement + or the like. Any license provided herein, whether implied or + otherwise, applies only to this software file. Patent licenses, if + any, provided herein do not apply to combinations of this program with + other software, or any other product whatsoever. + + You should have received a copy of the GNU Lesser General Public + License along with this program; if not, write the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, + USA. + + Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, + Mountain View, CA 94043, or: + + http://www.sgi.com + + For further information regarding this notice, see: + + http://oss.sgi.com/projects/GenInfo/NoticeExplan + +*/ + + +#pragma ident "@(#) libu/ffio/ffopensg.c 92.2 10/11/99 15:30:43" + +#include +#include +#include +#include +#include +#include "spec_parse.h" +#if defined(_UNICOS) || defined(__mips) || defined(_LITTLE_ENDIAN) +#include "fflock.h" +#endif + +#define MAX_SPEC 128 /* arbitrary limit on size of the layer list */ + +/* + * _ffopensg + * + * Open an FFIO file. Apply -F attribute specified by "cspec", which is + * of the same form as that used in assign and asgcmd, without the '-F'. + * ("cos:20,bmx") + * This routine was requested by applications because they want to + * use the oinf field in their user layers. + * + * Calling sequence: + * + * fd = _ffopensg(name, flags, mode, cbits, cblks, stat, cspec, oinf); + * + * Return value: + * + * Positive integer (really a pointer on Cray MPP and PVP systems) + * on success. -1 on failure with stat->sw_error + * set to the error code. + */ + +int +_ffopensg( +const char *name, +int flags, +mode_t mode, +long cbits, +int cblks, +struct ffsw *stat, +const char *cspec, +struct gl_o_inf *oinf) +{ + int retfd, length; + _ffopen_t fd; + union spec_u specs[MAX_SPEC]; + struct fdinfo *nfio; + + if( cspec == NULL ) cspec ="" ; + + length = _parse_forstr(specs, cspec, MAX_SPEC, NO, _LELVL_RETURN); + if (length <= 0) + ERETURN(stat, FDC_ERR_BADSPC, 0); + + fd = _ffopen(name, flags, mode, specs, stat, cbits, cblks, NULL, + oinf); + +#if defined(_CRAY1) || defined(__mips) + if (fd != _FFOPEN_ERR && MULTI_ON) { + nfio = NULL; + if (_ff_top_lock(fd, &nfio, stat) < 0) + fd = _FFOPEN_ERR; + if (nfio != NULL) + fd = (_ffopen_t)nfio; + } +#endif +#if defined(__mips) || defined(_LITTLE_ENDIAN) + /* + * _ffopensg returns an int. Call a routine which associates an + * int with what is returned by _ffopen + */ + retfd = _ff_fdinfo_to_int(fd, stat); +#else + retfd = (int)fd; +#endif + + return(retfd); +} + diff --git a/pool/shard008/C/0130156_g_dsp_name.c b/pool/shard008/C/0130156_g_dsp_name.c new file mode 100644 index 0000000000000000000000000000000000000000..825bf4d58b3b70efa2d7ceb7642a229ce3123a21 --- /dev/null +++ b/pool/shard008/C/0130156_g_dsp_name.c @@ -0,0 +1,137 @@ +/* #pragma ident "@(#)g_dsp_name.c 1.13 04/02/23 SMI" */ +/* + * Copyright 1996 by Sun Microsystems, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software + * and its documentation for any purpose is hereby granted without fee, + * provided that the above copyright notice appears in all copies and + * that both that copyright notice and this permission notice appear in + * supporting documentation, and that the name of Sun Microsystems not be used + * in advertising or publicity pertaining to distribution of the software + * without specific, written prior permission. Sun Microsystems makes no + * representations about the suitability of this software for any + * purpose. It is provided "as is" without express or implied warranty. + * + * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL SUN MICROSYSTEMS BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF + * USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + */ + +/* + * glue routine for gss_display_name() + * + */ + +#include "mglueP.h" +#include +#ifdef HAVE_STDLIB_H +#include +#endif +#include + +static OM_uint32 +val_dsp_name_args( + OM_uint32 *minor_status, + gss_name_t input_name, + gss_buffer_t output_name_buffer, + gss_OID *output_name_type) +{ + + /* Initialize outputs. */ + + if (minor_status != NULL) + *minor_status = 0; + + if (output_name_buffer != GSS_C_NO_BUFFER) { + output_name_buffer->length = 0; + output_name_buffer->value = NULL; + } + + if (output_name_type != NULL) + *output_name_type = GSS_C_NO_OID; + + /* Validate arguments. */ + + if (minor_status == NULL) + return (GSS_S_CALL_INACCESSIBLE_WRITE); + + if (output_name_buffer == GSS_C_NO_BUFFER) + return (GSS_S_CALL_INACCESSIBLE_WRITE); + + if (input_name == GSS_C_NO_NAME) + return (GSS_S_CALL_INACCESSIBLE_READ | GSS_S_BAD_NAME); + + return (GSS_S_COMPLETE); +} + + +OM_uint32 KRB5_CALLCONV +gss_display_name (minor_status, + input_name, + output_name_buffer, + output_name_type) + +OM_uint32 * minor_status; +gss_name_t input_name; +gss_buffer_t output_name_buffer; +gss_OID * output_name_type; + +{ + OM_uint32 major_status; + gss_union_name_t union_name; + + major_status = val_dsp_name_args(minor_status, input_name, + output_name_buffer, output_name_type); + if (major_status != GSS_S_COMPLETE) + return (major_status); + + union_name = (gss_union_name_t) input_name; + + if (union_name->mech_type) { + /* + * OK, we have a mechanism-specific name; let's use it! + */ + return (gssint_display_internal_name(minor_status, + union_name->mech_type, + union_name->mech_name, + output_name_buffer, + output_name_type)); + } + + /* + * copy the value of the external_name component of the union + * name into the output_name_buffer and point the output_name_type + * to the name_type component of union_name + */ + if (output_name_type != NULL && + union_name->name_type != GSS_C_NULL_OID) { + major_status = generic_gss_copy_oid(minor_status, + union_name->name_type, + output_name_type); + if (major_status != GSS_S_COMPLETE) { + map_errcode(minor_status); + return (major_status); + } + } + + if ((output_name_buffer->value = + gssalloc_malloc(union_name->external_name->length + 1)) == NULL) { + if (output_name_type && *output_name_type != GSS_C_NULL_OID) { + (void) generic_gss_release_oid(minor_status, + output_name_type); + *output_name_type = NULL; + } + return (GSS_S_FAILURE); + } + output_name_buffer->length = union_name->external_name->length; + (void) memcpy(output_name_buffer->value, + union_name->external_name->value, + union_name->external_name->length); + ((char *)output_name_buffer->value)[output_name_buffer->length] = '\0'; + + return(GSS_S_COMPLETE); +} diff --git a/pool/shard008/C/0130157_memory.c b/pool/shard008/C/0130157_memory.c new file mode 100644 index 0000000000000000000000000000000000000000..ea7ed7fcdc7e449369e65f7ab6ff765bc52c8c8a --- /dev/null +++ b/pool/shard008/C/0130157_memory.c @@ -0,0 +1,150 @@ + +#ifdef HAVE_CONFIG_H +#include "../../ext_config.h" +#endif + +#include +#include "../../php_ext.h" +#include "../../ext.h" + +#include +#include +#include + +#include "kernel/main.h" +#include "kernel/memory.h" +#include "kernel/object.h" +#include "kernel/fcall.h" +#include "kernel/operators.h" +#include "kernel/array.h" +#include "kernel/exception.h" + + +ZEPHIR_INIT_CLASS(OAuth_TokenStorage_Memory) { + + ZEPHIR_REGISTER_CLASS(OAuth\\TokenStorage, Memory, oauth, tokenstorage_memory, oauth_tokenstorage_memory_method_entry, 0); + + zend_declare_property_null(oauth_tokenstorage_memory_ce, SL("tokens"), ZEND_ACC_PROTECTED TSRMLS_CC); + + zend_class_implements(oauth_tokenstorage_memory_ce TSRMLS_CC, 1, oauth_tokenstorageinterface_ce); + + return SUCCESS; + +} + +PHP_METHOD(OAuth_TokenStorage_Memory, __construct) { + + zval *_0; + + ZEPHIR_MM_GROW(); + + ZEPHIR_INIT_VAR(_0); + array_init(_0); + zephir_update_property_this(this_ptr, SL("tokens"), _0 TSRMLS_CC); + ZEPHIR_MM_RESTORE(); + +} + +/** + * {@inheritDoc} + */ +PHP_METHOD(OAuth_TokenStorage_Memory, retrieveAccessToken) { + + zval *service_param = NULL, *hasAccess, *_0, *_1; + zval *service = NULL; + + ZEPHIR_MM_GROW(); + zephir_fetch_params(1, 1, 0, &service_param); + + zephir_get_strval(service, service_param); + + + ZEPHIR_INIT_VAR(hasAccess); + zephir_call_method_p1(hasAccess, this_ptr, "hasaccesstoken", service); + if (zephir_is_true(hasAccess)) { + _0 = zephir_fetch_nproperty_this(this_ptr, SL("tokens"), PH_NOISY_CC); + zephir_array_fetch(&_1, _0, service, PH_NOISY | PH_READONLY TSRMLS_CC); + RETURN_CTOR(_1); + } + ZEPHIR_THROW_EXCEPTION_STR(oauth_tokennotfoundexception_ce, "Token not stored"); + return; + +} + +/** + * {@inheritDoc} + */ +PHP_METHOD(OAuth_TokenStorage_Memory, storeAccessToken) { + + zval *service_param = NULL, *token; + zval *service = NULL; + + ZEPHIR_MM_GROW(); + zephir_fetch_params(1, 2, 0, &service_param, &token); + + zephir_get_strval(service, service_param); + + + zephir_update_property_array(this_ptr, SL("tokens"), service, token TSRMLS_CC); + RETURN_THIS(); + +} + +/** + * {@inheritDoc} + */ +PHP_METHOD(OAuth_TokenStorage_Memory, hasAccessToken) { + + zval *service_param = NULL, *token, *_0; + zval *service = NULL; + + ZEPHIR_MM_GROW(); + zephir_fetch_params(1, 1, 0, &service_param); + + zephir_get_strval(service, service_param); + + + _0 = zephir_fetch_nproperty_this(this_ptr, SL("tokens"), PH_NOISY_CC); + if (zephir_array_isset_fetch(&token, _0, service, 1 TSRMLS_CC)) { + if (zephir_is_instance_of(token, SL("OAuth\\TokenInterface") TSRMLS_CC)) { + RETURN_MM_BOOL(1); + } + } + RETURN_MM_BOOL(0); + +} + +/** + * {@inheritDoc} + */ +PHP_METHOD(OAuth_TokenStorage_Memory, clearToken) { + + zval *service, *_0; + + zephir_fetch_params(0, 1, 0, &service); + + + + _0 = zephir_fetch_nproperty_this(this_ptr, SL("tokens"), PH_NOISY_CC); + if (zephir_array_isset(_0, service)) { + } + RETURN_THISW(); + +} + +/** + * {@inheritDoc} + */ +PHP_METHOD(OAuth_TokenStorage_Memory, clearAllTokens) { + + zval *_0; + + ZEPHIR_MM_GROW(); + + ZEPHIR_INIT_VAR(_0); + array_init(_0); + zephir_update_property_this(this_ptr, SL("tokens"), _0 TSRMLS_CC); + RETURN_THIS(); + +} + diff --git a/pool/shard008/C/0130164_xdgmimealias.c b/pool/shard008/C/0130164_xdgmimealias.c new file mode 100644 index 0000000000000000000000000000000000000000..bf95bc0d344184c6fce998025ef0eb52217dde6a --- /dev/null +++ b/pool/shard008/C/0130164_xdgmimealias.c @@ -0,0 +1,182 @@ +/* -*- mode: C; c-file-style: "gnu" -*- */ +/* xdgmimealias.c: Private file. Datastructure for storing the aliases. + * + * More info can be found at http://www.freedesktop.org/standards/ + * + * Copyright (C) 2004 Red Hat, Inc. + * Copyright (C) 2004 Matthias Clasen + * + * Licensed under the Academic Free License version 2.0 + * Or under the following terms: + * + * 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. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + */ + +#include "config.h" + +#include "xdgmimealias.h" +#include "xdgmimeint.h" +#include +#include +#include +#include +#include + +#ifndef FALSE +#define FALSE (0) +#endif + +#ifndef TRUE +#define TRUE (!FALSE) +#endif + +typedef struct XdgAlias XdgAlias; + +struct XdgAlias +{ + char *alias; + char *mime_type; +}; + +struct XdgAliasList +{ + struct XdgAlias *aliases; + int n_aliases; +}; + +XdgAliasList * +_xdg_mime_alias_list_new (void) +{ + XdgAliasList *list; + + list = malloc (sizeof (XdgAliasList)); + + list->aliases = NULL; + list->n_aliases = 0; + + return list; +} + +void +_xdg_mime_alias_list_free (XdgAliasList *list) +{ + int i; + + if (list->aliases) + { + for (i = 0; i < list->n_aliases; i++) + { + free (list->aliases[i].alias); + free (list->aliases[i].mime_type); + } + free (list->aliases); + } + free (list); +} + +static int +alias_entry_cmp (const void *v1, const void *v2) +{ + return strcmp (((XdgAlias *)v1)->alias, ((XdgAlias *)v2)->alias); +} + +const char * +_xdg_mime_alias_list_lookup (XdgAliasList *list, + const char *alias) +{ + XdgAlias *entry; + XdgAlias key; + + if (list->n_aliases > 0) + { + key.alias = (char *)alias; + key.mime_type = NULL; + + entry = bsearch (&key, list->aliases, list->n_aliases, + sizeof (XdgAlias), alias_entry_cmp); + if (entry) + return entry->mime_type; + } + + return NULL; +} + +void +_xdg_mime_alias_read_from_file (XdgAliasList *list, + const char *file_name) +{ + FILE *file; + char line[255]; + int alloc; + + file = fopen (file_name, "r"); + + if (file == NULL) + return; + + /* FIXME: Not UTF-8 safe. Doesn't work if lines are greater than 255 chars. + * Blah */ + alloc = list->n_aliases + 16; + list->aliases = realloc (list->aliases, alloc * sizeof (XdgAlias)); + while (fgets (line, 255, file) != NULL) + { + char *sep; + if (line[0] == '#') + continue; + + sep = strchr (line, ' '); + if (sep == NULL) + continue; + *(sep++) = '\000'; + sep[strlen (sep) -1] = '\000'; + if (list->n_aliases == alloc) + { + alloc <<= 1; + list->aliases = realloc (list->aliases, + alloc * sizeof (XdgAlias)); + } + list->aliases[list->n_aliases].alias = strdup (line); + list->aliases[list->n_aliases].mime_type = strdup (sep); + list->n_aliases++; + } + list->aliases = realloc (list->aliases, + list->n_aliases * sizeof (XdgAlias)); + + fclose (file); + + if (list->n_aliases > 1) + qsort (list->aliases, list->n_aliases, + sizeof (XdgAlias), alias_entry_cmp); +} + + +#ifdef NOT_USED_IN_GIO + +void +_xdg_mime_alias_list_dump (XdgAliasList *list) +{ + int i; + + if (list->aliases) + { + for (i = 0; i < list->n_aliases; i++) + { + printf ("%s %s\n", + list->aliases[i].alias, + list->aliases[i].mime_type); + } + } +} + +#endif diff --git a/pool/shard008/C/0130166_BothNativeKernel.c b/pool/shard008/C/0130166_BothNativeKernel.c new file mode 100644 index 0000000000000000000000000000000000000000..9a9d29396e3680373ffaa6a88a4d692fa3fdc128 --- /dev/null +++ b/pool/shard008/C/0130166_BothNativeKernel.c @@ -0,0 +1,85 @@ + +void org_trifort_syncthreads() +{ + org_trifort_barrier(); +} + +void org_trifort_threadfence() +{ +} + +void org_trifort_threadfence_block() +{ +} + +char * +org_trifort_gc_deref(char * gc_info, int handle){ + long long lhandle; + long long * to_space; + long space_size; + long long array; + long long offset; + long long address; + char * data_arr; + + lhandle = handle; + lhandle = lhandle << 4; + to_space = org_trifort_gc_get_to_space_address(gc_info); + space_size = org_trifort_getlong(gc_info, 16); + array = lhandle / space_size; + offset = lhandle % space_size; + + address = to_space[array]; + data_arr = (char *) address; + return &data_arr[offset]; +} + +int +org_trifort_gc_malloc(char * gc_info, int size){ + long long * addr; + long long space_size; + long long ret; + int mod; + long long start_array; + long long end_array; + + addr = (long long *) (gc_info + TO_SPACE_FREE_POINTER_OFFSET); + space_size = org_trifort_getlong(gc_info, 16); + + mod = size % 16; + if(mod != 0){ + size += (16 - mod); + } + + while(1){ + ret = atom_add(addr, (long) size); + + start_array = ret / space_size; + end_array = (ret + size) / space_size; + + if(start_array != end_array){ + continue; + } + + ret = ret >> 4; + return (int) ret; + } +} + +int +org_trifort_classConstant(int type_num){ + return global_class_refs[type_num]; +} + +char * +org_trifort_gc_init(char * gc_info_space, + long long * to_space, + long long to_space_free_ptr, + long long space_size){ + + org_trifort_setlong(gc_info_space, 0, (long long) to_space); + org_trifort_setlong(gc_info_space, 8, to_space_free_ptr); + org_trifort_setlong(gc_info_space, 16, space_size); + + return (char *) gc_info_space; +} diff --git a/pool/shard008/C/0130173_lpr.c b/pool/shard008/C/0130173_lpr.c new file mode 100644 index 0000000000000000000000000000000000000000..a03b19c88857bb1f58e045478314574a28daee1b --- /dev/null +++ b/pool/shard008/C/0130173_lpr.c @@ -0,0 +1,144 @@ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include +#include + +#include "global.h" +#include "data.h" +#include "misc.h" + +#include "hid.h" +#include "../hidint.h" +#include "../ps/ps.h" +#include "hid/common/hidnogui.h" +#include "hid/common/hidinit.h" + +#ifdef HAVE_LIBDMALLOC +#include +#endif + +#define CRASH fprintf(stderr, "HID error: pcb called unimplemented PS function %s.\n", __FUNCTION__); abort() + +static HID_Attribute base_lpr_options[] = { + +/* %start-doc options "98 lpr Printing Options" +@ftable @code +@item --lprcommand +Command to use for printing. Defaults to @code{lpr}. This can be used to produce +PDF output with a virtual PDF printer. Example: @* +@code{--lprcommand "lp -d CUPS-PDF-Printer"}. +@end ftable +@noindent In addition, all @ref{Postscript Export} options are valid. +%end-doc +*/ + {"lprcommand", "Command to use for printing", + HID_String, 0, 0, {0, 0, 0}, 0, 0}, +#define HA_lprcommand 0 +}; + +#define NUM_OPTIONS (sizeof(lpr_options)/sizeof(lpr_options[0])) + +static HID_Attribute *lpr_options = 0; +static int num_lpr_options = 0; +static HID_Attr_Val *lpr_values; + +static HID_Attribute * +lpr_get_export_options (int *n) +{ + /* + * We initialize the default value in this manner because the GUI + * HID's may want to free() this string value and replace it with a + * new one based on how a user fills out a print dialog. + */ + if (base_lpr_options[HA_lprcommand].default_val.str_value == NULL) + { + base_lpr_options[HA_lprcommand].default_val.str_value = strdup("lpr"); + } + + if (lpr_options == 0) + { + HID_Attribute *ps_opts = ps_hid.get_export_options (&num_lpr_options); + lpr_options = + (HID_Attribute *) calloc (num_lpr_options, sizeof (HID_Attribute)); + memcpy (lpr_options, ps_opts, num_lpr_options * sizeof (HID_Attribute)); + memcpy (lpr_options, base_lpr_options, sizeof (base_lpr_options)); + lpr_values = + (HID_Attr_Val *) calloc (num_lpr_options, sizeof (HID_Attr_Val)); + } + if (n) + *n = num_lpr_options; + return lpr_options; +} + +static void +lpr_do_export (HID_Attr_Val * options) +{ + FILE *f; + int i; + const char *filename; + + if (!options) + { + lpr_get_export_options (0); + for (i = 0; i < num_lpr_options; i++) + lpr_values[i] = lpr_options[i].default_val; + options = lpr_values; + } + + filename = options[HA_lprcommand].str_value; + + printf ("LPR: open %s\n", filename); + f = popen (filename, "w"); + if (!f) + { + perror (filename); + return; + } + + ps_hid_export_to_file (f, options); + + pclose (f); +} + +static void +lpr_parse_arguments (int *argc, char ***argv) +{ + lpr_get_export_options (0); + hid_register_attributes (lpr_options, num_lpr_options); + hid_parse_command_line (argc, argv); +} + +static void +lpr_calibrate (double xval, double yval) +{ + ps_calibrate_1 (xval, yval, 1); +} + +static HID lpr_hid; + +void +hid_lpr_init () +{ + memset (&lpr_hid, 0, sizeof (HID)); + + common_nogui_init (&lpr_hid); + ps_ps_init (&lpr_hid); + + lpr_hid.struct_size = sizeof (HID); + lpr_hid.name = "lpr"; + lpr_hid.description = "Postscript print"; + lpr_hid.printer = 1; + lpr_hid.poly_before = 1; + + lpr_hid.get_export_options = lpr_get_export_options; + lpr_hid.do_export = lpr_do_export; + lpr_hid.parse_arguments = lpr_parse_arguments; + lpr_hid.calibrate = lpr_calibrate; + + hid_register_hid (&lpr_hid); +} diff --git a/pool/shard008/C/0130174_e-oauth2-support.c b/pool/shard008/C/0130174_e-oauth2-support.c new file mode 100644 index 0000000000000000000000000000000000000000..98ed21a3b6f81c8f831e5453c9c57d9e78de110a --- /dev/null +++ b/pool/shard008/C/0130174_e-oauth2-support.c @@ -0,0 +1,264 @@ +/* + * e-oauth2-support.c + * + * 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. + * + * 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. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this library. If not, see . + * + */ + +/** + * SECTION: e-oauth2-support + * @include: libebackend/libebackend.h + * @short_description: An interface for OAuth 2.0 support + * + * Support for OAuth 2.0 access tokens is typically provided through + * dynamically loaded modules. The module will provide an extension + * class which implements the #EOAuth2SupportInterface, which can be + * plugged into all appropriate #EServerSideSource instances through + * e_server_side_source_set_oauth2_support(). Incoming requests for + * access tokens are then forwarded to the extension providing OAuth + * 2.0 support through e_oauth2_support_get_access_token(). + **/ + +#include "e-oauth2-support.h" + +typedef struct _AsyncContext AsyncContext; + +struct _AsyncContext { + ESource *source; + gchar *access_token; + gint expires_in; +}; + +G_DEFINE_INTERFACE ( + EOAuth2Support, + e_oauth2_support, + G_TYPE_OBJECT) + +static void +async_context_free (AsyncContext *async_context) +{ + if (async_context->source != NULL) + g_object_unref (async_context->source); + + g_free (async_context->access_token); + + g_slice_free (AsyncContext, async_context); +} + +/* Helper for oauth2_support_get_access_token() */ +static void +oauth2_support_get_access_token_thread (GSimpleAsyncResult *simple, + GObject *object, + GCancellable *cancellable) +{ + AsyncContext *async_context; + GError *error = NULL; + + async_context = g_simple_async_result_get_op_res_gpointer (simple); + + e_oauth2_support_get_access_token_sync ( + E_OAUTH2_SUPPORT (simple), + async_context->source, + cancellable, + &async_context->access_token, + &async_context->expires_in, + &error); + + if (error != NULL) + g_simple_async_result_take_error (simple, error); +} + +static void +oauth2_support_get_access_token (EOAuth2Support *support, + ESource *source, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + GSimpleAsyncResult *simple; + AsyncContext *async_context; + + async_context = g_slice_new0 (AsyncContext); + async_context->source = g_object_ref (source); + + simple = g_simple_async_result_new ( + G_OBJECT (support), callback, user_data, + oauth2_support_get_access_token); + + g_simple_async_result_set_check_cancellable (simple, cancellable); + + g_simple_async_result_set_op_res_gpointer ( + simple, async_context, (GDestroyNotify) async_context_free); + + g_simple_async_result_run_in_thread ( + simple, oauth2_support_get_access_token_thread, + G_PRIORITY_DEFAULT, cancellable); + + g_object_unref (simple); +} + +static gboolean +oauth2_support_get_access_token_finish (EOAuth2Support *support, + GAsyncResult *result, + gchar **out_access_token, + gint *out_expires_in, + GError **error) +{ + GSimpleAsyncResult *simple; + AsyncContext *async_context; + + g_return_val_if_fail ( + g_simple_async_result_is_valid ( + result, G_OBJECT (support), + oauth2_support_get_access_token), FALSE); + + simple = G_SIMPLE_ASYNC_RESULT (result); + async_context = g_simple_async_result_get_op_res_gpointer (simple); + + if (g_simple_async_result_propagate_error (simple, error)) + return FALSE; + + g_return_val_if_fail (async_context->access_token != NULL, FALSE); + + if (out_access_token != NULL) { + *out_access_token = async_context->access_token; + async_context->access_token = NULL; + } + + if (out_expires_in != NULL) + *out_expires_in = async_context->expires_in; + + return TRUE; +} + +static void +e_oauth2_support_default_init (EOAuth2SupportInterface *iface) +{ + iface->get_access_token = + oauth2_support_get_access_token; + iface->get_access_token_finish = + oauth2_support_get_access_token_finish; +} + +/** + * e_oauth2_support_get_access_token_sync: + * @support: an #EOAuthSupport + * @source: an #ESource + * @cancellable: optional #GCancellable object, or %NULL + * @out_access_token: return location for the access token, or %NULL + * @out_expires_in: return location for the token expiry, or %NULL + * @error: return location for a #GError, or %NULL + * + * Obtains the OAuth 2.0 access token for @source along with its expiry + * in seconds from the current time (or 0 if unknown). + * + * Free the returned access token with g_free() when finished with it. + * If an error occurs, the function will set @error and return %FALSE. + * + * Returns: %TRUE on success, %FALSE on failure + * + * Since: 3.8 + **/ +gboolean +e_oauth2_support_get_access_token_sync (EOAuth2Support *support, + ESource *source, + GCancellable *cancellable, + gchar **out_access_token, + gint *out_expires_in, + GError **error) +{ + EOAuth2SupportInterface *iface; + + g_return_val_if_fail (E_IS_OAUTH2_SUPPORT (support), FALSE); + g_return_val_if_fail (E_IS_SOURCE (source), FALSE); + + iface = E_OAUTH2_SUPPORT_GET_INTERFACE (support); + g_return_val_if_fail (iface->get_access_token_sync != NULL, FALSE); + + return iface->get_access_token_sync ( + support, source, cancellable, + out_access_token, out_expires_in, error); +} + +/** + * e_oauth2_support_get_access_token: + * @support: an #EOAuth2Support + * @source: an #ESource + * @cancellable: optional #GCancellable object, or %NULL + * @callback: a #GAsyncReadyCallback to call when the request is satisfied + * @user_data: data to pass to the callback function + * + * Asynchronously obtains the OAuth 2.0 access token for @source along + * with its expiry in seconds from the current time (or 0 if unknown). + * + * When the operation is finished, @callback will be called. You can then + * call e_oauth2_support_get_access_token_finish() to get the result of the + * operation. + * + * Since: 3.8 + **/ +void +e_oauth2_support_get_access_token (EOAuth2Support *support, + ESource *source, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + EOAuth2SupportInterface *iface; + + g_return_if_fail (E_IS_OAUTH2_SUPPORT (support)); + g_return_if_fail (E_IS_SOURCE (source)); + + iface = E_OAUTH2_SUPPORT_GET_INTERFACE (support); + g_return_if_fail (iface->get_access_token != NULL); + + return iface->get_access_token ( + support, source, cancellable, callback, user_data); +} + +/** + * e_oauth2_support_get_access_token_finish: + * @support: an #EOAuth2Support + * @result: a #GAsyncResult + * @out_access_token: return location for the access token, or %NULL + * @out_expires_in: return location for the token expiry, or %NULL + * @error: return location for a #GError, or %NULL + * + * Finishes the operation started with e_oauth2_support_get_access_token(). + * + * Free the returned access token with g_free() when finished with it. + * If an error occurred, the function will set @error and return %FALSE. + * + * Returns: %TRUE on success, %FALSE on failure + * + * Since: 3.8 + **/ +gboolean +e_oauth2_support_get_access_token_finish (EOAuth2Support *support, + GAsyncResult *result, + gchar **out_access_token, + gint *out_expires_in, + GError **error) +{ + EOAuth2SupportInterface *iface; + + g_return_val_if_fail (E_IS_OAUTH2_SUPPORT (support), FALSE); + g_return_val_if_fail (G_IS_ASYNC_RESULT (result), FALSE); + + iface = E_OAUTH2_SUPPORT_GET_INTERFACE (support); + g_return_val_if_fail (iface->get_access_token_finish != NULL, FALSE); + + return iface->get_access_token_finish ( + support, result, out_access_token, out_expires_in, error); +} + diff --git a/pool/shard008/C/0130175_295396_buggy.c b/pool/shard008/C/0130175_295396_buggy.c new file mode 100644 index 0000000000000000000000000000000000000000..1aff4de171992094fd4744ad32816321bf5b9c0e --- /dev/null +++ b/pool/shard008/C/0130175_295396_buggy.c @@ -0,0 +1,53 @@ +/*numPass=5, numTotal=9 +Verdict:ACCEPTED, Visibility:1, Input:"abcdef +2", ExpOutput:"efabcd", Output:"efabcd" +Verdict:ACCEPTED, Visibility:1, Input:"programming +11", ExpOutput:"programming", Output:"programming" +Verdict:WRONG_ANSWER, Visibility:1, Input:"hello-@programmer +5", ExpOutput:"ammerhello-@progr", Output:"erammhello-@progr" +Verdict:ACCEPTED, Visibility:0, Input:"hellodear +3", ExpOutput:"earhellod", Output:"earhellod" +Verdict:ACCEPTED, Visibility:0, Input:"progamming +0", ExpOutput:"progamming", Output:"progamming" +Verdict:WRONG_ANSWER, Visibility:0, Input:"programming +10", ExpOutput:"rogrammingp", Output:"grogramminp" +Verdict:WRONG_ANSWER, Visibility:0, Input:"programming +13", ExpOutput:"ngprogrammi", Output:"programming" +Verdict:WRONG_ANSWER, Visibility:0, Input:"abcde +4", ExpOutput:"bcdea", Output:"ebcda" +Verdict:ACCEPTED, Visibility:0, Input:"abcdz +5", ExpOutput:"abcdz", Output:"abcdz" +*/ +#include +void right_rotate(char s[],int); + +int main() { + char str[101]; + int n; + scanf("%s%d",str,&n); + right_rotate(str,n); + printf("%s",str); + + return 0; +} + +void right_rotate(char str[],int n) +{ + char str1[101]; + int len=0; + while(str[len]!='\0') + { + len++; + } + int i,j; + for(i=0;i=len) + j=(i+n)%n; + else + j=i+n; + str1[j]=str[i]; + } + for(i=0;i + * + * Copyright (C) 2012 ST Microelectronics + * Shiraz Hashim + * + * This file is licensed under the terms of the GNU General Public + * License version 2. This program is licensed "as is" without any + * warranty of any kind, whether express or implied. + */ +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "irqchip.h" + +/* + * struct spear_shirq: shared irq structure + * + * base: Base register address + * status_reg: Status register offset for chained interrupt handler + * mask_reg: Mask register offset for irq chip + * mask: Mask to apply to the status register + * virq_base: Base virtual interrupt number + * nr_irqs: Number of interrupts handled by this block + * offset: Bit offset of the first interrupt + * irq_chip: Interrupt controller chip used for this instance, + * if NULL group is disabled, but accounted + */ +struct spear_shirq { + void __iomem *base; + u32 status_reg; + u32 mask_reg; + u32 mask; + u32 virq_base; + u32 nr_irqs; + u32 offset; + struct irq_chip *irq_chip; +}; + +/* spear300 shared irq registers offsets and masks */ +#define SPEAR300_INT_ENB_MASK_REG 0x54 +#define SPEAR300_INT_STS_MASK_REG 0x58 + +static DEFINE_RAW_SPINLOCK(shirq_lock); + +static void shirq_irq_mask(struct irq_data *d) +{ + struct spear_shirq *shirq = irq_data_get_irq_chip_data(d); + u32 val, shift = d->irq - shirq->virq_base + shirq->offset; + u32 __iomem *reg = shirq->base + shirq->mask_reg; + + raw_spin_lock(&shirq_lock); + val = readl(reg) & ~(0x1 << shift); + writel(val, reg); + raw_spin_unlock(&shirq_lock); +} + +static void shirq_irq_unmask(struct irq_data *d) +{ + struct spear_shirq *shirq = irq_data_get_irq_chip_data(d); + u32 val, shift = d->irq - shirq->virq_base + shirq->offset; + u32 __iomem *reg = shirq->base + shirq->mask_reg; + + raw_spin_lock(&shirq_lock); + val = readl(reg) | (0x1 << shift); + writel(val, reg); + raw_spin_unlock(&shirq_lock); +} + +static struct irq_chip shirq_chip = { + .name = "spear-shirq", + .irq_mask = shirq_irq_mask, + .irq_unmask = shirq_irq_unmask, +}; + +static struct spear_shirq spear300_shirq_ras1 = { + .offset = 0, + .nr_irqs = 9, + .mask = ((0x1 << 9) - 1) << 0, + .irq_chip = &shirq_chip, + .status_reg = SPEAR300_INT_STS_MASK_REG, + .mask_reg = SPEAR300_INT_ENB_MASK_REG, +}; + +static struct spear_shirq *spear300_shirq_blocks[] = { + &spear300_shirq_ras1, +}; + +/* spear310 shared irq registers offsets and masks */ +#define SPEAR310_INT_STS_MASK_REG 0x04 + +static struct spear_shirq spear310_shirq_ras1 = { + .offset = 0, + .nr_irqs = 8, + .mask = ((0x1 << 8) - 1) << 0, + .irq_chip = &dummy_irq_chip, + .status_reg = SPEAR310_INT_STS_MASK_REG, +}; + +static struct spear_shirq spear310_shirq_ras2 = { + .offset = 8, + .nr_irqs = 5, + .mask = ((0x1 << 5) - 1) << 8, + .irq_chip = &dummy_irq_chip, + .status_reg = SPEAR310_INT_STS_MASK_REG, +}; + +static struct spear_shirq spear310_shirq_ras3 = { + .offset = 13, + .nr_irqs = 1, + .mask = ((0x1 << 1) - 1) << 13, + .irq_chip = &dummy_irq_chip, + .status_reg = SPEAR310_INT_STS_MASK_REG, +}; + +static struct spear_shirq spear310_shirq_intrcomm_ras = { + .offset = 14, + .nr_irqs = 3, + .mask = ((0x1 << 3) - 1) << 14, + .irq_chip = &dummy_irq_chip, + .status_reg = SPEAR310_INT_STS_MASK_REG, +}; + +static struct spear_shirq *spear310_shirq_blocks[] = { + &spear310_shirq_ras1, + &spear310_shirq_ras2, + &spear310_shirq_ras3, + &spear310_shirq_intrcomm_ras, +}; + +/* spear320 shared irq registers offsets and masks */ +#define SPEAR320_INT_STS_MASK_REG 0x04 +#define SPEAR320_INT_CLR_MASK_REG 0x04 +#define SPEAR320_INT_ENB_MASK_REG 0x08 + +static struct spear_shirq spear320_shirq_ras3 = { + .offset = 0, + .nr_irqs = 7, + .mask = ((0x1 << 7) - 1) << 0, +}; + +static struct spear_shirq spear320_shirq_ras1 = { + .offset = 7, + .nr_irqs = 3, + .mask = ((0x1 << 3) - 1) << 7, + .irq_chip = &dummy_irq_chip, + .status_reg = SPEAR320_INT_STS_MASK_REG, +}; + +static struct spear_shirq spear320_shirq_ras2 = { + .offset = 10, + .nr_irqs = 1, + .mask = ((0x1 << 1) - 1) << 10, + .irq_chip = &dummy_irq_chip, + .status_reg = SPEAR320_INT_STS_MASK_REG, +}; + +static struct spear_shirq spear320_shirq_intrcomm_ras = { + .offset = 11, + .nr_irqs = 11, + .mask = ((0x1 << 11) - 1) << 11, + .irq_chip = &dummy_irq_chip, + .status_reg = SPEAR320_INT_STS_MASK_REG, +}; + +static struct spear_shirq *spear320_shirq_blocks[] = { + &spear320_shirq_ras3, + &spear320_shirq_ras1, + &spear320_shirq_ras2, + &spear320_shirq_intrcomm_ras, +}; + +static void shirq_handler(unsigned irq, struct irq_desc *desc) +{ + struct spear_shirq *shirq = irq_get_handler_data(irq); + u32 pend; + + pend = readl(shirq->base + shirq->status_reg) & shirq->mask; + pend >>= shirq->offset; + + while (pend) { + int irq = __ffs(pend); + + pend &= ~(0x1 << irq); + generic_handle_irq(shirq->virq_base + irq); + } +} + +static void __init spear_shirq_register(struct spear_shirq *shirq, + int parent_irq) +{ + int i; + + if (!shirq->irq_chip) + return; + + irq_set_chained_handler_and_data(parent_irq, shirq_handler, shirq); + + for (i = 0; i < shirq->nr_irqs; i++) { + irq_set_chip_and_handler(shirq->virq_base + i, + shirq->irq_chip, handle_simple_irq); + set_irq_flags(shirq->virq_base + i, IRQF_VALID); + irq_set_chip_data(shirq->virq_base + i, shirq); + } +} + +static int __init shirq_init(struct spear_shirq **shirq_blocks, int block_nr, + struct device_node *np) +{ + int i, parent_irq, virq_base, hwirq = 0, nr_irqs = 0; + struct irq_domain *shirq_domain; + void __iomem *base; + + base = of_iomap(np, 0); + if (!base) { + pr_err("%s: failed to map shirq registers\n", __func__); + return -ENXIO; + } + + for (i = 0; i < block_nr; i++) + nr_irqs += shirq_blocks[i]->nr_irqs; + + virq_base = irq_alloc_descs(-1, 0, nr_irqs, 0); + if (IS_ERR_VALUE(virq_base)) { + pr_err("%s: irq desc alloc failed\n", __func__); + goto err_unmap; + } + + shirq_domain = irq_domain_add_legacy(np, nr_irqs, virq_base, 0, + &irq_domain_simple_ops, NULL); + if (WARN_ON(!shirq_domain)) { + pr_warn("%s: irq domain init failed\n", __func__); + goto err_free_desc; + } + + for (i = 0; i < block_nr; i++) { + shirq_blocks[i]->base = base; + shirq_blocks[i]->virq_base = irq_find_mapping(shirq_domain, + hwirq); + + parent_irq = irq_of_parse_and_map(np, i); + spear_shirq_register(shirq_blocks[i], parent_irq); + hwirq += shirq_blocks[i]->nr_irqs; + } + + return 0; + +err_free_desc: + irq_free_descs(virq_base, nr_irqs); +err_unmap: + iounmap(base); + return -ENXIO; +} + +static int __init spear300_shirq_of_init(struct device_node *np, + struct device_node *parent) +{ + return shirq_init(spear300_shirq_blocks, + ARRAY_SIZE(spear300_shirq_blocks), np); +} +IRQCHIP_DECLARE(spear300_shirq, "st,spear300-shirq", spear300_shirq_of_init); + +static int __init spear310_shirq_of_init(struct device_node *np, + struct device_node *parent) +{ + return shirq_init(spear310_shirq_blocks, + ARRAY_SIZE(spear310_shirq_blocks), np); +} +IRQCHIP_DECLARE(spear310_shirq, "st,spear310-shirq", spear310_shirq_of_init); + +static int __init spear320_shirq_of_init(struct device_node *np, + struct device_node *parent) +{ + return shirq_init(spear320_shirq_blocks, + ARRAY_SIZE(spear320_shirq_blocks), np); +} +IRQCHIP_DECLARE(spear320_shirq, "st,spear320-shirq", spear320_shirq_of_init); diff --git a/pool/shard008/C/0130180_zad4.c b/pool/shard008/C/0130180_zad4.c new file mode 100644 index 0000000000000000000000000000000000000000..12184ad4a1df3c45f0629668a0198e31cdfdf73c --- /dev/null +++ b/pool/shard008/C/0130180_zad4.c @@ -0,0 +1,35 @@ +#include +int main() +{ + float x = 1.0; + double x1 = 1.0; + long double x2 = 1.0; + int l=1; + + printf("Float:\n"); + while(1.0+x>1.0) + { + x=x/2.0; + printf("%i. %f >> %e\n", l, x, x); + l++; + } + + l=1; + printf("Double:\n"); + while(1.0+x1>1.0) + { + x1=x1/2.0; + printf("%i. %f >> %e\n", l, x1, x1); + l++; + } + + l=1; + printf("Long double:\n"); + while(1.0+x2>1.0) + { + x2=x2/2.0; + printf("%i. %Lf >> %Le\n", l, x2, x2); + l++; + } + return 0; +} \ No newline at end of file diff --git a/pool/shard008/C/0130183_hash.c b/pool/shard008/C/0130183_hash.c new file mode 100644 index 0000000000000000000000000000000000000000..591db4b1b9cd79031c68149a51bfac82750e46be --- /dev/null +++ b/pool/shard008/C/0130183_hash.c @@ -0,0 +1,294 @@ +/* Hash tables for Objective C internal structures + Copyright (C) 1993-2015 Free Software Foundation, Inc. + +This file is part of GCC. + +GCC 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, or (at your option) +any later version. + +GCC 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. + +Under Section 7 of GPL version 3, you are granted additional +permissions described in the GCC Runtime Library Exception, version +3.1, as published by the Free Software Foundation. + +You should have received a copy of the GNU General Public License and +a copy of the GCC Runtime Library Exception along with this program; +see the files COPYING3 and COPYING.RUNTIME respectively. If not, see +. */ + +#include "objc-private/common.h" +#include /* For assert. */ + +#include "objc/runtime.h" /* For objc_calloc. */ +#include "objc-private/hash.h" + +/* These two macros determine when a hash table is full and + by how much it should be expanded respectively. + + These equations are percentages. */ +#define FULLNESS(cache) \ + ((((cache)->size * 75) / 100) <= (cache)->used) +#define EXPANSION(cache) \ + ((cache)->size * 2) + +cache_ptr +objc_hash_new (unsigned int size, hash_func_type hash_func, + compare_func_type compare_func) +{ + cache_ptr cache; + + /* Pass me a value greater than 0 and a power of 2. */ + assert (size); + assert (! (size & (size - 1))); + + /* Allocate the cache structure. calloc insures its initialization + for default values. */ + cache = (cache_ptr) objc_calloc (1, sizeof (struct cache)); + assert (cache); + + /* Allocate the array of buckets for the cache. calloc initializes + all of the pointers to NULL. */ + cache->node_table + = (node_ptr *) objc_calloc (size, sizeof (node_ptr)); + assert (cache->node_table); + + cache->size = size; + + /* This should work for all processor architectures (?). */ + cache->mask = (size - 1); + + /* Store the hashing function so that codes can be computed. */ + cache->hash_func = hash_func; + + /* Store the function that compares hash keys to determine if they + are equal. */ + cache->compare_func = compare_func; + + return cache; +} + + +void +objc_hash_delete (cache_ptr cache) +{ + node_ptr node; + node_ptr next_node; + unsigned int i; + + /* Purge all key/value pairs from the table. */ + /* Step through the nodes one by one and remove every node WITHOUT + using objc_hash_next. this makes objc_hash_delete much more + efficient. */ + for (i = 0; i < cache->size; i++) + { + if ((node = cache->node_table[i])) + { + /* An entry in the hash table has been found. Now step + through the nodes next in the list and free them. */ + while ((next_node = node->next)) + { + objc_hash_remove (cache,node->key); + node = next_node; + } + objc_hash_remove (cache,node->key); + } + } + + /* Release the array of nodes and the cache itself. */ + objc_free(cache->node_table); + objc_free(cache); +} + + +void +objc_hash_add (cache_ptr *cachep, const void *key, void *value) +{ + size_t indx = (*(*cachep)->hash_func) (*cachep, key); + node_ptr node = (node_ptr) objc_calloc (1, sizeof (struct cache_node)); + + assert (node); + + /* Initialize the new node. */ + node->key = key; + node->value = value; + node->next = (*cachep)->node_table[indx]; + + /* Debugging. Check the list for another key. */ +#ifdef DEBUG + { + node_ptr node1 = (*cachep)->node_table[indx]; + while (node1) + { + assert (node1->key != key); + node1 = node1->next; + } + } +#endif + + /* Install the node as the first element on the list. */ + (*cachep)->node_table[indx] = node; + + /* Bump the number of entries in the cache. */ + ++(*cachep)->used; + + /* Check the hash table's fullness. We're going to expand if it is + above the fullness level. */ + if (FULLNESS (*cachep)) + { + /* The hash table has reached its fullness level. Time to + expand it. + + I'm using a slow method here but is built on other primitive + functions thereby increasing its correctness. */ + node_ptr node1 = NULL; + cache_ptr new = objc_hash_new (EXPANSION (*cachep), + (*cachep)->hash_func, + (*cachep)->compare_func); + + DEBUG_PRINTF ("Expanding cache %#x from %d to %d\n", + (int) *cachep, (*cachep)->size, new->size); + + /* Copy the nodes from the first hash table to the new one. */ + while ((node1 = objc_hash_next (*cachep, node1))) + objc_hash_add (&new, node1->key, node1->value); + + /* Trash the old cache. */ + objc_hash_delete (*cachep); + + /* Return a pointer to the new hash table. */ + *cachep = new; + } +} + +void +objc_hash_remove (cache_ptr cache, const void *key) +{ + size_t indx = (*cache->hash_func) (cache, key); + node_ptr node = cache->node_table[indx]; + + /* We assume there is an entry in the table. Error if it is + not. */ + assert (node); + + /* Special case. First element is the key/value pair to be + removed. */ + if ((*cache->compare_func) (node->key, key)) + { + cache->node_table[indx] = node->next; + objc_free(node); + } + else + { + /* Otherwise, find the hash entry. */ + node_ptr prev = node; + BOOL removed = NO; + do + { + if ((*cache->compare_func) (node->key, key)) + { + prev->next = node->next, removed = YES; + objc_free(node); + } + else + prev = node, node = node->next; + } + while (!removed && node); + assert (removed); + } + + /* Decrement the number of entries in the hash table. */ + --cache->used; +} + + +node_ptr +objc_hash_next (cache_ptr cache, node_ptr node) +{ + /* If the scan is being started then reset the last node visitied + pointer and bucket index. */ + if (!node) + cache->last_bucket = 0; + + /* If there is a node visited last then check for another entry in + the same bucket. Otherwise step to the next bucket. */ + if (node) + { + if (node->next) + { + /* There is a node which follows the last node returned. + Step to that node and retun it. */ + return node->next; + } + else + ++cache->last_bucket; + } + + /* If the list isn't exhausted then search the buckets for other + nodes. */ + if (cache->last_bucket < cache->size) + { + /* Scan the remainder of the buckets looking for an entry at + the head of the list. Return the first item found. */ + while (cache->last_bucket < cache->size) + if (cache->node_table[cache->last_bucket]) + return cache->node_table[cache->last_bucket]; + else + ++cache->last_bucket; + + /* No further nodes were found in the hash table. */ + return NULL; + } + else + return NULL; +} + + +/* Given KEY, return corresponding value for it in CACHE. Return NULL + if the KEY is not recorded. */ +void * +objc_hash_value_for_key (cache_ptr cache, const void *key) +{ + node_ptr node = cache->node_table[(*cache->hash_func) (cache, key)]; + void *retval = NULL; + + if (node) + do + { + if ((*cache->compare_func) (node->key, key)) + { + retval = node->value; + break; + } + else + node = node->next; + } + while (! retval && node); + + return retval; +} + +/* Given KEY, return YES if it exists in the CACHE. Return NO if it + does not */ +BOOL +objc_hash_is_key_in_hash (cache_ptr cache, const void *key) +{ + node_ptr node = cache->node_table[(*cache->hash_func) (cache, key)]; + + if (node) + do + { + if ((*cache->compare_func)(node->key, key)) + return YES; + else + node = node->next; + } + while (node); + + return NO; +} diff --git a/pool/shard008/C/0130184_write.c b/pool/shard008/C/0130184_write.c new file mode 100644 index 0000000000000000000000000000000000000000..88e2f32fbda97e686f81af45d2c951319f15ef8e --- /dev/null +++ b/pool/shard008/C/0130184_write.c @@ -0,0 +1,146 @@ +#include "clar_libgit2.h" + +static const char *committer_name = "Vicent Marti"; +static const char *committer_email = "vicent@github.com"; +static const char *commit_message = "This commit has been created in memory\n\ + This is a commit created in memory and it will be written back to disk\n"; +static const char *tree_oid = "1810dff58d8a660512d4832e740f692884338ccd"; +static const char *root_commit_message = "This is a root commit\n\ + This is a root commit and should be the only one in this branch\n"; +static char *head_old; +static git_reference *head, *branch; +static git_commit *commit; + +// Fixture setup +static git_repository *g_repo; +void test_commit_write__initialize(void) +{ + g_repo = cl_git_sandbox_init("testrepo"); +} + +void test_commit_write__cleanup(void) +{ + git_reference_free(head); + head = NULL; + + git_reference_free(branch); + branch = NULL; + + git_commit_free(commit); + commit = NULL; + + git__free(head_old); + head_old = NULL; + + cl_git_sandbox_cleanup(); +} + + +// write a new commit object from memory to disk +void test_commit_write__from_memory(void) +{ + git_oid tree_id, parent_id, commit_id; + git_signature *author, *committer; + const git_signature *author1, *committer1; + git_commit *parent; + git_tree *tree; + const char *commit_id_str = "8496071c1b46c854b31185ea97743be6a8774479"; + + git_oid_fromstr(&tree_id, tree_oid); + cl_git_pass(git_tree_lookup(&tree, g_repo, &tree_id)); + + git_oid_fromstr(&parent_id, commit_id_str); + cl_git_pass(git_commit_lookup(&parent, g_repo, &parent_id)); + + /* create signatures */ + cl_git_pass(git_signature_new(&committer, committer_name, committer_email, 123456789, 60)); + cl_git_pass(git_signature_new(&author, committer_name, committer_email, 987654321, 90)); + + cl_git_pass(git_commit_create_v( + &commit_id, /* out id */ + g_repo, + NULL, /* do not update the HEAD */ + author, + committer, + NULL, + commit_message, + tree, + 1, parent)); + + git_object_free((git_object *)parent); + git_object_free((git_object *)tree); + + git_signature_free(committer); + git_signature_free(author); + + cl_git_pass(git_commit_lookup(&commit, g_repo, &commit_id)); + + /* Check attributes were set correctly */ + author1 = git_commit_author(commit); + cl_assert(author1 != NULL); + cl_assert_equal_s(committer_name, author1->name); + cl_assert_equal_s(committer_email, author1->email); + cl_assert(author1->when.time == 987654321); + cl_assert(author1->when.offset == 90); + + committer1 = git_commit_committer(commit); + cl_assert(committer1 != NULL); + cl_assert_equal_s(committer_name, committer1->name); + cl_assert_equal_s(committer_email, committer1->email); + cl_assert(committer1->when.time == 123456789); + cl_assert(committer1->when.offset == 60); + + cl_assert_equal_s(commit_message, git_commit_message(commit)); +} + +// create a root commit +void test_commit_write__root(void) +{ + git_oid tree_id, commit_id; + const git_oid *branch_oid; + git_signature *author, *committer; + const char *branch_name = "refs/heads/root-commit-branch"; + git_tree *tree; + + git_oid_fromstr(&tree_id, tree_oid); + cl_git_pass(git_tree_lookup(&tree, g_repo, &tree_id)); + + /* create signatures */ + cl_git_pass(git_signature_new(&committer, committer_name, committer_email, 123456789, 60)); + cl_git_pass(git_signature_new(&author, committer_name, committer_email, 987654321, 90)); + + /* First we need to update HEAD so it points to our non-existant branch */ + cl_git_pass(git_reference_lookup(&head, g_repo, "HEAD")); + cl_assert(git_reference_type(head) == GIT_REF_SYMBOLIC); + head_old = git__strdup(git_reference_symbolic_target(head)); + cl_assert(head_old != NULL); + + cl_git_pass(git_reference_symbolic_set_target(head, branch_name)); + + cl_git_pass(git_commit_create_v( + &commit_id, /* out id */ + g_repo, + "HEAD", + author, + committer, + NULL, + root_commit_message, + tree, + 0)); + + git_object_free((git_object *)tree); + git_signature_free(committer); + git_signature_free(author); + + /* + * The fact that creating a commit works has already been + * tested. Here we just make sure it's our commit and that it was + * written as a root commit. + */ + cl_git_pass(git_commit_lookup(&commit, g_repo, &commit_id)); + cl_assert(git_commit_parentcount(commit) == 0); + cl_git_pass(git_reference_lookup(&branch, g_repo, branch_name)); + branch_oid = git_reference_target(branch); + cl_git_pass(git_oid_cmp(branch_oid, &commit_id)); + cl_assert_equal_s(root_commit_message, git_commit_message(commit)); +} diff --git a/pool/shard008/C/0130189_bn_mp_to_signed_bin.c b/pool/shard008/C/0130189_bn_mp_to_signed_bin.c new file mode 100644 index 0000000000000000000000000000000000000000..25dae7240d1b5a2afaf6072de418d852d8f7cb38 --- /dev/null +++ b/pool/shard008/C/0130189_bn_mp_to_signed_bin.c @@ -0,0 +1,31 @@ +#include "tommath_private.h" +#ifdef BN_MP_TO_SIGNED_BIN_C +/* LibTomMath, multiple-precision integer library -- Tom St Denis + * + * LibTomMath is a library that provides multiple-precision + * integer arithmetic as well as number theoretic functionality. + * + * The library was designed directly after the MPI library by + * Michael Fromberger but has been written from scratch with + * additional optimizations in place. + * + * The library is free for all purposes without any express + * guarantee it works. + */ + +/* store in signed [big endian] format */ +int mp_to_signed_bin(const mp_int *a, unsigned char *b) +{ + int res; + + if ((res = mp_to_unsigned_bin(a, b + 1)) != MP_OKAY) { + return res; + } + b[0] = (a->sign == MP_ZPOS) ? (unsigned char)0 : (unsigned char)1; + return MP_OKAY; +} +#endif + +/* ref: HEAD -> develop */ +/* git commit: 8b9f98baa16b21e1612ac6746273febb74150a6f */ +/* commit time: 2018-09-23 21:37:58 +0200 */ diff --git a/pool/shard008/C/0130190_metadata.c b/pool/shard008/C/0130190_metadata.c new file mode 100644 index 0000000000000000000000000000000000000000..3268f7125c79aa7d8b8742349b6f863116125624 --- /dev/null +++ b/pool/shard008/C/0130190_metadata.c @@ -0,0 +1,173 @@ +/* metadata.c + * Copyright (c) 2001-3 Brendan Cully + * + * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + */ + +#include "definitions.h" + +#define INITDELAY 500000 + +extern ices_config_t ices_config; + +static char* Artist = NULL; +static char* Title = NULL; +static char* Filename = NULL; + +/* Private function declarations */ +static char* metadata_clean_filename (const char* path, char* buf, + size_t len); +static void metadata_update (int delay); + +/* Global function definitions */ + +void +ices_metadata_get (char* artist, size_t alen, char* title, size_t tlen) +{ + if (Artist) + snprintf (artist, alen, "%s", Artist); + if (Title) + snprintf (title, tlen, "%s", Title); +} + +void +ices_metadata_set (const char* artist, const char* title) +{ + ices_util_free (Artist); + Artist = NULL; + ices_util_free (Title); + Title = NULL; + + if (artist && *artist) + Artist = ices_util_strdup (artist); + if (title && *title) + Title = ices_util_strdup (title); +} + +void +ices_metadata_set_file (const char* filename) +{ + char buf[1024]; + + ices_util_free (Filename); + Filename = NULL; + + if (filename && *filename) { + metadata_clean_filename (filename, buf, sizeof (buf)); + Filename = ices_util_strdup (buf); + } +} + +/* Update metadata on server via fork. + * Note that the very first metadata update after connection is delayed, + * because if we try to update our new info to the server and the server has + * not yet accepted us as a source, the information is lost. */ +void +ices_metadata_update (int delay) +{ + pid_t child; + + if (delay) + ices_log_debug ("Delaying metadata update..."); + + if ((child = fork()) == 0) { + metadata_update (delay ? INITDELAY : 0); + _exit (0); + } + + if (child == -1) + ices_log_debug ("Metadata update failed: fork"); +} + +static void +metadata_update (int delay) +{ + ices_stream_t* stream; + shout_metadata_t* metadata; + char song[1024]; + char* playlist_metadata; + char* value; + int rc; + + if (delay) + usleep (delay); + + if (! (playlist_metadata = ices_playlist_get_metadata ())) { + if (Title) { + if (Artist) + snprintf (song, sizeof (song), "%s - %s", Artist, Title); + else + snprintf (song, sizeof (song), "%s", Title); + } else + snprintf (song, sizeof (song), "%s", Filename); + + value = song; + } else + value = playlist_metadata; + + if (!(metadata = shout_metadata_new())) { + ices_log_error ("Error allocating metadata structure"); + ices_util_free (playlist_metadata); + return; + } + + if (shout_metadata_add (metadata, "song", value) != SHOUTERR_SUCCESS) { + ices_log_error ("Error adding info to metadata structure"); + ices_util_free (playlist_metadata); + shout_metadata_free (metadata); + return; + } + + for (stream = ices_config.streams; stream; stream = stream->next) { + rc = shout_set_metadata (stream->conn, metadata); + + if (rc != SHOUTERR_SUCCESS) + ices_log_error ("Updating metadata on %s failed.", stream->mount); + else + ices_log_debug ("Updated metadata on %s to: %s", stream->mount, value); + } + + ices_util_free (playlist_metadata); + shout_metadata_free (metadata); +} + +/* Cleanup a filename so it looks more like a song name */ +static char * +metadata_clean_filename (const char* path, char *buf, size_t len) +{ + char *ptr =NULL; + + if (!path || !buf) { + ices_log ("ERROR: Polluted strings sent to filename cleanup."); + return NULL; + } + + /* Find last slash */ + ptr = strrchr (path, '/'); + + if (ptr && strlen (ptr) > 0) { + strncpy (buf, ptr + 1, len); + } else { + strncpy (buf, path, len); + } + + if ((ptr = strrchr (buf, '.'))) { + *ptr = '\0'; + } + + ices_log_debug ("Filename cleaned up from [%s] to [%s]", path, buf); + return buf; +} diff --git a/pool/shard008/C/0130192_problem48.c b/pool/shard008/C/0130192_problem48.c new file mode 100644 index 0000000000000000000000000000000000000000..b882721cf10f5b8e9c3cdfcdf6efa82afa1da5a2 --- /dev/null +++ b/pool/shard008/C/0130192_problem48.c @@ -0,0 +1,36 @@ +#include + + +int count_even(int*array, int size){ + + int i,n=0; + for(i=0;i + * + * This file is released under the 2-clause BSD license. Please refer to the + * file LICENSE for details. + */ + +#include +#include + +#include "cafebabe/attribute_info.h" +#include "cafebabe/line_number_table_attribute.h" +#include "cafebabe/stream.h" + +int cafebabe_line_number_table_attribute_init( + struct cafebabe_line_number_table_attribute *a, + struct cafebabe_stream *s) +{ + if (cafebabe_stream_read_uint16(s, &a->line_number_table_length)) + goto out; + + a->line_number_table = cafebabe_stream_malloc(s, + sizeof(*a->line_number_table) * a->line_number_table_length); + if (!a->line_number_table) + goto out; + + for (uint16_t i = 0; i < a->line_number_table_length; ++i) { + struct cafebabe_line_number_table_entry *e + = &a->line_number_table[i]; + + if (cafebabe_stream_read_uint16(s, &e->start_pc)) + goto out_line_number_table; + + if (cafebabe_stream_read_uint16(s, &e->line_number)) + goto out_line_number_table; + } + + if (!cafebabe_stream_eof(s)) { + s->cafebabe_errno = CAFEBABE_ERROR_EXPECTED_EOF; + goto out_line_number_table; + } + + /* Success */ + return 0; + +out_line_number_table: + free(a->line_number_table); +out: + return 1; +} + +void cafebabe_line_number_table_attribute_deinit( + struct cafebabe_line_number_table_attribute *a) +{ + free(a->line_number_table); +} + +int cafebabe_read_line_number_table_attribute( + const struct cafebabe_class *class, + const struct cafebabe_attribute_array *attributes, + struct cafebabe_line_number_table_attribute *attrib) +{ + unsigned int line_number_table_index = 0; + if (cafebabe_attribute_array_get(attributes, + "LineNumberTable", class, &line_number_table_index)) + { + attrib->line_number_table_length = 0; + attrib->line_number_table = NULL; + return 0; + } + + const struct cafebabe_attribute_info *attribute + = &attributes->array[line_number_table_index]; + + struct cafebabe_stream stream; + cafebabe_stream_open_buffer(&stream, + attribute->info, attribute->attribute_length); + + if (cafebabe_line_number_table_attribute_init(attrib, &stream)) + return -1; + + cafebabe_stream_close_buffer(&stream); + return 0; +} diff --git a/pool/shard008/C/0130195_log_daemon_config.c b/pool/shard008/C/0130195_log_daemon_config.c new file mode 100644 index 0000000000000000000000000000000000000000..10b42e91210391fc53c1035a32aac3c45d5a7531 --- /dev/null +++ b/pool/shard008/C/0130195_log_daemon_config.c @@ -0,0 +1,137 @@ +/* + * log_daemon_config.c: virtlogd config file handling + * + * Copyright (C) 2006-2015 Red Hat, Inc. + * Copyright (C) 2006 Daniel P. Berrange + * + * 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. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see + * . + * + * Author: Daniel P. Berrange + */ + +#include + +#include "log_daemon_config.h" +#include "virconf.h" +#include "viralloc.h" +#include "virerror.h" +#include "virlog.h" +#include "rpc/virnetserver.h" +#include "configmake.h" +#include "virstring.h" +#include "virutil.h" + +#define VIR_FROM_THIS VIR_FROM_CONF + +VIR_LOG_INIT("logging.log_daemon_config"); + + +int +virLogDaemonConfigFilePath(bool privileged, char **configfile) +{ + if (privileged) { + if (VIR_STRDUP(*configfile, SYSCONFDIR "/libvirt/virtlogd.conf") < 0) + goto error; + } else { + char *configdir = NULL; + + if (!(configdir = virGetUserConfigDirectory())) + goto error; + + if (virAsprintf(configfile, "%s/virtlogd.conf", configdir) < 0) { + VIR_FREE(configdir); + goto error; + } + VIR_FREE(configdir); + } + + return 0; + + error: + return -1; +} + + +virLogDaemonConfigPtr +virLogDaemonConfigNew(bool privileged ATTRIBUTE_UNUSED) +{ + virLogDaemonConfigPtr data; + + if (VIR_ALLOC(data) < 0) + return NULL; + + data->max_clients = 1024; + data->max_size = 1024 * 1024 * 2; + data->max_backups = 3; + + return data; +} + +void +virLogDaemonConfigFree(virLogDaemonConfigPtr data) +{ + if (!data) + return; + + VIR_FREE(data->log_filters); + VIR_FREE(data->log_outputs); + + VIR_FREE(data); +} + +static int +virLogDaemonConfigLoadOptions(virLogDaemonConfigPtr data, + virConfPtr conf) +{ + if (virConfGetValueUInt(conf, "log_level", &data->log_level) < 0) + return -1; + if (virConfGetValueString(conf, "log_filters", &data->log_filters) < 0) + return -1; + if (virConfGetValueString(conf, "log_outputs", &data->log_filters) < 0) + return -1; + if (virConfGetValueUInt(conf, "max_clients", &data->max_clients) < 0) + return -1; + if (virConfGetValueSizeT(conf, "max_size", &data->max_size) < 0) + return -1; + if (virConfGetValueSizeT(conf, "max_backups", &data->max_backups) < 0) + return -1; + + return 0; +} + + +/* Read the config file if it exists. + */ +int +virLogDaemonConfigLoadFile(virLogDaemonConfigPtr data, + const char *filename, + bool allow_missing) +{ + virConfPtr conf; + int ret; + + if (allow_missing && + access(filename, R_OK) == -1 && + errno == ENOENT) + return 0; + + conf = virConfReadFile(filename, 0); + if (!conf) + return -1; + + ret = virLogDaemonConfigLoadOptions(data, conf); + virConfFree(conf); + return ret; +} diff --git a/pool/shard008/C/0130196_NativeMemoryChunk.c b/pool/shard008/C/0130196_NativeMemoryChunk.c new file mode 100644 index 0000000000000000000000000000000000000000..acddeca5a8e0820a308a7cad8484d0658ec9e5fa --- /dev/null +++ b/pool/shard008/C/0130196_NativeMemoryChunk.c @@ -0,0 +1,148 @@ +#include +#include + +#include + +#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) +#define JLONG_TO_PTR(j) ((void*) (intptr_t) (j)) +#define PTR_TO_JLONG(p) ((jlong) (intptr_t) (p)) + +/** + * Explicitly marks result of an expression as unused. + * + * We instruct the compiler to be very strict when it comes to code + * like unused arguments that could indicate a bug. Because of that, handling + * intentionally unused arguments requires tricks like casting to void. This + * macro provides a readable name for this operation. + */ +#define UNUSED(p) ((void) (p)) + +jclass jRuntimeException_class; + +static jlong NativeMemoryChunk_nativeAllocate( + JNIEnv* env, + jclass clzz, + jint size) { + UNUSED(clzz); + void* pointer = malloc(size); + if (!pointer) { + (*env)->ThrowNew(env, jRuntimeException_class, "could not allocate memory"); + return 0; + } + return PTR_TO_JLONG(pointer); +} + +static void NativeMemoryChunk_nativeFree( + JNIEnv* env, + jclass clzz, + jlong lpointer) { + UNUSED(env); + UNUSED(clzz); + free(JLONG_TO_PTR(lpointer)); +} + +static void NativeMemoryChunk_nativeCopyToByteArray( + JNIEnv* env, + jclass clzz, + jlong lpointer, + jbyteArray byteArray, + jint offset, + jint count) { + UNUSED(clzz); + (*env)->SetByteArrayRegion( + env, + byteArray, + offset, + count, + JLONG_TO_PTR(lpointer)); +} + +static void NativeMemoryChunk_nativeCopyFromByteArray( + JNIEnv* env, + jclass clzz, + jlong lpointer, + jbyteArray byteArray, + jint offset, + jint count) { + UNUSED(clzz); + (*env)->GetByteArrayRegion( + env, + byteArray, + offset, + count, + JLONG_TO_PTR(lpointer)); +} + +static void NativeMemoryChunk_nativeMemcpy( + JNIEnv* env, + jclass clzz, + jlong dst, + jlong src, + jint count) { + UNUSED(env); + UNUSED(clzz); + memcpy(JLONG_TO_PTR(dst), JLONG_TO_PTR(src), count); +} + +static jbyte NativeMemoryChunk_nativeReadByte( + JNIEnv* env, + jclass clzz, + jlong lpointer){ + UNUSED(env); + UNUSED(clzz); + jbyte* jbyte_ptr = JLONG_TO_PTR(lpointer); + return *jbyte_ptr; +} + +static JNINativeMethod gNativeMemoryChunkMethods[] = { + { "nativeAllocate", "(I)J", (void*) NativeMemoryChunk_nativeAllocate }, + { "nativeFree", "(J)V", (void*) NativeMemoryChunk_nativeFree }, + { "nativeCopyToByteArray", "(J[BII)V", + (void*) NativeMemoryChunk_nativeCopyToByteArray }, + { "nativeCopyFromByteArray", "(J[BII)V", + (void*) NativeMemoryChunk_nativeCopyFromByteArray }, + { "nativeMemcpy", "(JJI)V", (void*) NativeMemoryChunk_nativeMemcpy }, + { "nativeReadByte", "(J)B", (void*) NativeMemoryChunk_nativeReadByte }, +}; + +/** + * Executed when libmemchunk.so is loaded. + * + * Responsibilites: + * - looks up and stores global references to Java classes used by native code + * - registers native methods of NativeMemoryChunk + */ +JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) { + UNUSED(reserved); + + JNIEnv* env; + if ((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_6) != JNI_OK) { + return JNI_ERR; + } + + jclass runtimeException = (*env)->FindClass( + env, + "java/lang/RuntimeException"); + if (!runtimeException) { + return JNI_ERR; + } + jRuntimeException_class = (*env)->NewGlobalRef(env, runtimeException); + + jclass chunk_class = (*env)->FindClass( + env, + "com/facebook/imagepipeline/memory/NativeMemoryChunk"); + if (!chunk_class) { + return JNI_ERR; + } + + jint result = (*env)->RegisterNatives( + env, + chunk_class, + gNativeMemoryChunkMethods, + ARRAY_SIZE(gNativeMemoryChunkMethods)); + if (result != JNI_OK) { + return JNI_ERR; + } + + return JNI_VERSION_1_6; +} diff --git a/pool/shard008/C/0130197_prog_1_5_4.c b/pool/shard008/C/0130197_prog_1_5_4.c new file mode 100644 index 0000000000000000000000000000000000000000..21b82a31a8a2b5b23e4e540995190ab8907d67a1 --- /dev/null +++ b/pool/shard008/C/0130197_prog_1_5_4.c @@ -0,0 +1,26 @@ +#include + +#define IN 1 +#define OUT 0 + +/* count lines, words, and characters in input */ +int main() +{ + int c, nl, nw, nc, state; + + state = OUT; + nl = nw = nc = 0; + while ((c=getchar()) != EOF) { + ++nc; + if (c == '\n') + ++nl; + if (c == ' ' || c == '\n' || c == '\t') + state = OUT; + else if (state == OUT) { + state = IN; + ++nw; + } + } + + printf("\nLines:\t%d\nWords:\t%d\nCharacters:\t%d\n", nl, nw, nc); +} diff --git a/pool/shard008/C/0130198_snprintf.c b/pool/shard008/C/0130198_snprintf.c new file mode 100644 index 0000000000000000000000000000000000000000..4a8a7035c97c46068debe02f45cefc062a9a79bb --- /dev/null +++ b/pool/shard008/C/0130198_snprintf.c @@ -0,0 +1,108 @@ +/* -*- Mode: c; c-basic-offset: 2 -*- + * + * snprintf.c - Rasqal formatted numbers utilities + * + * Copyright (C) 2011, David Beckett http://www.dajobe.org/ + * + * This package is Free Software and part of Redland http://librdf.org/ + * + * It is licensed under the following three licenses as alternatives: + * 1. GNU Lesser General Public License (LGPL) V2.1 or any newer version + * 2. GNU General Public License (GPL) V2 or any newer version + * 3. Apache License, V2.0 or any newer version + * + * You may not use this file except in compliance with at least one of + * the above three licenses. + * + * See LICENSE.html or LICENSE.txt at the top of this package for the + * complete terms and further detail along with the license texts for + * the licenses in COPYING.LIB, COPYING and LICENSE-2.0.txt respectively. + * + * + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#ifdef WIN32 +#include +#endif + +#include +#include +#ifdef HAVE_STDLIB_H +#include +#endif +#include + +#include "rasqal.h" +#include "rasqal_internal.h" + + +static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz"; + +/** + * rasqal_format_integer: + * @buffer: buffer (or NULL) + * @bufsize: size of above (or 0) + * @integer: integer value to format + * + * INTERNAL - Format an integer as a decimal into a buffer or + * calculate the size needed. + * + * Works Like the C99 snprintf() but just for integers. + * + * If @buffer is NULL or the @bufsize is too small, the number of + * bytes needed (excluding NUL) is returned and no formatting is done. + * + * Return value: number of bytes needed or written (excluding NUL) or 0 on failure + */ +size_t +rasqal_format_integer(char* buffer, size_t bufsize, int integer, + int width, char padding) +{ + size_t len = 1; + char *p; + unsigned int value; + unsigned int base = 10; + + if(integer < 0) { + value = RASQAL_GOOD_CAST(unsigned int, -integer); + len++; + width++; + } else + value = RASQAL_GOOD_CAST(unsigned int, integer); + while(value /= base) + len++; + + if(width > 0) { + size_t width_l = RASQAL_GOOD_CAST(size_t, width); + if(width_l > len) + len = width_l; + } + + if(!buffer || bufsize < (len + 1)) /* +1 for NUL */ + return len; + + if(!padding) + padding = ' '; + + if(integer < 0) + value = RASQAL_GOOD_CAST(unsigned int, -integer); + else + value = RASQAL_GOOD_CAST(unsigned int, integer); + + p = &buffer[len]; + *p-- = '\0'; + while(value > 0 && p >= buffer) { + *p-- = digits[value % base]; + value /= base; + } + while(p >= buffer) + *p-- = padding; + if(integer < 0) + *buffer = '-'; + + return len; +} diff --git a/pool/shard008/C/0130203_pcy_data.c b/pool/shard008/C/0130203_pcy_data.c new file mode 100644 index 0000000000000000000000000000000000000000..773faaf1e774aaee4837083a562cd6c556d0d2ff --- /dev/null +++ b/pool/shard008/C/0130203_pcy_data.c @@ -0,0 +1,130 @@ +/* $OpenBSD: pcy_data.c,v 1.7 2014/06/12 15:49:31 deraadt Exp $ */ +/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL + * project 2004. + */ +/* ==================================================================== + * Copyright (c) 2004 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include "cryptlib.h" +#include +#include + +#include "pcy_int.h" + +/* Policy Node routines */ + +void +policy_data_free(X509_POLICY_DATA *data) +{ + ASN1_OBJECT_free(data->valid_policy); + /* Don't free qualifiers if shared */ + if (!(data->flags & POLICY_DATA_FLAG_SHARED_QUALIFIERS)) + sk_POLICYQUALINFO_pop_free(data->qualifier_set, + POLICYQUALINFO_free); + sk_ASN1_OBJECT_pop_free(data->expected_policy_set, ASN1_OBJECT_free); + free(data); +} + +/* Create a data based on an existing policy. If 'id' is NULL use the + * oid in the policy, otherwise use 'id'. This behaviour covers the two + * types of data in RFC3280: data with from a CertificatePolcies extension + * and additional data with just the qualifiers of anyPolicy and ID from + * another source. + */ + +X509_POLICY_DATA * +policy_data_new(POLICYINFO *policy, const ASN1_OBJECT *cid, int crit) +{ + X509_POLICY_DATA *ret; + ASN1_OBJECT *id; + + if (!policy && !cid) + return NULL; + if (cid) { + id = OBJ_dup(cid); + if (!id) + return NULL; + } else + id = NULL; + ret = malloc(sizeof(X509_POLICY_DATA)); + if (!ret) + return NULL; + ret->expected_policy_set = sk_ASN1_OBJECT_new_null(); + if (!ret->expected_policy_set) { + free(ret); + if (id) + ASN1_OBJECT_free(id); + return NULL; + } + + if (crit) + ret->flags = POLICY_DATA_FLAG_CRITICAL; + else + ret->flags = 0; + + if (id) + ret->valid_policy = id; + else { + ret->valid_policy = policy->policyid; + policy->policyid = NULL; + } + + if (policy) { + ret->qualifier_set = policy->qualifiers; + policy->qualifiers = NULL; + } else + ret->qualifier_set = NULL; + + return ret; +} diff --git a/pool/shard008/C/0130207_aubiomodule.c b/pool/shard008/C/0130207_aubiomodule.c new file mode 100644 index 0000000000000000000000000000000000000000..27e8e51a128a9032b260a5d9656f92c1f1bc0315 --- /dev/null +++ b/pool/shard008/C/0130207_aubiomodule.c @@ -0,0 +1,160 @@ +#include +#define PY_ARRAY_UNIQUE_SYMBOL PyArray_API +#include + +#include "aubio-types.h" +#include "generated/aubio-generated.h" + +static char Py_alpha_norm_doc[] = "compute alpha normalisation factor"; + +static PyObject * +Py_alpha_norm (PyObject * self, PyObject * args) +{ + PyObject *input; + fvec_t *vec; + smpl_t alpha; + PyObject *result; + + if (!PyArg_ParseTuple (args, "Of:alpha_norm", &input, &alpha)) { + return NULL; + } + + if (input == NULL) { + return NULL; + } + + vec = PyAubio_ArrayToCFvec (input); + + if (vec == NULL) { + return NULL; + } + + // compute the function + result = Py_BuildValue ("f", fvec_alpha_norm (vec, alpha)); + if (result == NULL) { + return NULL; + } + + return result; +} + +static char Py_zero_crossing_rate_doc[] = "compute zero crossing rate"; + +static PyObject * +Py_zero_crossing_rate (PyObject * self, PyObject * args) +{ + PyObject *input; + fvec_t *vec; + PyObject *result; + + if (!PyArg_ParseTuple (args, "O:zero_crossing_rate", &input)) { + return NULL; + } + + if (input == NULL) { + return NULL; + } + + vec = PyAubio_ArrayToCFvec (input); + + if (vec == NULL) { + return NULL; + } + + // compute the function + result = Py_BuildValue ("f", aubio_zero_crossing_rate (vec)); + if (result == NULL) { + return NULL; + } + + return result; +} + +static char Py_min_removal_doc[] = "compute zero crossing rate"; + +static PyObject * +Py_min_removal(PyObject * self, PyObject * args) +{ + PyObject *input; + fvec_t *vec; + + if (!PyArg_ParseTuple (args, "O:min_removal", &input)) { + return NULL; + } + + if (input == NULL) { + return NULL; + } + + vec = PyAubio_ArrayToCFvec (input); + + if (vec == NULL) { + return NULL; + } + + // compute the function + fvec_min_removal (vec); + + // since this function does not return, we could return None + //return Py_None; + // however it is convenient to return the modified vector + return (PyObject *) PyAubio_CFvecToArray(vec); + // or even without converting it back to an array + //Py_INCREF(vec); + //return (PyObject *)vec; +} + +static PyMethodDef aubio_methods[] = { + {"alpha_norm", Py_alpha_norm, METH_VARARGS, Py_alpha_norm_doc}, + {"zero_crossing_rate", Py_zero_crossing_rate, METH_VARARGS, + Py_zero_crossing_rate_doc}, + {"min_removal", Py_min_removal, METH_VARARGS, Py_min_removal_doc}, + {NULL, NULL} /* Sentinel */ +}; + +static char aubio_module_doc[] = "Python module for the aubio library"; + +PyMODINIT_FUNC +init_aubio (void) +{ + PyObject *m; + int err; + + if ( (PyType_Ready (&Py_cvecType) < 0) + || (PyType_Ready (&Py_filterType) < 0) + || (PyType_Ready (&Py_filterbankType) < 0) + || (PyType_Ready (&Py_fftType) < 0) + || (PyType_Ready (&Py_pvocType) < 0) + // generated objects + || (generated_types_ready() < 0 ) + ) { + return; + } + + err = _import_array (); + + if (err != 0) { + fprintf (stderr, + "Unable to import Numpy C API from aubio module (error %d)\n", err); + } + + m = Py_InitModule3 ("_aubio", aubio_methods, aubio_module_doc); + + if (m == NULL) { + return; + } + + Py_INCREF (&Py_cvecType); + PyModule_AddObject (m, "cvec", (PyObject *) & Py_cvecType); + Py_INCREF (&Py_filterType); + PyModule_AddObject (m, "digital_filter", (PyObject *) & Py_filterType); + Py_INCREF (&Py_filterbankType); + PyModule_AddObject (m, "filterbank", (PyObject *) & Py_filterbankType); + Py_INCREF (&Py_fftType); + PyModule_AddObject (m, "fft", (PyObject *) & Py_fftType); + Py_INCREF (&Py_pvocType); + PyModule_AddObject (m, "pvoc", (PyObject *) & Py_pvocType); + + // generated objects + add_generated_objects(m); +} diff --git a/pool/shard008/C/0130211_tt_xml_unit_test.c b/pool/shard008/C/0130211_tt_xml_unit_test.c new file mode 100644 index 0000000000000000000000000000000000000000..44356de3b3059b01518cd038d1876d20fdc22a42 --- /dev/null +++ b/pool/shard008/C/0130211_tt_xml_unit_test.c @@ -0,0 +1,93 @@ +/* Copyright (C) 2017 haniu (niuhao.cn@gmail.com) + * + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * 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. + */ + +//////////////////////////////////////////////////////////// +// import header files +//////////////////////////////////////////////////////////// + +#include + +//////////////////////////////////////////////////////////// +// internal macro +//////////////////////////////////////////////////////////// + +#define TT_XML_UT_DECLARE(name) \ + extern tt_test_unit_t TT_MAKE_TEST_UNIT_NAME(name); + +//////////////////////////////////////////////////////////// +// internal type +//////////////////////////////////////////////////////////// + +typedef enum { + XML_UT_BEGIN = 0, + + XML_UT_XDOC = XML_UT_BEGIN, + XML_UT_XATTR, + XML_UT_XNODE, + XML_UT_XPATH, + + XML_UT_NUM // number of test units +} tt_xml_ut_id_t; + +//////////////////////////////////////////////////////////// +// extern declaration +//////////////////////////////////////////////////////////// + +TT_XML_UT_DECLARE(XML_UT_XDOC) +TT_XML_UT_DECLARE(XML_UT_XATTR) +TT_XML_UT_DECLARE(XML_UT_XNODE) +TT_XML_UT_DECLARE(XML_UT_XPATH) + +//////////////////////////////////////////////////////////// +// global variant +//////////////////////////////////////////////////////////// + +tt_test_unit_t *tt_g_xml_ut_list[XML_UT_NUM] = { + &TT_MAKE_TEST_UNIT_NAME(XML_UT_XDOC), + &TT_MAKE_TEST_UNIT_NAME(XML_UT_XATTR), + &TT_MAKE_TEST_UNIT_NAME(XML_UT_XNODE), + &TT_MAKE_TEST_UNIT_NAME(XML_UT_XPATH), +}; + +//////////////////////////////////////////////////////////// +// interface declaration +//////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////// +// interface implementation +//////////////////////////////////////////////////////////// + +tt_result_t tt_xml_ut_init(IN tt_ptr_t reserved) +{ + tt_xml_ut_id_t unit_id = XML_UT_BEGIN; + while (unit_id < XML_UT_NUM) { + tt_result_t result = TT_FAIL; + + if (tt_g_xml_ut_list[unit_id] != NULL) { + result = tt_test_unit_to_class(tt_g_xml_ut_list[unit_id]); + if (!TT_OK(result)) { + return TT_FAIL; + } + } + + // next + ++unit_id; + } + + return TT_SUCCESS; +} diff --git a/pool/shard008/C/0130218_auto_map.c b/pool/shard008/C/0130218_auto_map.c new file mode 100644 index 0000000000000000000000000000000000000000..229df53e05ffa92f9fd580b1541f3db476392272 --- /dev/null +++ b/pool/shard008/C/0130218_auto_map.c @@ -0,0 +1,211 @@ +/* + * automated event map creation code + * + * Copyright 2004 Jacob Robbins + * + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + + +#include + +#include "../include.h" + + + +int rtobject_create_auto_map(rtobject_t* rtobj){ + int pitch_control, i; + ev_route_frame_t frame; + map_test_t test_struct; + char *pitch_control_string; + + /*initialize variables including pesky test structure*/ + frame.rtobj = rtobj; + memset((void*)&test_struct, 0, sizeof(map_test_t)); + frame.test = &test_struct; + + /*see if there is a pitch control*/ + pitch_control = -1; + for (i=0;i= 0){ + + /*put the index of the pitch control into a string*/ + if (!(pitch_control_string = (char*)malloc(16 * sizeof(char)))){ + printf("auto map error: memory error/n"); + return -1; + } + sprintf(pitch_control_string, "%d", pitch_control); + + /*create the map*/ + if (!(frame.map = event_map_alloca())){ + printf("auto map error: couldn't create new map/n"); + return -1; + } + + /*note-on test*/ + map_test_clear(&test_struct); + { + char * pass[] = { "type", "noteon" }; + + /*initialize test (tests aren't allocated)*/ + if (map_test_init(&frame, 2, pass) < 0){ + printf("auto map error: couldn't create noteon test\n"); + event_map_dealloca(frame.map); + return -1; + } + + /*note-on test, action 0 : set note flag*/ + { + char * action_pass[] = { "flag", "note", "on" }; + + if (map_action_init(&frame, 3, action_pass) < 0){ + printf("auto map error: couldn't create flag action\n"); + event_map_dealloca(frame.map); + return -1; + } + + if (map_test_insert_action(frame.test, frame.action, -1) < 0){ + printf("auto map error: couldn't insert action\n"); + event_map_dealloca(frame.map); + return -1; + } + } + + /*note-on test, action 1 : set pitch using default scale*/ + { + char * action_pass[] = { "pitch", pitch_control_string,\ + "def", "match" }; + + if (map_action_init(&frame, 4, action_pass) < 0){ + printf("auto map error: couldn't create flag action\n"); + event_map_dealloca(frame.map); + return -1; + } + + if (map_test_insert_action(frame.test, frame.action, -1) < 0){ + printf("auto map error: couldn't insert action\n"); + event_map_dealloca(frame.map); + return -1; + } + } + + /*note-on test, action 2 : activate instance*/ + { + char * action_pass[] = { "set", "0",\ + "const", "1", "match" }; + + if (map_action_init(&frame, 5, action_pass) < 0){ + printf("auto map error: couldn't create flag action\n"); + event_map_dealloca(frame.map); + return -1; + } + + if (map_test_insert_action(frame.test, frame.action, -1) < 0){ + printf("auto map error: couldn't insert action\n"); + event_map_dealloca(frame.map); + return -1; + } + } + + /*put test into map*/ + if (event_map_insert_test(frame.map, frame.test, -1) < 0){ + printf("auto map error: couldn't insert noteon test\n"); + event_map_dealloca(frame.map); + return -1; + } + } + + /*create the note-off test*/ + memset((void*)&test_struct, 0, sizeof(map_test_t)); + { + char * pass[] = { "type", "noteoff" }; + + if (map_test_init(&frame, 2, pass) < 0){ + printf("auto map error: couldn't create noteoff test\n"); + event_map_dealloca(frame.map); + return -1; + } + + /*note-off test, action 0 : deactivate instance*/ + { + char * action_pass[] = { "set", "0",\ + "const", "0", "match" }; + + if (map_action_init(&frame, 5, action_pass) < 0){ + printf("auto map error: couldn't create flag action\n"); + event_map_dealloca(frame.map); + return -1; + } + + if (map_test_insert_action(frame.test, frame.action, -1) < 0){ + printf("auto map error: couldn't insert action\n"); + event_map_dealloca(frame.map); + return -1; + } + } + + /*note-off test, action 1 : unset the note flag*/ + { + char * action_pass[] = { "flag", "note", "off" }; + + if (map_action_init(&frame, 3, action_pass) < 0){ + printf("auto map error: couldn't create flag action\n"); + event_map_dealloca(frame.map); + return -1; + } + + if (map_test_insert_action(frame.test, frame.action, -1) < 0){ + printf("auto map error: couldn't insert action\n"); + event_map_dealloca(frame.map); + return -1; + } + } + + /*put test into map*/ + if (event_map_insert_test(frame.map, frame.test, -1) < 0){ + printf("auto map error: couldn't insert noteoff test\n"); + event_map_dealloca(frame.map); + return -1; + } + } + + /*stick map in rtobject*/ + if (rtobject_insert_map(rtobj, frame.map, 0) < 0){ + printf("auto map error: couldn't insert new map into rtobject\n"); + event_map_dealloca(frame.map); + return -1; + } + + } + + return 0; +} + diff --git a/pool/shard008/C/0130223_nio_csma_send.c b/pool/shard008/C/0130223_nio_csma_send.c new file mode 100644 index 0000000000000000000000000000000000000000..a5d7ce1caab7ef409847946a41a2f3353c2faccc --- /dev/null +++ b/pool/shard008/C/0130223_nio_csma_send.c @@ -0,0 +1,242 @@ +/******************************************************************************* + * csma_send + * This project implements a frame sending node based on TiCsma component. This + * component is in module "svc_csma". + * + * @state + * - compile passed. tested. released. + * + * @modified by openwsn on 2010.10.12 + * - complied successfully. The sniffer have recv the data successfully + * + * @modified by Xu-Fuzhen in TongJi University(xufz0726@126.com) in 2010.10 + * - tested ok. + ******************************************************************************/ + +#define CONFIG_NIOACCEPTOR_RXQUE_CAPACITY 2 +#define CONFIG_NIOACCEPTOR_TXQUE_CAPACITY 2 + +#include "../../common/openwsn/hal/hal_configall.h" +#include +#include +#include +#include "../../common/openwsn/hal/hal_foundation.h" +#include "../../common/openwsn/rtl/rtl_foundation.h" +#include "../../common/openwsn/rtl/rtl_frame.h" +#include "../../common/openwsn/rtl/rtl_debugio.h" +#include "../../common/openwsn/rtl/rtl_ieee802frame154.h" +#include "../../common/openwsn/hal/hal_cpu.h" +#include "../../common/openwsn/hal/hal_interrupt.h" +#include "../../common/openwsn/hal/hal_led.h" +#include "../../common/openwsn/hal/hal_assert.h" +#include "../../common/openwsn/hal/hal_uart.h" +#include "../../common/openwsn/hal/hal_cc2420.h" +#include "../../common/openwsn/hal/hal_targetboard.h" +#include "../../common/openwsn/hal/hal_debugio.h" +//#include "../../common/openwsn/svc/svc_nio_csma.h" +#include "../../common/openwsn/svc/svc_nio_aloha.h" +#include "../../common/openwsn/svc/svc_nio_acceptor.h" + +#define CONFIG_DEBUG + +#ifdef CONFIG_DEBUG + #define GDEBUG +#endif + +#define CONFIG_CSMA_PANID 0x0001 +#define CONFIG_CSMA_LOCAL_ADDRESS 0x01 +#define CONFIG_CSMA_REMOTE_ADDRESS 0x02 +#define CONFIG_CSMA_CHANNEL 11 + +#define MAX_IEEE802FRAME154_SIZE 128 + +#define NAC_SIZE NIOACCEPTOR_HOPESIZE(CONFIG_NIOACCEPTOR_RXQUE_CAPACITY,CONFIG_NIOACCEPTOR_TXQUE_CAPACITY) + +static TiCc2420Adapter m_cc; +static TiFrameRxTxInterface m_rxtx; +static char m_nacmem[NAC_SIZE]; +//static TiCsma m_csma; +static TiAloha m_aloha; +static TiTimerAdapter m_timer; +static char m_txbuf[FRAME_HOPESIZE(MAX_IEEE802FRAME154_SIZE)]; +static char m_rxbuf[FRAME_HOPESIZE(MAX_IEEE802FRAME154_SIZE)]; + +void csma_sendnode(void); + +int main(void) +{ + csma_sendnode(); + return 0; +} + +void csma_sendnode(void) +{ + TiCc2420Adapter * cc; + TiFrameRxTxInterface * rxtx;; + //TiCsma * mac; + TiAloha * mac; + TiNioAcceptor * nac; + TiTimerAdapter *timer; + TiFrame * txbuf; + TiFrame * rxbuf; + char * pc; + + char * msg = "welcome to csma sendnode..."; + uint8 i,j, seqid=0, option; + + target_init(); + + led_open(); + led_on( LED_ALL ); + hal_delay( 500 ); + led_off( LED_ALL ); + led_on( LED_RED ); + dbo_open( 38400 ); + + rtl_init( (void *)dbio_open(38400), (TiFunDebugIoPutChar)dbio_putchar, (TiFunDebugIoGetChar)dbio_getchar, hal_assert_report ); + dbc_mem( msg, strlen(msg) ); + + cc = cc2420_construct( (char *)(&m_cc), sizeof(TiCc2420Adapter) ); + nac = nac_construct( &m_nacmem[0], NAC_SIZE ); + mac = csma_construct( (char *)(&m_aloha), sizeof(TiAloha) );//mac = csma_construct( (char *)(&m_csma), sizeof(TiCsma) ); + timer= timer_construct(( char *)(&m_timer),sizeof(TiTimerAdapter)); + + cc2420_open(cc, 0, NULL, NULL, 0x00 ); + rxtx = cc2420_interface( cc, &m_rxtx ); + + hal_assert( rxtx != NULL ); + // attention: since timer0 is used for the osx kernel, we propose the next 16bit + // timer to be used in this module. If you port this example to other hardware + // platform, you may need to adjust the timer_open parameters. + // + // Q: is the second parameter be 2 or 3 for atmega's 16 bit timer? + timer = timer_open( timer, 2, NULL, NULL, 0x00 ); + + // initialize the standard aloha component for sending/recving + hal_assert( (rxtx != NULL) && (timer != NULL) ); + + nac_open( nac, rxtx, CONFIG_NIOACCEPTOR_RXQUE_CAPACITY, CONFIG_NIOACCEPTOR_TXQUE_CAPACITY); + + //csma_open( mac, rxtx, nac,CONFIG_CSMA_CHANNEL, CONFIG_CSMA_PANID, CONFIG_CSMA_LOCAL_ADDRESS, + // timer, NULL, NULL ); + + aloha_open( mac,rxtx,nac, CONFIG_CSMA_CHANNEL, CONFIG_CSMA_PANID, + CONFIG_CSMA_LOCAL_ADDRESS,timer, NULL, NULL, 0x00 ); + + txbuf = frame_open( (char*)(&m_txbuf), FRAME_HOPESIZE(MAX_IEEE802FRAME154_SIZE), 3, 20, 25 ); + rxbuf = frame_open( (char*)(&m_rxbuf), FRAME_HOPESIZE(MAX_IEEE802FRAME154_SIZE), 3, 20, 25 ); + + cc2420_setchannel( cc, CONFIG_CSMA_CHANNEL ); + cc2420_setrxmode( cc ); // enable RX mode + cc2420_setpanid( cc, CONFIG_CSMA_PANID ); // network identifier, seems no use in sniffer mode + cc2420_setshortaddress( cc, CONFIG_CSMA_LOCAL_ADDRESS ); // in network address, seems no use in sniffer mode + cc2420_enable_autoack( cc ); + + hal_enable_interrupts(); + + dbc_putchar(0x01); + + while(1) + { + j = 0; + //csma_setremoteaddress( mac, CONFIG_CSMA_REMOTE_ADDRESS ); + frame_reset(txbuf, 3, 20, 25); + + dbc_putchar(0x02); + + + #define TEST1 + + #ifdef TEST1 + pc = frame_startptr( txbuf ); + for (i=0; ioption = option;//¾ö¶¨ÊÇ·ñÓÃACK + + while (1) + { + if (aloha_send(mac,CONFIG_CSMA_REMOTE_ADDRESS, txbuf, txbuf->option) > 0)//if (csma_send(mac,CONFIG_CSMA_REMOTE_ADDRESS, txbuf, txbuf->option) > 0) + { + dbc_putchar(0x22); + led_toggle( LED_YELLOW ); + dbo_putchar( 0x11); + dbo_putchar( seqid ); + break; + } + else{ + dbo_putchar(0x22); + dbo_putchar( seqid ); + nac_evolve( mac->nac,NULL); + } + hal_delay(1000); + } + + // for simple aloha, you needn't to call aloha_evolve(). it's necessary for + // standard aloha. + + // csma_evolve( mac, NULL ); + aloha_evolve( mac, NULL ); + + // controls the sending rate. if you want to test the RXFIFO overflow processing + // you can decrease this value. + // attention: this long delay will occupy the CPU and it may lead to frame lossing. + + while ( j<0xff) + { + frame_reset( rxbuf, 3, 20, 0 ); + //len = csma_recv( mac, rxbuf, 0x00 ); + if (aloha_recv( mac, rxbuf, 0x01 )>0)//if (csma_recv( mac, rxbuf, 0x01 )>0) + { + dbc_putchar( 0xF3 ); + + + frame_moveouter( rxbuf ); + //_output_frame( rxbuf, NULL ); + ieee802frame154_dump( rxbuf); + frame_moveinner( rxbuf ); + + // led_off( LED_RED ); + + /* warning: You shouldn't wait too long in the while loop, or else + * you may encounter frame loss. However, the program should still + * work properly even the delay time is an arbitrary value. No error + * are allowed in this case. + */ + // hal_delay( 500 ); + led_toggle( LED_RED ); + //hal_delay( 500 + break; + } + j++; + + } + + hal_delay(1000); + + //break; + } + + frame_close( txbuf ); + //csma_close( mac ); + aloha_close( mac ); + cc2420_close( cc ); +} + + + diff --git a/pool/shard008/C/0130224_ejsMemory.c b/pool/shard008/C/0130224_ejsMemory.c new file mode 100644 index 0000000000000000000000000000000000000000..027915ab047964e57de3186078aacb4c04f75dbb --- /dev/null +++ b/pool/shard008/C/0130224_ejsMemory.c @@ -0,0 +1,117 @@ +/* + * ejsMemory.c - Memory class + * + * Copyright (c) All Rights Reserved. See details at the end of the file. + */ +/********************************** Includes **********************************/ + +#include "ejs.h" + +/*********************************** Methods *********************************/ + +#if FUTURE +static EjsVar *getUsedMemoryProc(Ejs *ejs, EjsVar *unused, int argc, EjsVar **argv) +{ + return (EjsVar*) ejsCreateNumber(ejs, getUsedMemory(ejs)); +} + + +static int getUsedStackProc(Ejs *ejs, EjsVar *unused, int argc, EjsVar **argv) +{ + return (EjsVar*) ejsCreateNumber(ejs, mprStackSize(ejs)); +} + + +uint ejsGetAvailableMemory(Ejs *ejs) +{ + EjsVar *memoryClass; + uint ram; + + memoryClass = ejsFindClass(ejs, 0, "System.Memory"); + + ram = ejsGetPropertyAsInteger(ejs, memoryClass, "ram"); + return ram - getUsedMemory(ejs); +} + + + +static EjsVar *getAvailableMemoryProc(Ejs *ejs, EjsVar *unused, int argc, EjsVar **argv) +{ + EjsVar *memoryClass; + uint ram; + + memoryClass = ejsFindClass(ejs, 0, "System.Memory"); + + ram = ejsGetPropertyAsInteger(ejs, memoryClass, "ram"); + ejsSetReturnValueToInteger(ejs, 0); + return 0; +} + + + +static uint getUsedMemory(Ejs *ejs) +{ + return 0; +} +#endif + + +static EjsVar *printStats(Ejs *ejs, EjsVar *unused, int argc, EjsVar **argv) +{ + mprPrintAllocReport(ejs, "Memory.printStats()"); + ejsPrintAllocReport(ejs); + return 0; +} + +/******************************** Initialization ******************************/ + +void ejsCreateMemoryType(Ejs *ejs) +{ + EjsName qname; + + ejsCreateCoreType(ejs, ejsName(&qname, "ejs.sys", "Memory"), ejs->objectType, sizeof(EjsObject), ES_ejs_sys_Memory, + ES_ejs_sys_Memory_NUM_CLASS_PROP, ES_ejs_sys_Memory_NUM_INSTANCE_PROP, EJS_ATTR_NATIVE | EJS_ATTR_OBJECT_HELPERS); +} + + +void ejsConfigureMemoryType(Ejs *ejs) +{ + EjsType *type; + + type = ejsGetType(ejs, ES_ejs_sys_Memory); + + ejsBindMethod(ejs, type, ES_ejs_sys_Memory_printStats, (EjsNativeFunction) printStats); +#if FUTURE + ejsBindMethod(ejs, type, ES_ejs_sys_App_NAME, (EjsNativeFunction) NAME); +#endif +} + +/* + * @copy default + * + * Copyright (c) Embedthis Software LLC, 2003-2009. All Rights Reserved. + * Copyright (c) Michael O'Brien, 1993-2009. All Rights Reserved. + * + * This software is distributed under commercial and open source licenses. + * You may use the GPL open source license described below or you may acquire + * a commercial license from Embedthis Software. You agree to be fully bound + * by the terms of either license. Consult the LICENSE.TXT distributed with + * this software for full details. + * + * This software is open source; 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. See the GNU General Public License for more + * details at: http://www.embedthis.com/downloads/gplLicense.html + * + * This program is distributed WITHOUT ANY WARRANTY; without even the + * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * + * This GPL license does NOT permit incorporating this software into + * proprietary programs. If you are unable to comply with the GPL, you must + * acquire a commercial license to use this software. Commercial licenses + * for this software and support services are available from Embedthis + * Software at http://www.embedthis.com + * + * @end + */ diff --git a/pool/shard008/C/0130226_eap_sim_plugin.c b/pool/shard008/C/0130226_eap_sim_plugin.c new file mode 100644 index 0000000000000000000000000000000000000000..b1529254412e247352459075fa1a57e427c4d4a3 --- /dev/null +++ b/pool/shard008/C/0130226_eap_sim_plugin.c @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2008-2009 Martin Willi + * Hochschule fuer Technik Rapperswil + * + * 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. See . + * + * 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. + */ + +#include "eap_sim_plugin.h" + +#include "eap_sim_server.h" +#include "eap_sim_peer.h" + +#include + +METHOD(plugin_t, get_name, char*, + eap_sim_plugin_t *this) +{ + return "eap-sim"; +} + +METHOD(plugin_t, destroy, void, + eap_sim_plugin_t *this) +{ + charon->eap->remove_method(charon->eap, + (eap_constructor_t)eap_sim_server_create); + charon->eap->remove_method(charon->eap, + (eap_constructor_t)eap_sim_peer_create); + free(this); +} + +/* + * see header file + */ +plugin_t *eap_sim_plugin_create() +{ + eap_sim_plugin_t *this; + + INIT(this, + .plugin = { + .get_name = _get_name, + .reload = (void*)return_false, + .destroy = _destroy, + }, + ); + + charon->eap->add_method(charon->eap, EAP_SIM, 0, EAP_SERVER, + (eap_constructor_t)eap_sim_server_create); + charon->eap->add_method(charon->eap, EAP_SIM, 0, EAP_PEER, + (eap_constructor_t)eap_sim_peer_create); + + return &this->plugin; +} + diff --git a/pool/shard008/C/0130228_test_device_simulator_serial_gps.c b/pool/shard008/C/0130228_test_device_simulator_serial_gps.c new file mode 100644 index 0000000000000000000000000000000000000000..ca7952650c6b71bc13c533bff2d4b0d1d78489a9 --- /dev/null +++ b/pool/shard008/C/0130228_test_device_simulator_serial_gps.c @@ -0,0 +1,109 @@ +#include +#include +#include +#include +#include + +static const struct device_operations_t * device = &simulator_serial_gps_operations; + +static void test_existance(void) +{ + CU_ASSERT_PTR_NOT_NULL(device); + CU_ASSERT_PTR_NOT_NULL(device->open); + CU_ASSERT_PTR_NOT_NULL(device->close); + CU_ASSERT_PTR_NOT_NULL(device->read); + CU_ASSERT_PTR_NOT_NULL(device->write); +} + +static void test_open(void) +{ + struct device_t dev; + + device_init(&dev); + + CU_ASSERT_EQUAL(device->open(NULL, NULL), -1); + + dev.fd = -1; + CU_ASSERT_EQUAL(device->open(&dev, NULL), 0); + CU_ASSERT_NOT_EQUAL(dev.fd, -1); + + dev.fd = 1; + CU_ASSERT_EQUAL(device->open(&dev, NULL), 0); +} + +static void test_close(void) +{ + struct device_t dev; + + device_init(&dev); + + CU_ASSERT_EQUAL(device->close(NULL), -1); + + dev.fd = -1; + CU_ASSERT_EQUAL(device->close(&dev), 0); + + dev.fd = 0; + CU_ASSERT_EQUAL(device->close(&dev), 0); + CU_ASSERT_EQUAL(dev.fd, -1); +} + +static void test_open_close(void) +{ + struct device_t dev; + + device_init(&dev); + CU_ASSERT_EQUAL(dev.fd, -1); + CU_ASSERT_PTR_NULL(dev.data); + CU_ASSERT_EQUAL(device->open(&dev, NULL), 0); + CU_ASSERT_NOT_EQUAL(dev.fd, -1); + CU_ASSERT_PTR_NULL(dev.data); + CU_ASSERT_EQUAL(device->close(&dev), 0); + CU_ASSERT_EQUAL(dev.fd, -1); + CU_ASSERT_PTR_NULL(dev.data); +} + +static void test_write(void) +{ + CU_ASSERT_EQUAL(device->write(NULL, NULL, 0), -1); +} + +static void test_read(void) +{ + struct device_t dev; + char buf[1]; + + /* TODO: must set up signal handling in order to block SIGALRM or else the test fails anyway */ + + device_init(&dev); + + CU_ASSERT_EQUAL(device->read(NULL, NULL, 0), -1); + CU_ASSERT_EQUAL(device->read(NULL, NULL, sizeof(buf)), -1); + CU_ASSERT_EQUAL(device->read(NULL, buf, 0), -1); + CU_ASSERT_EQUAL(device->read(NULL, buf, sizeof(buf)), -1); + + CU_ASSERT_EQUAL(device->open(&dev, NULL), 0); + CU_ASSERT_NOT_EQUAL_FATAL(dev.fd, -1); + + CU_ASSERT_EQUAL(device->read(&dev, NULL, 0), -1); + CU_ASSERT_EQUAL(device->read(&dev, NULL, sizeof(buf)), -1); + CU_ASSERT_EQUAL(device->read(&dev, buf, 0), 0); + + CU_ASSERT_EQUAL(device->close(&dev), 0); + + dev.fd = -1; + CU_ASSERT_EQUAL(device->read(&dev, buf, sizeof(buf)), -1); +} + +void register_suite_device_simulator_serial_gps(void) +{ + CU_Suite * suite; + suite = CU_add_suite("device/simulator_serial_gps", NULL, NULL); + + CU_add_test(suite, "existance", test_existance); + CU_add_test(suite, "open", test_open); + CU_add_test(suite, "close", test_close); + CU_add_test(suite, "open/close", test_open_close); + CU_add_test(suite, "write", test_write); + CU_add_test(suite, "read", test_read); +} + diff --git a/pool/shard008/C/0130232_pcic_p.c b/pool/shard008/C/0130232_pcic_p.c new file mode 100644 index 0000000000000000000000000000000000000000..51214910f7b583e98a621262edca0f73d5b2fe72 --- /dev/null +++ b/pool/shard008/C/0130232_pcic_p.c @@ -0,0 +1,222 @@ +/* + * Copyright (c) 1997 Ted Faber + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice immediately at the beginning of the file, without modification, + * this list of conditions, and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Absolutely no warranty of function or purpose is made by the author + * Ted Faber. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $Id: pcic_p.c,v 1.7.2.1 1999/05/02 05:59:12 nate Exp $ + */ + +#include "pci.h" +#if NPCI > 0 + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static u_long pcic_pci_count = 0; + +static const char *pcic_pci_probe(pcici_t, pcidi_t); +static void pcic_pci_attach(pcici_t, int); + +static void pd6832_legacy_init(pcici_t tag, int unit); + +static struct pci_device pcic_pci_driver = { + "pcic", + pcic_pci_probe, + pcic_pci_attach, + &pcic_pci_count, + NULL +}; + +DATA_SET(pcidevice_set, pcic_pci_driver); + +/* + * Return the ID string for the controller if the vendor/product id + * matches, NULL otherwise. + */ +static const char * +pcic_pci_probe(pcici_t tag, pcidi_t type) +{ + switch (type) { + case PCI_DEVICE_ID_PCIC_CLPD6832: + return ("Cirrus Logic PD6832 PCI/CardBus Bridge"); + case PCI_DEVICE_ID_PCIC_TI1130: + return ("TI PCI-1130 PCI-CardBus Bridge"); + case PCI_DEVICE_ID_PCIC_TI1131: + return ("TI PCI-1131 PCI-CardBus Bridge"); + case PCI_DEVICE_ID_PCIC_TI1220: + return ("TI PCI-1220 PCI-CardBus Bridge"); + case PCI_DEVICE_ID_PCIC_TI1221: + return ("TI PCI-1221 PCI-CardBus Bridge"); + case PCI_DEVICE_ID_PCIC_TI1250: + return ("TI PCI-1250 PCI-CardBus Bridge"); + case PCI_DEVICE_ID_PCIC_TI1251: + return ("TI PCI-1251 PCI-CardBus Bridge"); + case PCI_DEVICE_ID_TOSHIBA_TOPIC95: + return ("Toshiba ToPIC95 PCI-CardBus Bridge"); + case PCI_DEVICE_ID_TOSHIBA_TOPIC97: + return ("Toshiba ToPIC97 PCI-CardBus Bridge"); + case PCI_DEVICE_ID_RICOH_RL5C465: + return ("Ricoh RL5C465 PCI-CardBus Brige"); + case PCI_DEVICE_ID_RICOH_RL5C475: + return ("Ricoh RL5C475 PCI-CardBus Brige"); + case PCI_DEVICE_ID_RICOH_RL5C476: + return ("Ricoh RL5C476 PCI-CardBus Brige"); + case PCI_DEVICE_ID_RICOH_RL5C478: + return ("Ricoh RL5C478 PCI-CardBus Brige"); + /* 16bit PC-card bridges */ + case PCI_DEVICE_ID_PCIC_CLPD6729: + return ("Cirrus Logic PD6729/6730 PC-Card Controller"); + case PCI_DEVICE_ID_PCIC_OZ6729: + return ("O2micro OZ6729 PC-Card Bridge"); + case PCI_DEVICE_ID_PCIC_OZ6730: + return ("O2micro OZ6730 PC-Card Bridge"); + + default: + break; + } + return (NULL); +} + + +/* + * General PCI based card dispatch routine. Right now + * it only understands the CL-PD6832. + */ +static void +pcic_pci_attach(pcici_t config_id, int unit) +{ + u_long pcic_type; /* The vendor id of the PCI pcic */ + + pcic_type = pci_conf_read(config_id, PCI_ID_REG); + + switch (pcic_type) { + case PCI_DEVICE_ID_PCIC_CLPD6832: + pd6832_legacy_init(config_id, unit); + break; + } + + if (bootverbose) { + int i, j; + u_char *p; + u_long *pl; + + printf("PCI Config space:\n"); + for (j = 0; j < 0x98; j += 16) { + printf("%02x: ", j); + for (i = 0; i < 16; i += 4) + printf(" %08lx", pci_conf_read(config_id, i+j)); + printf("\n"); + } + p = (u_char *)pmap_mapdev(pci_conf_read(config_id, 0x10), + 0x1000); + pl = (u_long *)p; + printf("Cardbus Socket registers:\n"); + printf("00: "); + for (i = 0; i < 4; i += 1) + printf(" %08lx:", pl[i]); + printf("\n10: "); + for (i = 4; i < 8; i += 1) + printf(" %08lx:", pl[i]); + printf("\nExCa registers:\n"); + for (i = 0; i < 0x40; i += 16) + printf("%02x: %16D\n", i, p + 0x800 + i, " "); + } +} + +/* + * Set up the CL-PD6832 to look like a ISA based PCMCIA chip (a + * PD672X). This routine is called once per PCMCIA socket. + */ +static void +pd6832_legacy_init(pcici_t tag, int unit) +{ + u_long bcr; /* to set interrupts */ + u_short io_port; /* the io_port to map this slot on */ + static int num6832 = 0; /* The number of 6832s initialized */ + + /* + * Some BIOS leave the legacy address uninitialized. This + * insures that the PD6832 puts itself where the driver will + * look. We assume that multiple 6832's should be laid out + * sequentially. We only initialize the first socket's legacy port, + * the other is a dummy. + */ + io_port = PCIC_INDEX_0 + num6832 * CLPD6832_NUM_REGS; + if (unit == 0) + pci_conf_write(tag, CLPD6832_LEGACY_16BIT_IOADDR, + io_port & ~PCI_MAP_IO); + + /* + * I think this should be a call to pci_map_port, but that + * routine won't map regiaters above 0x28, and the register we + * need to map is 0x44. + */ + io_port = pci_conf_read(tag, CLPD6832_LEGACY_16BIT_IOADDR) + & ~PCI_MAP_IO; + + /* + * Configure the first I/O window to contain CLPD6832_NUM_REGS + * words and deactivate the second by setting the limit lower + * than the base. + */ + pci_conf_write(tag, CLPD6832_IO_BASE0, io_port | 1); + pci_conf_write(tag, CLPD6832_IO_LIMIT0, + (io_port + CLPD6832_NUM_REGS) | 1); + + pci_conf_write(tag, CLPD6832_IO_BASE1, (io_port + 0x20) | 1); + pci_conf_write(tag, CLPD6832_IO_LIMIT1, io_port | 1 ); + + /* + * Set default operating mode (I/O port space) and allocate + * this socket to the current unit. + */ + pci_conf_write(tag, PCI_COMMAND_STATUS_REG, CLPD6832_COMMAND_DEFAULTS ); + pci_conf_write(tag, CLPD6832_SOCKET, unit); + + /* + * Set up the card inserted/card removed interrupts to come + * through the isa IRQ. + */ + bcr = pci_conf_read(tag, CLPD6832_BRIDGE_CONTROL); + bcr |= (CLPD6832_BCR_ISA_IRQ|CLPD6832_BCR_MGMT_IRQ_ENA); + pci_conf_write(tag, CLPD6832_BRIDGE_CONTROL, bcr); + + /* After initializing 2 sockets, the chip is fully configured */ + if (unit == 1) + num6832++; + + if (bootverbose) + printf("CardBus: Legacy PC-card 16bit I/O address [0x%x]\n", + io_port); +} +#endif /* NPCI > 0 */ diff --git a/pool/shard008/C/0130234_dw9712_act.c b/pool/shard008/C/0130234_dw9712_act.c new file mode 100644 index 0000000000000000000000000000000000000000..546cffabee6b56cb30f2291398e2238559495c9b --- /dev/null +++ b/pool/shard008/C/0130234_dw9712_act.c @@ -0,0 +1,277 @@ +/* Copyright (c) 2012, Code Aurora Forum. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 and + * only version 2 as published by the Free Software Foundation. + * + * 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. + * + */ + +#include "msm_actuator.h" +#include "msm_camera_i2c.h" + +#define DW9712_TOTAL_STEPS_NEAR_TO_FAR 32 +DEFINE_MUTEX(dw9712_act_mutex); +static struct msm_actuator_ctrl_t dw9712_act_t; + +static struct region_params_t g_regions[] = { + /* step_bound[0] - macro side boundary + * step_bound[1] - infinity side boundary + */ + /* Region 1 */ + { + .step_bound = {DW9712_TOTAL_STEPS_NEAR_TO_FAR, 0}, + .code_per_step = 2, + }, +}; + +static uint16_t g_scenario[] = { + /* MOVE_NEAR and MOVE_FAR dir*/ + DW9712_TOTAL_STEPS_NEAR_TO_FAR, +}; + +static int32_t dw9712_af_i2c_txdata(unsigned short saddr, + unsigned char *txdata, int length, + struct msm_actuator_ctrl_t *a_ctrl) +{ + struct i2c_msg msg[] = { + { + .addr = saddr, + .flags = 0, + .len = length, + .buf = txdata, + }, + }; + if (i2c_transfer(a_ctrl->i2c_client.client->adapter, msg, 1) < 0) { + pr_err("s5k4e1_af_i2c_txdata faild 0x%x\n", saddr); + return -EIO; + } + + return 0; +} + +static int32_t dw9712_af_i2c_write_b_sensor(struct msm_actuator_ctrl_t *a_ctrl, + uint8_t waddr, uint8_t bdata) +{ + int32_t rc = -EFAULT; + unsigned char buf[2]; + + memset(buf, 0, sizeof(buf)); + buf[0] = waddr; + buf[1] = bdata; + rc = dw9712_af_i2c_txdata(a_ctrl->i2c_addr, buf, 2, a_ctrl); + if (rc < 0) { + pr_err("i2c_write_b failed, addr = 0x%x, val = 0x%x!\n", + waddr, bdata); + } + return rc; +} + +static int32_t dw9712_wrapper_i2c_write(struct msm_actuator_ctrl_t *a_ctrl, + int16_t next_lens_position, void *params) +{ + uint8_t msb, lsb; + + msb = (next_lens_position & 0xFF00) >> 8; + lsb = next_lens_position & 0xFF; + dw9712_af_i2c_write_b_sensor(a_ctrl, msb, lsb); + + return 0; +} + +int32_t msm_dw9712_act_move_focus( + struct msm_actuator_ctrl_t *a_ctrl, + int dir, + int32_t num_steps) +{ + int32_t rc = 0; + int8_t sign_dir = 0; + int16_t dest_step_pos = 0; + uint8_t code_val_msb, code_val_lsb; + uint16_t code_val; + + LINFO("%s called, dir %d, num_steps %d\n", + __func__, + dir, + num_steps); + + /* Determine sign direction */ + if (dir == MOVE_NEAR) + sign_dir = 16; + else if (dir == MOVE_FAR) + sign_dir = -16; + else { + pr_err("Illegal focus direction\n"); + rc = -EINVAL; + return rc; + } + + /* Determine destination step position */ + dest_step_pos = a_ctrl->curr_step_pos + + (sign_dir * num_steps); + + if (dest_step_pos < 0) + dest_step_pos = 0; + else if (dest_step_pos > 1023) + dest_step_pos = 1023; + + if (dest_step_pos == a_ctrl->curr_step_pos) + return rc; + + code_val_msb = dest_step_pos >> 4; + code_val_lsb = (dest_step_pos & 0x000F) << 4; + code_val = (code_val_msb << 8) | (code_val_lsb); + rc = dw9712_wrapper_i2c_write(a_ctrl, code_val, NULL); + if (rc >= 0) { + rc = 0; + a_ctrl->curr_step_pos = dest_step_pos; + } + return 0; +} + +static int32_t dw9712_set_default_focus( + struct msm_actuator_ctrl_t *a_ctrl) +{ + int32_t rc = 0; + + if (!a_ctrl->step_position_table) + a_ctrl->func_tbl.actuator_init_table(a_ctrl); + + if (a_ctrl->curr_step_pos != 0) { + rc = a_ctrl->func_tbl.actuator_move_focus(a_ctrl, + MOVE_FAR, a_ctrl->curr_step_pos); + a_ctrl->curr_step_pos = 0; + } else + rc = dw9712_wrapper_i2c_write(a_ctrl, 0x00, NULL); + if (rc >= 0) + rc = 0; + return rc; +} + +static const struct i2c_device_id dw9712_act_i2c_id[] = { + {"dw9712_act", (kernel_ulong_t)&dw9712_act_t}, + { } +}; + +static int dw9712_act_config(void __user *argp) +{ + LINFO("%s called\n", __func__); + return (int) msm_actuator_config(&dw9712_act_t, argp); +} + +static int dw9712_i2c_add_driver_table(void) +{ + LINFO("%s called\n", __func__); + return (int) msm_actuator_init_table(&dw9712_act_t); +} + +static struct i2c_driver dw9712_act_i2c_driver = { + .id_table = dw9712_act_i2c_id, + .probe = msm_actuator_i2c_probe, + .remove = __exit_p(dw9712_act_i2c_remove), + .driver = { + .name = "dw9712_act", + }, +}; + +static int __init dw9712_i2c_add_driver(void) +{ + int rc = 0; + + LINFO("%s called :%x\n", __func__, dw9712_act_t.i2c_addr); + rc = i2c_add_driver(dw9712_act_t.i2c_driver); + LINFO("%s called:%d %x\n", __func__, rc, dw9712_act_t.i2c_addr); + return rc; +} + +static struct v4l2_subdev_core_ops dw9712_act_subdev_core_ops; + +static struct v4l2_subdev_ops dw9712_act_subdev_ops = { + .core = &dw9712_act_subdev_core_ops, +}; + +static int32_t dw9712_act_create_subdevice( + void *board_info, + void *sdev) +{ + int rc = 0; + + struct msm_actuator_info *ptr; + LINFO("%s called\n", __func__); + + ptr = board_info; + dw9712_act_t.vcm_pwd = ptr->vcm_pwd; + dw9712_act_t.vcm_enable = ptr->vcm_enable; + LINFO("vcm info: %x %x\n", dw9712_act_t.vcm_pwd, + dw9712_act_t.vcm_enable); + if (dw9712_act_t.vcm_enable) { + rc = gpio_request(dw9712_act_t.vcm_pwd, "dw9712_af"); + if (!rc) { + LINFO("Enable VCM PWD\n"); + gpio_direction_output(dw9712_act_t.vcm_pwd, 1); + } + } + return (int) msm_actuator_create_subdevice(&dw9712_act_t, + ptr->board_info, + (struct v4l2_subdev *)sdev); +} + +static struct msm_actuator_ctrl_t dw9712_act_t = { + .i2c_driver = &dw9712_act_i2c_driver, + .i2c_addr = 0x8C, + .act_v4l2_subdev_ops = &dw9712_act_subdev_ops, + .actuator_ext_ctrl = { + .a_init_table = dw9712_i2c_add_driver_table, + .a_create_subdevice = dw9712_act_create_subdevice, + .a_config = dw9712_act_config, + }, + + .i2c_client = { + .addr_type = MSM_CAMERA_I2C_WORD_ADDR, + }, + + .set_info = { + .total_steps = DW9712_TOTAL_STEPS_NEAR_TO_FAR, + }, + + .curr_step_pos = 0, + .curr_region_index = 0, + .initial_code = 0x0, + .actuator_mutex = &dw9712_act_mutex, + + .func_tbl = { + .actuator_init_table = msm_actuator_init_table, + .actuator_move_focus = msm_dw9712_act_move_focus, + .actuator_set_default_focus = dw9712_set_default_focus, + .actuator_i2c_write = dw9712_wrapper_i2c_write, + }, + + .get_info = { + .focal_length_num = 46, + .focal_length_den = 10, + .f_number_num = 265, + .f_number_den = 100, + .f_pix_num = 14, + .f_pix_den = 10, + .total_f_dist_num = 197681, + .total_f_dist_den = 1000, + }, + + /* Initialize scenario */ + .ringing_scenario[MOVE_NEAR] = g_scenario, + .scenario_size[MOVE_NEAR] = ARRAY_SIZE(g_scenario), + .ringing_scenario[MOVE_FAR] = g_scenario, + .scenario_size[MOVE_FAR] = ARRAY_SIZE(g_scenario), + + /* Initialize region params */ + .region_params = g_regions, + .region_size = ARRAY_SIZE(g_regions), +}; + +subsys_initcall(dw9712_i2c_add_driver); +MODULE_DESCRIPTION("DW9712 actuator"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard008/C/0130237_CWE78_OS_Command_Injection__char_connect_socket_w32_spawnvp_54a.c b/pool/shard008/C/0130237_CWE78_OS_Command_Injection__char_connect_socket_w32_spawnvp_54a.c new file mode 100644 index 0000000000000000000000000000000000000000..48e7e73ad0230bd9f90eff9f08bb5bb2c52518b2 --- /dev/null +++ b/pool/shard008/C/0130237_CWE78_OS_Command_Injection__char_connect_socket_w32_spawnvp_54a.c @@ -0,0 +1,188 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__char_connect_socket_w32_spawnvp_54a.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-54a.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: connect_socket Read data using a connect socket (client side) + * GoodSource: Fixed string + * Sink: w32_spawnvp + * BadSink : execute command with spawnvp + * Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files + * + * */ + +#include "std_testcase.h" + +#include + +#ifdef _WIN32 +#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT "cmd.exe" +#define COMMAND_ARG1 "/c" +#define COMMAND_ARG2 "dir " +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH "/bin/sh" +#define COMMAND_INT "sh" +#define COMMAND_ARG1 "-c" +#define COMMAND_ARG2 "ls " +#define COMMAND_ARG3 data +#endif + +#ifdef _WIN32 +#include +#include +#include +#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ +#define CLOSE_SOCKET closesocket +#else /* NOT _WIN32 */ +#include +#include +#include +#include +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define CLOSE_SOCKET close +#define SOCKET int +#endif + +#define TCP_PORT 27015 +#define IP_ADDRESS "127.0.0.1" + +#include + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE78_OS_Command_Injection__char_connect_socket_w32_spawnvp_54b_badSink(char * data); + +void CWE78_OS_Command_Injection__char_connect_socket_w32_spawnvp_54_bad() +{ + char * data; + char dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + struct sockaddr_in service; + char *replace; + SOCKET connectSocket = INVALID_SOCKET; + size_t dataLen = strlen(data); + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + /* POTENTIAL FLAW: Read data using a connect socket */ + connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (connectSocket == INVALID_SOCKET) + { + break; + } + memset(&service, 0, sizeof(service)); + service.sin_family = AF_INET; + service.sin_addr.s_addr = inet_addr(IP_ADDRESS); + service.sin_port = htons(TCP_PORT); + if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + /* Abort on error or the connection was closed, make sure to recv one + * less char than is in the recv_buf in order to append a terminator */ + /* Abort on error or the connection was closed */ + recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0); + if (recvResult == SOCKET_ERROR || recvResult == 0) + { + break; + } + /* Append null terminator */ + data[dataLen + recvResult / sizeof(char)] = '\0'; + /* Eliminate CRLF */ + replace = strchr(data, '\r'); + if (replace) + { + *replace = '\0'; + } + replace = strchr(data, '\n'); + if (replace) + { + *replace = '\0'; + } + } + while (0); + if (connectSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(connectSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + CWE78_OS_Command_Injection__char_connect_socket_w32_spawnvp_54b_badSink(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good function declaration */ +void CWE78_OS_Command_Injection__char_connect_socket_w32_spawnvp_54b_goodG2BSink(char * data); + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + char * data; + char dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + /* FIX: Append a fixed string to data (not user / external input) */ + strcat(data, "*.*"); + CWE78_OS_Command_Injection__char_connect_socket_w32_spawnvp_54b_goodG2BSink(data); +} + +void CWE78_OS_Command_Injection__char_connect_socket_w32_spawnvp_54_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__char_connect_socket_w32_spawnvp_54_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__char_connect_socket_w32_spawnvp_54_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard008/C/0130241_dsp.c b/pool/shard008/C/0130241_dsp.c new file mode 100644 index 0000000000000000000000000000000000000000..0bf8b6b1a290033476513340f4ae399c9da02b95 --- /dev/null +++ b/pool/shard008/C/0130241_dsp.c @@ -0,0 +1,100 @@ + +#include "asm/arch-m1/firm/regs.h" +#include "asm/arch-m1/firm/io.h" + +#include "dsp_firmware.h" + +#define S_1K (1024) +#define S_1M (S_1K*S_1K) + +#define AUDIO_DSP_MEM_SIZE S_1M +#define AUDIO_DSP_START_PHY_ADDR 0xa6000000 +#define AUDIO_DSP_START_ADDR AUDIO_DSP_START_PHY_ADDR//((SYS_MEM_START+SYS_MEM_SIZE)-AUDIO_DSP_MEM_SIZE) +#define AUDIO_DSP_END_ADDR ((AUDIO_DSP_START_ADDR+AUDIO_DSP_MEM_SIZE)) +#define REG_MEM_SIZE (S_1K*4) + + + + +#define DSP_REG_OFFSET (AUDIO_DSP_START_ADDR+ AUDIO_DSP_MEM_SIZE-REG_MEM_SIZE) +#define DSP_REG_END (AUDIO_DSP_START_ADDR+ AUDIO_DSP_MEM_SIZE-4) +#define DSP_REG(x) (DSP_REG_OFFSET | ((x)<<5)) + +#define DSP_ARM_REF_CLK_VAL DSP_REG(16) + +#define DSP_WD(reg,val) ({(*((volatile unsigned long *)(reg)))=val;}) + + +#define DSP_MEM_START DSP_REG(7) +#define DSP_MEM_END DSP_REG(8) + +#define DSP_STATUS DSP_REG(0) +#define DSP_STACK_START DSP_REG(3) +#define DSP_STACK_END DSP_REG(4) +#define DSP_GP_STACK_START DSP_REG(5) +#define DSP_GP_STACK_END DSP_REG(6) + +#define DSP_STATUS_HALT ('H'<<24 | 'a'<<16|'l'<<8 |'t') + + +static int dsp_start=0; + +int start_dsp() +{ + + + unsigned long clk; + + if(dsp_start) + return 0; + memcpy((void *)AUDIO_DSP_START_PHY_ADDR,dsp_firmware,sizeof(dsp_firmware)); + clk=READ_CBUS_REG_BITS(PREG_CTLREG0_ADDR,4,5); + clk=clk*1000*1000; + DSP_WD(DSP_MEM_START,0xa7020000); + DSP_WD(DSP_MEM_END,0xa7120000); + + DSP_WD(DSP_STACK_START,0xa7000000); + DSP_WD(DSP_STACK_END,0xa7010000); + + DSP_WD(DSP_GP_STACK_START,0xa7010000); + DSP_WD(DSP_GP_STACK_END,0xa7020000); + + + CLEAR_MPEG_REG_MASK(AUD_ARC_CTL, (0xfff << 4)); + // SET_MPEG_REG_MASK(SDRAM_CTL0,1);//arc mapping to ddr memory + SET_MPEG_REG_MASK(AUD_ARC_CTL, ((AUDIO_DSP_START_PHY_ADDR)>> 20) << 4); + + + SET_MPEG_REG_MASK(AUD_ARC_CTL, 1); + CLEAR_MPEG_REG_MASK(AUD_ARC_CTL, 1); + +#if 0 +#define RESET_AUD_ARC (1<<13) + SET_MPEG_REG_MASK(RESET2_REGISTER, RESET_AUD_ARC); + SET_MPEG_REG_MASK(RESET2_REGISTER, RESET_AUD_ARC); + SET_MPEG_REG_MASK(RESET2_REGISTER, RESET_AUD_ARC); +#endif + //clk=clk_get_sys("a9_clk", NULL); + DSP_WD(DSP_ARM_REF_CLK_VAL, clk); + //flush_cache(0x84000000, S_1M); + printf("starting dsp...\n"); + dsp_start=1; + return 0; +} + +int stop_dsp() +{ + if(!dsp_start) + return 0; + CLEAR_MPEG_REG_MASK(AUD_ARC_CTL, 1); +#define RESET_AUD_ARC (1<<13) + SET_MPEG_REG_MASK(RESET2_REGISTER, RESET_AUD_ARC); + DSP_WD(DSP_STATUS, DSP_STATUS_HALT); + dsp_start=0; + return 0; + + +} + + + diff --git a/pool/shard008/C/0130244_main.c b/pool/shard008/C/0130244_main.c new file mode 100644 index 0000000000000000000000000000000000000000..d26e7e5d83317d727ba220515ffbe39d5882086a --- /dev/null +++ b/pool/shard008/C/0130244_main.c @@ -0,0 +1,78 @@ +#include "kernel.h" +#include "kdata.h" +#include "printf.h" +#include "soc/gpio_struct.h" +#include "kernel-esp32.def" +#include "xtos.h" + +#define LED 2 + +uint8_t sys_cpu; +uint8_t sys_cpu_feat; + +void set_cpu_type(void) +{ + sys_cpu = A_LX6; +} + +/* On entry we're running on the app core default stack, which is owned by + * XTOS. We'll switch to a process stack when the first process starts and then + * never touch it again. + */ +void __attribute__((noreturn)) appcore_main(void) { + gpio_dev_t* gpio = &GPIO; + gpio->func_out_sel_cfg[LED].func_sel = 0x100; + gpio->enable_w1ts = 1<out_w1ts = 1< + * + * Licensed under the GNU Lesser General Public License Version 2.1 + * + * 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. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include + +static gboolean +pk_socket_example_accept_connection_cb (GSocket *socket, GIOCondition condition, gpointer user_data) +{ + gsize len; + gchar buffer[1024]; + GMainLoop *loop = (GMainLoop *) user_data; + g_autoptr(GError) error = NULL; + + /* the helper process exited */ + if ((condition & G_IO_HUP) > 0) { + g_warning ("socket was disconnected"); + g_main_loop_quit (loop); + return FALSE; + } + + /* there is data */ + if ((condition & G_IO_IN) > 0) { + len = g_socket_receive (socket, buffer, 1024, NULL, &error); + if (error != NULL) { + g_warning ("failed to get data: %s", error->message); + return FALSE; + } + if (len == 0) + return TRUE; + g_debug ("got data: %s : %" G_GSIZE_FORMAT, buffer, len); + } + return TRUE; +} + +gint +main (void) +{ + gboolean ret; + gsize wrote; + const gchar *buffer = "ping\n"; + const gchar *socket_filename = "/tmp/pk-self-test.socket"; + GSource *source; + g_autoptr(GError) error = NULL; + g_autoptr(GMainLoop) loop = NULL; + g_autoptr(GSocketAddress) address = NULL; + g_autoptr(GSocket) socket = NULL; + + loop = g_main_loop_new (NULL, FALSE); + + /* create socket */ + socket = g_socket_new (G_SOCKET_FAMILY_UNIX, G_SOCKET_TYPE_STREAM, G_SOCKET_PROTOCOL_DEFAULT, &error); + if (socket == NULL) { + g_warning ("failed to create socket: %s", error->message); + return 1; + } + g_socket_set_blocking (socket, FALSE); + g_socket_set_keepalive (socket, TRUE); + + /* connect to it */ + address = g_unix_socket_address_new (socket_filename); + ret = g_socket_connect (socket, address, NULL, &error); + if (!ret) { + g_warning ("failed to connect to socket: %s", error->message); + return 1; + } + + /* socket has data */ + source = g_socket_create_source (socket, G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL, NULL); + g_source_set_callback (source, G_SOURCE_FUNC (pk_socket_example_accept_connection_cb), loop, NULL); + g_source_attach (source, NULL); + + /* send some data */ + wrote = g_socket_send (socket, buffer, 5, NULL, &error); + if (wrote != 5) { + g_warning ("failed to write 5 bytes"); + return 1; + } + + /* run main loop */ + g_debug ("running main loop"); + g_main_loop_run (loop); + return 0; +} diff --git a/pool/shard008/C/0130248_basic.c b/pool/shard008/C/0130248_basic.c new file mode 100644 index 0000000000000000000000000000000000000000..4a6cffa68703edbc2b7d9f07182b74b2a09152df --- /dev/null +++ b/pool/shard008/C/0130248_basic.c @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2000-2006, Darren Hiebert, Elias Pschernig + * + * This source code is released for free distribution under the terms of the + * GNU General Public License version 2 or (at your option) any later version. + * + * This module contains functions for generating tags for BlitzBasic + * (BlitzMax), PureBasic and FreeBasic language files. For now, this is kept + * quite simple - but feel free to ask for more things added any time - + * patches are of course most welcome. + */ + +/* + * INCLUDE FILES + */ +#include "general.h" /* must always come first */ + +#include + +#include "parse.h" +#include "read.h" +#include "routines.h" +#include "vstring.h" + +/* + * DATA DEFINITIONS + */ +typedef enum { + K_CONST, + K_FUNCTION, + K_LABEL, + K_TYPE, + K_VARIABLE, + K_ENUM +} BasicKind; + +typedef struct { + char const *token; + BasicKind kind; + int skip; +} KeyWord; + +static kindDefinition BasicKinds[] = { + {true, 'c', "constant", "constants"}, + {true, 'f', "function", "functions"}, + {true, 'l', "label", "labels"}, + {true, 't', "type", "types"}, + {true, 'v', "variable", "variables"}, + {true, 'g', "enum", "enumerations"} +}; + +static KeyWord blitzbasic_keywords[] = { + {"const", K_CONST, 0}, + {"global", K_VARIABLE, 0}, + {"dim", K_VARIABLE, 0}, + {"function", K_FUNCTION, 0}, + {"type", K_TYPE, 0}, + {NULL, 0, 0} +}; + +static KeyWord purebasic_keywords[] = { + {"newlist", K_VARIABLE, 0}, + {"global", K_VARIABLE, 0}, + {"dim", K_VARIABLE, 0}, + {"procedure", K_FUNCTION, 0}, + {"interface", K_TYPE, 0}, + {"structure", K_TYPE, 0}, + {NULL, 0, 0} +}; + +static KeyWord freebasic_keywords[] = { + {"const", K_CONST, 0}, + {"dim as", K_VARIABLE, 1}, + {"dim", K_VARIABLE, 0}, + {"common", K_VARIABLE, 0}, + {"function", K_FUNCTION, 0}, + {"sub", K_FUNCTION, 0}, + {"private sub", K_FUNCTION, 0}, + {"public sub", K_FUNCTION, 0}, + {"private function", K_FUNCTION, 0}, + {"public function", K_FUNCTION, 0}, + {"type", K_TYPE, 0}, + {"enum", K_ENUM, 0}, + {NULL, 0, 0} +}; + +/* + * FUNCTION DEFINITIONS + */ + +/* Match the name of a tag (function, variable, type, ...) starting at pos. */ +static char const *extract_name (char const *pos, vString * name) +{ + while (isspace (*pos)) + pos++; + vStringClear (name); + for (; *pos && !isspace (*pos) && *pos != '(' && *pos != ','; pos++) + vStringPut (name, *pos); + return pos; +} + +/* Match a keyword starting at p (case insensitive). */ +static int match_keyword (const char *p, KeyWord const *kw) +{ + vString *name; + size_t i; + int j; + for (i = 0; i < strlen (kw->token); i++) + { + if (tolower (p[i]) != kw->token[i]) + return 0; + } + name = vStringNew (); + p += i; + for (j = 0; j < 1 + kw->skip; j++) + { + p = extract_name (p, name); + } + makeSimpleTag (name, kw->kind); + vStringDelete (name); + return 1; +} + +/* Match a "label:" style label. */ +static void match_colon_label (char const *p) +{ + char const *end = p + strlen (p) - 1; + while (isspace (*end)) + end--; + if (*end == ':') + { + vString *name = vStringNew (); + vStringNCatS (name, p, end - p); + makeSimpleTag (name, K_LABEL); + vStringDelete (name); + } +} + +/* Match a ".label" style label. */ +static void match_dot_label (char const *p) +{ + if (*p == '.') + { + vString *name = vStringNew (); + extract_name (p + 1, name); + makeSimpleTag (name, K_LABEL); + vStringDelete (name); + } +} + +static void findBasicTags (void) +{ + const char *line; + const char *extension = fileExtension (getInputFileName ()); + KeyWord *keywords; + + if (strcmp (extension, "bb") == 0) + keywords = blitzbasic_keywords; + else if (strcmp (extension, "pb") == 0) + keywords = purebasic_keywords; + else + keywords = freebasic_keywords; + + while ((line = (const char *) readLineFromInputFile ()) != NULL) + { + const char *p = line; + KeyWord const *kw; + + while (isspace (*p)) + p++; + + /* Empty line? */ + if (!*p) + continue; + + /* REM comment? */ + if (strncasecmp (p, "REM", 3) == 0 && + (isspace (*(p + 3)) || *(p + 3) == '\0')) + continue; + + /* Single-quote comment? */ + if (*p == '\'') + continue; + + /* In Basic, keywords always are at the start of the line. */ + for (kw = keywords; kw->token; kw++) + if (match_keyword (p, kw)) break; + + /* Is it a label? */ + if (strcmp (extension, "bb") == 0) + match_dot_label (p); + else + match_colon_label (p); + } +} + +parserDefinition *BasicParser (void) +{ + static char const *extensions[] = { "bas", "bi", "bm", "bb", "pb", NULL }; + parserDefinition *def = parserNew ("Basic"); + def->kindTable = BasicKinds; + def->kindCount = ARRAY_SIZE (BasicKinds); + def->extensions = extensions; + def->parser = findBasicTags; + return def; +} diff --git a/pool/shard008/C/0130250_unlink_3.c b/pool/shard008/C/0130250_unlink_3.c new file mode 100644 index 0000000000000000000000000000000000000000..800823850dcec20402cb4c36ea09c2ca1db8ca9e --- /dev/null +++ b/pool/shard008/C/0130250_unlink_3.c @@ -0,0 +1,57 @@ +#include +#include +#include +#include + +#define MAX_BUFF_SIZE 255 +char g_workgroup[MAX_BUFF_SIZE]; +char g_username[MAX_BUFF_SIZE]; +char g_password[MAX_BUFF_SIZE]; +char g_server[MAX_BUFF_SIZE]; +char g_share[MAX_BUFF_SIZE]; + + +static void auth_fn(const char *server, const char *share, char *workgroup, int wgmaxlen, + char *username, int unmaxlen, char *password, int pwmaxlen) +{ + + strncpy(workgroup, g_workgroup, wgmaxlen - 1); + + strncpy(username, g_username, unmaxlen - 1); + + strncpy(password, g_password, pwmaxlen - 1); + + strcpy(g_server, server); + strcpy(g_share, share); + +} + +int main(int argc, char** argv) +{ + int err = -1; + int fd = 0; + char url[MAX_BUFF_SIZE]; + + bzero(g_workgroup,MAX_BUFF_SIZE); + bzero(url,MAX_BUFF_SIZE); + + if ( argc == 5 ) + { + + strncpy(g_workgroup,argv[1],strlen(argv[1])); + strncpy(g_username,argv[2],strlen(argv[2])); + strncpy(g_password,argv[3],strlen(argv[3])); + strncpy(url,argv[4],strlen(argv[4])); + + smbc_init(auth_fn, 0); + fd = smbc_mkdir(url, 0666); + smbc_unlink(url); + + err = errno; + + } + + return err; + +} + diff --git a/pool/shard008/C/0130252_ike_auth_lifetime.c b/pool/shard008/C/0130252_ike_auth_lifetime.c new file mode 100644 index 0000000000000000000000000000000000000000..75ff351684098a3182aad22c829d0b0f15226cef --- /dev/null +++ b/pool/shard008/C/0130252_ike_auth_lifetime.c @@ -0,0 +1,182 @@ +/* + * Copyright (C) 2007 Martin Willi + * Hochschule fuer Technik Rapperswil + * + * 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. See . + * + * 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. + */ + +#include "ike_auth_lifetime.h" + +#include + +#include +#include + + +typedef struct private_ike_auth_lifetime_t private_ike_auth_lifetime_t; + +/** + * Private members of a ike_auth_lifetime_t task. + */ +struct private_ike_auth_lifetime_t { + + /** + * Public methods and task_t interface. + */ + ike_auth_lifetime_t public; + + /** + * Assigned IKE_SA. + */ + ike_sa_t *ike_sa; +}; + +/** + * add the AUTH_LIFETIME notify to the message + */ +static void add_auth_lifetime(private_ike_auth_lifetime_t *this, message_t *message) +{ + chunk_t chunk; + u_int32_t lifetime; + + lifetime = this->ike_sa->get_statistic(this->ike_sa, STAT_REAUTH); + if (lifetime) + { + lifetime -= time_monotonic(NULL); + chunk = chunk_from_thing(lifetime); + *(u_int32_t*)chunk.ptr = htonl(lifetime); + message->add_notify(message, FALSE, AUTH_LIFETIME, chunk); + } +} + +/** + * read notifys from message and evaluate them + */ +static void process_payloads(private_ike_auth_lifetime_t *this, message_t *message) +{ + notify_payload_t *notify; + chunk_t data; + u_int32_t lifetime; + + notify = message->get_notify(message, AUTH_LIFETIME); + if (notify) + { + data = notify->get_notification_data(notify); + lifetime = ntohl(*(u_int32_t*)data.ptr); + this->ike_sa->set_auth_lifetime(this->ike_sa, lifetime); + } +} + +/** + * Implementation of task_t.process for initiator + */ +static status_t build_i(private_ike_auth_lifetime_t *this, message_t *message) +{ + if (message->get_exchange_type(message) == INFORMATIONAL) + { + add_auth_lifetime(this, message); + return SUCCESS; + } + return NEED_MORE; +} + +/** + * Implementation of task_t.process for responder + */ +static status_t process_r(private_ike_auth_lifetime_t *this, message_t *message) +{ + if (message->get_exchange_type(message) == INFORMATIONAL) + { + process_payloads(this, message); + return SUCCESS; + } + return NEED_MORE; +} + +/** + * Implementation of task_t.build for responder + */ +static status_t build_r(private_ike_auth_lifetime_t *this, message_t *message) +{ + if (message->get_exchange_type(message) == IKE_AUTH && + this->ike_sa->get_state(this->ike_sa) == IKE_ESTABLISHED) + { + add_auth_lifetime(this, message); + return SUCCESS; + } + return NEED_MORE; +} + +/** + * Implementation of task_t.process for initiator + */ +static status_t process_i(private_ike_auth_lifetime_t *this, message_t *message) +{ + if (message->get_exchange_type(message) == IKE_AUTH && + this->ike_sa->get_state(this->ike_sa) == IKE_ESTABLISHED) + { + process_payloads(this, message); + return SUCCESS; + } + return NEED_MORE; +} + +/** + * Implementation of task_t.get_type + */ +static task_type_t get_type(private_ike_auth_lifetime_t *this) +{ + return IKE_AUTH_LIFETIME; +} + +/** + * Implementation of task_t.migrate + */ +static void migrate(private_ike_auth_lifetime_t *this, ike_sa_t *ike_sa) +{ + this->ike_sa = ike_sa; +} + +/** + * Implementation of task_t.destroy + */ +static void destroy(private_ike_auth_lifetime_t *this) +{ + free(this); +} + +/* + * Described in header. + */ +ike_auth_lifetime_t *ike_auth_lifetime_create(ike_sa_t *ike_sa, bool initiator) +{ + private_ike_auth_lifetime_t *this = malloc_thing(private_ike_auth_lifetime_t); + + this->public.task.get_type = (task_type_t(*)(task_t*))get_type; + this->public.task.migrate = (void(*)(task_t*,ike_sa_t*))migrate; + this->public.task.destroy = (void(*)(task_t*))destroy; + + if (initiator) + { + this->public.task.build = (status_t(*)(task_t*,message_t*))build_i; + this->public.task.process = (status_t(*)(task_t*,message_t*))process_i; + } + else + { + this->public.task.build = (status_t(*)(task_t*,message_t*))build_r; + this->public.task.process = (status_t(*)(task_t*,message_t*))process_r; + } + + this->ike_sa = ike_sa; + + return &this->public; +} + diff --git a/pool/shard008/C/0130254_ser-pipe.c b/pool/shard008/C/0130254_ser-pipe.c new file mode 100644 index 0000000000000000000000000000000000000000..9c5b99b45c980d00a46842994470d18106076392 --- /dev/null +++ b/pool/shard008/C/0130254_ser-pipe.c @@ -0,0 +1,238 @@ +/* Serial interface for a pipe to a separate program + Copyright (C) 1999-2014 Free Software Foundation, Inc. + + Contributed by Cygnus Solutions. + + This file is part of GDB. + + 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 . */ + +#include "defs.h" +#include "serial.h" +#include "ser-base.h" +#include "ser-unix.h" + +#include "gdb_vfork.h" + +#include +#include +#include +#include +#include +#include "filestuff.h" + +#include + +static int pipe_open (struct serial *scb, const char *name); +static void pipe_close (struct serial *scb); + +extern void _initialize_ser_pipe (void); + +struct pipe_state + { + int pid; + }; + +/* Open up a raw pipe. */ + +static int +pipe_open (struct serial *scb, const char *name) +{ +#if !HAVE_SOCKETPAIR + return -1; +#else + struct pipe_state *state; + /* This chunk: */ + /* Copyright (c) 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software written by Ken Arnold and + * published in UNIX Review, Vol. 6, No. 8. + */ + int pdes[2]; + int err_pdes[2]; + int pid; + + if (gdb_socketpair_cloexec (AF_UNIX, SOCK_STREAM, 0, pdes) < 0) + return -1; + if (gdb_socketpair_cloexec (AF_UNIX, SOCK_STREAM, 0, err_pdes) < 0) + { + close (pdes[0]); + close (pdes[1]); + return -1; + } + + /* Create the child process to run the command in. Note that the + apparent call to vfork() below *might* actually be a call to + fork() due to the fact that autoconf will ``#define vfork fork'' + on certain platforms. */ + pid = vfork (); + + /* Error. */ + if (pid == -1) + { + close (pdes[0]); + close (pdes[1]); + close (err_pdes[0]); + close (err_pdes[1]); + return -1; + } + + if (fcntl (err_pdes[0], F_SETFL, O_NONBLOCK) == -1) + { + close (err_pdes[0]); + close (err_pdes[1]); + err_pdes[0] = err_pdes[1] = -1; + } + + /* Child. */ + if (pid == 0) + { + /* We don't want ^c to kill the connection. */ +#ifdef HAVE_SETSID + pid_t sid = setsid (); + if (sid == -1) + signal (SIGINT, SIG_IGN); +#else + signal (SIGINT, SIG_IGN); +#endif + + /* Re-wire pdes[1] to stdin/stdout. */ + close (pdes[0]); + if (pdes[1] != STDOUT_FILENO) + { + dup2 (pdes[1], STDOUT_FILENO); + close (pdes[1]); + } + dup2 (STDOUT_FILENO, STDIN_FILENO); + + if (err_pdes[0] != -1) + { + close (err_pdes[0]); + dup2 (err_pdes[1], STDERR_FILENO); + close (err_pdes[1]); + } + + close_most_fds (); + execl ("/bin/sh", "sh", "-c", name, (char *) 0); + _exit (127); + } + + /* Parent. */ + close (pdes[1]); + if (err_pdes[1] != -1) + close (err_pdes[1]); + /* :end chunk */ + state = XMALLOC (struct pipe_state); + state->pid = pid; + scb->fd = pdes[0]; + scb->error_fd = err_pdes[0]; + scb->state = state; + + /* If we don't do this, GDB simply exits when the remote side dies. */ + signal (SIGPIPE, SIG_IGN); + return 0; +#endif +} + +static void +pipe_close (struct serial *scb) +{ + struct pipe_state *state = scb->state; + + close (scb->fd); + scb->fd = -1; + + if (state != NULL) + { + int wait_result, status; + + /* Don't kill the task right away, give it a chance to shut down cleanly. + But don't wait forever though. */ +#define PIPE_CLOSE_TIMEOUT 5 + + /* Assume the program will exit after SIGTERM. Might be + useful to print any remaining stderr output from + scb->error_fd while waiting. */ +#define SIGTERM_TIMEOUT INT_MAX + + wait_result = -1; +#ifdef HAVE_WAITPID + wait_result = wait_to_die_with_timeout (state->pid, &status, + PIPE_CLOSE_TIMEOUT); +#endif + if (wait_result == -1) + { + kill (state->pid, SIGTERM); +#ifdef HAVE_WAITPID + wait_to_die_with_timeout (state->pid, &status, SIGTERM_TIMEOUT); +#endif + } + + if (scb->error_fd != -1) + close (scb->error_fd); + scb->error_fd = -1; + xfree (state); + scb->state = NULL; + } +} + +int +gdb_pipe (int pdes[2]) +{ +#if !HAVE_SOCKETPAIR + errno = ENOSYS; + return -1; +#else + + if (gdb_socketpair_cloexec (AF_UNIX, SOCK_STREAM, 0, pdes) < 0) + return -1; + + /* If we don't do this, GDB simply exits when the remote side + dies. */ + signal (SIGPIPE, SIG_IGN); + return 0; +#endif +} + +static const struct serial_ops pipe_ops = +{ + "pipe", + pipe_open, + pipe_close, + NULL, + ser_base_readchar, + ser_base_write, + ser_base_flush_output, + ser_base_flush_input, + ser_base_send_break, + ser_base_raw, + ser_base_get_tty_state, + ser_base_copy_tty_state, + ser_base_set_tty_state, + ser_base_print_tty_state, + ser_base_noflush_set_tty_state, + ser_base_setbaudrate, + ser_base_setstopbits, + ser_base_drain_output, + ser_base_async, + ser_unix_read_prim, + ser_unix_write_prim +}; + +void +_initialize_ser_pipe (void) +{ + serial_add_interface (&pipe_ops); +} diff --git a/pool/shard008/C/0130257_timer.c b/pool/shard008/C/0130257_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..83ab74e0de3bed6ed976e3c71318b341f01ca09e --- /dev/null +++ b/pool/shard008/C/0130257_timer.c @@ -0,0 +1,116 @@ +/* + * ubirch#1 timer driver code. + * + * Found some inspiration here: + * https://github.com/mbedmicro/mbed/blob/master/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KSDK2_MCUS/TARGET_K64F/us_ticker.c + * + * TODO may make sense to move this into the board code and provide a programmatic interface. + * + * @author Matthias L. Jugel + * @date 2016-04-06 + * + * @copyright © 2015 ubirch GmbH (https://ubirch.com) + * + * ``` + * 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. + * ``` + */ + +#include +#include +#include "timer.h" + +static bool initialized = false; + +void BOARD_TIMER_HANDLER() { + // clear interrupt flag + PIT_ClearStatusFlags(BOARD_TIMER, kPIT_Chnl_3, kPIT_TimerFlag); + PIT_DisableInterrupts(BOARD_TIMER, kPIT_Chnl_3, kPIT_TimerInterruptEnable); + + // stop the timer + PIT_StopTimer(BOARD_TIMER, kPIT_Chnl_3); + PIT_StopTimer(BOARD_TIMER, kPIT_Chnl_2); + + // create continue event + __SEV(); +} + +void timer_init() { + if (initialized) return; + initialized = true; + + pit_config_t pitConfig; + PIT_GetDefaultConfig(&pitConfig); + PIT_Init(BOARD_TIMER, &pitConfig); + + PIT_SetTimerPeriod(BOARD_TIMER, kPIT_Chnl_0, (uint32_t) USEC_TO_COUNT(1U, CLOCK_GetFreq(kCLOCK_BusClk)) - 1); + PIT_SetTimerPeriod(BOARD_TIMER, kPIT_Chnl_1, 0xFFFFFFFF); + PIT_SetTimerChainMode(BOARD_TIMER, kPIT_Chnl_1, true); + + PIT_StartTimer(BOARD_TIMER, kPIT_Chnl_0); + PIT_StartTimer(BOARD_TIMER, kPIT_Chnl_1); + + PIT_SetTimerPeriod(BOARD_TIMER, kPIT_Chnl_2, (uint32_t) USEC_TO_COUNT(1U, CLOCK_GetFreq(kCLOCK_BusClk)) - 1); + PIT_SetTimerPeriod(BOARD_TIMER, kPIT_Chnl_3, 0xFFFFFFFF); + PIT_SetTimerChainMode(BOARD_TIMER, kPIT_Chnl_3, true); + + EnableIRQ(BOARD_TIMER_IRQ); +} + +uint32_t timer_read() { + if (!initialized) timer_init(); + return ~(PIT_GetCurrentTimerCount(BOARD_TIMER, kPIT_Chnl_1)); +} + +// TODO: handle longer than 71 minute interrupt times (chaining both timers) +void timer_set_interrupt(uint32_t us) { + if (!initialized) timer_init(); + + PIT_StopTimer(BOARD_TIMER, kPIT_Chnl_3); + PIT_StopTimer(BOARD_TIMER, kPIT_Chnl_2); + PIT_SetTimerPeriod(BOARD_TIMER, kPIT_Chnl_3, (uint32_t) us); + PIT_EnableInterrupts(BOARD_TIMER, kPIT_Chnl_3, kPIT_TimerInterruptEnable); + PIT_StartTimer(BOARD_TIMER, kPIT_Chnl_3); + PIT_StartTimer(BOARD_TIMER, kPIT_Chnl_2); +} + +void timer_set_timeout(uint32_t us) { + if (us) timer_set_interrupt(us); +} + +uint32_t timer_timeout_remaining() { + if (!initialized) timer_init(); + + if (PIT_GetEnabledInterrupts(PIT, kPIT_Chnl_3) & kPIT_TimerInterruptEnable) + return PIT_GetCurrentTimerCount(PIT, kPIT_Chnl_3); + return 0; +} + +void delay_us(uint32_t us) { + // save the current timeout, so delay() does not interfere + uint32_t remaining = timer_timeout_remaining(); + + timer_set_timeout(us); + while (timer_timeout_remaining()) { __WFE(); } + + // set timeout to the value before delay and minus this delay + if (remaining > us) timer_set_timeout(remaining - us); +} + +void delay(uint32_t ms) { + if (ms > (uTimer_MaxTimeout - 1) / 1000) return; + + uint32_t us_delay = ms * 1000; + delay_us(us_delay); +} + diff --git a/pool/shard008/C/0130258_test-rfifolock.c b/pool/shard008/C/0130258_test-rfifolock.c new file mode 100644 index 0000000000000000000000000000000000000000..471a81114d4dae1c9b933a3422025118ddd93713 --- /dev/null +++ b/pool/shard008/C/0130258_test-rfifolock.c @@ -0,0 +1,91 @@ +/* + * RFifoLock tests + * + * Copyright Red Hat, Inc. 2013 + * + * Authors: + * Stefan Hajnoczi + * + * This work is licensed under the terms of the GNU LGPL, version 2 or later. + * See the COPYING.LIB file in the top-level directory. + */ + +#include "qemu/osdep.h" +#include "qemu-common.h" +#include "qemu/rfifolock.h" + +static void test_nesting(void) +{ + RFifoLock lock; + + /* Trivial test, ensure the lock is recursive */ + rfifolock_init(&lock, NULL, NULL); + rfifolock_lock(&lock); + rfifolock_lock(&lock); + rfifolock_lock(&lock); + rfifolock_unlock(&lock); + rfifolock_unlock(&lock); + rfifolock_unlock(&lock); + rfifolock_destroy(&lock); +} + +typedef struct { + RFifoLock lock; + int fd[2]; +} CallbackTestData; + +static void rfifolock_cb(void *opaque) +{ + CallbackTestData *data = opaque; + int ret; + char c = 0; + + ret = write(data->fd[1], &c, sizeof(c)); + g_assert(ret == 1); +} + +static void *callback_thread(void *opaque) +{ + CallbackTestData *data = opaque; + + /* The other thread holds the lock so the contention callback will be + * invoked... + */ + rfifolock_lock(&data->lock); + rfifolock_unlock(&data->lock); + return NULL; +} + +static void test_callback(void) +{ + CallbackTestData data; + QemuThread thread; + int ret; + char c; + + rfifolock_init(&data.lock, rfifolock_cb, &data); + ret = qemu_pipe(data.fd); + g_assert(ret == 0); + + /* Hold lock but allow the callback to kick us by writing to the pipe */ + rfifolock_lock(&data.lock); + qemu_thread_create(&thread, "callback_thread", + callback_thread, &data, QEMU_THREAD_JOINABLE); + ret = read(data.fd[0], &c, sizeof(c)); + g_assert(ret == 1); + rfifolock_unlock(&data.lock); + /* If we got here then the callback was invoked, as expected */ + + qemu_thread_join(&thread); + close(data.fd[0]); + close(data.fd[1]); + rfifolock_destroy(&data.lock); +} + +int main(int argc, char **argv) +{ + g_test_init(&argc, &argv, NULL); + g_test_add_func("/nesting", test_nesting); + g_test_add_func("/callback", test_callback); + return g_test_run(); +} diff --git a/pool/shard008/C/0130259_comba_sqr_smallgen.c b/pool/shard008/C/0130259_comba_sqr_smallgen.c new file mode 100644 index 0000000000000000000000000000000000000000..df149c51053545d1924c43c781f717e1e1d01c3e --- /dev/null +++ b/pool/shard008/C/0130259_comba_sqr_smallgen.c @@ -0,0 +1,109 @@ +/* TomsFastMath, a fast ISO C bignum library. + * + * This project is meant to fill in where LibTomMath + * falls short. That is speed ;-) + * + * This project is public domain and free for all purposes. + * + * Tom St Denis, tomstdenis@gmail.com + */ + +/* Generates squaring comba code... it learns it knows our secrets! */ +#include + +int main(int argc, char **argv) +{ + int x, y, z, N, f; + +printf( +"void fp_sqr_comba_small(fp_int *A, fp_int *B)\n" +"{\n" +" fp_digit *a, b[32], c0, c1, c2, sc0, sc1, sc2;\n" +); + +printf(" switch (A->used) { \n"); + +for (N = 1; N <= 16; N++) { +printf( +" case %d:\n" +" a = A->dp;\n" +" COMBA_START; \n" +"\n" +" /* clear carries */\n" +" CLEAR_CARRY;\n" +"\n" +" /* output 0 */\n" +" SQRADD(a[0],a[0]);\n" +" COMBA_STORE(b[0]);\n", N); + + for (x = 1; x < N+N-1; x++) { +printf( +"\n /* output %d */\n" +" CARRY_FORWARD;\n ", x); + + for (f = y = 0; y < N; y++) { + for (z = 0; z < N; z++) { + if (z != y && z + y == x && y <= z) { + ++f; + } + } + } + + if (f <= 2) { + for (y = 0; y < N; y++) { + for (z = 0; z < N; z++) { + if (y<=z && (y+z)==x) { + if (y == z) { + printf(" SQRADD(a[%d], a[%d]); ", y, y); + } else { + printf(" SQRADD2(a[%d], a[%d]); ", y, z); + } + } + } + } + } else { + // new method + /* do evens first */ + f = 0; + for (y = 0; y < N; y++) { + for (z = 0; z < N; z++) { + if (z != y && z + y == x && y <= z) { + if (f == 0) { + // first double + printf("SQRADDSC(a[%d], a[%d]); ", y, z); + f = 1; + } else { + printf("SQRADDAC(a[%d], a[%d]); ", y, z); + } + } + } + } + // forward the carry + printf("SQRADDDB; "); + if ((x&1) == 0) { + // add the square + printf("SQRADD(a[%d], a[%d]); ", x/2, x/2); + } + } +printf("\n COMBA_STORE(b[%d]);\n", x); + } +printf(" COMBA_STORE2(b[%d]);\n", N+N-1); + +printf( +" COMBA_FINI;\n" +"\n" +" B->used = %d;\n" +" B->sign = FP_ZPOS;\n" +" memcpy(B->dp, b, %d * sizeof(fp_digit));\n" +" fp_clamp(B);\n" +" break;\n\n", N+N, N+N); +} + +printf("}\n\n}\n"); + + return 0; +} + +/* $Source: /cvs/libtom/tomsfastmath/src/generators/comba_sqr_smallgen.c,v $ */ +/* $Revision: 1.1 $ */ +/* $Date: 2006/12/31 21:25:53 $ */ diff --git a/pool/shard008/C/0130262_g2mblopt03d.c b/pool/shard008/C/0130262_g2mblopt03d.c new file mode 100644 index 0000000000000000000000000000000000000000..8b84908c01e4a83b0e68564649e2d0e4aca42579 --- /dev/null +++ b/pool/shard008/C/0130262_g2mblopt03d.c @@ -0,0 +1,40 @@ + +/* ///////////////////////////////////////////////////////////////////////// */ +/* This file is a part of the BSTools package */ +/* written by Przemyslaw Kiciak */ +/* ///////////////////////////////////////////////////////////////////////// */ +/* (C) Copyright by Przemyslaw Kiciak, 2010 */ +/* this package is distributed under the terms of the */ +/* Lesser GNU Public License, see the file COPYING.LIB */ +/* ///////////////////////////////////////////////////////////////////////// */ + +#include +#include +#include +#include +#include + +#include "pkvaria.h" +#include "pknum.h" +#include "pkgeom.h" +#include "multibs.h" +#include "bsmesh.h" +#include "egholed.h" +#include "g2blendingd.h" +#include "g2mblendingd.h" + +#include "g2blprivated.h" +#include "g2mblprivated.h" + +/* ///////////////////////////////////////////////////////////////////////// */ +void _g2mbl_AddCPIncrement ( int nvcp, int *vncpi, point3d *mvcp, + vector3d *incr, point3d *omvcp ) +{ + int i, j; + + for ( i = 0; i < nvcp; i++ ) { + j = vncpi[i]; + SubtractPoints3d ( &mvcp[j], &incr[i], &omvcp[j] ); + } +} /*_g2mbl_AddCPIncrement*/ + diff --git a/pool/shard008/C/0130265_mul_fabric_servlet.c b/pool/shard008/C/0130265_mul_fabric_servlet.c new file mode 100644 index 0000000000000000000000000000000000000000..4a6e1b2b2d812e532709cab402122a284c85c2cf --- /dev/null +++ b/pool/shard008/C/0130265_mul_fabric_servlet.c @@ -0,0 +1,257 @@ +/* + * mul_fabric_servlet.c: MUL fabric cli service + * Copyright (C) 2012, Dipjyoti Saikia + * + * 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. + */ + +#include "mul_fabric_servlet.h" + +/** + * fab_dump_add_host_cmd_from_flow - + * + */ +static char * +fab_dump_add_host_cmd_from_flow(uint64_t dpid, struct flow *fl) +{ + char *pbuf = calloc(1, HOST_PBUF_SZ); + int len = 0; + struct in_addr in_addr = { .s_addr = fl->nw_src }; + + len += snprintf(pbuf+len, HOST_PBUF_SZ-len-1, + "add fabric-host tenant %hu network %hu host-ip %s host-mac " + "%02x:%02x:%02x:%02x:%02x:%02x switch " + "0x%llx port %hu %s \r\n", + fab_extract_tenant_id(fl), + fab_extract_network_id(fl), + inet_ntoa(in_addr), + fl->dl_src[0], fl->dl_src[1], + fl->dl_src[2], fl->dl_src[3], + fl->dl_src[4], fl->dl_src[5], + dpid, + ntohs(fl->in_port), + fl->FL_DFL_GW ? "gw" : "non-gw"); + assert(len < HOST_PBUF_SZ-1); + return pbuf; +} + +static bool +check_reply_type(struct cbuf *b, uint32_t cmd_code) +{ + c_ofp_auxapp_cmd_t *cofp_auc = (void *)(b->data); + + if (ntohs(cofp_auc->header.length) < sizeof(*cofp_auc)) { + return false; + } + + if (cofp_auc->header.type != C_OFPT_AUX_CMD || + cofp_auc->cmd_code != htonl(cmd_code)) { + return false; + } + + return true; +} + +static char * +mul_fabric_route_link_dump(struct c_ofp_route_link *rl, size_t n_links) +{ + int i = 0 , len = 0; + char *pbuf = calloc(1, FAB_DFL_PBUF_SZ); + + if (!pbuf) { + return NULL; + } + + for (; i < n_links; i++) { + len += snprintf(pbuf+len, FAB_DFL_PBUF_SZ-len-1, + "Node(0x%llx):Link(%hu)", + ntohll(rl->datapath_id), ntohs(rl->src_link)); + if (len >= FAB_DFL_PBUF_SZ-1) { + c_log_err("%s: print buf overrun", FN); + free(pbuf); + return NULL; + } + rl++; + } + + return pbuf; +} + +/** + * mul_fabric_host_mod - + * + */ +int +mul_fabric_host_mod(void *service, uint64_t dpid, struct flow *fl, bool add) +{ + struct cbuf *b; + struct c_ofp_auxapp_cmd *cofp_auc; + struct c_ofp_host_mod *cofp_hm; + int ret = -1; + + b = of_prep_msg(sizeof(struct c_ofp_auxapp_cmd) + + sizeof(struct c_ofp_host_mod), + C_OFPT_AUX_CMD, 0); + + cofp_auc = (void *)(b->data); + cofp_auc->cmd_code = add ? htonl(C_AUX_CMD_FAB_HOST_ADD): + htonl(C_AUX_CMD_FAB_HOST_DEL); + cofp_hm = (void *)(cofp_auc->data); + cofp_hm->switch_id.datapath_id = htonll(dpid); + memcpy(&cofp_hm->host_flow, fl, sizeof(*fl)); + + c_service_send(service, b); + b = c_service_wait_response(service); + if (b) { + if (check_reply_type(b, C_AUX_CMD_SUCCESS)) { + ret = 0; + } + + free_cbuf(b); + } + + return ret; +} + +/** + * mul_fabric_show_hosts - + * + */ +void +mul_fabric_show_hosts(void *service, bool active, bool dump_cmd, + void *arg, void (*cb_fn)(void *arg, char *pbuf)) +{ + struct cbuf *b; + struct c_ofp_auxapp_cmd *cofp_auc; + struct c_ofp_host_mod *cofp_hm; + char *pbuf; + + b = of_prep_msg(sizeof(struct c_ofp_auxapp_cmd), + C_OFPT_AUX_CMD, 0); + + cofp_auc = (void *)(b->data); + cofp_auc->cmd_code = active ? + htonl(C_AUX_CMD_FAB_SHOW_ACTIVE_HOSTS): + htonl(C_AUX_CMD_FAB_SHOW_INACTIVE_HOSTS); + c_service_send(service, b); + while (1) { + b = c_service_wait_response(service); + if (b) { + if (check_reply_type(b, C_AUX_CMD_SUCCESS) || + !check_reply_type(b, C_AUX_CMD_FAB_HOST_ADD)) { + free_cbuf(b); + break; + } + cofp_auc = (void *)(b->data); + cofp_hm = (void *)(cofp_auc->data); + + if (ntohs(cofp_auc->header.length) < + sizeof(*cofp_auc) + sizeof(*cofp_hm)) { + free_cbuf(b); + break; + + } + + if (!dump_cmd) { + pbuf = fab_dump_single_host_from_flow( + ntohll(cofp_hm->switch_id.datapath_id), + &cofp_hm->host_flow); + } else { + pbuf = fab_dump_add_host_cmd_from_flow( + ntohll(cofp_hm->switch_id.datapath_id), + &cofp_hm->host_flow); + } + if (pbuf) { + cb_fn(arg, pbuf); + free(pbuf); + } + free_cbuf(b); + } else { + break; + } + } +} + + +/** + * mul_fabric_show_routes - + * + */ +void +mul_fabric_show_routes(void *service, + void *arg, + void (*show_src_host)(void *arg, char *pbuf), + void (*show_dst_host)(void *arg, char *pbuf), + void (*show_route_links)(void *arg, char *pbuf)) +{ + struct cbuf *b; + struct c_ofp_auxapp_cmd *cofp_auc; + struct c_ofp_route *cofp_r; + struct c_ofp_route_link *cofp_rl; + char *pbuf; + size_t n_links = 0; + + b = of_prep_msg(sizeof(struct c_ofp_auxapp_cmd), + C_OFPT_AUX_CMD, 0); + + cofp_auc = (void *)(b->data); + cofp_auc->cmd_code = htonl(C_AUX_CMD_FAB_SHOW_ROUTES); + c_service_send(service, b); + while (1) { + b = c_service_wait_response(service); + if (b) { + if (check_reply_type(b, C_AUX_CMD_SUCCESS) || + !check_reply_type(b, C_AUX_CMD_FAB_ROUTE)) { + free_cbuf(b); + break; + } + cofp_auc = (void *)(b->data); + + if (ntohs(cofp_auc->header.length) < + sizeof(*cofp_auc) + sizeof(*cofp_r)) { + free_cbuf(b); + continue; + } + n_links = (ntohs(cofp_auc->header.length) - + (sizeof(*cofp_auc) + sizeof(*cofp_r)))/sizeof(*cofp_rl); + cofp_r = (void *)(cofp_auc->data); + pbuf = fab_dump_single_host_from_flow( + ntohll(cofp_r->src_host.switch_id.datapath_id), + &cofp_r->src_host.host_flow); + if (pbuf) { + show_src_host(arg, pbuf); + free(pbuf); + } + pbuf = fab_dump_single_host_from_flow( + ntohll(cofp_r->dst_host.switch_id.datapath_id), + &cofp_r->dst_host.host_flow); + if (pbuf) { + show_dst_host(arg, pbuf); + free(pbuf); + } + + pbuf = mul_fabric_route_link_dump( + (void *)(cofp_r->route_links), n_links); + if (pbuf) { + show_route_links(arg, pbuf); + free(pbuf); + } + + free_cbuf(b); + } else { + break; + } + } +} diff --git a/pool/shard008/C/0130266_pktview.c b/pool/shard008/C/0130266_pktview.c new file mode 100644 index 0000000000000000000000000000000000000000..3cbdfc39581057e0acc7ff4cbc4e31b93b0eefe2 --- /dev/null +++ b/pool/shard008/C/0130266_pktview.c @@ -0,0 +1,201 @@ +/* + * testcode/pktview.c - debug program to disassemble a DNS packet. + * + * Copyright (c) 2007, NLnet Labs. All rights reserved. + * + * This software is open source. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of the NLNET LABS nor the names of its contributors may + * be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/** + * \file + * + * This program shows a dns packet wire format. + */ + +#include "config.h" +#include +#include "util/log.h" +#include "util/data/dname.h" +#include "util/data/msgparse.h" +#include "testcode/unitmain.h" +#include "testcode/readhex.h" + +/** usage information for pktview */ +static void usage(char* argv[]) +{ + printf("usage: %s\n", argv[0]); + printf("present hex packet on stdin.\n"); + exit(1); +} + +/** read hex input */ +static void read_input(ldns_buffer* pkt, FILE* in) +{ + char buf[102400]; + char* np = buf; + while(fgets(np, (int)sizeof(buf) - (np-buf), in)) { + if(buf[0] == ';') /* comment */ + continue; + np = &np[strlen(np)]; + } + hex_to_buf(pkt, buf); +} + +/** analyze domain name in packet, possibly compressed */ +static void analyze_dname(ldns_buffer* pkt) +{ + size_t oldpos = ldns_buffer_position(pkt); + size_t len; + printf("[pos %d] dname: ", (int)oldpos); + dname_print(stdout, pkt, ldns_buffer_current(pkt)); + len = pkt_dname_len(pkt); + printf(" len=%d", (int)len); + if(ldns_buffer_position(pkt)-oldpos != len) + printf(" comprlen=%d\n", + (int)(ldns_buffer_position(pkt)-oldpos)); + else printf("\n"); +} + +/** analyze rdata in packet */ +static void analyze_rdata(ldns_buffer*pkt, const ldns_rr_descriptor* desc, + uint16_t rdlen) +{ + int rdf = 0; + int count = (int)desc->_dname_count; + size_t len, oldpos; + while(rdlen > 0 && count) { + switch(desc->_wireformat[rdf]) { + case LDNS_RDF_TYPE_DNAME: + oldpos = ldns_buffer_position(pkt); + analyze_dname(pkt); + rdlen -= ldns_buffer_position(pkt)-oldpos; + count --; + len = 0; + break; + case LDNS_RDF_TYPE_STR: + len = ldns_buffer_current(pkt)[0] + 1; + break; + default: + len = get_rdf_size(desc->_wireformat[rdf]); + } + if(len) { + printf(" wf[%d]", (int)len); + ldns_buffer_skip(pkt, (ssize_t)len); + rdlen -= len; + } + rdf++; + } + if(rdlen) { + size_t i; + printf(" remain[%d]\n", (int)rdlen); + for(i=0; i_name: "??" , (int)type); + printf(" class %s(%d) ", ldns_lookup_by_id(ldns_rr_classes, + (int)dclass)?ldns_lookup_by_id( ldns_rr_classes, + (int)dclass)->name:"??", (int)dclass); + if(q) { + printf("\n"); + } else { + ttl = ldns_buffer_read_u32(pkt); + printf(" ttl %d (0x%x)", (int)ttl, (unsigned)ttl); + len = ldns_buffer_read_u16(pkt); + printf(" rdata len %d:\n", (int)len); + if(ldns_rr_descript(type)) + analyze_rdata(pkt, ldns_rr_descript(type), len); + else ldns_buffer_skip(pkt, (ssize_t)len); + } +} + +/** analyse pkt */ +static void analyze(ldns_buffer* pkt) +{ + uint16_t i, f, qd, an, ns, ar; + int rrnum = 0; + printf("packet length %d\n", (int)ldns_buffer_limit(pkt)); + if(ldns_buffer_limit(pkt) < 12) return; + + i = ldns_buffer_read_u16(pkt); + printf("id (hostorder): %d (0x%x)\n", (int)i, (unsigned)i); + f = ldns_buffer_read_u16(pkt); + printf("flags: 0x%x\n", (unsigned)f); + qd = ldns_buffer_read_u16(pkt); + printf("qdcount: %d\n", (int)qd); + an = ldns_buffer_read_u16(pkt); + printf("ancount: %d\n", (int)an); + ns = ldns_buffer_read_u16(pkt); + printf("nscount: %d\n", (int)ns); + ar = ldns_buffer_read_u16(pkt); + printf("arcount: %d\n", (int)ar); + + printf(";-- query section\n"); + while(ldns_buffer_remaining(pkt) > 0) { + if(rrnum == (int)qd) + printf(";-- answer section\n"); + if(rrnum == (int)qd+(int)an) + printf(";-- authority section\n"); + if(rrnum == (int)qd+(int)an+(int)ns) + printf(";-- additional section\n"); + printf("rr %d ", rrnum); + analyze_rr(pkt, rrnum < (int)qd); + rrnum++; + } +} + +/** main program for pktview */ +int main(int argc, char* argv[]) +{ + ldns_buffer* pkt = ldns_buffer_new(65553); + if(argc != 1) { + usage(argv); + } + if(!pkt) fatal_exit("out of memory"); + + read_input(pkt, stdin); + analyze(pkt); + + ldns_buffer_free(pkt); + return 0; +} diff --git a/pool/shard008/C/0130268_speed.c b/pool/shard008/C/0130268_speed.c new file mode 100644 index 0000000000000000000000000000000000000000..4c6fb571abbe92f40c59df6fcbb4967736ee460f --- /dev/null +++ b/pool/shard008/C/0130268_speed.c @@ -0,0 +1,275 @@ +/* + * (C) Copyright 2001-2004 + * Wolfgang Denk, DENX Software Engineering, wd@denx.de. + * + * (C) Copyright 2002 + * David Mueller, ELSOFT AG, d.mueller@elsoft.ch + * + * See file CREDITS for list of people who contributed to this + * project. + * + * 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., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + */ + +/* This code should work for both the S5PC110 + * as they seem to have the same PLL and clock machinery inside. + * The different address mapping is handled by the s5pc110.h files below. + */ + +#include +#include + +#define APLL 0 +#define MPLL 1 +#define EPLL 2 + + +/* ------------------------------------------------------------------------- */ +/* NOTE: This describes the proper use of this file. + * + * CONFIG_SYS_CLK_FREQ should be defined as the input frequency of the PLL. + * + * get_FCLK(), get_HCLK(), get_PCLK() and get_UCLK() return the clock of + * the specified bus in HZ. + */ +/* ------------------------------------------------------------------------- */ + +static ulong get_PLLCLK(int pllreg) +{ + ulong r, m, p, s; + + if (pllreg == APLL) { + r = APLL_CON0_REG; + m = (r>>16) & 0x3ff; + } else if (pllreg == MPLL) { + r = MPLL_CON_REG; + m = (r>>16) & 0x3ff; + } else if (pllreg == EPLL) { + r = EPLL_CON_REG; + m = (r>>16) & 0x1ff; + } else + hang(); + + p = (r>>8) & 0x3f; + s = r & 0x7; + + if (pllreg == APLL) + s= s-1; + + return (m * (CONFIG_SYS_CLK_FREQ / (p * (1 << s)))); +} + +/* return ARMCORE frequency */ +ulong get_ARMCLK(void) +{ + ulong div,apll_ratio; + + div = CLK_DIV0_REG; + apll_ratio = ((div>>0) & 0x7); + + return ((get_PLLCLK(APLL)) / (apll_ratio + 1)); + +} + +/* return FCLK frequency */ +ulong get_FCLK(void) +{ + return (get_PLLCLK(APLL)); +} + +/* return FCLK frequency */ +ulong get_MPLL_CLK(void) +{ + return (get_PLLCLK(MPLL)); +} + + +/* return HCLK frequency */ +ulong get_HCLK(void) +{ + ulong fclk; + uint mux_stat = CLK_MUX_STAT0_REG; + uint div,hclk_msys_ratio,apll_ratio; + + div = CLK_DIV0_REG; + + apll_ratio = ((div>>0) & 0x7); + hclk_msys_ratio = ((div>>8)&0x7); + + switch ((mux_stat>>16) & 0x7) { + case 2: //SCLKMPLL source + fclk = get_MPLL_CLK(); + break; + case 1: //SCLKAPLL source + default: + fclk = get_FCLK(); + break; + } + + return fclk/((apll_ratio+1)*(hclk_msys_ratio+1)); +} + +/* return PCLK frequency */ +ulong get_PCLK(void) +{ + ulong hclk; + uint div = CLK_DIV0_REG; + uint pclk_msys_ratio = ((div>>12) & 0x7); + + hclk = get_HCLK(); + + return hclk/(pclk_msys_ratio+1); +} + +/* return HCLKDSYS frequency */ +ulong get_HCLKD(void) +{ + ulong fclk; + uint mux_stat = CLK_MUX_STAT0_REG; + + uint div,a2m_ratio,hclk_dsys_ratio; + + div = CLK_DIV0_REG; + + a2m_ratio = ((div >>4) & 0x7); + hclk_dsys_ratio = ((div >>16) & 0xf); + + switch ((mux_stat>>20) & 0x7) { + case 2: //SCLKA2M source + fclk = get_FCLK()/(a2m_ratio+1); + break; + case 1: //SCLKMPLL source + default: + fclk = get_MPLL_CLK(); + break; + } + + return fclk/(hclk_dsys_ratio+1); +} + +/* return PCLKDSYS frequency */ +ulong get_PCLKD(void) +{ + ulong fclk; + uint div = CLK_DIV0_REG; + uint pclk_dsys_ratio = ((div>>20) & 0x7); + + fclk = get_HCLKD(); + + return fclk/(pclk_dsys_ratio+1); +} + +/* return HCLKPSYS frequency */ +ulong get_HCLKP(void) +{ + ulong fclk; + uint mux_stat = CLK_MUX_STAT0_REG; + uint div,hclk_psys_ratio,a2m_ratio; + + div = CLK_DIV0_REG; + a2m_ratio = ((div >>4) & 0x7); + hclk_psys_ratio = ((div>>24)&0xf); + + switch ((mux_stat>>20) & 0x7) { + case 2: //SCLKA2M source + fclk = get_FCLK()/(a2m_ratio+1); + break; + case 1: //SCLKMPLL source + default: + fclk = get_MPLL_CLK(); + break; + } + + + return fclk/(hclk_psys_ratio+1); +} + +/* return PCLKPSYS frequency */ +ulong get_PCLKP(void) +{ + ulong fclk; + uint div = CLK_DIV0_REG; + uint pclk_psys_ratio = ((div>>28) & 0x7); + + fclk = get_HCLKP(); + + return fclk/(pclk_psys_ratio+1); +} + +/* return SCLKA2M frequency */ +ulong get_SCLKA2M(void) +{ + ulong fclk; + uint div = CLK_DIV0_REG; + uint a2m_ratio = ((div>>4) & 0x7); + + fclk = get_FCLK(); + + return fclk/(a2m_ratio+1); +}/* return UCLK frequency */ +ulong get_UCLK(void) +{ + return (get_PLLCLK(EPLL)); +} + +int print_cpuinfo(void) +{ + uint set_speed; + uint tmp; + uchar result_set; + +#if defined(CONFIG_CLK_533_133_100_100) + set_speed = 53300; +#elif defined(CONFIG_CLK_667_166_166_133) + set_speed = 66700; +#elif defined(CONFIG_CLK_800_200_166_133) + set_speed = 80000; +#elif defined(CONFIG_CLK_1000_200_166_133) + set_speed = 100000; +#elif defined(CONFIG_CLK_1200_200_166_133) + set_speed = 120000; +#else + set_speed = 100000; + printf("Any CONFIG_CLK_XXX is not enabled\n"); +#endif + tmp = (set_speed / (get_ARMCLK()/1000000)); + + if((tmp < 105) && (tmp > 95)){ + result_set = 1; + } else { + result_set = 0; + } + +#ifdef CONFIG_MCP_SINGLE + printf("\nCPU: S5PV210@%ldMHz(%s)\n", get_ARMCLK()/1000000, ((result_set == 1) ? "OK" : "FAIL")); +#else + printf("\nCPU: S5PC110@%ldMHz(%s)\n", get_ARMCLK()/1000000, ((result_set == 1) ? "OK" : "FAIL")); +#endif + printf(" APLL = %ldMHz, HclkMsys = %ldMHz, PclkMsys = %ldMHz\n", + get_FCLK()/1000000, get_HCLK()/1000000, get_PCLK()/1000000); +#if 1 + printf(" MPLL = %ldMHz, EPLL = %ldMHz\n", + get_MPLL_CLK()/1000000, get_PLLCLK(EPLL)/1000000); + printf(" HclkDsys = %ldMHz, PclkDsys = %ldMHz\n", + get_HCLKD()/1000000, get_PCLKD()/1000000); + printf(" HclkPsys = %ldMHz, PclkPsys = %ldMHz\n", + get_HCLKP()/1000000, get_PCLKP()/1000000); + printf(" SCLKA2M = %ldMHz\n", get_SCLKA2M()/1000000); +#endif + puts("Serial = CLKUART "); + + return 0; +} diff --git a/pool/shard008/C/0130278_doublePtr.c b/pool/shard008/C/0130278_doublePtr.c new file mode 100644 index 0000000000000000000000000000000000000000..e6b4b8ae3dc11acddcf4d7e5429873634771f79c --- /dev/null +++ b/pool/shard008/C/0130278_doublePtr.c @@ -0,0 +1,21 @@ +#include + +int doublePtr(int** x, int nbElem) +{ + int sum = 0; + for(nbElem--;nbElem>=0;nbElem--) + sum += (*x)[nbElem]; + return sum; +} + +#ifdef __GNUC__ +#ifndef __clang__ +int main(void) __attribute__((optimize("-O0"))); +#endif +#endif +int main(void) { + int tab[10]={10,1,2,3,4,5,6,7,8,9}; + int* ptr = tab; + + return doublePtr(&ptr, 10); +} diff --git a/pool/shard008/C/0130282_isl-ast-gen-if-1.c b/pool/shard008/C/0130282_isl-ast-gen-if-1.c new file mode 100644 index 0000000000000000000000000000000000000000..867b84e8359dd852297ab8e7c35377b0b213d9a9 --- /dev/null +++ b/pool/shard008/C/0130282_isl-ast-gen-if-1.c @@ -0,0 +1,37 @@ +/* { dg-do run } */ +/* { dg-options "-O2 -fgraphite-identity -fgraphite-code-generator=isl" } */ + +int st = 1; +static void __attribute__((noinline)) +foo (int a[], int n) +{ + int i; + for (i = 0; i < n; i++) + { + if (i < 25) + a[i] = i; + a[n - i] = 1; + } +} + +static int __attribute__((noinline)) +array_sum (int a[]) +{ + int i, res = 0; + for(i = 0; i < 50; i += st) + res += a[i]; + return res; +} + +extern void abort (); + +int +main (void) +{ + int a[50]; + foo (a, 50); + int res = array_sum (a); + if (res != 49) + abort (); + return 0; +} diff --git a/pool/shard008/C/0130284_CWE78_OS_Command_Injection__char_listen_socket_execlp_01.c b/pool/shard008/C/0130284_CWE78_OS_Command_Injection__char_listen_socket_execlp_01.c new file mode 100644 index 0000000000000000000000000000000000000000..b97464435f325fbf536f0c57c2927a8b11c0e699 --- /dev/null +++ b/pool/shard008/C/0130284_CWE78_OS_Command_Injection__char_listen_socket_execlp_01.c @@ -0,0 +1,205 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__char_listen_socket_execlp_01.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-01.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: listen_socket Read data using a listen socket (server side) + * GoodSource: Fixed string + * Sink: execlp + * BadSink : execute command with execlp + * Flow Variant: 01 Baseline + * + * */ + +#include "std_testcase.h" + +#include + +#ifdef _WIN32 +#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT "cmd.exe" +#define COMMAND_ARG1 "/c" +#define COMMAND_ARG2 "dir " +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH "/bin/sh" +#define COMMAND_INT "sh" +#define COMMAND_ARG1 "-c" +#define COMMAND_ARG2 "ls " +#define COMMAND_ARG3 data +#endif + +#ifdef _WIN32 +#include +#include +#include +#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ +#define CLOSE_SOCKET closesocket +#else +#include +#include +#include +#include +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define CLOSE_SOCKET close +#define SOCKET int +#endif + +#define TCP_PORT 27015 +#define LISTEN_BACKLOG 5 + +#ifdef _WIN32 +#include +#define EXECLP _execlp +#else /* NOT _WIN32 */ +#define EXECLP execlp +#endif + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__char_listen_socket_execlp_01_bad() +{ + char * data; + char dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + struct sockaddr_in service; + char *replace; + SOCKET listenSocket = INVALID_SOCKET; + SOCKET acceptSocket = INVALID_SOCKET; + size_t dataLen = strlen(data); + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + /* POTENTIAL FLAW: Read data using a listen socket */ + listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (listenSocket == INVALID_SOCKET) + { + break; + } + memset(&service, 0, sizeof(service)); + service.sin_family = AF_INET; + service.sin_addr.s_addr = INADDR_ANY; + service.sin_port = htons(TCP_PORT); + if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) + { + break; + } + acceptSocket = accept(listenSocket, NULL, NULL); + if (acceptSocket == SOCKET_ERROR) + { + break; + } + /* Abort on error or the connection was closed */ + recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0); + if (recvResult == SOCKET_ERROR || recvResult == 0) + { + break; + } + /* Append null terminator */ + data[dataLen + recvResult / sizeof(char)] = '\0'; + /* Eliminate CRLF */ + replace = strchr(data, '\r'); + if (replace) + { + *replace = '\0'; + } + replace = strchr(data, '\n'); + if (replace) + { + *replace = '\0'; + } + } + while (0); + if (listenSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(listenSocket); + } + if (acceptSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(acceptSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + /* execlp - searches for the location of the command among + * the directories specified by the PATH environment variable */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECLP(COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG3, NULL); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + char * data; + char dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + /* FIX: Append a fixed string to data (not user / external input) */ + strcat(data, "*.*"); + /* execlp - searches for the location of the command among + * the directories specified by the PATH environment variable */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECLP(COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG3, NULL); +} + +void CWE78_OS_Command_Injection__char_listen_socket_execlp_01_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__char_listen_socket_execlp_01_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__char_listen_socket_execlp_01_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard008/C/0130285_saml_advice.c b/pool/shard008/C/0130285_saml_advice.c new file mode 100644 index 0000000000000000000000000000000000000000..dd1fd6771ef15a9b7ade59fc198183f7b58cf472 --- /dev/null +++ b/pool/shard008/C/0130285_saml_advice.c @@ -0,0 +1,114 @@ +/* $Id$ + * + * Lasso - A free implementation of the Liberty Alliance specifications. + * + * Copyright (C) 2004-2007 Entr'ouvert + * http://lasso.entrouvert.org + * + * Authors: See AUTHORS file in top-level directory. + * + * 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, see . + */ + +#include "private.h" +#include "saml_advice.h" +#include "saml_assertion.h" + +/** + * SECTION:saml_advice + * @short_description: <saml:Advice> + * + *
Schema fragment for saml:Advice + * + * + * + * + * + * + * + * + * + * + * + * + * + * ]]> + *
+ */ + +/*****************************************************************************/ +/* private methods */ +/*****************************************************************************/ + +static struct XmlSnippet schema_snippets[] = { + { "AssertionIDReference", SNIPPET_LIST_CONTENT, + G_STRUCT_OFFSET(LassoSamlAdvice, AssertionIDReference), NULL, NULL, NULL}, + { "Assertion", SNIPPET_NODE, G_STRUCT_OFFSET(LassoSamlAdvice, Assertion), NULL, NULL, NULL}, + {NULL, 0, 0, NULL, NULL, NULL} +}; + +/*****************************************************************************/ +/* instance and class init functions */ +/*****************************************************************************/ + + +static void +class_init(LassoSamlAdviceClass *klass) +{ + LassoNodeClass *nclass = LASSO_NODE_CLASS(klass); + + nclass->node_data = g_new0(LassoNodeClassData, 1); + lasso_node_class_set_nodename(nclass, "Advice"); + lasso_node_class_set_ns(nclass, LASSO_SAML_ASSERTION_HREF, LASSO_SAML_ASSERTION_PREFIX); + lasso_node_class_add_snippets(nclass, schema_snippets); +} + +GType +lasso_saml_advice_get_type() +{ + static GType this_type = 0; + + if (!this_type) { + static const GTypeInfo this_info = { + sizeof (LassoSamlAdviceClass), + NULL, + NULL, + (GClassInitFunc) class_init, + NULL, + NULL, + sizeof(LassoSamlAdvice), + 0, + NULL, + NULL + }; + + this_type = g_type_register_static(LASSO_TYPE_NODE, + "LassoSamlAdvice", &this_info, 0); + } + return this_type; +} + +/** + * lasso_saml_advice_new: + * + * Creates a new #LassoSamlAdvice object. + * + * Return value: a newly created #LassoSamlAdvice + **/ +LassoNode* +lasso_saml_advice_new() +{ + return g_object_new(LASSO_TYPE_SAML_ADVICE, NULL); +} diff --git a/pool/shard008/C/0130287_strv.c b/pool/shard008/C/0130287_strv.c new file mode 100644 index 0000000000000000000000000000000000000000..6fdd361db8f81ded8597ac8e30042b576d0b5b52 --- /dev/null +++ b/pool/shard008/C/0130287_strv.c @@ -0,0 +1,89 @@ +/* strv.c + * + * Copyright (C) 2017 Matthias Clasen + * + * 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 . + */ + +#include "config.h" +#include +#include +#include +#include "gr-utils.h" + +static void +test_strv_prepend (void) +{ + char **strv; + + strv = g_new0 (char *, 3); + strv[0] = g_strdup ("b"); + strv[1] = g_strdup ("c"); + + strv_prepend (&strv, "a"); + + g_assert (g_strv_length (strv) == 3); + g_assert_cmpstr (strv[0], ==, "a"); + g_assert_cmpstr (strv[1], ==, "b"); + g_assert_cmpstr (strv[2], ==, "c"); + + g_strfreev (strv); + + strv = g_new0 (char *, 1); + + strv_prepend (&strv, "a"); + + g_assert (g_strv_length (strv) == 1); + g_assert_cmpstr (strv[0], ==, "a"); + + g_strfreev (strv); +} + +static void +test_strv_remove (void) +{ + char **strv; + + strv = g_new0 (char *, 4); + strv[0] = g_strdup ("b"); + strv[1] = g_strdup ("c"); + strv[2] = g_strdup ("b"); + + strv_remove (&strv, "b"); + + g_assert (g_strv_length (strv) == 1); + g_assert_cmpstr (strv[0], ==, "c"); + + strv_remove (&strv, "a"); + + g_assert (g_strv_length (strv) == 1); + g_assert_cmpstr (strv[0], ==, "c"); + + strv_remove (&strv, "c"); + + g_assert (g_strv_length (strv) == 0); + + g_strfreev (strv); +} + +int +main (int argc, char *argv[]) +{ + g_test_init (&argc, &argv, NULL); + + g_test_add_func ("/strv/prepend", test_strv_prepend); + g_test_add_func ("/strv/remove", test_strv_remove); + + return g_test_run (); +} diff --git a/pool/shard008/C/0130291_sub.c b/pool/shard008/C/0130291_sub.c new file mode 100644 index 0000000000000000000000000000000000000000..b2408b5df6cf8315ab80a9cdd7cff9c98135183a --- /dev/null +++ b/pool/shard008/C/0130291_sub.c @@ -0,0 +1,128 @@ +/* + Copyright (c) 2013-2014 Dong Fang. All rights reserved. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom + the Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + IN THE SOFTWARE. +*/ + +#include "sub.h" + +static struct epbase* sub_ep_alloc() { + struct sub_ep* sub_ep = mem_zalloc(sizeof(struct sub_ep)); + + if (sub_ep) { + epbase_init(&sub_ep->base); + } + + return &sub_ep->base; +} + +static void sub_ep_destroy(struct epbase* ep) { + struct sub_ep* sub_ep = cont_of(ep, struct sub_ep, base); + epbase_exit(ep); + mem_free(sub_ep, sizeof(*sub_ep)); +} + +static int sub_ep_send(struct epbase* ep, char* ubuf) { + ERRNO_RETURN(EPERM); +} + +static int sub_ep_add(struct epbase* ep, struct tgtd* tg, char* ubuf) { + mutex_lock(&ep->lock); + msgbuf_head_in(&ep->rcv, ubuf); + + if (ep->rcv.waiters) { + condition_broadcast(&ep->cond); + } + + mutex_unlock(&ep->lock); + return 0; +} + +static int sub_ep_rm(struct epbase* ep, struct tgtd* tg, char** ubuf) { + tgtd_try_disable_out(tg); + return -1; +} + +static struct tgtd* sub_ep_join(struct epbase* ep, int fd) { + struct pubsub_tgtd* ps_tg = mem_zalloc(sizeof(struct pubsub_tgtd)); + + if (!ps_tg) { + return 0; + } + + msgbuf_head_init(&ps_tg->ls_head, SP_SNDWND); + generic_tgtd_init(ep, &ps_tg->tg, fd); + return &ps_tg->tg; +} + +static void sub_ep_term(struct epbase* ep, struct tgtd* tg) { + pubsub_tgtd_free(get_pubsub_tgtd(tg)); +} + +static const ep_setopt setopt_vfptr[] = { + 0, +}; + +static const ep_getopt getopt_vfptr[] = { + 0, +}; + +static int sub_ep_setopt(struct epbase* ep, int opt, void* optval, int optlen) { + int rc; + + if (opt < 0 || opt >= NELEM(setopt_vfptr) || !setopt_vfptr[opt]) { + ERRNO_RETURN(EINVAL); + } + + rc = setopt_vfptr[opt](ep, optval, optlen); + return rc; +} + +static int sub_ep_getopt(struct epbase* ep, int opt, void* optval, int* optlen) { + int rc; + + if (opt < 0 || opt >= NELEM(getopt_vfptr) || !getopt_vfptr[opt]) { + ERRNO_RETURN(EINVAL); + } + + rc = getopt_vfptr[opt](ep, optval, optlen); + return rc; +} + +static struct epbase_vfptr sub_epbase = { + .sp_family = SP_PUBSUB, + .sp_type = SP_SUB, + .alloc = sub_ep_alloc, + .destroy = sub_ep_destroy, + .send = sub_ep_send, + .add = sub_ep_add, + .rm = sub_ep_rm, + .join = sub_ep_join, + .term = sub_ep_term, + .setopt = sub_ep_setopt, + .getopt = sub_ep_getopt, +}; + +struct epbase_vfptr* subep_vfptr = &sub_epbase; + + + + + + diff --git a/pool/shard008/C/0130293_memopen.c b/pool/shard008/C/0130293_memopen.c new file mode 100644 index 0000000000000000000000000000000000000000..96e20a3fc5ed129d5e4c4aa957d353cd20cc6e8c --- /dev/null +++ b/pool/shard008/C/0130293_memopen.c @@ -0,0 +1,34 @@ +/* String Streams + Copyright (C) 1991-2016 Free Software Foundation, Inc. + + 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, if not, see . +*/ + +#include + +static char buffer[] = "foobar"; + +int +main (void) +{ + int ch; + FILE *stream; + + stream = fmemopen (buffer, strlen (buffer), "r"); + while ((ch = fgetc (stream)) != EOF) + printf ("Got %c\n", ch); + fclose (stream); + + return 0; +} diff --git a/pool/shard008/C/0130295_ddr.c b/pool/shard008/C/0130295_ddr.c new file mode 100644 index 0000000000000000000000000000000000000000..1252e758f7085a6d6e7ac67db04a2c09d84a5b96 --- /dev/null +++ b/pool/shard008/C/0130295_ddr.c @@ -0,0 +1,251 @@ +/* + * Copyright 2010-2011 Freescale Semiconductor, Inc. + * + * See file CREDITS for list of people who contributed to this + * project. + * + * 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., 59 Temple Place, Suite 330, Boston, + * MA 02111-1307 USA + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +DECLARE_GLOBAL_DATA_PTR; + +#ifndef CONFIG_DDR_RAW_TIMING +#define CONFIG_SYS_DRAM_SIZE 1024 + +fsl_ddr_cfg_regs_t ddr_cfg_regs_800 = { + .cs[0].bnds = CONFIG_SYS_DDR_CS0_BNDS, + .cs[0].config = CONFIG_SYS_DDR_CS0_CONFIG, + .cs[0].config_2 = CONFIG_SYS_DDR_CS0_CONFIG_2, + .timing_cfg_3 = CONFIG_SYS_DDR_TIMING_3_800, + .timing_cfg_0 = CONFIG_SYS_DDR_TIMING_0_800, + .timing_cfg_1 = CONFIG_SYS_DDR_TIMING_1_800, + .timing_cfg_2 = CONFIG_SYS_DDR_TIMING_2_800, + .ddr_sdram_cfg = CONFIG_SYS_DDR_CONTROL, + .ddr_sdram_cfg_2 = CONFIG_SYS_DDR_CONTROL_2, + .ddr_sdram_mode = CONFIG_SYS_DDR_MODE_1_800, + .ddr_sdram_mode_2 = CONFIG_SYS_DDR_MODE_2_800, + .ddr_sdram_md_cntl = CONFIG_SYS_DDR_MODE_CONTROL, + .ddr_sdram_interval = CONFIG_SYS_DDR_INTERVAL_800, + .ddr_data_init = CONFIG_MEM_INIT_VALUE, + .ddr_sdram_clk_cntl = CONFIG_SYS_DDR_CLK_CTRL_800, + .ddr_init_addr = CONFIG_SYS_DDR_INIT_ADDR, + .ddr_init_ext_addr = CONFIG_SYS_DDR_INIT_EXT_ADDR, + .timing_cfg_4 = CONFIG_SYS_DDR_TIMING_4, + .timing_cfg_5 = CONFIG_SYS_DDR_TIMING_5, + .ddr_zq_cntl = CONFIG_SYS_DDR_ZQ_CONTROL, + .ddr_wrlvl_cntl = CONFIG_SYS_DDR_WRLVL_CONTROL_800, + .ddr_sr_cntr = CONFIG_SYS_DDR_SR_CNTR, + .ddr_sdram_rcw_1 = CONFIG_SYS_DDR_RCW_1, + .ddr_sdram_rcw_2 = CONFIG_SYS_DDR_RCW_2 +}; + +fsl_ddr_cfg_regs_t ddr_cfg_regs_667 = { + .cs[0].bnds = CONFIG_SYS_DDR_CS0_BNDS, + .cs[0].config = CONFIG_SYS_DDR_CS0_CONFIG, + .cs[0].config_2 = CONFIG_SYS_DDR_CS0_CONFIG_2, + .timing_cfg_3 = CONFIG_SYS_DDR_TIMING_3_667, + .timing_cfg_0 = CONFIG_SYS_DDR_TIMING_0_667, + .timing_cfg_1 = CONFIG_SYS_DDR_TIMING_1_667, + .timing_cfg_2 = CONFIG_SYS_DDR_TIMING_2_667, + .ddr_sdram_cfg = CONFIG_SYS_DDR_CONTROL, + .ddr_sdram_cfg_2 = CONFIG_SYS_DDR_CONTROL_2, + .ddr_sdram_mode = CONFIG_SYS_DDR_MODE_1_667, + .ddr_sdram_mode_2 = CONFIG_SYS_DDR_MODE_2_667, + .ddr_sdram_md_cntl = CONFIG_SYS_DDR_MODE_CONTROL, + .ddr_sdram_interval = CONFIG_SYS_DDR_INTERVAL_667, + .ddr_data_init = CONFIG_MEM_INIT_VALUE, + .ddr_sdram_clk_cntl = CONFIG_SYS_DDR_CLK_CTRL_667, + .ddr_init_addr = CONFIG_SYS_DDR_INIT_ADDR, + .ddr_init_ext_addr = CONFIG_SYS_DDR_INIT_EXT_ADDR, + .timing_cfg_4 = CONFIG_SYS_DDR_TIMING_4, + .timing_cfg_5 = CONFIG_SYS_DDR_TIMING_5, + .ddr_zq_cntl = CONFIG_SYS_DDR_ZQ_CONTROL, + .ddr_wrlvl_cntl = CONFIG_SYS_DDR_WRLVL_CONTROL_667, + .ddr_sr_cntr = CONFIG_SYS_DDR_SR_CNTR, + .ddr_sdram_rcw_1 = CONFIG_SYS_DDR_RCW_1, + .ddr_sdram_rcw_2 = CONFIG_SYS_DDR_RCW_2 +}; + +fixed_ddr_parm_t fixed_ddr_parm_0[] = { + {750, 850, &ddr_cfg_regs_800}, + {607, 749, &ddr_cfg_regs_667}, + {0, 0, NULL} +}; + +unsigned long get_sdram_size(void) +{ + struct cpu_type *cpu; + phys_size_t ddr_size; + + cpu = gd->cpu; + /* P1014 and it's derivatives support max 16it DDR width */ + if (cpu->soc_ver == SVR_P1014) + ddr_size = (CONFIG_SYS_DRAM_SIZE / 2); + else + ddr_size = CONFIG_SYS_DRAM_SIZE; + + return ddr_size; +} + +/* + * Fixed sdram init -- doesn't use serial presence detect. + */ +phys_size_t fixed_sdram(void) +{ + int i; + char buf[32]; + fsl_ddr_cfg_regs_t ddr_cfg_regs; + phys_size_t ddr_size; + ulong ddr_freq, ddr_freq_mhz; + struct cpu_type *cpu; + +#if defined(CONFIG_SYS_RAMBOOT) + return CONFIG_SYS_SDRAM_SIZE * 1024 * 1024; +#endif + + ddr_freq = get_ddr_freq(0); + ddr_freq_mhz = ddr_freq / 1000000; + + printf("Configuring DDR for %s MT/s data rate\n", + strmhz(buf, ddr_freq)); + + for (i = 0; fixed_ddr_parm_0[i].max_freq > 0; i++) { + if ((ddr_freq_mhz > fixed_ddr_parm_0[i].min_freq) && + (ddr_freq_mhz <= fixed_ddr_parm_0[i].max_freq)) { + memcpy(&ddr_cfg_regs, fixed_ddr_parm_0[i].ddr_settings, + sizeof(ddr_cfg_regs)); + break; + } + } + + if (fixed_ddr_parm_0[i].max_freq == 0) + panic("Unsupported DDR data rate %s MT/s data rate\n", + strmhz(buf, ddr_freq)); + + cpu = gd->cpu; + /* P1014 and it's derivatives support max 16bit DDR width */ + if (cpu->soc_ver == SVR_P1014) { + ddr_cfg_regs.ddr_sdram_cfg &= ~SDRAM_CFG_DBW_MASK; + ddr_cfg_regs.ddr_sdram_cfg |= SDRAM_CFG_16_BE; + /* divide SA and EA by two and then mask the rest so we don't + * write to reserved fields */ + ddr_cfg_regs.cs[0].bnds = (CONFIG_SYS_DDR_CS0_BNDS >> 1) & 0x0fff0fff; + } + + ddr_size = (phys_size_t) CONFIG_SYS_SDRAM_SIZE * 1024 * 1024; + fsl_ddr_set_memctl_regs(&ddr_cfg_regs, 0); + + if (set_ddr_laws(CONFIG_SYS_DDR_SDRAM_BASE, ddr_size, + LAW_TRGT_IF_DDR_1) < 0) { + printf("ERROR setting Local Access Windows for DDR\n"); + return 0; + } + + return ddr_size; +} + +#else /* CONFIG_DDR_RAW_TIMING */ +/* + * Samsung K4B2G0846C-HCF8 + * The following timing are for "downshift" + * i.e. to use CL9 part as CL7 + * otherwise, tAA, tRCD, tRP will be 13500ps + * and tRC will be 49500ps + */ +dimm_params_t ddr_raw_timing = { + .n_ranks = 1, + .rank_density = 1073741824u, + .capacity = 1073741824u, + .primary_sdram_width = 32, + .ec_sdram_width = 0, + .registered_dimm = 0, + .mirrored_dimm = 0, + .n_row_addr = 15, + .n_col_addr = 10, + .n_banks_per_sdram_device = 8, + .edc_config = 0, + .burst_lengths_bitmask = 0x0c, + + .tCKmin_X_ps = 1875, + .caslat_X = 0x1e << 4, /* 5,6,7,8 */ + .tAA_ps = 13125, + .tWR_ps = 15000, + .tRCD_ps = 13125, + .tRRD_ps = 7500, + .tRP_ps = 13125, + .tRAS_ps = 37500, + .tRC_ps = 50625, + .tRFC_ps = 160000, + .tWTR_ps = 7500, + .tRTP_ps = 7500, + .refresh_rate_ps = 7800000, + .tFAW_ps = 37500, +}; + +int fsl_ddr_get_dimm_params(dimm_params_t *pdimm, + unsigned int controller_number, + unsigned int dimm_number) +{ + const char dimm_model[] = "Fixed DDR on board"; + + if ((controller_number == 0) && (dimm_number == 0)) { + memcpy(pdimm, &ddr_raw_timing, sizeof(dimm_params_t)); + memset(pdimm->mpart, 0, sizeof(pdimm->mpart)); + memcpy(pdimm->mpart, dimm_model, sizeof(dimm_model) - 1); + } + + return 0; +} + +void fsl_ddr_board_options(memctl_options_t *popts, + dimm_params_t *pdimm, + unsigned int ctrl_num) +{ + struct cpu_type *cpu; + int i; + popts->clk_adjust = 6; + popts->cpo_override = 0x1f; + popts->write_data_delay = 2; + popts->half_strength_driver_enable = 1; + /* Write leveling override */ + popts->wrlvl_en = 1; + popts->wrlvl_override = 1; + popts->wrlvl_sample = 0xf; + popts->wrlvl_start = 0x8; + popts->trwt_override = 1; + popts->trwt = 0; + + cpu = gd->cpu; + /* P1014 and it's derivatives support max 16it DDR width */ + if (cpu->soc_ver == SVR_P1014) + popts->data_bus_width = DDR_DATA_BUS_WIDTH_16; + + for (i = 0; i < CONFIG_CHIP_SELECTS_PER_CTRL; i++) { + popts->cs_local_opts[i].odt_rd_cfg = FSL_DDR_ODT_NEVER; + popts->cs_local_opts[i].odt_wr_cfg = FSL_DDR_ODT_CS; + } +} + +#endif /* CONFIG_DDR_RAW_TIMING */ diff --git a/pool/shard008/C/0130300_wee-hook-modifier.c b/pool/shard008/C/0130300_wee-hook-modifier.c new file mode 100644 index 0000000000000000000000000000000000000000..654439e14ec91f7b31ede3522110f7dedead59e3 --- /dev/null +++ b/pool/shard008/C/0130300_wee-hook-modifier.c @@ -0,0 +1,204 @@ +/* + * wee-hook-modifier.c - WeeChat modifier hook + * + * Copyright (C) 2003-2018 Sébastien Helleu + * + * This file is part of WeeChat, the extensible chat client. + * + * WeeChat 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. + * + * WeeChat 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 WeeChat. If not, see . + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include + +#include "../weechat.h" +#include "../wee-hook.h" +#include "../wee-infolist.h" +#include "../wee-log.h" +#include "../wee-string.h" + + +/* + * Hooks a modifier. + * + * Returns pointer to new hook, NULL if error. + */ + +struct t_hook * +hook_modifier (struct t_weechat_plugin *plugin, const char *modifier, + t_hook_callback_modifier *callback, + const void *callback_pointer, + void *callback_data) +{ + struct t_hook *new_hook; + struct t_hook_modifier *new_hook_modifier; + int priority; + const char *ptr_modifier; + + if (!modifier || !modifier[0] || !callback) + return NULL; + + new_hook = malloc (sizeof (*new_hook)); + if (!new_hook) + return NULL; + new_hook_modifier = malloc (sizeof (*new_hook_modifier)); + if (!new_hook_modifier) + { + free (new_hook); + return NULL; + } + + hook_get_priority_and_name (modifier, &priority, &ptr_modifier); + hook_init_data (new_hook, plugin, HOOK_TYPE_MODIFIER, priority, + callback_pointer, callback_data); + + new_hook->hook_data = new_hook_modifier; + new_hook_modifier->callback = callback; + new_hook_modifier->modifier = strdup ((ptr_modifier) ? ptr_modifier : modifier); + + hook_add_to_list (new_hook); + + return new_hook; +} + +/* + * Executes a modifier hook. + * + * Note: result must be freed after use. + */ + +char * +hook_modifier_exec (struct t_weechat_plugin *plugin, const char *modifier, + const char *modifier_data, const char *string) +{ + struct t_hook *ptr_hook, *next_hook; + char *new_msg, *message_modified; + + /* make C compiler happy */ + (void) plugin; + + if (!modifier || !modifier[0]) + return NULL; + + new_msg = NULL; + message_modified = strdup (string); + if (!message_modified) + return NULL; + + hook_exec_start (); + + ptr_hook = weechat_hooks[HOOK_TYPE_MODIFIER]; + while (ptr_hook) + { + next_hook = ptr_hook->next_hook; + + if (!ptr_hook->deleted + && !ptr_hook->running + && (string_strcasecmp (HOOK_MODIFIER(ptr_hook, modifier), + modifier) == 0)) + { + ptr_hook->running = 1; + new_msg = (HOOK_MODIFIER(ptr_hook, callback)) + (ptr_hook->callback_pointer, + ptr_hook->callback_data, + modifier, + modifier_data, + message_modified); + ptr_hook->running = 0; + + /* empty string returned => message dropped */ + if (new_msg && !new_msg[0]) + { + free (message_modified); + hook_exec_end (); + return new_msg; + } + + /* new message => keep it as base for next modifier */ + if (new_msg) + { + free (message_modified); + message_modified = new_msg; + } + } + + ptr_hook = next_hook; + } + + hook_exec_end (); + + return message_modified; +} + +/* + * Frees data in a modifier hook. + */ + +void +hook_modifier_free_data (struct t_hook *hook) +{ + if (!hook || !hook->hook_data) + return; + + if (HOOK_MODIFIER(hook, modifier)) + { + free (HOOK_MODIFIER(hook, modifier)); + HOOK_MODIFIER(hook, modifier) = NULL; + } + + free (hook->hook_data); + hook->hook_data = NULL; +} + +/* + * Adds modifier hook data in the infolist item. + * + * Returns: + * 1: OK + * 0: error + */ + +int +hook_modifier_add_to_infolist (struct t_infolist_item *item, + struct t_hook *hook) +{ + if (!item || !hook || !hook->hook_data) + return 0; + + if (!infolist_new_var_pointer (item, "callback", HOOK_MODIFIER(hook, callback))) + return 0; + if (!infolist_new_var_string (item, "modifier", HOOK_MODIFIER(hook, modifier))) + return 0; + + return 1; +} + +/* + * Prints modifier hook data in WeeChat log file (usually for crash dump). + */ + +void +hook_modifier_print_log (struct t_hook *hook) +{ + if (!hook || !hook->hook_data) + return; + + log_printf (" modifier data:"); + log_printf (" callback. . . . . . . : 0x%lx", HOOK_MODIFIER(hook, callback)); + log_printf (" modifier. . . . . . . : '%s'", HOOK_MODIFIER(hook, modifier)); +} diff --git a/pool/shard008/C/0130305_reader.c b/pool/shard008/C/0130305_reader.c new file mode 100644 index 0000000000000000000000000000000000000000..c7912c1f5cfc659a282747b7edd3dae267b8efcd --- /dev/null +++ b/pool/shard008/C/0130305_reader.c @@ -0,0 +1,136 @@ +/* + * Data reader. + * + * Copyright (c) 2007-2010, Naoaki Okazaki + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the names of the authors nor the names of its contributors + * may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* $Id$ */ + +#include + +#include +#include + +#include +#include "iwa.h" + +static int progress(FILE *fpo, int prev, int current) +{ + while (prev < current) { + ++prev; + if (prev % 2 == 0) { + if (prev % 10 == 0) { + fprintf(fpo, "%d", prev / 10); + fflush(fpo); + } else { + fprintf(fpo, ".", prev / 10); + fflush(fpo); + } + } + } + return prev; +} + +int read_data(FILE *fpi, FILE *fpo, crfsuite_data_t* data, int group) +{ + int n = 0; + int lid = -1; + crfsuite_instance_t inst; + crfsuite_item_t item; + crfsuite_attribute_t cont; + iwa_t* iwa = NULL; + crfsuite_dictionary_t *attrs = data->attrs; + crfsuite_dictionary_t *labels = data->labels; + const iwa_token_t *token = NULL; + long filesize = 0, begin = 0, offset = 0; + int prev = 0, current = 0; + + /* Initialize the instance.*/ + crfsuite_instance_init(&inst); + inst.group = group; + + /* Obtain the file size. */ + begin = ftell(fpi); + fseek(fpi, 0, SEEK_END); + filesize = ftell(fpi) - begin; + fseek(fpi, begin, SEEK_SET); + + /* */ + fprintf(fpo, "0"); + fflush(fpo); + prev = 0; + + iwa = iwa_reader(fpi); + while (token = iwa_read(iwa), token != NULL) { + /* Progress report. */ + offset = ftell(fpi); + current = (int)((offset - begin) * 100.0 / (double)filesize); + prev = progress(fpo, prev, current); + + switch (token->type) { + case IWA_BOI: + /* Initialize an item. */ + lid = -1; + crfsuite_item_init(&item); + break; + case IWA_EOI: + /* Append the item to the instance. */ + if (0 <= lid) { + crfsuite_instance_append(&inst, &item, lid); + } + crfsuite_item_finish(&item); + break; + case IWA_ITEM: + if (lid == -1) { + lid = labels->get(labels, token->attr); + } else { + crfsuite_attribute_init(&cont); + cont.aid = attrs->get(attrs, token->attr); + if (token->value && *token->value) { + cont.value = atof(token->value); + } else { + cont.value = 1.0; + } + crfsuite_item_append_attribute(&item, &cont); + } + break; + case IWA_NONE: + case IWA_EOF: + /* Put the training instance. */ + crfsuite_data_append(data, &inst); + crfsuite_instance_finish(&inst); + inst.group = group; + ++n; + break; + } + } + + progress(fpo, prev, 100); + fprintf(fpo, "\n"); + + return n; +} diff --git a/pool/shard008/C/0130306_CWE134_Uncontrolled_Format_String__wchar_t_console_w32_vsnprintf_09.c b/pool/shard008/C/0130306_CWE134_Uncontrolled_Format_String__wchar_t_console_w32_vsnprintf_09.c new file mode 100644 index 0000000000000000000000000000000000000000..16076e79e91c796b8d7c81fa842d534029fc2f69 --- /dev/null +++ b/pool/shard008/C/0130306_CWE134_Uncontrolled_Format_String__wchar_t_console_w32_vsnprintf_09.c @@ -0,0 +1,293 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE134_Uncontrolled_Format_String__wchar_t_console_w32_vsnprintf_09.c +Label Definition File: CWE134_Uncontrolled_Format_String.vasinks.label.xml +Template File: sources-vasinks-09.tmpl.c +*/ +/* + * @description + * CWE: 134 Uncontrolled Format String + * BadSource: console Read input from the console + * GoodSource: Copy a fixed string into data + * Sinks: w32_vsnprintf + * GoodSink: _vsnwprintf with a format string + * BadSink : _vsnwprintf without a format string + * Flow Variant: 09 Control flow: if(GLOBAL_CONST_TRUE) and if(GLOBAL_CONST_FALSE) + * + * */ + +#include +#include "std_testcase.h" + +#ifndef _WIN32 +#include +#endif + +#ifndef OMITBAD + +static void badVaSinkB(wchar_t * data, ...) +{ + { + wchar_t dest[100] = L""; + va_list args; + va_start(args, data); + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + _vsnwprintf(dest, 100-1, data, args); + va_end(args); + printWLine(dest); + } +} + +void CWE134_Uncontrolled_Format_String__wchar_t_console_w32_vsnprintf_09_bad() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(GLOBAL_CONST_TRUE) + { + { + /* Read input from the console */ + size_t dataLen = wcslen(data); + /* if there is room in data, read into it from the console */ + if (100-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgetws() */ + dataLen = wcslen(data); + if (dataLen > 0 && data[dataLen-1] == L'\n') + { + data[dataLen-1] = L'\0'; + } + } + else + { + printLine("fgetws() failed"); + /* Restore NUL terminator if fgetws fails */ + data[dataLen] = L'\0'; + } + } + } + } + if(GLOBAL_CONST_TRUE) + { + badVaSinkB(data, data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +static void goodB2G1VaSinkG(wchar_t * data, ...) +{ + { + wchar_t dest[100] = L""; + va_list args; + va_start(args, data); + /* FIX: Specify the format disallowing a format string vulnerability */ + _vsnwprintf(dest, 100-1, L"%s", args); + va_end(args); + printWLine(dest); + } +} + +/* goodB2G1() - use badsource and goodsink by changing the second GLOBAL_CONST_TRUE to GLOBAL_CONST_FALSE */ +static void goodB2G1() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(GLOBAL_CONST_TRUE) + { + { + /* Read input from the console */ + size_t dataLen = wcslen(data); + /* if there is room in data, read into it from the console */ + if (100-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgetws() */ + dataLen = wcslen(data); + if (dataLen > 0 && data[dataLen-1] == L'\n') + { + data[dataLen-1] = L'\0'; + } + } + else + { + printLine("fgetws() failed"); + /* Restore NUL terminator if fgetws fails */ + data[dataLen] = L'\0'; + } + } + } + } + if(GLOBAL_CONST_FALSE) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + goodB2G1VaSinkG(data, data); + } +} + +static void goodB2G2VaSinkG(wchar_t * data, ...) +{ + { + wchar_t dest[100] = L""; + va_list args; + va_start(args, data); + /* FIX: Specify the format disallowing a format string vulnerability */ + _vsnwprintf(dest, 100-1, L"%s", args); + va_end(args); + printWLine(dest); + } +} + +/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ +static void goodB2G2() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(GLOBAL_CONST_TRUE) + { + { + /* Read input from the console */ + size_t dataLen = wcslen(data); + /* if there is room in data, read into it from the console */ + if (100-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgetws() */ + dataLen = wcslen(data); + if (dataLen > 0 && data[dataLen-1] == L'\n') + { + data[dataLen-1] = L'\0'; + } + } + else + { + printLine("fgetws() failed"); + /* Restore NUL terminator if fgetws fails */ + data[dataLen] = L'\0'; + } + } + } + } + if(GLOBAL_CONST_TRUE) + { + goodB2G2VaSinkG(data, data); + } +} + +static void goodG2B1VaSinkB(wchar_t * data, ...) +{ + { + wchar_t dest[100] = L""; + va_list args; + va_start(args, data); + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + _vsnwprintf(dest, 100-1, data, args); + va_end(args); + printWLine(dest); + } +} + +/* goodG2B1() - use goodsource and badsink by changing the first GLOBAL_CONST_TRUE to GLOBAL_CONST_FALSE */ +static void goodG2B1() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(GLOBAL_CONST_FALSE) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Use a fixed string that does not contain a format specifier */ + wcscpy(data, L"fixedstringtest"); + } + if(GLOBAL_CONST_TRUE) + { + goodG2B1VaSinkB(data, data); + } +} + +static void goodG2B2VaSinkB(wchar_t * data, ...) +{ + { + wchar_t dest[100] = L""; + va_list args; + va_start(args, data); + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + _vsnwprintf(dest, 100-1, data, args); + va_end(args); + printWLine(dest); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */ +static void goodG2B2() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(GLOBAL_CONST_TRUE) + { + /* FIX: Use a fixed string that does not contain a format specifier */ + wcscpy(data, L"fixedstringtest"); + } + if(GLOBAL_CONST_TRUE) + { + goodG2B2VaSinkB(data, data); + } +} + +void CWE134_Uncontrolled_Format_String__wchar_t_console_w32_vsnprintf_09_good() +{ + goodG2B1(); + goodG2B2(); + goodB2G1(); + goodB2G2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE134_Uncontrolled_Format_String__wchar_t_console_w32_vsnprintf_09_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE134_Uncontrolled_Format_String__wchar_t_console_w32_vsnprintf_09_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard008/C/0130307_CWE134_Uncontrolled_Format_String__char_environment_vprintf_04.c b/pool/shard008/C/0130307_CWE134_Uncontrolled_Format_String__char_environment_vprintf_04.c new file mode 100644 index 0000000000000000000000000000000000000000..3d1d8188523f70b4469b903d9c6176e7cee9f34b --- /dev/null +++ b/pool/shard008/C/0130307_CWE134_Uncontrolled_Format_String__char_environment_vprintf_04.c @@ -0,0 +1,255 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE134_Uncontrolled_Format_String__char_environment_vprintf_04.c +Label Definition File: CWE134_Uncontrolled_Format_String.vasinks.label.xml +Template File: sources-vasinks-04.tmpl.c +*/ +/* + * @description + * CWE: 134 Uncontrolled Format String + * BadSource: environment Read input from an environment variable + * GoodSource: Copy a fixed string into data + * Sinks: vprintf + * GoodSink: vprintf with a format string + * BadSink : vprintf without a format string + * Flow Variant: 04 Control flow: if(STATIC_CONST_TRUE) and if(STATIC_CONST_FALSE) + * + * */ + +#include +#include "std_testcase.h" + +#ifndef _WIN32 +#include +#endif + +#define ENV_VARIABLE "ADD" + +#ifdef _WIN32 +#define GETENV getenv +#else +#define GETENV getenv +#endif + +/* The two variables below are declared "const", so a tool should + be able to identify that reads of these will always return their + initialized values. */ +static const int STATIC_CONST_TRUE = 1; /* true */ +static const int STATIC_CONST_FALSE = 0; /* false */ + +#ifndef OMITBAD + +static void badVaSinkB(char * data, ...) +{ + { + va_list args; + va_start(args, data); + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + vprintf(data, args); + va_end(args); + } +} + +void CWE134_Uncontrolled_Format_String__char_environment_vprintf_04_bad() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(STATIC_CONST_TRUE) + { + { + /* Append input from an environment variable to data */ + size_t dataLen = strlen(data); + char * environment = GETENV(ENV_VARIABLE); + /* If there is data in the environment variable */ + if (environment != NULL) + { + /* POTENTIAL FLAW: Read data from an environment variable */ + strncat(data+dataLen, environment, 100-dataLen-1); + } + } + } + if(STATIC_CONST_TRUE) + { + badVaSinkB(data, data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +static void goodB2G1VaSinkG(char * data, ...) +{ + { + va_list args; + va_start(args, data); + /* FIX: Specify the format disallowing a format string vulnerability */ + vprintf("%s", args); + va_end(args); + } +} + +/* goodB2G1() - use badsource and goodsink by changing the second STATIC_CONST_TRUE to STATIC_CONST_FALSE */ +static void goodB2G1() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(STATIC_CONST_TRUE) + { + { + /* Append input from an environment variable to data */ + size_t dataLen = strlen(data); + char * environment = GETENV(ENV_VARIABLE); + /* If there is data in the environment variable */ + if (environment != NULL) + { + /* POTENTIAL FLAW: Read data from an environment variable */ + strncat(data+dataLen, environment, 100-dataLen-1); + } + } + } + if(STATIC_CONST_FALSE) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + goodB2G1VaSinkG(data, data); + } +} + +static void goodB2G2VaSinkG(char * data, ...) +{ + { + va_list args; + va_start(args, data); + /* FIX: Specify the format disallowing a format string vulnerability */ + vprintf("%s", args); + va_end(args); + } +} + +/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ +static void goodB2G2() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(STATIC_CONST_TRUE) + { + { + /* Append input from an environment variable to data */ + size_t dataLen = strlen(data); + char * environment = GETENV(ENV_VARIABLE); + /* If there is data in the environment variable */ + if (environment != NULL) + { + /* POTENTIAL FLAW: Read data from an environment variable */ + strncat(data+dataLen, environment, 100-dataLen-1); + } + } + } + if(STATIC_CONST_TRUE) + { + goodB2G2VaSinkG(data, data); + } +} + +static void goodG2B1VaSinkB(char * data, ...) +{ + { + va_list args; + va_start(args, data); + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + vprintf(data, args); + va_end(args); + } +} + +/* goodG2B1() - use goodsource and badsink by changing the first STATIC_CONST_TRUE to STATIC_CONST_FALSE */ +static void goodG2B1() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(STATIC_CONST_FALSE) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Use a fixed string that does not contain a format specifier */ + strcpy(data, "fixedstringtest"); + } + if(STATIC_CONST_TRUE) + { + goodG2B1VaSinkB(data, data); + } +} + +static void goodG2B2VaSinkB(char * data, ...) +{ + { + va_list args; + va_start(args, data); + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + vprintf(data, args); + va_end(args); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */ +static void goodG2B2() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + if(STATIC_CONST_TRUE) + { + /* FIX: Use a fixed string that does not contain a format specifier */ + strcpy(data, "fixedstringtest"); + } + if(STATIC_CONST_TRUE) + { + goodG2B2VaSinkB(data, data); + } +} + +void CWE134_Uncontrolled_Format_String__char_environment_vprintf_04_good() +{ + goodG2B1(); + goodG2B2(); + goodB2G1(); + goodB2G2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE134_Uncontrolled_Format_String__char_environment_vprintf_04_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE134_Uncontrolled_Format_String__char_environment_vprintf_04_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard008/C/0130312_attr-alloc_size-8.c b/pool/shard008/C/0130312_attr-alloc_size-8.c new file mode 100644 index 0000000000000000000000000000000000000000..b8ba9424b4e5186418162968924e01275d0c5af3 --- /dev/null +++ b/pool/shard008/C/0130312_attr-alloc_size-8.c @@ -0,0 +1,62 @@ +/* PR c/78284 - warn on malloc with very large arguments + Test to exercise the interaction of the -Walloca-larger-than, + -Wvla-larger-than, and -Walloc-size-larger-than options. The former + two more specific options override the more general latter option. */ +/* { dg-do compile } */ +/* { dg-require-effective-target alloca } */ +/* { dg-options "-O2 -Walloc-size-larger-than=123 -Walloca-larger-than=234 -Wvla-larger-than=345" } */ + +#define SIZE_MAX __SIZE_MAX__ + +typedef __SIZE_TYPE__ size_t; + +void sink (void*); + +size_t alloc_size_limit (void) +{ + return 123; +} + +size_t alloca_limit (void) +{ + return 234; +} + +size_t vla_limit (void) +{ + return 345; +} + +void test_alloca (void) +{ + void *p; + + /* No warning should be issued for the following call because the more + permissive alloca limit overrides the stricter alloc_size limit. */ + p = __builtin_alloca (alloca_limit ()); + sink (p); + + p = __builtin_alloca (alloca_limit () + 1); /* { dg-warning "argument to .alloca. is too large" } */ + sink (p); +} + +void test_vla (void) +{ + /* Same as above, no warning should be issued here because the more + permissive VLA limit overrides the stricter alloc_size limit. */ + char vla1 [vla_limit ()]; + sink (vla1); + + char vla2 [vla_limit () + 1]; /* { dg-warning "argument to variable-length array is too large" } */ + sink (vla2); +} + +void test_malloc (void) +{ + void *p; + p = __builtin_malloc (alloc_size_limit ()); + sink (p); + + p = __builtin_malloc (alloc_size_limit () + 1); /* { dg-warning "argument 1 value .124\[lu\]*. exceeds maximum object size 123" } */ + sink (p); +} diff --git a/pool/shard008/C/0130318_179_largest_number.c b/pool/shard008/C/0130318_179_largest_number.c new file mode 100644 index 0000000000000000000000000000000000000000..2d0c68783515622cceae8b9f602e5b03db61e4f0 --- /dev/null +++ b/pool/shard008/C/0130318_179_largest_number.c @@ -0,0 +1,55 @@ +#include +#include +#include + +static int cmpfun(const void *a, const void *b) +{ + static char buf1[32], buf2[32]; + int i; + + sprintf(buf1, "%d%d", *(int *)a, *(int *)b); + sprintf(buf2, "%d%d", *(int *)b, *(int *)a); + for (i = 0; buf1[i] && buf2[i]; i++) { + if (buf1[i] > buf2[i]) + return(-1); + else if (buf1[i] < buf2[i]) + return(1); + } + return(0); +} + +char *largestNumber(int *nums, int numsSize) +{ + static char buf[16]; + int i, total, len; + char *res; + + if (!numsSize) { + return(strdup("0")); + } + qsort(nums, numsSize, sizeof(int), cmpfun); + res = 0; + total = 1; + for (i = 0; i < numsSize; i++) { + len = sprintf(buf, "%d", nums[i]); + if (!res) { + res = malloc((len + 1)); + res[0] = 0; + } else { + res = realloc(res, total + len); + } + strcat(res, buf); + if (i == 0 && nums[i] == 0) + break; + total += len; + } + return(res); +} + +int main(void) +{ + int x[] = { 824, 938, 1399, 5607, 6973, 5703, 9609, 4398, + 8247}; + printf("%s\n", largestNumber(x, sizeof(x) / sizeof(int))); + return(0); +} diff --git a/pool/shard008/C/0130327_main.c b/pool/shard008/C/0130327_main.c new file mode 100644 index 0000000000000000000000000000000000000000..59e42c994cc6d02b0c036f2559816cd0e193ca45 --- /dev/null +++ b/pool/shard008/C/0130327_main.c @@ -0,0 +1,486 @@ +/* + FreeRTOS V9.0.0rc2 - Copyright (C) 2016 Real Time Engineers Ltd. + All rights reserved + + VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + This file is part of the FreeRTOS distribution. + + FreeRTOS is free software; you can redistribute it and/or modify it under + the terms of the GNU General Public License (version 2) as published by the + Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception. + + *************************************************************************** + >>! NOTE: The modification to the GPL is included to allow you to !<< + >>! distribute a combined work that includes FreeRTOS without being !<< + >>! obliged to provide the source code for proprietary components !<< + >>! outside of the FreeRTOS kernel. !<< + *************************************************************************** + + FreeRTOS 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. Full license text is available on the following + link: http://www.freertos.org/a00114.html + + *************************************************************************** + * * + * FreeRTOS provides completely free yet professionally developed, * + * robust, strictly quality controlled, supported, and cross * + * platform software that is more than just the market leader, it * + * is the industry's de facto standard. * + * * + * Help yourself get started quickly while simultaneously helping * + * to support the FreeRTOS project by purchasing a FreeRTOS * + * tutorial book, reference manual, or both: * + * http://www.FreeRTOS.org/Documentation * + * * + *************************************************************************** + + http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading + the FAQ page "My application does not run, what could be wrong?". Have you + defined configASSERT()? + + http://www.FreeRTOS.org/support - In return for receiving this top quality + embedded software for free we request you assist our global community by + participating in the support forum. + + http://www.FreeRTOS.org/training - Investing in training allows your team to + be as productive as possible as early as possible. Now you can receive + FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers + Ltd, and the world's leading authority on the world's leading RTOS. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool, a DOS + compatible FAT file system, and our tiny thread aware UDP/IP stack. + + http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate. + Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS. + + http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High + Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS + licenses offer ticketed support, indemnification and commercial middleware. + + http://www.SafeRTOS.com - High Integrity Systems also provide a safety + engineered and independently SIL3 certified version for use in safety and + mission critical applications that require provable dependability. + + 1 tab == 4 spaces! +*/ + +/* + NOTE : Tasks run in system mode and the scheduler runs in Supervisor mode. + The processor MUST be in supervisor mode when vTaskStartScheduler is + called. The demo applications included in the FreeRTOS.org download switch + to supervisor mode prior to main being called. If you are not using one of + these demo application projects then ensure Supervisor mode is used. +*/ + +/* + * Creates all the demo application tasks, then starts the scheduler. The WEB + * documentation provides more details of the demo application tasks. + * + * A few tasks are created that are not part of the standard demo. These are + * the 'LCD' task, the 'LCD Message' task, a WEB server task and the 'Check' + * task. + * + * The LCD task is the only task that accesses the LCD directly, so mutual + * exclusion is ensured. Any task wishing to display text sends the LCD task + * a message containing a pointer to the string that should be displayed. + * The LCD task itself just blocks on a queue waiting for such a message to + * arrive - processing each in turn. + * + * The LCD Message task does nothing other than periodically send messages to + * the LCD task. The messages originating from the LCD Message task are + * displayed on the top row of the LCD. + * + * The Check task only executes every three seconds but has the highest + * priority so is guaranteed to get processor time. Its main function is to + * check that all the other tasks are still operational. Most tasks maintain + * a unique count that is incremented each time the task successfully completes + * a cycle of its function. Should any error occur within such a task the + * count is permanently halted. The check task sets a bit in an error status + * flag should it find any counter variable at a value that indicates an + * error has occurred. The error flag value is converted to a string and sent + * to the LCD task for display on the bottom row on the LCD. + */ + +/* Standard includes. */ +#include + +/* Library includes. */ +#include "91x_lib.h" + +/* Scheduler includes. */ +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" + +/* Demo application includes. */ +#include "lcd.h" +#include "flash.h" +#include "integer.h" +#include "PollQ.h" +#include "BlockQ.h" +#include "semtest.h" +#include "dynamic.h" +#include "partest.h" +#include "flop.h" +#include "comtest2.h" +#include "serial.h" +#include "GenQTest.h" +#include "QPeek.h" + +#ifdef STACK_LWIP + #include "BasicWEB.h" + #include "sys.h" +#endif + +/* Priorities for the demo application tasks. */ +#define mainLED_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 ) +#define mainQUEUE_POLL_PRIORITY ( tskIDLE_PRIORITY + 2 ) +#define mainCHECK_TASK_PRIORITY ( tskIDLE_PRIORITY + 4 ) +#define mainSEM_TEST_PRIORITY ( tskIDLE_PRIORITY + 1 ) +#define mainBLOCK_Q_PRIORITY ( tskIDLE_PRIORITY + 2 ) +#define mainCOM_TEST_PRIORITY ( tskIDLE_PRIORITY + 3 ) +#define mainLCD_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 ) +#define mainMSG_TASK_PRIORITY ( tskIDLE_PRIORITY + 1 ) +#define mainGENERIC_QUEUE_PRIORITY ( tskIDLE_PRIORITY ) + +/* Delays used by the various tasks defined in this file. */ +#define mainCHECK_PERIOD ( ( TickType_t ) 3000 / portTICK_PERIOD_MS ) +#define mainSTRING_WRITE_DELAY ( 500 / portTICK_PERIOD_MS ) +#define mainLCD_DELAY ( 20 / portTICK_PERIOD_MS ) + +/* Constants for the ComTest tasks. */ +#define mainCOM_TEST_BAUD_RATE ( ( unsigned long ) 115200 ) +#define mainCOM_TEST_LED ( 3 ) + +/* The maximum number of messages that can be pending to be written to the LCD. */ +#define mainLCD_QUEUE_LEN ( 6 ) + +/* Dimension the buffer used to write the error flag string. */ +#define mainMAX_FLAG_STRING_LEN ( 32 ) + +/* The structure that is passed on the LCD message queue. */ +typedef struct +{ + char **ppcMessageToDisplay; /*<< Points to a char* pointing to the message to display. */ + portBASE_TYPE xRow; /*<< The row on which the message should be displayed. */ +} xLCDMessage; +/*-----------------------------------------------------------*/ + +/* + * The task that executes at the highest priority and calls + * prvCheckOtherTasksAreStillRunning(). See the description at the top + * of the file. + */ +static void vErrorChecks( void *pvParameters ); + +/* + * Configure the processor clock and ports. + */ +static void prvSetupHardware( void ); + +/* + * Checks that all the demo application tasks are still executing without error + * - as described at the top of the file. Called by vErrorChecks(). + */ +static void prvCheckOtherTasksAreStillRunning( void ); + +#ifdef STACK_UIP + /* + * The WEB server task prototype. The task is created in this file but defined + * elsewhere. STACK_UIP is defined when the uIP stack is used in preference + * to the lwIP stack. + */ + extern void vuIP_Task(void *pvParameters); +#endif + +/* + * The task that displays text on the LCD. + */ +static void prvLCDTask( void * pvParameters ); + +/* + * The task that sends messages to be displayed on the top row of the LCD. + */ +static void prvLCDMessageTask( void * pvParameters ); + +/*-----------------------------------------------------------*/ + +/* The queue used to pass messages to the LCD task. */ +static QueueHandle_t xLCDQueue; + +/* Error status flag. */ +static unsigned long ulErrorFlags = 0; + +/*-----------------------------------------------------------*/ + +/* + * Starts all the other tasks, then starts the scheduler. + */ +void main( void ) +{ + #ifdef DEBUG + debug(); + #endif + + /* Setup any hardware that has not already been configured by the low + level init routines. */ + prvSetupHardware(); + /* Create the queue used to send data to the LCD task. */ + xLCDQueue = xQueueCreate( mainLCD_QUEUE_LEN, sizeof( xLCDMessage ) ); + + /* Start all the standard demo application tasks. */ + vStartIntegerMathTasks( tskIDLE_PRIORITY ); + vStartLEDFlashTasks( mainLED_TASK_PRIORITY ); + vStartPolledQueueTasks( mainQUEUE_POLL_PRIORITY ); + vStartSemaphoreTasks( mainSEM_TEST_PRIORITY ); + vStartBlockingQueueTasks( mainBLOCK_Q_PRIORITY ); + vStartDynamicPriorityTasks(); + vStartMathTasks( tskIDLE_PRIORITY ); + vAltStartComTestTasks( mainCOM_TEST_PRIORITY, mainCOM_TEST_BAUD_RATE, mainCOM_TEST_LED ); + vStartGenericQueueTasks( mainGENERIC_QUEUE_PRIORITY ); + vStartQueuePeekTasks(); + + /* Start the tasks which are defined in this file. */ + xTaskCreate( vErrorChecks, "Check", configMINIMAL_STACK_SIZE, NULL, mainCHECK_TASK_PRIORITY, NULL ); + xTaskCreate( prvLCDTask, "LCD", configMINIMAL_STACK_SIZE, ( void * ) &xLCDQueue, mainLCD_TASK_PRIORITY, NULL ); + xTaskCreate( prvLCDMessageTask, "MSG", configMINIMAL_STACK_SIZE, ( void * ) &xLCDQueue, mainMSG_TASK_PRIORITY, NULL ); + + /* Start either the uIP TCP/IP stack or the lwIP TCP/IP stack. */ + #ifdef STACK_UIP + /* Finally, create the WEB server task. */ + xTaskCreate( vuIP_Task, "uIP", configMINIMAL_STACK_SIZE * 3, NULL, mainCHECK_TASK_PRIORITY - 1, NULL ); + #endif + + #ifdef STACK_LWIP + /* Create the lwIP task. This uses the lwIP RTOS abstraction layer.*/ + vlwIPInit(); + sys_set_state( ( signed char * ) "httpd", lwipBASIC_SERVER_STACK_SIZE ); + sys_thread_new( vBasicWEBServer, ( void * ) NULL, basicwebWEBSERVER_PRIORITY ); + sys_set_default_state(); + #endif + + /* Start the scheduler. + + NOTE : Tasks run in system mode and the scheduler runs in Supervisor mode. + The processor MUST be in supervisor mode when vTaskStartScheduler is + called. The demo applications included in the FreeRTOS.org download switch + to supervisor mode prior to main being called. If you are not using one of + these demo application projects then ensure Supervisor mode is used here. */ + + vTaskStartScheduler(); + + /* We should never get here as control is now taken by the scheduler. */ + for( ;; ); +} +/*-----------------------------------------------------------*/ + +static void prvSetupHardware( void ) +{ + /* Configuration taken from the ST code. + + Set Flash banks size & address */ + FMI_BankRemapConfig( 4, 2, 0, 0x80000 ); + + /* FMI Waite States */ + FMI_Config( FMI_READ_WAIT_STATE_2, FMI_WRITE_WAIT_STATE_0, FMI_PWD_ENABLE, FMI_LVD_ENABLE, FMI_FREQ_HIGH ); + + /* Configure the FPLL = 96MHz, and APB to 48MHz. */ + SCU_PCLKDivisorConfig( SCU_PCLK_Div2 ); + SCU_PLLFactorsConfig( 192, 25, 2 ); + SCU_PLLCmd( ENABLE ); + SCU_MCLKSourceConfig( SCU_MCLK_PLL ); + + WDG_Cmd( DISABLE ); + VIC_DeInit(); + + /* GPIO8 clock source enable, used by the LCD. */ + SCU_APBPeriphClockConfig(__GPIO8, ENABLE); + GPIO_DeInit(GPIO8); + + /* GPIO 9 clock source enable, used by the LCD. */ + SCU_APBPeriphClockConfig(__GPIO9, ENABLE); + GPIO_DeInit(GPIO9); + + /* Enable VIC clock */ + SCU_AHBPeriphClockConfig(__VIC, ENABLE); + SCU_AHBPeriphReset(__VIC, DISABLE); + + /* Peripheral initialisation. */ + vParTestInitialise(); +} +/*-----------------------------------------------------------*/ + +static void vErrorChecks( void *pvParameters ) +{ +static char cCheckVal[ mainMAX_FLAG_STRING_LEN ]; +char *pcFlagString; +xLCDMessage xMessageToSend; +TickType_t xLastWakeTime; +char *pcStringsToDisplay[] = { + "Check status flag" + }; + + /* The parameters are not used in this task. */ + ( void ) pvParameters; + + pcFlagString = &cCheckVal[ 0 ]; + + /* Initialise xLastWakeTime to ensure the first call to vTaskDelayUntil() + functions correctly. */ + xLastWakeTime = xTaskGetTickCount(); + + /* Cycle for ever, delaying then checking all the other tasks are still + operating without error. */ + for( ;; ) + { + /* Delay until it is time to execute again. */ + vTaskDelayUntil( &xLastWakeTime, mainCHECK_PERIOD ); + + /* Check all the other tasks to see if the error flag needs updating. */ + prvCheckOtherTasksAreStillRunning(); + + /* Create a string indicating the error flag status. */ + sprintf( cCheckVal, "equals 0x%x ", ulErrorFlags ); + xMessageToSend.xRow = Line2; + + /* Send the first part of the message to the LCD task. */ + xMessageToSend.ppcMessageToDisplay = &pcStringsToDisplay[ 0 ]; + xQueueSend( xLCDQueue, ( void * ) &xMessageToSend, 0 ); + vTaskDelay( mainSTRING_WRITE_DELAY ); + + /* Send the second part of the message to the LCD task. */ + xMessageToSend.ppcMessageToDisplay = &pcFlagString; + xQueueSend( xLCDQueue, ( void * ) &xMessageToSend, 0 ); + } +} +/*-----------------------------------------------------------*/ + +static void prvCheckOtherTasksAreStillRunning( void ) +{ + if( xAreIntegerMathsTaskStillRunning() != pdTRUE ) + { + ulErrorFlags |= 0x01; + } + + if( xArePollingQueuesStillRunning() != pdTRUE ) + { + ulErrorFlags |= 0x02; + } + + if( xAreSemaphoreTasksStillRunning() != pdTRUE ) + { + ulErrorFlags |= 0x04; + } + + if( xAreBlockingQueuesStillRunning() != pdTRUE ) + { + ulErrorFlags |= 0x08; + } + + if( xAreComTestTasksStillRunning() != pdTRUE ) + { + ulErrorFlags |= 0x10; + } + + if( xAreDynamicPriorityTasksStillRunning() != pdTRUE ) + { + ulErrorFlags |= 0x20; + } + + if( xAreMathsTaskStillRunning() != pdTRUE ) + { + ulErrorFlags |= 0x40; + } + + if( xAreGenericQueueTasksStillRunning() != pdTRUE ) + { + ulErrorFlags |= 0x80; + } + + if( xAreQueuePeekTasksStillRunning() != pdTRUE ) + { + ulErrorFlags |= 0x100; + } + +} +/*-----------------------------------------------------------*/ + +static void prvLCDMessageTask( void * pvParameters ) +{ +QueueHandle_t *pxLCDQueue; +xLCDMessage xMessageToSend; +portBASE_TYPE xIndex = 0; + +/* The strings that are written to the LCD. */ +char *pcStringsToDisplay[] = { + "IAR ", + "STR912 ", + "Demo ", + "www.FreeRTOS.org", + "" + }; + + + /* To test the parameter passing mechanism, the queue on which messages are + posted is passed in as a parameter even though it is available as a file + scope variable anyway. */ + pxLCDQueue = ( QueueHandle_t * ) pvParameters; + + for( ;; ) + { + /* Wait until it is time to move onto the next string. */ + vTaskDelay( mainSTRING_WRITE_DELAY ); + + /* Configure the message object to send to the LCD task. */ + xMessageToSend.ppcMessageToDisplay = &pcStringsToDisplay[ xIndex ]; + xMessageToSend.xRow = Line1; + + /* Post the message to be displayed. */ + xQueueSend( *pxLCDQueue, ( void * ) &xMessageToSend, 0 ); + + /* Move onto the next message, wrapping when necessary. */ + xIndex++; + if( *( pcStringsToDisplay[ xIndex ] ) == 0x00 ) + { + xIndex = 0; + + /* Delay longer before going back to the start of the messages. */ + vTaskDelay( mainSTRING_WRITE_DELAY * 2 ); + } + } +} +/*-----------------------------------------------------------*/ + +void prvLCDTask( void * pvParameters ) +{ +QueueHandle_t *pxLCDQueue; +xLCDMessage xReceivedMessage; +char *pcString; + + /* To test the parameter passing mechanism, the queue on which messages are + received is passed in as a parameter even though it is available as a file + scope variable anyway. */ + pxLCDQueue = ( QueueHandle_t * ) pvParameters; + + LCD_Init(); + + for( ;; ) + { + /* Wait for a message to arrive. */ + if( xQueueReceive( *pxLCDQueue, &xReceivedMessage, portMAX_DELAY ) ) + { + /* Where is the string we are going to display? */ + pcString = *xReceivedMessage.ppcMessageToDisplay; + LCD_DisplayString(xReceivedMessage.xRow, pcString, BlackText); + + /* The delay here is just to ensure the LCD task does not starve + out lower priority tasks as writing to the LCD can take a long + time. */ + vTaskDelay( mainLCD_DELAY ); + } + } +} +/*-----------------------------------------------------------*/ diff --git a/pool/shard008/C/0130333_adis16203.c b/pool/shard008/C/0130333_adis16203.c new file mode 100644 index 0000000000000000000000000000000000000000..1d3026dae827e25b07b9c7cc858a2a52724535dc --- /dev/null +++ b/pool/shard008/C/0130333_adis16203.c @@ -0,0 +1,314 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * ADIS16203 Programmable 360 Degrees Inclinometer + * + * Copyright 2010 Analog Devices Inc. + */ + +#include + +#include +#include + +#include +#include +#include + +#define ADIS16203_STARTUP_DELAY 220 /* ms */ + +/* Flash memory write count */ +#define ADIS16203_FLASH_CNT 0x00 + +/* Output, power supply */ +#define ADIS16203_SUPPLY_OUT 0x02 + +/* Output, auxiliary ADC input */ +#define ADIS16203_AUX_ADC 0x08 + +/* Output, temperature */ +#define ADIS16203_TEMP_OUT 0x0A + +/* Output, x-axis inclination */ +#define ADIS16203_XINCL_OUT 0x0C + +/* Output, y-axis inclination */ +#define ADIS16203_YINCL_OUT 0x0E + +/* Incline null calibration */ +#define ADIS16203_INCL_NULL 0x18 + +/* Alarm 1 amplitude threshold */ +#define ADIS16203_ALM_MAG1 0x20 + +/* Alarm 2 amplitude threshold */ +#define ADIS16203_ALM_MAG2 0x22 + +/* Alarm 1, sample period */ +#define ADIS16203_ALM_SMPL1 0x24 + +/* Alarm 2, sample period */ +#define ADIS16203_ALM_SMPL2 0x26 + +/* Alarm control */ +#define ADIS16203_ALM_CTRL 0x28 + +/* Auxiliary DAC data */ +#define ADIS16203_AUX_DAC 0x30 + +/* General-purpose digital input/output control */ +#define ADIS16203_GPIO_CTRL 0x32 + +/* Miscellaneous control */ +#define ADIS16203_MSC_CTRL 0x34 + +/* Internal sample period (rate) control */ +#define ADIS16203_SMPL_PRD 0x36 + +/* Operation, filter configuration */ +#define ADIS16203_AVG_CNT 0x38 + +/* Operation, sleep mode control */ +#define ADIS16203_SLP_CNT 0x3A + +/* Diagnostics, system status register */ +#define ADIS16203_DIAG_STAT 0x3C + +/* Operation, system command register */ +#define ADIS16203_GLOB_CMD 0x3E + +/* MSC_CTRL */ + +/* Self-test at power-on: 1 = disabled, 0 = enabled */ +#define ADIS16203_MSC_CTRL_PWRUP_SELF_TEST BIT(10) + +/* Reverses rotation of both inclination outputs */ +#define ADIS16203_MSC_CTRL_REVERSE_ROT_EN BIT(9) + +/* Self-test enable */ +#define ADIS16203_MSC_CTRL_SELF_TEST_EN BIT(8) + +/* Data-ready enable: 1 = enabled, 0 = disabled */ +#define ADIS16203_MSC_CTRL_DATA_RDY_EN BIT(2) + +/* Data-ready polarity: 1 = active high, 0 = active low */ +#define ADIS16203_MSC_CTRL_ACTIVE_HIGH BIT(1) + +/* Data-ready line selection: 1 = DIO1, 0 = DIO0 */ +#define ADIS16203_MSC_CTRL_DATA_RDY_DIO1 BIT(0) + +/* DIAG_STAT */ + +/* Alarm 2 status: 1 = alarm active, 0 = alarm inactive */ +#define ADIS16203_DIAG_STAT_ALARM2 BIT(9) + +/* Alarm 1 status: 1 = alarm active, 0 = alarm inactive */ +#define ADIS16203_DIAG_STAT_ALARM1 BIT(8) + +/* Self-test diagnostic error flag */ +#define ADIS16203_DIAG_STAT_SELFTEST_FAIL_BIT 5 + +/* SPI communications failure */ +#define ADIS16203_DIAG_STAT_SPI_FAIL_BIT 3 + +/* Flash update failure */ +#define ADIS16203_DIAG_STAT_FLASH_UPT_BIT 2 + +/* Power supply above 3.625 V */ +#define ADIS16203_DIAG_STAT_POWER_HIGH_BIT 1 + +/* Power supply below 2.975 V */ +#define ADIS16203_DIAG_STAT_POWER_LOW_BIT 0 + +/* GLOB_CMD */ + +#define ADIS16203_GLOB_CMD_SW_RESET BIT(7) +#define ADIS16203_GLOB_CMD_CLEAR_STAT BIT(4) +#define ADIS16203_GLOB_CMD_FACTORY_CAL BIT(1) + +#define ADIS16203_ERROR_ACTIVE BIT(14) + +enum adis16203_scan { + ADIS16203_SCAN_INCLI_X, + ADIS16203_SCAN_INCLI_Y, + ADIS16203_SCAN_SUPPLY, + ADIS16203_SCAN_AUX_ADC, + ADIS16203_SCAN_TEMP, +}; + +#define DRIVER_NAME "adis16203" + +static const u8 adis16203_addresses[] = { + [ADIS16203_SCAN_INCLI_X] = ADIS16203_INCL_NULL, +}; + +static int adis16203_write_raw(struct iio_dev *indio_dev, + struct iio_chan_spec const *chan, + int val, + int val2, + long mask) +{ + struct adis *st = iio_priv(indio_dev); + /* currently only one writable parameter which keeps this simple */ + u8 addr = adis16203_addresses[chan->scan_index]; + + return adis_write_reg_16(st, addr, val & 0x3FFF); +} + +static int adis16203_read_raw(struct iio_dev *indio_dev, + struct iio_chan_spec const *chan, + int *val, int *val2, + long mask) +{ + struct adis *st = iio_priv(indio_dev); + int ret; + u8 addr; + s16 val16; + + switch (mask) { + case IIO_CHAN_INFO_RAW: + return adis_single_conversion(indio_dev, chan, + ADIS16203_ERROR_ACTIVE, val); + case IIO_CHAN_INFO_SCALE: + switch (chan->type) { + case IIO_VOLTAGE: + if (chan->channel == 0) { + *val = 1; + *val2 = 220000; /* 1.22 mV */ + } else { + *val = 0; + *val2 = 610000; /* 0.61 mV */ + } + return IIO_VAL_INT_PLUS_MICRO; + case IIO_TEMP: + *val = -470; /* -0.47 C */ + *val2 = 0; + return IIO_VAL_INT_PLUS_MICRO; + case IIO_INCLI: + *val = 0; + *val2 = 25000; /* 0.025 degree */ + return IIO_VAL_INT_PLUS_MICRO; + default: + return -EINVAL; + } + case IIO_CHAN_INFO_OFFSET: + *val = 25000 / -470 - 1278; /* 25 C = 1278 */ + return IIO_VAL_INT; + case IIO_CHAN_INFO_CALIBBIAS: + addr = adis16203_addresses[chan->scan_index]; + ret = adis_read_reg_16(st, addr, &val16); + if (ret) + return ret; + *val = sign_extend32(val16, 13); + return IIO_VAL_INT; + default: + return -EINVAL; + } +} + +static const struct iio_chan_spec adis16203_channels[] = { + ADIS_SUPPLY_CHAN(ADIS16203_SUPPLY_OUT, ADIS16203_SCAN_SUPPLY, 0, 12), + ADIS_AUX_ADC_CHAN(ADIS16203_AUX_ADC, ADIS16203_SCAN_AUX_ADC, 0, 12), + ADIS_INCLI_CHAN(X, ADIS16203_XINCL_OUT, ADIS16203_SCAN_INCLI_X, + BIT(IIO_CHAN_INFO_CALIBBIAS), 0, 14), + /* Fixme: Not what it appears to be - see data sheet */ + ADIS_INCLI_CHAN(Y, ADIS16203_YINCL_OUT, ADIS16203_SCAN_INCLI_Y, + 0, 0, 14), + ADIS_TEMP_CHAN(ADIS16203_TEMP_OUT, ADIS16203_SCAN_TEMP, 0, 12), + IIO_CHAN_SOFT_TIMESTAMP(5), +}; + +static const struct iio_info adis16203_info = { + .read_raw = adis16203_read_raw, + .write_raw = adis16203_write_raw, + .update_scan_mode = adis_update_scan_mode, +}; + +static const char * const adis16203_status_error_msgs[] = { + [ADIS16203_DIAG_STAT_SELFTEST_FAIL_BIT] = "Self test failure", + [ADIS16203_DIAG_STAT_SPI_FAIL_BIT] = "SPI failure", + [ADIS16203_DIAG_STAT_FLASH_UPT_BIT] = "Flash update failed", + [ADIS16203_DIAG_STAT_POWER_HIGH_BIT] = "Power supply above 3.625V", + [ADIS16203_DIAG_STAT_POWER_LOW_BIT] = "Power supply below 2.975V", +}; + +static const struct adis_timeout adis16203_timeouts = { + .reset_ms = ADIS16203_STARTUP_DELAY, + .sw_reset_ms = ADIS16203_STARTUP_DELAY, + .self_test_ms = ADIS16203_STARTUP_DELAY +}; + +static const struct adis_data adis16203_data = { + .read_delay = 20, + .msc_ctrl_reg = ADIS16203_MSC_CTRL, + .glob_cmd_reg = ADIS16203_GLOB_CMD, + .diag_stat_reg = ADIS16203_DIAG_STAT, + + .self_test_mask = ADIS16203_MSC_CTRL_SELF_TEST_EN, + .self_test_reg = ADIS16203_MSC_CTRL, + .self_test_no_autoclear = true, + .timeouts = &adis16203_timeouts, + + .status_error_msgs = adis16203_status_error_msgs, + .status_error_mask = BIT(ADIS16203_DIAG_STAT_SELFTEST_FAIL_BIT) | + BIT(ADIS16203_DIAG_STAT_SPI_FAIL_BIT) | + BIT(ADIS16203_DIAG_STAT_FLASH_UPT_BIT) | + BIT(ADIS16203_DIAG_STAT_POWER_HIGH_BIT) | + BIT(ADIS16203_DIAG_STAT_POWER_LOW_BIT), +}; + +static int adis16203_probe(struct spi_device *spi) +{ + int ret; + struct iio_dev *indio_dev; + struct adis *st; + + /* setup the industrialio driver allocated elements */ + indio_dev = devm_iio_device_alloc(&spi->dev, sizeof(*st)); + if (!indio_dev) + return -ENOMEM; + st = iio_priv(indio_dev); + /* this is only used for removal purposes */ + spi_set_drvdata(spi, indio_dev); + + indio_dev->name = spi->dev.driver->name; + indio_dev->channels = adis16203_channels; + indio_dev->num_channels = ARRAY_SIZE(adis16203_channels); + indio_dev->info = &adis16203_info; + indio_dev->modes = INDIO_DIRECT_MODE; + + ret = adis_init(st, indio_dev, spi, &adis16203_data); + if (ret) + return ret; + + ret = devm_adis_setup_buffer_and_trigger(st, indio_dev, NULL); + if (ret) + return ret; + + /* Get the device into a sane initial state */ + ret = adis_initial_startup(st); + if (ret) + return ret; + + return devm_iio_device_register(&spi->dev, indio_dev); +} + +static const struct of_device_id adis16203_of_match[] = { + { .compatible = "adi,adis16203" }, + { }, +}; + +MODULE_DEVICE_TABLE(of, adis16203_of_match); + +static struct spi_driver adis16203_driver = { + .driver = { + .name = "adis16203", + .of_match_table = adis16203_of_match, + }, + .probe = adis16203_probe, +}; +module_spi_driver(adis16203_driver); + +MODULE_AUTHOR("Barry Song <21cnbao@gmail.com>"); +MODULE_DESCRIPTION("Analog Devices ADIS16203 Programmable 360 Degrees Inclinometer"); +MODULE_LICENSE("GPL v2"); +MODULE_ALIAS("spi:adis16203"); diff --git a/pool/shard008/C/0130335_pcompress2.c b/pool/shard008/C/0130335_pcompress2.c new file mode 100644 index 0000000000000000000000000000000000000000..4216d4aa5fb4037513d8f0e7d390d01301592c98 --- /dev/null +++ b/pool/shard008/C/0130335_pcompress2.c @@ -0,0 +1,61 @@ +/********************************************************/ +/* pCompress/pUnCompress */ +/* A three stage file compressor, using Burrows Wheeler */ +/* blocksorting, Run Length Encoding and Arithmetic */ +/* coding to achieve good compression. */ +/* The fact that the compression is not that good in */ +/* reality is probably my fault. */ +/* It makes a neat benchmark anyways. */ +/* ---------------------------------------------------- */ +/* This is a part of FreeBench v1 and is only intended */ +/* to be used as a benchmark. The use of this software */ +/* for anyting else (such as compression) is not */ +/* recomended, and certainly not supported. Use gzip or */ +/* bzip instead, they are both faster and better. */ +/* Peter Rundberg, April 2001 */ +/********************************************************/ + +#define BENCHMARK + +#include +#include +#include "compress.h" +#include "uncompress.h" + +int main(int argc, char *argv[]) +{ +#ifndef BENCHMARK + const char* argv0; +#else + char filename[1000]; +#endif + +#ifdef BENCHMARK + fprintf(stderr,"Compile date: %s\n", COMPDATE); + fprintf(stderr,"Compiler switches: %s\n", CFLAGS); + compress(argc,argv); /* Compress four times to make it take some time... */ + compress(argc,argv); + compress(argc,argv); + compress(argc,argv); + strcpy(filename,argv[1]); + strcat(filename,".compr"); /* add the suffix '.compr' */ + argv[1]=filename; + uncompress(argc,argv); /* Uncompress the stuff */ + remove(filename); +#else + if((argv0 = strrchr(argv[0], '/')) == NULL) + argv0 = argv[0]; + else + argv0 += 1; + + if (!strcmp(argv0,"pcompress2")) { + compress(argc,argv); + } else if (!strcmp(argv0,"puncompress2")) { + uncompress(argc,argv); + } else { + printf("Call pCompress as 'pcompress2' or 'puncompress2', NOT %s\n",argv[0]); + } +#endif + return 0; +} + diff --git a/pool/shard008/C/0130337_data_sm_resp_test.c b/pool/shard008/C/0130337_data_sm_resp_test.c new file mode 100644 index 0000000000000000000000000000000000000000..7d9dce299c3780272eb032b15f7003a2965cb881 --- /dev/null +++ b/pool/shard008/C/0130337_data_sm_resp_test.c @@ -0,0 +1,58 @@ + +/* + * Copyright (C) 2006 Movilgate SRL. + * File : data_sm_resp_test.c + * Author: Raul Tremsal + * + * This file is part of libsmpp34 (c-open-smpp3.4 library). + * + * The libsmpp34 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. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this library; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +#include +#include +#include +#include +#ifdef __linux__ +#include +#endif + +#include "smpp34.h" +#include "smpp34_structs.h" +#include "smpp34_params.h" +#include "core.h" + + +int +main( int argc, char *argv[] ) +{ + + data_sm_resp_t a; + data_sm_resp_t b; + + memset(&a, 0, sizeof(data_sm_resp_t)); + memset(&b, 0, sizeof(data_sm_resp_t)); + + /* Init PDU ***********************************************************/ + b.command_length = 0; + b.command_id = DATA_SM_RESP; + b.command_status = ESME_ROK; + b.sequence_number = 1; + snprintf( b.message_id, sizeof(b.message_id), "%s", "88898239379"); + + doTest(DATA_SM_RESP, &a, &b); + return( 0 ); +}; diff --git a/pool/shard008/C/0130339_pci_ops.c b/pool/shard008/C/0130339_pci_ops.c new file mode 100644 index 0000000000000000000000000000000000000000..060b42807c8508806c676b852b5a3379a24881f0 --- /dev/null +++ b/pool/shard008/C/0130339_pci_ops.c @@ -0,0 +1,247 @@ +/* + * BRIEF MODULE DESCRIPTION + * Sony NSC MPU-200 specific pci support. + * + * Copyright 2001,2002 Sony Corporation. + * + * + * This file is modified from arch/mips/au1000/pb1000/pci_ops.c + * + * Copyright 2001 MontaVista Software Inc. + * Author: MontaVista Software, Inc. + * ppopov@mvista.com or source@mvista.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 2 of the License, or (at your + * option) any later version. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN + * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF + * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * 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., + * 675 Mass Ave, Cambridge, MA 02139, USA. + */ +#include + +#ifdef CONFIG_PCI + +#include +#include +#include +#include + +#include +#include +#include + +#define PCI_ACCESS_READ 0 +#define PCI_ACCESS_WRITE 1 + +#undef DEBUG +#ifdef DEBUG +#define DBG(x...) printk(x) +#else +#define DBG(x...) +#endif + +#ifdef CONFIG_PCI_PB1000_COMPAT +#error currenly broken because of no PCI hardware on MPU-200 +static struct resource pci_io_resource = { + "pci IO space", + PCI_IO_START, + PCI_IO_END, + IORESOURCE_IO +}; + +static struct resource pci_mem_resource = { + "pci memory space", + PCI_MEM_START, + PCI_MEM_END, + IORESOURCE_MEM +}; +#else /* CONFIG_PCI_PB1000_COMPAT */ +static struct resource pci_io_resource = { + "pci IO space", + 0, + 0, + IORESOURCE_IO +}; + +static struct resource pci_mem_resource = { + "pci memory space", + 0, + 0, + IORESOURCE_MEM +}; +#endif /* CONFIG_PCI_PB1000_COMPAT */ + +extern struct pci_ops snsc_mpu200_pci_ops; + +struct pci_channel mips_pci_channels[] = { + {&snsc_mpu200_pci_ops, &pci_io_resource, &pci_mem_resource, 0, 1}, + {(struct pci_ops *) NULL, (struct resource *) NULL, + (struct resource *) NULL, (int) NULL, (int) NULL} +}; + + +#ifdef CONFIG_PCI_PB1000_COMPAT +/* + * "Bus 2" is really the first and only external slot on the pb1000. + * We'll call that bus 0, and limit the accesses to that single + * external slot only. The SDRAM is already initialized in setup.c. + */ +static int config_access(unsigned char access_type, struct pci_dev *dev, + unsigned char where, u32 * data) +{ + unsigned char bus = dev->bus->number; + unsigned char dev_fn = dev->devfn; + unsigned long config; + + if (((dev_fn >> 3) != 0) || (bus != 0)) { + *data = 0xffffffff; + return -1; + } + + config = PCI_CONFIG_BASE | (where & ~0x3); + + if (access_type == PCI_ACCESS_WRITE) { + outl(*data, config); + } else { + *data = inl(config); + } + au_sync_udelay(1); + + DBG("config_access: %d bus %d dev_fn %x at %x *data %x, conf %x\n", + access_type, bus, dev_fn, where, *data, config); + + DBG("bridge config reg: %x (%x)\n", inl(PCI_BRIDGE_CONFIG), *data); + + if (inl(PCI_BRIDGE_CONFIG) & (1 << 16)) { + *data = 0xffffffff; + return -1; + } else { + return PCIBIOS_SUCCESSFUL; + } +} +#endif CONFIG_PCI_PB1000_COMPAT + +static int read_config_byte(struct pci_dev *dev, int where, u8 * val) +{ +#ifdef CONFIG_PCI_PB1000_COMPAT + u32 data; + int ret; + + ret = config_access(PCI_ACCESS_READ, dev, where, &data); + *val = data & 0xff; + return ret; +#else /* CONFIG_PCI_PB1000_COMPAT */ + return PCIBIOS_FUNC_NOT_SUPPORTED; +#endif /* CONFIG_PCI_PB1000_COMPAT */ +} + + +static int read_config_word(struct pci_dev *dev, int where, u16 * val) +{ +#ifdef CONFIG_PCI_PB1000_COMPAT + u32 data; + int ret; + + ret = config_access(PCI_ACCESS_READ, dev, where, &data); + *val = data & 0xffff; + return ret; +#else /* CONFIG_PCI_PB1000_COMPAT */ + return PCIBIOS_FUNC_NOT_SUPPORTED; +#endif /* CONFIG_PCI_PB1000_COMPAT */ +} + +static int read_config_dword(struct pci_dev *dev, int where, u32 * val) +{ +#ifdef CONFIG_PCI_PB1000_COMPAT + int ret; + + ret = config_access(PCI_ACCESS_READ, dev, where, val); + return ret; +#else /* CONFIG_PCI_PB1000_COMPAT */ + return PCIBIOS_FUNC_NOT_SUPPORTED; +#endif /* CONFIG_PCI_PB1000_COMPAT */ +} + + +static int write_config_byte(struct pci_dev *dev, int where, u8 val) +{ +#ifdef CONFIG_PCI_PB1000_COMPAT + u32 data = 0; + + if (config_access(PCI_ACCESS_READ, dev, where, &data)) + return -1; + + data = (data & ~(0xff << ((where & 3) << 3))) | + (val << ((where & 3) << 3)); + + if (config_access(PCI_ACCESS_WRITE, dev, where, &data)) + return -1; + + return PCIBIOS_SUCCESSFUL; +#else /* CONFIG_PCI_PB1000_COMPAT */ + return PCIBIOS_FUNC_NOT_SUPPORTED; +#endif /* CONFIG_PCI_PB1000_COMPAT */ +} + +static int write_config_word(struct pci_dev *dev, int where, u16 val) +{ +#ifdef CONFIG_PCI_PB1000_COMPAT + u32 data = 0; + + if (where & 1) + return PCIBIOS_BAD_REGISTER_NUMBER; + + if (config_access(PCI_ACCESS_READ, dev, where, &data)) + return -1; + + data = (data & ~(0xffff << ((where & 3) << 3))) | + (val << ((where & 3) << 3)); + + if (config_access(PCI_ACCESS_WRITE, dev, where, &data)) + return -1; + + + return PCIBIOS_SUCCESSFUL; +#else /* CONFIG_PCI_PB1000_COMPAT */ + return PCIBIOS_FUNC_NOT_SUPPORTED; +#endif /* CONFIG_PCI_PB1000_COMPAT */ +} + +static int write_config_dword(struct pci_dev *dev, int where, u32 val) +{ +#ifdef CONFIG_PCI_PB1000_COMPAT + if (where & 3) + return PCIBIOS_BAD_REGISTER_NUMBER; + + if (config_access(PCI_ACCESS_WRITE, dev, where, &val)) + return -1; + + return PCIBIOS_SUCCESSFUL; +#else /* CONFIG_PCI_PB1000_COMPAT */ + return PCIBIOS_FUNC_NOT_SUPPORTED; +#endif /* CONFIG_PCI_PB1000_COMPAT */ +} + +struct pci_ops snsc_mpu200_pci_ops = { + read_config_byte, + read_config_word, + read_config_dword, + write_config_byte, + write_config_word, + write_config_dword +}; +#endif /* CONFIG_PCI */ diff --git a/pool/shard008/C/0130341_keymap.c b/pool/shard008/C/0130341_keymap.c new file mode 100644 index 0000000000000000000000000000000000000000..b63b0c9f49586b5f6b8d8333d25bd7731c60660a --- /dev/null +++ b/pool/shard008/C/0130341_keymap.c @@ -0,0 +1,278 @@ +#include QMK_KEYBOARD_H +#include "keymap_jp.h" +#include "../common/oled_helper.h" + +extern keymap_config_t keymap_config; + +#ifdef RGBLIGHT_ENABLE +//Following line allows macro to read current RGB settings +extern rgblight_config_t rgblight_config; +#endif + +extern uint8_t is_master; + +// Each layer gets a name for readability, which is then used in the keymap matrix below. +// The underscores don't mean anything - you can have a layer called STUFF or any other name. +// Layer names don't all need to be of the same length, obviously, and you can also skip them +// entirely and just use numbers. +enum layer_number { + _BASE = 0, + _LOWER, + _RAISE, + _ADJUST, +}; + +enum custom_keycodes { + LOWER = SAFE_RANGE, + RAISE, + ADJUST, + KANJI, + RGBRST +}; + +enum tapdances{ + TD_SCCL = 0, + TD_SLRO, +}; + +// Layer Mode aliases +#define _____ KC_TRNS +#define XXXXX KC_NO + +#define KC_TBSF LSFT_T(KC_TAB) +// #define KC_SPSF LSFT_T(KC_SPC) +#define KC_ALAP LALT_T(KC_APP) +#define KC_JEQL LSFT(KC_MINS) + +#define KC_SCCL TD(TD_SCCL) +#define KC_SLRO TD(TD_SLRO) + +qk_tap_dance_action_t tap_dance_actions[] = { + [TD_SCCL] = ACTION_TAP_DANCE_DOUBLE(KC_SCLN, KC_QUOT), + [TD_SLRO] = ACTION_TAP_DANCE_DOUBLE(KC_SLSH, KC_RO), +}; + +const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = { + [_BASE] = LAYOUT_base( \ + //,--------------------------------------------------------------------------------------------------------------------. + KC_ESC, KC_Q, KC_W, KC_E, KC_R, KC_T, KC_Y, KC_U, KC_I, KC_O, KC_P, KC_MINS,\ + //|--------+--------+--------+--------+--------+--------|--------+--------+--------+--------+--------+-----------------| + KC_TBSF, KC_A, KC_S, KC_D, KC_F, KC_G, KC_H, KC_J, KC_K, KC_L, KC_SCCL, KC_ENT,\ + //|--------+--------+--------+--------+--------+--------|--------+--------+--------+--------+--------+--------+--------| + KC_LSFT, KC_Z, KC_X, KC_C, KC_V, KC_B, KC_N, KC_M, KC_COMM, KC_DOT, KC_SLRO, KC_UP, \ + //|--------+--------+--------+--------+--------+--------|--------+--------+--------+--------+--------+--------+--------| + KC_LCTRL, KC_LALT, KC_LGUI, LOWER, KC_BSPC, KC_SPC, RAISE, KC_ALAP, KC_LEFT, KC_DOWN, KC_RGHT,\ + //`-------------------------------------------------------------------------------------------------------------------' + KC_DEL \ + // ExtraKey: Split backspace key or it is below the enter key. + ), + + [_LOWER] = LAYOUT_base( \ + //,--------------------------------------------------------------------------------------------------------------------. + _____, KC_F1, KC_F2, KC_F3, KC_F4, KC_F5, KC_MINS, KC_EQL, KC_JYEN, KC_LBRC, KC_RBRC, KC_DEL,\ + //|--------+--------+--------+--------+--------+--------|--------+--------+--------+--------+--------+-----------------| + _____, KC_F6, KC_F7, KC_F8, KC_F9, KC_F10, XXXXX, XXXXX, KC_SCLN, KC_QUOT, KC_BSLS, _____,\ + //|--------+--------+--------+--------+--------+--------|--------+--------+--------+--------+--------+--------+--------| + _____, KC_F11, KC_F12, XXXXX, KANJI, KC_ENT, XXXXX, KC_COMM, KC_DOT, KC_SLSH, KC_RO, KC_PGUP, \ + //|--------+--------+--------+--------+--------+--------|--------+--------+--------+--------+--------+--------+--------| + _____, _____, _____, _____, KC_DEL, _____, _____, XXXXX, KC_HOME, KC_PGDN, KC_END,\ + //`-------------------------------------------------------------------------------------------------------------------' + XXXXX \ + // ExtraKey: Split backspace key or it is below the enter key. + ), + + [_RAISE] = LAYOUT_base( \ + //,--------------------------------------------------------------------------------------------------------------------. + _____, KC_1, KC_2, KC_3, KC_4, KC_5, KC_6, KC_7, KC_8, KC_9, KC_0, XXXXX,\ + //|--------+--------+--------+--------+--------+--------|--------+--------+--------+--------+--------+-----------------| + _____, XXXXX, XXXXX, XXXXX, XXXXX, XXXXX, XXXXX, KC_4, KC_5, KC_6, KC_QUOT, _____,\ + //|--------+--------+--------+--------+--------+--------|--------+--------+--------+--------+--------+--------+--------| + _____, XXXXX, XXXXX, XXXXX, XXXXX, XXXXX, XXXXX, KC_1, KC_2, KC_3, KC_RO, XXXXX, \ + //|--------+--------+--------+--------+--------+--------|--------+--------+--------+--------+--------+--------+--------| + _____, _____, _____, _____, _____, _____, _____, KC_0, KC_DOT, KC_COMM, KC_SLSH,\ + //`-------------------------------------------------------------------------------------------------------------------' + XXXXX \ + // ExtraKey: Split backspace key or it is below the enter key. + ), + + [_ADJUST] = LAYOUT_base( \ + //,--------------------------------------------------------------------------------------------------------------------. + XXXXX, RESET, RGBRST, AG_NORM, AG_SWAP, XXXXX, XXXXX, KC_WH_L, KC_WH_U, KC_HOME, KC_PGUP, XXXXX,\ + //|--------+--------+--------+--------+--------+--------|--------+--------+--------+--------+--------+-----------------| + XXXXX, RGB_TOG, RGB_HUI, RGB_SAI, RGB_VAI, XXXXX, XXXXX, KC_WH_R, KC_WH_D, KC_END, KC_PGDN, XXXXX,\ + //|--------+--------+--------+--------+--------+--------|--------+--------+--------+--------+--------+--------+--------| + _____, RGB_MOD, RGB_HUD, RGB_SAD, RGB_VAD, XXXXX, XXXXX, XXXXX, KC_BTN1, KC_BTN2, XXXXX, KC_MS_U, \ + //|--------+--------+--------+--------+--------+--------|--------+--------+--------+--------+--------+--------+--------| + _____, _____, _____, _____, XXXXX, XXXXX, _____, XXXXX, KC_MS_L, KC_MS_D, KC_MS_R,\ + //`-------------------------------------------------------------------------------------------------------------------' + XXXXX \ + // ExtraKey: Split backspace key or it is below the enter key. + ) +}; + +#define L_BASE _BASE +#define L_LOWER (1<<_LOWER) +#define L_RAISE (1<<_RAISE) +#define L_ADJUST (1<<_ADJUST) +#define L_ADJUST_TRI (L_ADJUST|L_RAISE|L_LOWER) + +#ifdef SSD1306OLED +typedef struct { + uint8_t state; + char name[8]; +}LAYER_DISPLAY_NAME; + +#define LAYER_DISPLAY_MAX 5 +const LAYER_DISPLAY_NAME layer_display_name[LAYER_DISPLAY_MAX] = { + {L_BASE, "Base"}, + {L_BASE + 1, "Base"}, + {L_LOWER, "Lower"}, + {L_RAISE, "Raise"}, + {L_ADJUST_TRI, "Adjust"} +}; + +static inline const char* get_leyer_status(void) { + + for (uint8_t i = 0; i < LAYER_DISPLAY_MAX; ++i) { + if (layer_state == 0 && layer_display_name[i].state == default_layer_state) { + + return layer_display_name[i].name; + } else if (layer_state != 0 && layer_display_name[i].state == layer_state) { + + return layer_display_name[i].name; + } + } + + return "?"; +} + +static char layer_status_buf[24] = "Layer state ready.\n"; +static inline void update_keymap_status(void) { + + snprintf(layer_status_buf, sizeof(layer_status_buf) - 1, "OS:%s Layer:%s\n", + keymap_config.swap_lalt_lgui? "win" : "mac", get_leyer_status()); +} + +static inline void render_keymap_status(struct CharacterMatrix *matrix) { + + matrix_write(matrix, layer_status_buf); +} + +#define UPDATE_KEYMAP_STATUS() update_keymap_status() +#define RENDER_KEYMAP_STATUS(a) render_keymap_status(a) + +#else + +#define UPDATE_KEYMAP_STATUS() +#define RENDER_KEYMAP_STATUS(a) + +#endif + +static inline void update_change_layer(bool pressed, uint8_t layer1, uint8_t layer2, uint8_t layer3) { + + pressed ? layer_on(layer1) : layer_off(layer1); + IS_LAYER_ON(layer1) && IS_LAYER_ON(layer2) ? layer_on(layer3) : layer_off(layer3); +} + +int RGB_current_mode; +bool process_record_user(uint16_t keycode, keyrecord_t *record) { + + UPDATE_KEY_STATUS(keycode, record); + + bool result = false; + switch (keycode) { + case LOWER: + update_change_layer(record->event.pressed, _LOWER, _RAISE, _ADJUST); + break; + case RAISE: + update_change_layer(record->event.pressed, _RAISE, _LOWER, _ADJUST); + break; + case KANJI: + if (record->event.pressed) { + if (keymap_config.swap_lalt_lgui == false) { + register_code(KC_LANG2); + } else { + SEND_STRING(SS_LALT("`")); + } + } else { + unregister_code(KC_LANG2); + } + break; + #ifdef RGBLIGHT_ENABLE + case RGB_MOD: + if (record->event.pressed) { + rgblight_mode(RGB_current_mode); + rgblight_step(); + RGB_current_mode = rgblight_config.mode; + } + break; + case RGBRST: + if (record->event.pressed) { + eeconfig_update_rgblight_default(); + rgblight_enable(); + RGB_current_mode = rgblight_config.mode; + } + break; + #endif + default: + result = true; + break; + } + + UPDATE_KEYMAP_STATUS(); + return result; +} + +void matrix_init_user(void) { + #ifdef RGBLIGHT_ENABLE + RGB_current_mode = rgblight_config.mode; + #endif + //SSD1306 OLED init, make sure to add #define SSD1306OLED in config.h + #ifdef SSD1306OLED + iota_gfx_init(!has_usb()); // turns on the display + #endif +} + +//SSD1306 OLED update loop, make sure to add #define SSD1306OLED in config.h +#ifdef SSD1306OLED + +void matrix_scan_user(void) { + iota_gfx_task(); // this is what updates the display continuously +} + +static inline void matrix_update(struct CharacterMatrix *dest, + const struct CharacterMatrix *source) { + if (memcmp(dest->display, source->display, sizeof(dest->display))) { + memcpy(dest->display, source->display, sizeof(dest->display)); + dest->dirty = true; + } +} + +static inline void render_status(struct CharacterMatrix *matrix) { + + UPDATE_LED_STATUS(); + RENDER_LED_STATUS(matrix); + RENDER_KEYMAP_STATUS(matrix); + UPDATE_LOCK_STATUS(); + RENDER_LOCK_STATUS(matrix); + RENDER_KEY_STATUS(matrix); +} + +void iota_gfx_task_user(void) { + struct CharacterMatrix matrix; + + #if DEBUG_TO_SCREEN + if (debug_enable) { + return; + } + #endif + + matrix_clear(&matrix); + if (is_master) { + render_status(&matrix); + } + + matrix_update(&display, &matrix); +} + +#endif diff --git a/pool/shard008/C/0130342_dlarnd.c b/pool/shard008/C/0130342_dlarnd.c new file mode 100644 index 0000000000000000000000000000000000000000..9dee811c05aab37b0dacd74b2a4a20cfc2752c9a --- /dev/null +++ b/pool/shard008/C/0130342_dlarnd.c @@ -0,0 +1,94 @@ +/* -- translated by f2c (version 19940927). + You must link the resulting object file with the libraries: + -lf2c -lm (in that order) +*/ + +#include "f2c.h" + +doublereal dlarnd_slu(integer *idist, integer *iseed) +{ + /* System generated locals */ + doublereal ret_val; + + /* Builtin functions */ + double log(doublereal), sqrt(doublereal), cos(doublereal); + + /* Local variables */ + static doublereal t1, t2; + extern doublereal dlaran_slu(integer *); + + +/* -- LAPACK auxiliary routine (version 2.0) -- + Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., + Courant Institute, Argonne National Lab, and Rice University + September 30, 1994 + + + Purpose + ======= + + DLARND returns a random real number from a uniform or normal + distribution. + + Arguments + ========= + + IDIST (input) INTEGER + Specifies the distribution of the random numbers: + = 1: uniform (0,1) + = 2: uniform (-1,1) + = 3: normal (0,1) + + ISEED (input/output) INTEGER array, dimension (4) + On entry, the seed of the random number generator; the array + + elements must be between 0 and 4095, and ISEED(4) must be + odd. + On exit, the seed is updated. + + Further Details + =============== + + This routine calls the auxiliary routine DLARAN to generate a random + + real number from a uniform (0,1) distribution. The Box-Muller method + + is used to transform numbers from a uniform to a normal distribution. + + + ===================================================================== + + + + Generate a real random number from a uniform (0,1) distribution + + Parameter adjustments */ + --iseed; + + /* Function Body */ + t1 = dlaran_slu(&iseed[1]); + + if (*idist == 1) { + +/* uniform (0,1) */ + + ret_val = t1; + } else if (*idist == 2) { + +/* uniform (-1,1) */ + + ret_val = t1 * 2. - 1.; + } else if (*idist == 3) { + +/* normal (0,1) */ + + t2 = dlaran_slu(&iseed[1]); + ret_val = sqrt(log(t1) * -2.) * cos(t2 * + 6.2831853071795864769252867663); + } + return ret_val; + +/* End of DLARND */ + +} /* dlarnd_slu */ + diff --git a/pool/shard008/C/0130344_t_sched_getaffinity.c b/pool/shard008/C/0130344_t_sched_getaffinity.c new file mode 100644 index 0000000000000000000000000000000000000000..c98d543bcb74c7c684be915292c97734a4443154 --- /dev/null +++ b/pool/shard008/C/0130344_t_sched_getaffinity.c @@ -0,0 +1,41 @@ +/*************************************************************************\ +* Copyright (C) Michael Kerrisk, 2014. * +* * +* This program is free software. You may use, modify, and redistribute it * +* under the terms of the GNU Affero General Public License as published * +* by the Free Software Foundation, either version 3 or (at your option) * +* any later version. This program is distributed without any warranty. * +* See the file COPYING.agpl-v3 for details. * +\*************************************************************************/ + +/* Supplementary program for Chapter 35 */ + +#define _GNU_SOURCE +#include +#include "tlpi_hdr.h" + +int +main(int argc, char *argv[]) +{ + pid_t pid; + cpu_set_t set; + size_t s; + int cpu; + + if (argc != 2 || strcmp(argv[1], "--help") == 0) + usageErr("%s pid\n", argv[0]); + + pid = getInt(argv[1], GN_NONNEG, "pid"); + + s = sched_getaffinity(pid, sizeof(cpu_set_t), &set); + if (s == -1) + errExit("sched_getaffinity"); + + printf("CPUs:"); + for (cpu = 0; cpu < CPU_SETSIZE; cpu++) + if (CPU_ISSET(cpu, &set)) + printf(" %d", cpu); + printf("\n"); + + exit(EXIT_SUCCESS); +} diff --git a/pool/shard008/C/0130346_gelf_ehdr.c b/pool/shard008/C/0130346_gelf_ehdr.c new file mode 100644 index 0000000000000000000000000000000000000000..1efd8178c560b8816b68dff3ce42c83f08679621 --- /dev/null +++ b/pool/shard008/C/0130346_gelf_ehdr.c @@ -0,0 +1,168 @@ +/*- + * Copyright (c) 2006,2008 Joseph Koshy + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include + +#include +#include +#include +#include +#include + +#include "_libelf.h" + +ELFTC_VCSID("$Id: gelf_ehdr.c 2268 2011-12-03 17:05:11Z jkoshy $"); + +Elf32_Ehdr * +elf32_getehdr(Elf *e) +{ + return (_libelf_ehdr(e, ELFCLASS32, 0)); +} + +Elf64_Ehdr * +elf64_getehdr(Elf *e) +{ + return (_libelf_ehdr(e, ELFCLASS64, 0)); +} + +GElf_Ehdr * +gelf_getehdr(Elf *e, GElf_Ehdr *d) +{ + int ec; + Elf32_Ehdr *eh32; + Elf64_Ehdr *eh64; + + if (d == NULL || e == NULL || + ((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64)) { + LIBELF_SET_ERROR(ARGUMENT, 0); + return (NULL); + } + + if (ec == ELFCLASS32) { + if ((eh32 = _libelf_ehdr(e, ELFCLASS32, 0)) == NULL) + return (NULL); + + (void) memcpy(d->e_ident, eh32->e_ident, + sizeof(eh32->e_ident)); + d->e_type = eh32->e_type; + d->e_machine = eh32->e_machine; + d->e_version = eh32->e_version; + d->e_entry = eh32->e_entry; + d->e_phoff = eh32->e_phoff; + d->e_shoff = eh32->e_shoff; + d->e_flags = eh32->e_flags; + d->e_ehsize = eh32->e_ehsize; + d->e_phentsize = eh32->e_phentsize; + d->e_phnum = eh32->e_phnum; + d->e_shentsize = eh32->e_shentsize; + d->e_shnum = eh32->e_shnum; + d->e_shstrndx = eh32->e_shstrndx; + + return (d); + } + + assert(ec == ELFCLASS64); + + if ((eh64 = _libelf_ehdr(e, ELFCLASS64, 0)) == NULL) + return (NULL); + *d = *eh64; + + return (d); +} + +Elf32_Ehdr * +elf32_newehdr(Elf *e) +{ + return (_libelf_ehdr(e, ELFCLASS32, 1)); +} + +Elf64_Ehdr * +elf64_newehdr(Elf *e) +{ + return (_libelf_ehdr(e, ELFCLASS64, 1)); +} + +void * +gelf_newehdr(Elf *e, int ec) +{ + if (e != NULL && + (ec == ELFCLASS32 || ec == ELFCLASS64)) + return (_libelf_ehdr(e, ec, 1)); + + LIBELF_SET_ERROR(ARGUMENT, 0); + return (NULL); +} + +int +gelf_update_ehdr(Elf *e, GElf_Ehdr *s) +{ + int ec; + void *ehdr; + Elf32_Ehdr *eh32; + Elf64_Ehdr *eh64; + + if (s== NULL || e == NULL || e->e_kind != ELF_K_ELF || + ((ec = e->e_class) != ELFCLASS32 && ec != ELFCLASS64)) { + LIBELF_SET_ERROR(ARGUMENT, 0); + return (0); + } + + if (e->e_cmd == ELF_C_READ) { + LIBELF_SET_ERROR(MODE, 0); + return (0); + } + + if ((ehdr = _libelf_ehdr(e, ec, 0)) == NULL) + return (0); + + (void) elf_flagehdr(e, ELF_C_SET, ELF_F_DIRTY); + + if (ec == ELFCLASS64) { + eh64 = (Elf64_Ehdr *) ehdr; + *eh64 = *s; + return (1); + } + + eh32 = (Elf32_Ehdr *) ehdr; + + (void) memcpy(eh32->e_ident, s->e_ident, sizeof(eh32->e_ident)); + + eh32->e_type = s->e_type; + eh32->e_machine = s->e_machine; + eh32->e_version = s->e_version; + LIBELF_COPY_U32(eh32, s, e_entry); + LIBELF_COPY_U32(eh32, s, e_phoff); + LIBELF_COPY_U32(eh32, s, e_shoff); + eh32->e_flags = s->e_flags; + eh32->e_ehsize = s->e_ehsize; + eh32->e_phentsize = s->e_phentsize; + eh32->e_phnum = s->e_phnum; + eh32->e_shentsize = s->e_shentsize; + eh32->e_shnum = s->e_shnum; + eh32->e_shstrndx = s->e_shstrndx; + + return (1); +} diff --git a/pool/shard008/C/0130348_cffi1_module.c b/pool/shard008/C/0130348_cffi1_module.c new file mode 100644 index 0000000000000000000000000000000000000000..0581aa000fe2431e038806b74015322b5c2b64b1 --- /dev/null +++ b/pool/shard008/C/0130348_cffi1_module.c @@ -0,0 +1,225 @@ + +#include "parse_c_type.c" +#include "realize_c_type.c" + +#define CFFI_VERSION_MIN 0x2601 +#define CFFI_VERSION_MAX 0x27FF + +typedef struct FFIObject_s FFIObject; +typedef struct LibObject_s LibObject; + +static PyTypeObject FFI_Type; /* forward */ +static PyTypeObject Lib_Type; /* forward */ + +#include "ffi_obj.c" +#include "cglob.c" +#include "lib_obj.c" +#include "cdlopen.c" +#include "commontypes.c" +#include "call_python.c" + + +static int init_ffi_lib(PyObject *m) +{ + PyObject *x; + int i, res; + static char init_done = 0; + + if (PyType_Ready(&FFI_Type) < 0) + return -1; + if (PyType_Ready(&Lib_Type) < 0) + return -1; + + if (!init_done) { + if (init_global_types_dict(FFI_Type.tp_dict) < 0) + return -1; + + FFIError = PyErr_NewException("ffi.error", NULL, NULL); + if (FFIError == NULL) + return -1; + if (PyDict_SetItemString(FFI_Type.tp_dict, "error", FFIError) < 0) + return -1; + if (PyDict_SetItemString(FFI_Type.tp_dict, "CType", + (PyObject *)&CTypeDescr_Type) < 0) + return -1; + if (PyDict_SetItemString(FFI_Type.tp_dict, "CData", + (PyObject *)&CData_Type) < 0) + return -1; + + for (i = 0; all_dlopen_flags[i].name != NULL; i++) { + x = PyInt_FromLong(all_dlopen_flags[i].value); + if (x == NULL) + return -1; + res = PyDict_SetItemString(FFI_Type.tp_dict, + all_dlopen_flags[i].name, x); + Py_DECREF(x); + if (res < 0) + return -1; + } + init_done = 1; + } + + x = (PyObject *)&FFI_Type; + Py_INCREF(x); + if (PyModule_AddObject(m, "FFI", x) < 0) + return -1; + x = (PyObject *)&Lib_Type; + Py_INCREF(x); + if (PyModule_AddObject(m, "Lib", x) < 0) + return -1; + + return 0; +} + +static int make_included_tuples(char *module_name, + const char *const *ctx_includes, + PyObject **included_ffis, + PyObject **included_libs) +{ + Py_ssize_t num = 0; + const char *const *p_include; + + if (ctx_includes == NULL) + return 0; + + for (p_include = ctx_includes; *p_include; p_include++) { + num++; + } + *included_ffis = PyTuple_New(num); + *included_libs = PyTuple_New(num); + if (*included_ffis == NULL || *included_libs == NULL) + goto error; + + num = 0; + for (p_include = ctx_includes; *p_include; p_include++) { + PyObject *included_ffi, *included_lib; + PyObject *m = PyImport_ImportModule(*p_include); + if (m == NULL) + goto import_error; + + included_ffi = PyObject_GetAttrString(m, "ffi"); + PyTuple_SET_ITEM(*included_ffis, num, included_ffi); + + included_lib = (included_ffi == NULL) ? NULL : + PyObject_GetAttrString(m, "lib"); + PyTuple_SET_ITEM(*included_libs, num, included_lib); + + Py_DECREF(m); + if (included_lib == NULL) + goto import_error; + + if (!FFIObject_Check(included_ffi) || + !LibObject_Check(included_lib)) + goto import_error; + num++; + } + return 0; + + import_error: + PyErr_Format(PyExc_ImportError, + "while loading %.200s: failed to import ffi, lib from %.200s", + module_name, *p_include); + error: + Py_XDECREF(*included_ffis); *included_ffis = NULL; + Py_XDECREF(*included_libs); *included_libs = NULL; + return -1; +} + +static PyObject *_my_Py_InitModule(char *module_name) +{ +#if PY_MAJOR_VERSION >= 3 + struct PyModuleDef *module_def, local_module_def = { + PyModuleDef_HEAD_INIT, + module_name, + NULL, + -1, + NULL, NULL, NULL, NULL, NULL + }; + /* note: the 'module_def' is allocated dynamically and leaks, + but anyway the C extension module can never be unloaded */ + module_def = PyMem_Malloc(sizeof(struct PyModuleDef)); + if (module_def == NULL) + return PyErr_NoMemory(); + *module_def = local_module_def; + return PyModule_Create(module_def); +#else + return Py_InitModule(module_name, NULL); +#endif +} + +static PyObject *b_init_cffi_1_0_external_module(PyObject *self, PyObject *arg) +{ + PyObject *m, *modules_dict; + FFIObject *ffi; + LibObject *lib; + Py_ssize_t version, num_exports; + char *module_name, *exports, *module_name_with_lib; + void **raw; + const struct _cffi_type_context_s *ctx; + + raw = (void **)PyLong_AsVoidPtr(arg); + if (raw == NULL) + return NULL; + + module_name = (char *)raw[0]; + version = (Py_ssize_t)raw[1]; + exports = (char *)raw[2]; + ctx = (const struct _cffi_type_context_s *)raw[3]; + + if (version < CFFI_VERSION_MIN || version > CFFI_VERSION_MAX) { + if (!PyErr_Occurred()) + PyErr_Format(PyExc_ImportError, + "cffi extension module '%s' uses an unknown version tag %p. " + "This module might need a more recent version of cffi " + "than the one currently installed, which is %s", + module_name, (void *)version, CFFI_VERSION); + return NULL; + } + + /* initialize the exports array */ + num_exports = 25; + if (ctx->flags & 1) /* set to mean that 'extern "Python"' is used */ + num_exports = 26; + memcpy(exports, (char *)cffi_exports, num_exports * sizeof(void *)); + + /* make the module object */ + m = _my_Py_InitModule(module_name); + if (m == NULL) + return NULL; + + /* build the FFI and Lib object inside this new module */ + ffi = ffi_internal_new(&FFI_Type, ctx); + Py_XINCREF(ffi); /* make the ffi object really immortal */ + if (ffi == NULL || PyModule_AddObject(m, "ffi", (PyObject *)ffi) < 0) + return NULL; + + lib = lib_internal_new(ffi, module_name, NULL); + if (lib == NULL || PyModule_AddObject(m, "lib", (PyObject *)lib) < 0) + return NULL; + + if (make_included_tuples(module_name, ctx->includes, + &ffi->types_builder.included_ffis, + &lib->l_types_builder->included_libs) < 0) + return NULL; + + /* add manually 'module_name.lib' in sys.modules: + see test_import_from_lib */ + modules_dict = PySys_GetObject("modules"); + if (!modules_dict) + return NULL; + module_name_with_lib = alloca(strlen(module_name) + 5); + strcpy(module_name_with_lib, module_name); + strcat(module_name_with_lib, ".lib"); + if (PyDict_SetItemString(modules_dict, module_name_with_lib, + (PyObject *)lib) < 0) + return NULL; + +#if PY_MAJOR_VERSION >= 3 + /* add manually 'module_name' in sys.modules: it seems that + Py_InitModule() is not enough to do that */ + if (PyDict_SetItemString(modules_dict, module_name, m) < 0) + return NULL; +#endif + + return m; +} diff --git a/pool/shard008/C/0130363_refclock_fg.c b/pool/shard008/C/0130363_refclock_fg.c new file mode 100644 index 0000000000000000000000000000000000000000..655b6bcda1313cb78337a897e03253b5d89b9f99 --- /dev/null +++ b/pool/shard008/C/0130363_refclock_fg.c @@ -0,0 +1,348 @@ +/* + * refclock_fg - clock driver for the Forum Graphic GPS datating station + */ + +#ifdef HAVE_CONFIG_H +# include +#endif + +#if defined(REFCLOCK) && defined(CLOCK_FG) + +#include "ntpd.h" +#include "ntp_io.h" +#include "ntp_refclock.h" +#include "ntp_calendar.h" +#include "ntp_stdlib.h" + +/* + * This driver supports the Forum Graphic GPS dating station. + * More information about FG GPS is available on http://www.forumgraphic.com + * Contact das@amt.ru for any question about this driver. + */ + +/* + * Interface definitions + */ +#define DEVICE "/dev/fgclock%d" +#define PRECISION (-10) /* precision assumed (about 1 ms) */ +#define REFID "GPS" +#define DESCRIPTION "Forum Graphic GPS dating station" +#define LENFG 26 /* timecode length */ +#define SPEED232 B9600 /* uart speed (9600 baud) */ + +/* + * Function prototypes + */ +static int fg_init P((int)); +static int fg_start P((int, struct peer *)); +static void fg_shutdown P((int, struct peer *)); +static void fg_poll P((int, struct peer *)); +static void fg_receive P((struct recvbuf *)); + +/* + * Forum Graphic unit control structure + */ + +struct fgunit { + int pollnum; /* Use peer.poll instead? */ + int status; /* Hug to check status information on GPS */ + int y2kwarn; /* Y2K bug */ +}; + +/* + * Queries definition + */ +static char fginit[] = { 0x10, 0x48, 0x10, 0x0D, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, 0, 0, 0, 0, 0 }; +static char fgdate[] = { 0x10, 0x44, 0x10, 0x0D, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +0, 0, 0, 0, 0, 0, 0, 0, 0 }; + +/* + * Transfer vector + */ +struct refclock refclock_fg = { + fg_start, /* start up driver */ + fg_shutdown, /* shut down driver */ + fg_poll, /* transmit poll message */ + noentry, /* not used */ + noentry, /* initialize driver (not used) */ + noentry, /* not used */ + NOFLAGS /* not used */ +}; + +/* + * fg_init - Initialization of FG GPS. + */ + +static int +fg_init( + int fd + ) +{ + if (write(fd, fginit, LENFG) != LENFG) + return 0; + + return (1); + +} + +/* + * fg_start - open the device and initialize data for processing + */ +static int +fg_start( + int unit, + struct peer *peer + ) +{ + struct refclockproc *pp; + struct fgunit *up; + int fd; + char device[20]; + + + /* + * Open device file for reading. + */ + (void)sprintf(device, DEVICE, unit); + +#ifdef DEBUG + if (debug) + printf ("starting FG with device %s\n",device); +#endif + if (!(fd = refclock_open(device, SPEED232, LDISC_CLK))) + return (0); + + /* + * Allocate and initialize unit structure + */ + + if (!(up = (struct fgunit *) + emalloc(sizeof(struct fgunit)))) { + (void) close(fd); + return (0); + } + memset((char *)up, 0, sizeof(struct fgunit)); + pp = peer->procptr; + pp->unitptr = (caddr_t)up; + pp->io.clock_recv = fg_receive; + pp->io.srcclock = (caddr_t)peer; + pp->io.datalen = 0; + pp->io.fd = fd; + if (!io_addclock(&pp->io)) { + (void) close(fd); + return (0); + } + + + /* + * Initialize miscellaneous variables + */ + peer->precision = PRECISION; + pp->clockdesc = DESCRIPTION; + memcpy((char *)&pp->refid, REFID, 3); + up->pollnum = 0; + + /* + * Setup dating station to use GPS receiver. + * GPS receiver should work before this operation. + */ + if(!fg_init(pp->io.fd)) + refclock_report(peer, CEVNT_FAULT); + + return (1); +} + + +/* + * fg_shutdown - shut down the clock + */ +static void +fg_shutdown( + int unit, + struct peer *peer + ) +{ + struct refclockproc *pp; + struct fgunit *up; + + pp = peer->procptr; + up = (struct fgunit *)pp->unitptr; + io_closeclock(&pp->io); + free(up); +} + + +/* + * fg_poll - called by the transmit procedure + */ +static void +fg_poll( + int unit, + struct peer *peer + ) +{ + struct refclockproc *pp; + + pp = peer->procptr; + + /* + * Time to poll the clock. The FG clock responds to a + * "D" by returning a timecode in the format specified + * above. If nothing is heard from the clock for two polls, + * declare a timeout and keep going. + */ + + if (write(pp->io.fd, fgdate, LENFG) != LENFG) + refclock_report(peer, CEVNT_FAULT); + else + pp->polls++; + + if (peer->burst > 0) + return; + /* + if (pp->coderecv == pp->codeproc) { + refclock_report(peer, CEVNT_TIMEOUT); + return; + } + */ + peer->burst = NSTAGE; + + record_clock_stats(&peer->srcadr, pp->a_lastcode); + + + return; + +} + +/* + * fg_receive - receive data from the serial interface + */ +static void +fg_receive( + struct recvbuf *rbufp + ) +{ + struct refclockproc *pp; + struct fgunit *up; + struct peer *peer; + char *bpt; + + /* + * Initialize pointers and read the timecode and timestamp + * We can't use gtlin function because we need bynary data in buf */ + + peer = (struct peer *)rbufp->recv_srcclock; + pp = peer->procptr; + up = (struct fgunit *)pp->unitptr; + + /* + * Below hug to implement receiving of status information + */ + if(!up->pollnum) + { + up->pollnum++; + return; + } + + + if (rbufp->recv_length < (LENFG-2)) + { + refclock_report(peer, CEVNT_BADREPLY); + return; /* The reply is invalid discard it. */ + } + + /* Below I trying to find a correct reply in buffer. + * Sometime GPS reply located in the beginnig of buffer, + * sometime you can find it with some offset. + */ + + bpt = (char *)rbufp->recv_space.X_recv_buffer; + while(*bpt != '') + bpt++; + +#define BP2(x) ( bpt[x] & 15 ) +#define BP1(x) (( bpt[x] & 240 ) >> 4) + + pp->year = BP1(2)*10 + BP2(2); + + if(pp->year == 94) + { + refclock_report(peer, CEVNT_BADREPLY); + if(!fg_init(pp->io.fd)) + refclock_report(peer, CEVNT_FAULT); + return; + /* GPS is just powered up. The date is invalid - + discarding it. Initilize GPS one more time */ + /* Sorry - this driver will broken in 2094 ;) */ + } + + if (pp->year < 99) + pp->year += 100; + + pp->year += 1900; + pp->day = 100 * BP2(3) + 10 * BP1(4) + BP2(4); + +/* + After Jan, 10 2000 Forum Graphic GPS receiver had a very strange + benahour. It doubles day number for an hours in replys after 10:10:10 UTC + and doubles min every hour at HH:10:ss for a minute. + Hope it is a problem of my unit only and not a Y2K problem of FG GPS. + Below small code to avoid such situation. +*/ + if(up->y2kwarn > 10) + pp->hour = BP1(6)*10 + BP2(6); + else + pp->hour = BP1(5)*10 + BP2(5); + + if((up->y2kwarn > 10) && (pp->hour == 10)) + { + pp->minute = BP1(7)*10 + BP2(7); + pp->second = BP1(8)*10 + BP2(8); + pp->msec = BP1(9)*10 + BP2(9); + pp->usec = BP1(10); + } else { + pp->hour = BP1(5)*10 + BP2(5); + pp->minute = BP1(6)*10 + BP2(6); + pp->second = BP1(7)*10 + BP2(7); + pp->msec = BP1(8)*10 + BP2(8); + pp->usec = BP1(9); + } + + if((pp->hour == 10) && (pp->minute == 10)) + { + up->y2kwarn++; + } + + sprintf(pp->a_lastcode, "%d %d %d %d %d", pp->year, pp->day, pp->hour, pp->minute, pp->second); + pp->lencode = strlen(pp->a_lastcode); + /*get_systime(&pp->lastrec);*/ + +#ifdef DEBUG + if (debug) + printf ("fg: time is %04d/%03d %02d:%02d:%02d UTC\n", + pp->year, pp->day, pp->hour, pp->minute, pp->second); +#endif + + if (peer->stratum <= 1) + peer->refid = pp->refid; + pp->disp = (10e-6); + pp->lastrec = rbufp->recv_time; /* Is it better then get_systime()? */ + /* pp->leap = LEAP_NOWARNING; */ + + /* + * Process the new sample in the median filter and determine the + * timecode timestamp. + */ + + if (!refclock_process(pp)) + refclock_report(peer, CEVNT_BADTIME); + + refclock_receive(peer); + return; +} + + +#else +int refclock_fg_bs; +#endif /* REFCLOCK */ diff --git a/pool/shard008/C/0130366_demo_properties.c b/pool/shard008/C/0130366_demo_properties.c new file mode 100644 index 0000000000000000000000000000000000000000..b420abfa952238194ec6d2e1645836df85b8b8a8 --- /dev/null +++ b/pool/shard008/C/0130366_demo_properties.c @@ -0,0 +1,103 @@ +/* libUIOHook: Cross-platfrom userland keyboard and mouse hooking. + * Copyright (C) 2006-2016 Alexander Barker. All Rights Received. + * https://github.com/kwhat/libuiohook/ + * + * libUIOHook 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. + * + * libUIOHook 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 Lesser General Public License + * along with this program. If not, see . + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include + +bool logger_proc(unsigned int level, const char *format, ...) { + bool status = false; + + va_list args; + switch (level) { + case LOG_LEVEL_WARN: + case LOG_LEVEL_ERROR: + va_start(args, format); + status = vfprintf(stderr, format, args) >= 0; + va_end(args); + break; + } + + return status; +} + +int main() { + // Disable the logger. + hook_set_logger_proc(&logger_proc); + + // Retrieves the keyboard auto repeat rate. + long int repeat_rate = hook_get_auto_repeat_rate(); + if (repeat_rate >= 0) { + fprintf(stdout, "Auto Repeat Rate:\t%ld\n", repeat_rate); + } + else { + fprintf(stderr, "Failed to aquire keyboard auto repeat rate!\n"); + } + + // Retrieves the keyboard auto repeat delay. + long int repeat_delay = hook_get_auto_repeat_delay(); + if (repeat_delay >= 0) { + fprintf(stdout, "Auto Repeat Delay:\t%ld\n", repeat_delay); + } + else { + fprintf(stderr, "Failed to acquire keyboard auto repeat delay!\n"); + } + + // Retrieves the mouse acceleration multiplier. + long int acceleration_multiplier = hook_get_pointer_acceleration_multiplier(); + if (acceleration_multiplier >= 0) { + fprintf(stdout, "Mouse Acceleration Multiplier:\t%ld\n", acceleration_multiplier); + } + else { + fprintf(stderr, "Failed to acquire mouse acceleration multiplier!\n"); + } + + // Retrieves the mouse acceleration threshold. + long int acceleration_threshold = hook_get_pointer_acceleration_threshold(); + if (acceleration_threshold >= 0) { + fprintf(stdout, "Mouse Acceleration Threshold:\t%ld\n", acceleration_threshold); + } + else { + fprintf(stderr, "Failed to acquire mouse acceleration threshold!\n"); + } + + // Retrieves the mouse sensitivity. + long int sensitivity = hook_get_pointer_sensitivity(); + if (sensitivity >= 0) { + fprintf(stdout, "Mouse Sensitivity:\t%ld\n", sensitivity); + } + else { + fprintf(stderr, "Failed to acquire keyboard auto repeat rate!\n"); + } + + // Retrieves the double/triple click interval. + long int click_time = hook_get_multi_click_time(); + if (click_time >= 0) { + fprintf(stdout, "Multi-Click Time:\t%ld\n", click_time); + } + else { + fprintf(stderr, "Failed to acquire keyboard auto repeat rate!\n"); + } + + return EXIT_SUCCESS; +} diff --git a/pool/shard008/C/0130372_diosupd.c b/pool/shard008/C/0130372_diosupd.c new file mode 100644 index 0000000000000000000000000000000000000000..de8d9806d26c3155df94e668a5171788125c2a30 --- /dev/null +++ b/pool/shard008/C/0130372_diosupd.c @@ -0,0 +1,83 @@ +/********** +Copyright 1990 Regents of the University of California. All rights reserved. +Author: 1985 Thomas L. Quarles +**********/ +/* + */ + +/* update the charge sensitivities and their derivatives */ + +#include "spice.h" +#include +#include "util.h" +#include "smpdefs.h" +#include "cktdefs.h" +#include "diodefs.h" +#include "sperror.h" +#include "suffix.h" + + +int +DIOsUpdate(inModel,ckt) + GENmodel *inModel; + register CKTcircuit *ckt; +{ + register DIOmodel *model = (DIOmodel*)inModel; + register DIOinstance *here; + int iparmno; + double sposprm; + double sneg; + double sxp; + double dummy1; + double dummy2; + SENstruct *info; + + info = ckt->CKTsenInfo; + if(ckt->CKTtime == 0) return(OK); + dummy1=0; + dummy2=0; + +#ifdef SENSDEBUG + printf("DIOsenUpdate\n"); + printf("CKTtime = %.5e\n",ckt->CKTtime); + printf("CKTorder = %.5e\n",ckt->CKTorder); +#endif /* SENSDEBUG */ + + /* loop through all the diode models */ + for( ; model != NULL; model = model->DIOnextModel ) { + + /* loop through all the instances of the model */ + for (here = model->DIOinstances; here != NULL ; + here=here->DIOnextInstance) { + +#ifdef SENSDEBUG + printf("capd = %.7e \n",here->DIOcap); +#endif /* SENSDEBUG */ + + for(iparmno = 1;iparmno<=info->SENparms;iparmno++){ + + sposprm = *(info->SEN_Sap[here->DIOposPrimeNode] + iparmno); + sneg = *(info->SEN_Sap[here->DIOnegNode] + iparmno); + sxp = (sposprm - sneg) * here->DIOcap; + if(iparmno == here->DIOsenParmNo) sxp += *(here->DIOdphidp); + *(ckt->CKTstate0 + here->DIOsensxp + 2 * (iparmno - 1)) = sxp; + NIintegrate(ckt,&dummy1,&dummy2,here->DIOcap, + (here->DIOsensxp + 2 * (iparmno -1 ))); + + if(ckt->CKTmode & MODEINITTRAN){ + *(ckt->CKTstate1 + here->DIOsensxp + 2*(iparmno - 1)) = sxp; + *(ckt->CKTstate1 + here->DIOsensxp + 2*(iparmno - 1)+1) = 0; + } +#ifdef SENSDEBUG + printf("iparmno = %d\n",iparmno); + printf("sposprm = %.7e,sneg = %.7e\n",sposprm,sneg); + printf("sxp = %.7e,sdotxp = %.7e\n", + sxp,*(ckt->CKTstate0 + here->DIOsensxp + + 2*(iparmno - 1) + 1)); +#endif /* SENSDEBUG */ + } + } + } + return(OK); +} + diff --git a/pool/shard008/C/0130373_ex_02-03.c b/pool/shard008/C/0130373_ex_02-03.c new file mode 100644 index 0000000000000000000000000000000000000000..8dd1db31ebaea279ad1bea12f3e0196685e665e9 --- /dev/null +++ b/pool/shard008/C/0130373_ex_02-03.c @@ -0,0 +1,104 @@ +/**************************************************** +* Exercise 02.03 from the K&R book. +* by Foo74 -- April 19, 2016 +* A program that converts a string of hex to integer. +*****************************************************/ + +/* Include the standard io library. */ +#include + +#define MAX_STRING 10 + +/* Declare functions: + * + * Note: no need to declare a name here, the declare only needs data types of args. + */ +void htoi(char []); + +/* The main function of our program. */ +int main() +{ + /* Declare local variables to the main function. */ + int i; + char a[MAX_STRING]; + + /* Init variables. */ + for (i=0; i or 0X or where + * is a char between '0' to '9' and 'a' to 'f' or 'A' and + * 'F'. For example. these are valid: a A 0xa 0Xa 0xA 0XA. + */ +void htoi(char s[]) +{ + int i; + int j; + i = 0; + j = 0; + + for (i=0; i= '0' && s[i] <= '9') + { + if (s[i] == '0') + { + /* Look ahead to see if this is not 0x or 0X . */ + if (s[i+1] != 'x' && s[i+1] != 'X') + s[j++] = s[i] - 48; + } + else + s[j++] = s[i] - 48; + } + else if (s[i] >= 'A' && s[i] <= 'F') + { + s[j++] = s[i] - 55; + } + else if (s[i] >= 'a' && s[i] <= 'f') + { + s[j++] = s[i] - 87; + } + } + /* Set the rest of the array to 0's. */ + for ( ; j<=i; j++) + s[j] = 0; + +} diff --git a/pool/shard008/C/0130378_symlink_dummy.c b/pool/shard008/C/0130378_symlink_dummy.c new file mode 100644 index 0000000000000000000000000000000000000000..cecf2d07bc08390bf20b2816e26cca21b2e6e21b --- /dev/null +++ b/pool/shard008/C/0130378_symlink_dummy.c @@ -0,0 +1,38 @@ +/* XMMS2 - X Music Multiplexer System + * Copyright (C) 2003-2012 XMMS2 Team + * + * PLUGINS ARE NOT CONSIDERED TO BE DERIVED WORK !!! + * + * 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. + */ + + +/** @file + * Dummy used when symlinking not available. (could possibly copy the file) + */ + + +#include "xmmspriv/xmms_symlink.h" + +gboolean +xmms_symlink_file (gchar *source, gchar *dest) +{ + gchar *buf; + gsize len; + gboolean ret = FALSE; + + if (g_file_get_contents (source, &buf, &len, NULL)) { + ret = g_file_set_contents (dest, buf, len, NULL); + g_free (buf); + } + + return ret; +} diff --git a/pool/shard008/C/0130379_tst_kvercmp.c b/pool/shard008/C/0130379_tst_kvercmp.c new file mode 100644 index 0000000000000000000000000000000000000000..dc3bb669b554ba98e24ce640a2ae990a46a49bf8 --- /dev/null +++ b/pool/shard008/C/0130379_tst_kvercmp.c @@ -0,0 +1,168 @@ +/* + * Copyright (c) International Business Machines Corp., 2003 + * AUTHOR: Paul Larson + * Copyright (c) 2016 Cyril Hrubis + * + * 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 + */ + +#include +#include +#include +#include +#include +#include "test.h" + +static char *parse_digit(const char *str, int *d) +{ + unsigned long v; + char *end; + + v = strtoul(str, &end, 10); + if (str == end) + return NULL; + + if (v > INT_MAX) + return NULL; + + *d = v; + + return end; +} + +int tst_parse_kver(const char *str_kver, int *v1, int *v2, int *v3) +{ + const char *str = str_kver; + + *v1 = 0; + *v2 = 0; + *v3 = 0; + + if (!(str = parse_digit(str, v1))) + return 1; + + if (*(str++) != '.') + return 1; + + if (!(str = parse_digit(str, v2))) + return 1; + + /* + * Check for a short version e.g '2.4' + */ + if (*str == ' ' || *str == '\0') + return 0; + + if (*(str++) != '.') + return 1; + + /* + * Ignore rest of the string in order not to break on versions as + * 4.8.1-52-default. + */ + if (!parse_digit(str, v3)) + return 1; + + return 0; +} + +int tst_kvcmp(const char *cur_kver, int r1, int r2, int r3) +{ + int a1, a2, a3; + int testver, currver; + + if (tst_parse_kver(cur_kver, &a1, &a2, &a3)) { + tst_resm(TWARN, + "Invalid kernel version %s, expected %%d.%%d.%%d", + cur_kver); + } + + testver = (r1 << 16) + (r2 << 8) + r3; + currver = (a1 << 16) + (a2 << 8) + a3; + + return currver - testver; +} + +int tst_kvercmp(int r1, int r2, int r3) +{ + struct utsname uval; + + uname(&uval); + + return tst_kvcmp(uval.release, r1, r2, r3); +} + +int tst_kvexcmp(const char *tst_exv, const char *cur_ver) +{ + int c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0; + int t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0; + int ret; + + sscanf(cur_ver, "%d.%d.%d-%d.%d", &c1, &c2, &c3, &c4, &c5); + sscanf(tst_exv, "%d.%d.%d-%d.%d", &t1, &t2, &t3, &t4, &t5); + + if ((ret = c1 - t1)) + return ret; + if ((ret = c2 - t2)) + return ret; + if ((ret = c3 - t3)) + return ret; + if ((ret = c4 - t4)) + return ret; + + return c5 - t5; +} + +const char *tst_kvcmp_distname(const char *kver) +{ + if (strstr(kver, ".el5uek")) + return "OL5UEK"; + + if (strstr(kver, ".el5")) + return "RHEL5"; + + if (strstr(kver, ".el6uek")) + return "OL6UEK"; + + if (strstr(kver, ".el6")) + return "RHEL6"; + + return NULL; +} + +int tst_kvercmp2(int r1, int r2, int r3, struct tst_kern_exv *vers) +{ + int i; + const char *kver; + struct utsname uval; + const char *cur_dist_name; + + uname(&uval); + kver = uval.release; + cur_dist_name = tst_kvcmp_distname(kver); + + if (cur_dist_name == NULL) + return tst_kvercmp(r1, r2, r3); + + for (i = 0; vers[i].dist_name; i++) { + if (!strcmp(vers[i].dist_name, cur_dist_name)) { + tst_resm(TINFO, "Detected %s using kernel version %s", + cur_dist_name, kver); + return tst_kvexcmp(vers[i].extra_ver, kver); + } + } + + return tst_kvcmp(kver, r1, r2, r3); +} diff --git a/pool/shard008/C/0130383_CWE134_Uncontrolled_Format_String__char_console_printf_65a.c b/pool/shard008/C/0130383_CWE134_Uncontrolled_Format_String__char_console_printf_65a.c new file mode 100644 index 0000000000000000000000000000000000000000..ae29950a41ff0fd6534d4a204af6f15f2b3b1ca3 --- /dev/null +++ b/pool/shard008/C/0130383_CWE134_Uncontrolled_Format_String__char_console_printf_65a.c @@ -0,0 +1,152 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE134_Uncontrolled_Format_String__char_console_printf_65a.c +Label Definition File: CWE134_Uncontrolled_Format_String.label.xml +Template File: sources-sinks-65a.tmpl.c +*/ +/* + * @description + * CWE: 134 Uncontrolled Format String + * BadSource: console Read input from the console + * GoodSource: Copy a fixed string into data + * Sinks: printf + * GoodSink: printf with "%s" as the first argument and data as the second + * BadSink : printf with only data as an argument + * Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer + * + * */ + +#include "std_testcase.h" + +#ifndef _WIN32 +#include +#endif + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE134_Uncontrolled_Format_String__char_console_printf_65b_badSink(char * data); + +void CWE134_Uncontrolled_Format_String__char_console_printf_65_bad() +{ + char * data; + /* define a function pointer */ + void (*funcPtr) (char *) = CWE134_Uncontrolled_Format_String__char_console_printf_65b_badSink; + char dataBuffer[100] = ""; + data = dataBuffer; + { + /* Read input from the console */ + size_t dataLen = strlen(data); + /* if there is room in data, read into it from the console */ + if (100-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgets() */ + dataLen = strlen(data); + if (dataLen > 0 && data[dataLen-1] == '\n') + { + data[dataLen-1] = '\0'; + } + } + else + { + printLine("fgets() failed"); + /* Restore NUL terminator if fgets fails */ + data[dataLen] = '\0'; + } + } + } + /* use the function pointer */ + funcPtr(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE134_Uncontrolled_Format_String__char_console_printf_65b_goodG2BSink(char * data); + +static void goodG2B() +{ + char * data; + void (*funcPtr) (char *) = CWE134_Uncontrolled_Format_String__char_console_printf_65b_goodG2BSink; + char dataBuffer[100] = ""; + data = dataBuffer; + /* FIX: Use a fixed string that does not contain a format specifier */ + strcpy(data, "fixedstringtest"); + funcPtr(data); +} + +/* goodB2G uses the BadSource with the GoodSink */ +void CWE134_Uncontrolled_Format_String__char_console_printf_65b_goodB2GSink(char * data); + +static void goodB2G() +{ + char * data; + void (*funcPtr) (char *) = CWE134_Uncontrolled_Format_String__char_console_printf_65b_goodB2GSink; + char dataBuffer[100] = ""; + data = dataBuffer; + { + /* Read input from the console */ + size_t dataLen = strlen(data); + /* if there is room in data, read into it from the console */ + if (100-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgets() */ + dataLen = strlen(data); + if (dataLen > 0 && data[dataLen-1] == '\n') + { + data[dataLen-1] = '\0'; + } + } + else + { + printLine("fgets() failed"); + /* Restore NUL terminator if fgets fails */ + data[dataLen] = '\0'; + } + } + } + funcPtr(data); +} + +void CWE134_Uncontrolled_Format_String__char_console_printf_65_good() +{ + goodG2B(); + goodB2G(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE134_Uncontrolled_Format_String__char_console_printf_65_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE134_Uncontrolled_Format_String__char_console_printf_65_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard008/C/0130384_lapacke_zspsvx.c b/pool/shard008/C/0130384_lapacke_zspsvx.c new file mode 100644 index 0000000000000000000000000000000000000000..f57193301baa5cf885b7fea0d637e0d5586181eb --- /dev/null +++ b/pool/shard008/C/0130384_lapacke_zspsvx.c @@ -0,0 +1,91 @@ +/***************************************************************************** + Copyright (c) 2014, Intel Corp. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Intel Corporation nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + THE POSSIBILITY OF SUCH DAMAGE. +***************************************************************************** +* Contents: Native high-level C interface to LAPACK function zspsvx +* Author: Intel Corporation +* Generated November 2015 +*****************************************************************************/ + +#include "lapacke_utils.h" + +lapack_int LAPACKE_zspsvx( int matrix_layout, char fact, char uplo, lapack_int n, + lapack_int nrhs, const lapack_complex_double* ap, + lapack_complex_double* afp, lapack_int* ipiv, + const lapack_complex_double* b, lapack_int ldb, + lapack_complex_double* x, lapack_int ldx, + double* rcond, double* ferr, double* berr ) +{ + lapack_int info = 0; + double* rwork = NULL; + lapack_complex_double* work = NULL; + if( matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR ) { + LAPACKE_xerbla( "LAPACKE_zspsvx", -1 ); + return -1; + } +#ifndef LAPACK_DISABLE_NAN_CHECK + if( LAPACKE_get_nancheck() ) { + /* Optionally check input matrices for NaNs */ + if( LAPACKE_lsame( fact, 'f' ) ) { + if( LAPACKE_zsp_nancheck( n, afp ) ) { + return -7; + } + } + if( LAPACKE_zsp_nancheck( n, ap ) ) { + return -6; + } + if( LAPACKE_zge_nancheck( matrix_layout, n, nrhs, b, ldb ) ) { + return -9; + } + } +#endif + /* Allocate memory for working array(s) */ + rwork = (double*)LAPACKE_malloc( sizeof(double) * MAX(1,n) ); + if( rwork == NULL ) { + info = LAPACK_WORK_MEMORY_ERROR; + goto exit_level_0; + } + work = (lapack_complex_double*) + LAPACKE_malloc( sizeof(lapack_complex_double) * MAX(1,2*n) ); + if( work == NULL ) { + info = LAPACK_WORK_MEMORY_ERROR; + goto exit_level_1; + } + /* Call middle-level interface */ + info = LAPACKE_zspsvx_work( matrix_layout, fact, uplo, n, nrhs, ap, afp, + ipiv, b, ldb, x, ldx, rcond, ferr, berr, work, + rwork ); + /* Release memory and exit */ + LAPACKE_free( work ); +exit_level_1: + LAPACKE_free( rwork ); +exit_level_0: + if( info == LAPACK_WORK_MEMORY_ERROR ) { + LAPACKE_xerbla( "LAPACKE_zspsvx", info ); + } + return info; +} diff --git a/pool/shard008/C/0130387_openssl.c b/pool/shard008/C/0130387_openssl.c new file mode 100644 index 0000000000000000000000000000000000000000..f06f64d08ad83f25247d7530a191464fff7a794b --- /dev/null +++ b/pool/shard008/C/0130387_openssl.c @@ -0,0 +1,297 @@ +/* OpenSSL interface for optional HTTPS functions + * + * Copyright (C) 2014-2021 Joachim Wiberg + * + * 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, visit the Free Software Foundation + * website at http://www.gnu.org/licenses/gpl-2.0.html or write to the + * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "log.h" +#include "http.h" +#include "ssl.h" + +int ssl_init(void) +{ +#if OPENSSL_VERSION_NUMBER < 0x10100000L + SSL_library_init(); + SSL_load_error_strings(); + OpenSSL_add_all_algorithms(); +#endif + + return 0; +} + +void ssl_exit(void) +{ +#if OPENSSL_VERSION_NUMBER < 0x10100000L + ERR_free_strings(); + EVP_cleanup(); +#endif +} + +static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx) +{ + char buf[256]; + X509 *cert; + int err, depth; + + cert = X509_STORE_CTX_get_current_cert(ctx); + err = X509_STORE_CTX_get_error(ctx); + depth = X509_STORE_CTX_get_error_depth(ctx); + + X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf)); + + /* + * Catch a too long certificate chain. The depth limit set using + * SSL_CTX_set_verify_depth() is by purpose set to "limit+1" so + * that whenever the "depth>verify_depth" condition is met, we + * have violated the limit and want to log this error condition. + * We must do it here, because the CHAIN_TOO_LONG error would not + * be found explicitly; only errors introduced by cutting off the + * additional certificates would be logged. + */ + if (depth > 100) { + preverify_ok = 0; + err = X509_V_ERR_CERT_CHAIN_TOO_LONG; + X509_STORE_CTX_set_error(ctx, err); + } + + if (!preverify_ok) { + logit(LOG_ERR, "Certificate verification error:num=%d:%s:depth=%d:%s", + err, X509_verify_cert_error_string(err), depth, buf); + if (broken_rtc && err == X509_V_ERR_CERT_NOT_YET_VALID) + preverify_ok = 1; + } + + /* + * At this point, err contains the last verification error. We can use + * it for something special + */ + if (!preverify_ok && (err == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT)) { + X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf)); + logit(LOG_ERR, "issuer= %s", buf); + } + + if (secure_ssl) + return preverify_ok; + + return 1; +} + +static int ssl_set_ca_location(http_t *client) +{ + int ret; + + /* A user defined CA PEM bundle overrides any built-ins or fall-backs */ + if (ca_trust_file) { + ret = SSL_CTX_load_verify_locations(client->ssl_ctx, ca_trust_file, NULL); + goto done; + } + + ret = SSL_CTX_set_default_verify_paths(client->ssl_ctx); + if (ret < 1) + ret = SSL_CTX_load_verify_locations(client->ssl_ctx, CAFILE1, NULL); + if (ret < 1) + ret = SSL_CTX_load_verify_locations(client->ssl_ctx, CAFILE2, NULL); +done: + if (ret < 1) + return 1; + + return 0; +} + +static int ssl_error_cb(const char *str, size_t len, void *data) +{ + char buf[512]; + size_t sz; + + (void)data; + memset(buf, 0, sizeof(buf)); + sz = len < sizeof(buf) ? len : sizeof(buf) - 1; + memcpy(buf, str, sz); + + logit(LOG_ERR, "OpenSSL error: %s", buf); + + return 0; +} + +static void ssl_check_error(void) +{ + ERR_print_errors_cb(ssl_error_cb, NULL); +} + +static int ssl_fail(http_t *client, int rc) +{ + if (!client) + return rc; + + if (!client->ssl_ctx) + tcp_exit(&client->tcp); + else + ssl_close(client); + + return rc; +} + +int ssl_open(http_t *client, char *msg) +{ + const char *sn; + char buf[512]; + X509 *cert; + int rc; + + if (!client->ssl_enabled) + return tcp_init(&client->tcp, msg); + + tcp_set_port(&client->tcp, HTTPS_DEFAULT_PORT); + DO(tcp_init(&client->tcp, msg)); + + logit(LOG_INFO, "%s, initiating HTTPS ...", msg); + client->ssl_ctx = SSL_CTX_new(SSLv23_client_method()); + if (!client->ssl_ctx) + return ssl_fail(client, RC_HTTPS_OUT_OF_MEMORY); + + /* POODLE, only allow TLSv1.x or later */ +#ifndef OPENSSL_NO_EC + SSL_CTX_set_options(client->ssl_ctx, SSL_OP_SINGLE_ECDH_USE | SSL_OP_SINGLE_DH_USE | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION); +#else + SSL_CTX_set_options(client->ssl_ctx, SSL_OP_SINGLE_DH_USE | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_COMPRESSION); +#endif + SSL_CTX_set_verify(client->ssl_ctx, SSL_VERIFY_PEER, verify_callback); + SSL_CTX_set_verify_depth(client->ssl_ctx, 150); + + /* Try to figure out location of trusted CA certs on system */ + if (ssl_set_ca_location(client)) + return ssl_fail(client, RC_HTTPS_NO_TRUSTED_CA_STORE); + + client->ssl = SSL_new(client->ssl_ctx); + if (!client->ssl) + return ssl_fail(client, RC_HTTPS_OUT_OF_MEMORY); + + /* SSL SNI support: tell the servername we want to speak to */ + http_get_remote_name(client, &sn); + if (!SSL_set_tlsext_host_name(client->ssl, sn)) + return ssl_fail(client, RC_HTTPS_SNI_ERROR); + + SSL_set_fd(client->ssl, client->tcp.socket); + rc = SSL_connect(client->ssl); + if (rc < 0) { + ssl_check_error(); + return ssl_fail(client, RC_HTTPS_FAILED_CONNECT); + } + + client->connected = 1; + logit(LOG_INFO, "SSL connection using %s", SSL_get_cipher(client->ssl)); + + cert = SSL_get_peer_certificate(client->ssl); + if (!cert) + return ssl_fail(client, RC_HTTPS_FAILED_GETTING_CERT); + + if (SSL_get_verify_result(client->ssl) == X509_V_OK) + logit(LOG_DEBUG, "Certificate OK"); + + X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf)); + logit(LOG_INFO, "SSL server cert subject: %s", buf); + X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf)); + logit(LOG_INFO, "SSL server cert issuer: %s", buf); + + X509_free(cert); + + return 0; +} + +int ssl_close(http_t *client) +{ + if (client->ssl_enabled) { + if (client->ssl) { + /* SSL/TLS close_notify */ + if (client->connected) + SSL_shutdown(client->ssl); + + /* Clean up. */ + SSL_free(client->ssl); + client->ssl = NULL; + } + if (client->ssl_ctx) { + SSL_CTX_free(client->ssl_ctx); + client->ssl_ctx = NULL; + } + } + client->connected = 0; + + return tcp_exit(&client->tcp); +} + +int ssl_send(http_t *client, const char *buf, int len) +{ + int rc, err = SSL_ERROR_NONE; + + if (!client->ssl_enabled) + return tcp_send(&client->tcp, buf, len); + + do { + ERR_clear_error(); + rc = SSL_write(client->ssl, buf, len); + if (rc <= 0) + err = SSL_get_error(client->ssl, rc); + } while (err == SSL_ERROR_WANT_WRITE); + + if (rc <= 0) { + ssl_check_error(); + return RC_HTTPS_SEND_ERROR; + } + + logit(LOG_DEBUG, "Successfully sent HTTPS request!"); + + return 0; +} + +int ssl_recv(http_t *client, char *buf, int buf_len, int *recv_len) +{ + int rc, err, len = 0; + + if (!client->ssl_enabled) + return tcp_recv(&client->tcp, buf, buf_len, recv_len); + + err = SSL_ERROR_NONE; + do { + ERR_clear_error(); + rc = SSL_read(client->ssl, buf + len, buf_len - len); + if (rc > 0) { + len += rc; + } else { + err = SSL_get_error(client->ssl, rc); + } + } while (rc > 0 || err == SSL_ERROR_WANT_READ); + + if (rc < 0) { + ssl_check_error(); + return RC_HTTPS_RECV_ERROR; + } + + *recv_len = len; + + logit(LOG_DEBUG, "Successfully received HTTPS response (%d/%d bytes)!", *recv_len, buf_len); + + return 0; +} + +/** + * Local Variables: + * indent-tabs-mode: t + * c-file-style: "linux" + * End: + */ diff --git a/pool/shard008/C/0130389_virstats.c b/pool/shard008/C/0130389_virstats.c new file mode 100644 index 0000000000000000000000000000000000000000..910803f2b33d66eb47801f98641eb3a23675d809 --- /dev/null +++ b/pool/shard008/C/0130389_virstats.c @@ -0,0 +1,178 @@ +/* + * virstats.c: Block and network stats. + * + * Copyright (C) 2007-2010 Red Hat, Inc. + * + * 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. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see + * . + * + * Richard W.M. Jones + */ + +#include + +#include +#include +#include +#include +#include +#include + +#ifdef HAVE_GETIFADDRS +# include +# include +#endif + +#include "virerror.h" +#include "datatypes.h" +#include "virstats.h" +#include "viralloc.h" +#include "virfile.h" + +#define VIR_FROM_THIS VIR_FROM_STATS_LINUX + + +/*-------------------- interface stats --------------------*/ +/* Just reads the named interface, so not Xen or QEMU-specific. + * NB. Caller must check that libvirt user is trying to query + * the interface of a domain they own. We do no such checking. + */ +#ifdef __linux__ +int +virNetInterfaceStats(const char *path, + struct _virDomainInterfaceStats *stats) +{ + int path_len; + FILE *fp; + char line[256], *colon; + + fp = fopen("/proc/net/dev", "r"); + if (!fp) { + virReportSystemError(errno, "%s", + _("Could not open /proc/net/dev")); + return -1; + } + + path_len = strlen(path); + + while (fgets(line, sizeof(line), fp)) { + long long dummy; + long long rx_bytes; + long long rx_packets; + long long rx_errs; + long long rx_drop; + long long tx_bytes; + long long tx_packets; + long long tx_errs; + long long tx_drop; + + /* The line looks like: + * " eth0:..." + * Split it at the colon. + */ + colon = strchr(line, ':'); + if (!colon) continue; + *colon = '\0'; + if (colon-path_len >= line && + STREQ(colon-path_len, path)) { + /* IMPORTANT NOTE! + * /proc/net/dev vif.nn sees the network from the point + * of view of dom0 / hypervisor. So bytes TRANSMITTED by dom0 + * are bytes RECEIVED by the domain. That's why the TX/RX fields + * appear to be swapped here. + */ + if (sscanf(colon+1, + "%lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld %lld", + &tx_bytes, &tx_packets, &tx_errs, &tx_drop, + &dummy, &dummy, &dummy, &dummy, + &rx_bytes, &rx_packets, &rx_errs, &rx_drop, + &dummy, &dummy, &dummy, &dummy) != 16) + continue; + + stats->rx_bytes = rx_bytes; + stats->rx_packets = rx_packets; + stats->rx_errs = rx_errs; + stats->rx_drop = rx_drop; + stats->tx_bytes = tx_bytes; + stats->tx_packets = tx_packets; + stats->tx_errs = tx_errs; + stats->tx_drop = tx_drop; + VIR_FORCE_FCLOSE(fp); + + return 0; + } + } + VIR_FORCE_FCLOSE(fp); + + virReportError(VIR_ERR_INTERNAL_ERROR, "%s", + _("/proc/net/dev: Interface not found")); + return -1; +} +#elif defined(HAVE_GETIFADDRS) +int +virNetInterfaceStats(const char *path, + struct _virDomainInterfaceStats *stats) +{ + struct ifaddrs *ifap, *ifa; + struct if_data *ifd; + int ret = -1; + + if (getifaddrs(&ifap) < 0) { + virReportSystemError(errno, "%s", + _("Could not get interface list")); + return -1; + } + + for (ifa = ifap; ifa; ifa = ifa->ifa_next) { + if (ifa->ifa_addr->sa_family != AF_LINK) + continue; + + if (STREQ(ifa->ifa_name, path)) { + ifd = (struct if_data *)ifa->ifa_data; + stats->tx_bytes = ifd->ifi_ibytes; + stats->tx_packets = ifd->ifi_ipackets; + stats->tx_errs = ifd->ifi_ierrors; + stats->tx_drop = ifd->ifi_iqdrops; + stats->rx_bytes = ifd->ifi_obytes; + stats->rx_packets = ifd->ifi_opackets; + stats->rx_errs = ifd->ifi_oerrors; +# ifdef HAVE_STRUCT_IF_DATA_IFI_OQDROPS + stats->rx_drop = ifd->ifi_oqdrops; +# else + stats->rx_drop = 0; +# endif + + ret = 0; + break; + } + } + + if (ret < 0) + virReportError(VIR_ERR_INTERNAL_ERROR, "%s", + _("Interface not found")); + + freeifaddrs(ifap); + return ret; +} +#else +int +virNetInterfaceStats(const char *path ATTRIBUTE_UNUSED, + struct _virDomainInterfaceStats *stats ATTRIBUTE_UNUSED) +{ + virReportError(VIR_ERR_OPERATION_INVALID, "%s", + _("interface stats not implemented on this platform")); + return -1; +} + +#endif /* __linux__ */ diff --git a/pool/shard008/C/0130394_minimal_example_comet.c b/pool/shard008/C/0130394_minimal_example_comet.c new file mode 100644 index 0000000000000000000000000000000000000000..a8864d89502de01f44cecc0f5981f78b03d3577d --- /dev/null +++ b/pool/shard008/C/0130394_minimal_example_comet.c @@ -0,0 +1,95 @@ +/* + This file is part of libmicrohttpd + Copyright (C) 2007, 2008 Christian Grothoff (and other contributing authors) + + 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. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +*/ +/** + * @file minimal_example.c + * @brief minimal example for how to generate an infinite stream with libmicrohttpd + * @author Christian Grothoff + */ + +#include "platform.h" +#include + +static ssize_t +data_generator (void *cls, uint64_t pos, char *buf, size_t max) +{ + (void) cls; /* Unused. Silent compiler warning. */ + (void) pos; /* Unused. Silent compiler warning. */ + if (max < 80) + return 0; + memset (buf, 'A', max - 1); + buf[79] = '\n'; + return 80; +} + + +static enum MHD_Result +ahc_echo (void *cls, + struct MHD_Connection *connection, + const char *url, + const char *method, + const char *version, + const char *upload_data, size_t *upload_data_size, void **req_cls) +{ + static int aptr; + struct MHD_Response *response; + enum MHD_Result ret; + (void) cls; /* Unused. Silent compiler warning. */ + (void) url; /* Unused. Silent compiler warning. */ + (void) version; /* Unused. Silent compiler warning. */ + (void) upload_data; /* Unused. Silent compiler warning. */ + (void) upload_data_size; /* Unused. Silent compiler warning. */ + + if (0 != strcmp (method, "GET")) + return MHD_NO; /* unexpected method */ + if (&aptr != *req_cls) + { + /* do never respond on first call */ + *req_cls = &aptr; + return MHD_YES; + } + *req_cls = NULL; /* reset when done */ + response = MHD_create_response_from_callback (MHD_SIZE_UNKNOWN, + 80, + &data_generator, NULL, NULL); + ret = MHD_queue_response (connection, MHD_HTTP_OK, response); + MHD_destroy_response (response); + return ret; +} + + +int +main (int argc, char *const *argv) +{ + struct MHD_Daemon *d; + + if (argc != 2) + { + printf ("%s PORT\n", argv[0]); + return 1; + } + d = MHD_start_daemon (MHD_USE_AUTO | MHD_USE_THREAD_PER_CONNECTION + | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, + atoi (argv[1]), + NULL, NULL, &ahc_echo, NULL, MHD_OPTION_END); + if (d == NULL) + return 1; + (void) getc (stdin); + MHD_stop_daemon (d); + return 0; +} diff --git a/pool/shard008/C/0130395_kmemcheck.c b/pool/shard008/C/0130395_kmemcheck.c new file mode 100644 index 0000000000000000000000000000000000000000..cab58bb592d8fa881dccfcddf0dcc7612f05128b --- /dev/null +++ b/pool/shard008/C/0130395_kmemcheck.c @@ -0,0 +1,123 @@ +#include +#include +#include +#include +#include "slab.h" +#include + +void kmemcheck_alloc_shadow(struct page *page, int order, gfp_t flags, int node) +{ + struct page *shadow; + int pages; + int i; + + pages = 1 << order; + + /* + * With kmemcheck enabled, we need to allocate a memory area for the + * shadow bits as well. + */ + shadow = alloc_pages_node(node, flags | __GFP_NOTRACK, order); + if (!shadow) { + if (printk_ratelimit()) + printk(KERN_ERR "kmemcheck: failed to allocate " + "shadow bitmap\n"); + return; + } + + for(i = 0; i < pages; ++i) + page[i].shadow = page_address(&shadow[i]); + + /* + * Mark it as non-present for the MMU so that our accesses to + * this memory will trigger a page fault and let us analyze + * the memory accesses. + */ + kmemcheck_hide_pages(page, pages); +} + +void kmemcheck_free_shadow(struct page *page, int order) +{ + struct page *shadow; + int pages; + int i; + + if (!kmemcheck_page_is_tracked(page)) + return; + + pages = 1 << order; + + kmemcheck_show_pages(page, pages); + + shadow = virt_to_page(page[0].shadow); + + for(i = 0; i < pages; ++i) + page[i].shadow = NULL; + + __free_pages(shadow, order); +} + +void kmemcheck_slab_alloc(struct kmem_cache *s, gfp_t gfpflags, void *object, + size_t size) +{ + /* + * Has already been memset(), which initializes the shadow for us + * as well. + */ + if (gfpflags & __GFP_ZERO) + return; + + /* No need to initialize the shadow of a non-tracked slab. */ + if (s->flags & SLAB_NOTRACK) + return; + + if (!kmemcheck_enabled || gfpflags & __GFP_NOTRACK) { + /* + * Allow notracked objects to be allocated from + * tracked caches. Note however that these objects + * will still get page faults on access, they just + * won't ever be flagged as uninitialized. If page + * faults are not acceptable, the slab cache itself + * should be marked NOTRACK. + */ + kmemcheck_mark_initialized(object, size); + } else if (!s->ctor) { + /* + * New objects should be marked uninitialized before + * they're returned to the called. + */ + kmemcheck_mark_uninitialized(object, size); + } +} + +void kmemcheck_slab_free(struct kmem_cache *s, void *object, size_t size) +{ + /* TODO: RCU freeing is unsupported for now; hide false positives. */ + if (!s->ctor && !(s->flags & SLAB_DESTROY_BY_RCU)) + kmemcheck_mark_freed(object, size); +} + +void kmemcheck_pagealloc_alloc(struct page *page, unsigned int order, + gfp_t gfpflags) +{ + int pages; + + if (gfpflags & (__GFP_HIGHMEM | __GFP_NOTRACK)) + return; + + pages = 1 << order; + + /* + * NOTE: We choose to track GFP_ZERO pages too; in fact, they + * can become uninitialized by copying uninitialized memory + * into them. + */ + + /* XXX: Can use zone->node for node? */ + kmemcheck_alloc_shadow(page, order, gfpflags, -1); + + if (gfpflags & __GFP_ZERO) + kmemcheck_mark_initialized_pages(page, pages); + else + kmemcheck_mark_uninitialized_pages(page, pages); +} diff --git a/pool/shard008/C/0130396_histotest.c b/pool/shard008/C/0130396_histotest.c new file mode 100644 index 0000000000000000000000000000000000000000..88e71c7564c5c9e647f6b989d142113d9c2765b3 --- /dev/null +++ b/pool/shard008/C/0130396_histotest.c @@ -0,0 +1,98 @@ +/*====================================================================* + - Copyright (C) 2001 Leptonica. All rights reserved. + - + - Redistribution and use in source and binary forms, with or without + - modification, are permitted provided that the following conditions + - are met: + - 1. Redistributions of source code must retain the above copyright + - notice, this list of conditions and the following disclaimer. + - 2. Redistributions in binary form must reproduce the above + - copyright notice, this list of conditions and the following + - disclaimer in the documentation and/or other materials + - provided with the distribution. + - + - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + - ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + - LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + - A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ANY + - CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + - EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + - PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + - PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + - OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *====================================================================*/ + +/* + * histotest.c + * + * Makes histograms of grayscale and color pixels + * from a pix. For RGB color, this uses + * rgb --> octcube indexing. + * + * histotest filein sigbits + * + * where the number of octcubes is 8^(sigbits) + * + * For gray, sigbits is ignored. + */ + +#include "allheaders.h" + +int main(int argc, + char **argv) +{ +char *filein; +l_int32 d, sigbits; +GPLOT *gplot; +NUMA *na; +PIX *pixs; +static char mainName[] = "histotest"; + + if (argc != 3) + return ERROR_INT(" Syntax: histotest filein sigbits", mainName, 1); + + filein = argv[1]; + sigbits = atoi(argv[2]); + + lept_mkdir("lept/histo"); + + if ((pixs = pixRead(filein)) == NULL) + return ERROR_INT("pixs not made", mainName, 1); + d = pixGetDepth(pixs); + if (d != 8 && d != 32) + return ERROR_INT("depth not 8 or 32 bpp", mainName, 1); + + if (d == 32) { + startTimer(); + if ((na = pixOctcubeHistogram(pixs, sigbits, NULL)) == NULL) + return ERROR_INT("na not made", mainName, 1); + fprintf(stderr, "histo time = %7.3f sec\n", stopTimer()); + gplot = gplotCreate("/tmp/lept/histo/color", GPLOT_PNG, + "color histogram with octcube indexing", + "octcube index", "number of pixels in cube"); + gplotAddPlot(gplot, NULL, na, GPLOT_LINES, "input pix"); + gplotMakeOutput(gplot); + gplotDestroy(&gplot); + l_fileDisplay("/tmp/lept/histo/color.png", 100, 100, 1.0); + } + else { + if ((na = pixGetGrayHistogram(pixs, 1)) == NULL) + return ERROR_INT("na not made", mainName, 1); + numaWrite("/tmp/junkna", na); + gplot = gplotCreate("/tmp/lept/histo/gray", GPLOT_PNG, + "grayscale histogram", "gray value", + "number of pixels"); + gplotSetScaling(gplot, GPLOT_LOG_SCALE_Y); + gplotAddPlot(gplot, NULL, na, GPLOT_LINES, "input pix"); + gplotMakeOutput(gplot); + gplotDestroy(&gplot); + l_fileDisplay("/tmp/lept/histo/gray.png", 100, 100, 1.0); + } + + pixDestroy(&pixs); + numaDestroy(&na); + return 0; +} + diff --git a/pool/shard008/C/0130397_gp2d_driver.c b/pool/shard008/C/0130397_gp2d_driver.c new file mode 100644 index 0000000000000000000000000000000000000000..eaafd55b4bfca7be6ea8d0580643bb703e639bf4 --- /dev/null +++ b/pool/shard008/C/0130397_gp2d_driver.c @@ -0,0 +1,244 @@ +#ifdef GP2D_DEBUG_DRIVER +#define DIRECT_ENABLE_DEBUG +#endif + +#include + +#undef HAVE_STDLIB_H + +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +#include +#include + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +#include + +#include + +DFB_GRAPHICS_DRIVER( gp2d ) + + +#include "gp2d_driver.h" +#include "gp2d_blt.h" +#include "gp2d_engine.h" + +D_DEBUG_DOMAIN( GP2D_Driver, "GP2D/Driver", "Renesas GP2D Driver" ); + +/**********************************************************************************************************************/ + +static void * +gp2d_event_loop( DirectThread *thread, + void *arg ) +{ + int ret; + GP2DDriverData *gdrv = arg; + u32 buf[16384]; + + while (true) { + void *p; + + D_DEBUG_AT( GP2D_Driver, "%s() read...\n", __FUNCTION__ ); + + ret = read( gdrv->gfx_fd, buf, sizeof(buf) ); + if (ret < 0) { + switch (errno) { + case EINTR: + continue; + + default: + D_PERROR( "GP2D: read() from drm device failed!\n" ); + return NULL; + } + } + + p = buf; + + while (ret > 0) { + struct drm_gp2d_event_executed *event = p; + GP2DBuffer *buffer; + + D_ASSERT( event->base.length <= ret ); + + switch (event->base.type) { + case DRM_GP2D_EVENT_EXECUTED: + D_DEBUG_AT( GP2D_Driver, " -> EXECUTED %u (%p)\n", event->handle, event->user_data ); + + buffer = event->user_data; + D_MAGIC_ASSERT( buffer, GP2DBuffer ); + + if (buffer->task) + Task_Done( buffer->task ); + + D_ASSERT( buffer == (GP2DBuffer*) gdrv->emitted ); + D_ASSERT( buffer->handle == event->handle ); + + gp2d_put_buffer( gdrv, buffer ); + break; + + default: + break; + } + + ret -= event->base.length; + p += event->base.length; + } + } + + return NULL; +} + +/**********************************************************************************************************************/ + +static int +driver_probe( CoreGraphicsDevice *device ) +{ + D_DEBUG_AT( GP2D_Driver, "%s()\n", __FUNCTION__ ); + + return 1;//dfb_gfxcard_get_accelerator( device ) == 0x2D47; +} + +static void +driver_get_info( CoreGraphicsDevice *device, + GraphicsDriverInfo *info ) +{ + D_DEBUG_AT( GP2D_Driver, "%s()\n", __FUNCTION__ ); + + /* fill driver info structure */ + snprintf( info->name, + DFB_GRAPHICS_DRIVER_INFO_NAME_LENGTH, + "Renesas GP2D Driver" ); + + snprintf( info->vendor, + DFB_GRAPHICS_DRIVER_INFO_VENDOR_LENGTH, + "Denis Oliver Kropp" ); + + info->version.major = 0; + info->version.minor = 9; + + info->driver_data_size = sizeof(GP2DDriverData); + info->device_data_size = sizeof(GP2DDeviceData); +} + +static DFBResult +driver_init_driver( CoreGraphicsDevice *device, + GraphicsDeviceFuncs *funcs, + void *driver_data, + void *device_data, + CoreDFB *core ) +{ + GP2DDriverData *gdrv = driver_data; + + D_DEBUG_AT( GP2D_Driver, "%s()\n", __FUNCTION__ ); + + /* Keep pointer to shared device data. */ + gdrv->dev = device_data; + + /* Keep core and device pointer. */ + gdrv->core = core; + gdrv->device = device; + + D_DEBUG_AT( GP2D_Driver, " -> drmOpen...\n" ); + /* Open the drawing engine device. */ + gdrv->gfx_fd = drmOpen( "gp2d", NULL ); + if (gdrv->gfx_fd < 0) { + D_PERROR( "GP2D: drmOpen() failed!\n" ); + return DFB_INIT; + } + D_DEBUG_AT( GP2D_Driver, " -> drmOpen done.\n" ); + + /* Initialize function table. */ + funcs->EngineReset = gp2dEngineReset; + funcs->EngineSync = gp2dEngineSync; + funcs->EmitCommands = gp2dEmitCommands; + funcs->CheckState = gp2dCheckState; + funcs->SetState = gp2dSetState; + funcs->FillRectangle = gp2dFillRectangle; + funcs->FillTriangle = gp2dFillTriangle; + funcs->DrawRectangle = gp2dDrawRectangle; + funcs->DrawLine = gp2dDrawLine; + funcs->Blit = gp2dBlit; + funcs->StretchBlit = gp2dStretchBlit; + + return DFB_OK; +} + +static DFBResult +driver_init_device( CoreGraphicsDevice *device, + GraphicsDeviceInfo *device_info, + void *driver_data, + void *device_data ) +{ + GP2DDriverData *gdrv = driver_data; + GP2DDeviceData *gdev = device_data; + + D_DEBUG_AT( GP2D_Driver, "%s()\n", __FUNCTION__ ); + + /* Fill in the device info. */ + snprintf( device_info->name, DFB_GRAPHICS_DEVICE_INFO_NAME_LENGTH, "GP2D" ); + snprintf( device_info->vendor, DFB_GRAPHICS_DEVICE_INFO_VENDOR_LENGTH, "Renesas" ); + + /* Set device limitations. */ + device_info->limits.surface_byteoffset_alignment = 512; + device_info->limits.surface_bytepitch_alignment = 64; + + /* Set device capabilities. */ + device_info->caps.flags = CCF_CLIPPING | CCF_RENDEROPTS; + device_info->caps.accel = GP2D_SUPPORTED_DRAWINGFUNCTIONS | \ + GP2D_SUPPORTED_BLITTINGFUNCTIONS; + device_info->caps.drawing = GP2D_SUPPORTED_DRAWINGFLAGS; + device_info->caps.blitting = GP2D_SUPPORTED_BLITTINGFLAGS; + + gp2d_blt_gen_free( gdrv, 5 ); + + register_gp2d( gdrv ); + + gdrv->event_thread = direct_thread_create( DTT_CRITICAL, gp2d_event_loop, gdrv, "GP2D DRM Events" ); + + /* Reset the drawing engine. */ + gp2dEngineReset( gdrv, gdev ); + + return DFB_OK; +} + +static void +driver_close_device( CoreGraphicsDevice *device, + void *driver_data, + void *device_data ) +{ + D_DEBUG_AT( GP2D_Driver, "%s()\n", __FUNCTION__ ); +} + +static void +driver_close_driver( CoreGraphicsDevice *device, + void *driver_data ) +{ + GP2DDriverData *gdrv = driver_data; + + D_DEBUG_AT( GP2D_Driver, "%s()\n", __FUNCTION__ ); + + /* Close Drawing Engine device. */ + close( gdrv->gfx_fd ); +} + diff --git a/pool/shard008/C/0130399_page_070.c b/pool/shard008/C/0130399_page_070.c new file mode 100644 index 0000000000000000000000000000000000000000..8f0036850751af59214b1c4fcda01963619d70f9 --- /dev/null +++ b/pool/shard008/C/0130399_page_070.c @@ -0,0 +1,73 @@ +/* Setup of default icon theme */ +#include "e_wizard.h" + +E_API int +wizard_page_init(E_Wizard_Page *pg EINA_UNUSED, Eina_Bool *need_xdg_desktops EINA_UNUSED, Eina_Bool *need_xdg_icons) +{ + *need_xdg_icons = EINA_TRUE; + return 1; +} +/* +E_API int +wizard_page_shutdown(E_Wizard_Page *pg EINA_UNUSED) +{ + return 1; +} +*/ +E_API int +wizard_page_show(E_Wizard_Page *pg EINA_UNUSED) +{ + Eina_List *l, *themes = efreet_icon_theme_list_get(); + Efreet_Icon_Theme *th; + int i; + const char *selected = NULL; + const char *search[] = + { + "gnome", + "Humanity", + "Humanity-Dark", + "ubuntu-mono-light", + "ubuntu-mono-dark", + "ubuntu-mono-light", + "unity-icon-theme", + "Oxygen", /* KDE 4 */ + "Adwaita", /* Gnome 3 */ + "Breeze", /* KDE 5 */ + "HighContrast", + NULL + }; + + if (!themes) return 0; + for (i = 0; search[i]; i++) + { + EINA_LIST_FOREACH(themes, l, th) + { + if (!strcasecmp(search[i], th->name.internal)) + { + selected = search[i]; + goto done; + } + } + } +done: + if (selected) + { + if (e_config->icon_theme) eina_stringshare_del(e_config->icon_theme); + e_config->icon_theme = eina_stringshare_add(selected); + } + eina_list_free(themes); + return 0; /* 1 == show ui, and wait for user, 0 == just continue */ +} +/* +E_API int +wizard_page_hide(E_Wizard_Page *pg EINA_UNUSED) +{ + return 1; +} + +E_API int +wizard_page_apply(E_Wizard_Page *pg EINA_UNUSED) +{ + return 1; +} +*/ diff --git a/pool/shard008/C/0130404_modem_net_flowcontrol_device.c b/pool/shard008/C/0130404_modem_net_flowcontrol_device.c new file mode 100644 index 0000000000000000000000000000000000000000..5dcf1a22bf241ba095ebf8b0d972b82f3cf665dc --- /dev/null +++ b/pool/shard008/C/0130404_modem_net_flowcontrol_device.c @@ -0,0 +1,116 @@ +/* /linux/drivers/misc/modem_if/modem_net_flowcontrol_device.c + * + * Copyright (C) 2011 Google, Inc. + * Copyright (C) 2011 Samsung Electronics. + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * 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. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "modem_prj.h" + + +#define NET_FLOWCONTROL_DEV_NAME_LEN 8 + +static int modem_net_flowcontrol_device_open( + struct inode *inode, struct file *filp) +{ + return 0; +} + +static int modem_net_flowcontrol_device_release( + struct inode *inode, struct file *filp) +{ + return 0; +} + +static long modem_net_flowcontrol_device_ioctl( + struct file *filp, unsigned int cmd, unsigned long arg) +{ + struct net *this_net; + struct net_device *ndev; + char dev_name[NET_FLOWCONTROL_DEV_NAME_LEN]; + u8 chan; + + if (copy_from_user(&chan, (void __user *)arg, sizeof(char))) + return -EFAULT; + + if (chan > 15) + return -ENODEV; + + snprintf(dev_name, NET_FLOWCONTROL_DEV_NAME_LEN, "rmnet%d", (int)chan); + this_net = get_net_ns_by_pid(current->pid); + ndev = __dev_get_by_name(this_net, dev_name); + if (ndev == NULL) { + mif_err("device = %s not exist\n", dev_name); + return -ENODEV; + } + + switch (cmd) { + case IOCTL_MODEM_NET_SUSPEND: + netif_stop_queue(ndev); + mif_info("NET SUSPEND(%s)\n", dev_name); + break; + case IOCTL_MODEM_NET_RESUME: + netif_wake_queue(ndev); + mif_info("NET RESUME(%s)\n", dev_name); + break; + default: + return -EINVAL; + } + return 0; +} + +static const struct file_operations modem_net_flowcontrol_device_fops = { + .owner = THIS_MODULE, + .open = modem_net_flowcontrol_device_open, + .release = modem_net_flowcontrol_device_release, + .unlocked_ioctl = modem_net_flowcontrol_device_ioctl, +}; + +static int __init modem_net_flowcontrol_device_init(void) +{ + int ret = 0; + struct io_device *net_flowcontrol_dev; + + net_flowcontrol_dev = kzalloc(sizeof(struct io_device), GFP_KERNEL); + if (!net_flowcontrol_dev) { + mif_err("net_flowcontrol_dev io device memory alloc fail\n"); + return -ENOMEM; + } + + net_flowcontrol_dev->miscdev.minor = MISC_DYNAMIC_MINOR; + net_flowcontrol_dev->miscdev.name = "modem_br"; + net_flowcontrol_dev->miscdev.fops = &modem_net_flowcontrol_device_fops; + + ret = misc_register(&net_flowcontrol_dev->miscdev); + if (ret) { + mif_err("failed to register misc br device : %s\n", + net_flowcontrol_dev->miscdev.name); + kfree(net_flowcontrol_dev); + } + + return ret; +} + +module_init(modem_net_flowcontrol_device_init); + +MODULE_LICENSE("GPL"); +MODULE_DESCRIPTION("Samsung Modem IF Net Flowcontrol Driver"); diff --git a/pool/shard008/C/0130407_latlong_options.c b/pool/shard008/C/0130407_latlong_options.c new file mode 100644 index 0000000000000000000000000000000000000000..6d5223776ce78ac0a7571d4c1f3b411771cebd16 --- /dev/null +++ b/pool/shard008/C/0130407_latlong_options.c @@ -0,0 +1,184 @@ +/* +Copyright (c) 2012 Carsten Burstedde, Donna Calhoun +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include "latlong_user.h" + +static int s_user_options_package_id = -1; + +static void * +latlong_register (user_options_t *user, sc_options_t * opt) +{ + fclaw_options_add_double_array(opt, 0, "latitude", &user->latitude_string, + "-50 50", &user->latitude, 2, + "[user] Latitude range (degrees) [-50 50]"); + + fclaw_options_add_double_array(opt, 0, "longitude", &user->longitude_string, + "0 360", &user->longitude, 2, + "[user] Longitude range (degrees) [0 360]"); + + + sc_options_add_int (opt, 0, "claw-version", &user->claw_version, 5, + "[user] Clawpack version (4 or 5) [5]"); + + user->is_registered = 1; + return NULL; +} + +static +fclaw_exit_type_t +latlong_postprocess (user_options_t *user) +{ + fclaw_options_convert_double_array (user->latitude_string, + &user->latitude, 2); + fclaw_options_convert_double_array (user->longitude_string, + &user->longitude, 2); + return FCLAW_NOEXIT; +} + +static fclaw_exit_type_t +latlong_check (user_options_t *user) +{ + /* Nothing to check ? */ + return FCLAW_NOEXIT; +} + + +static void +latlong_destroy (user_options_t *user) +{ + fclaw_options_destroy_array (user->latitude); + fclaw_options_destroy_array (user->longitude); +} + + +/* ------- Generic option handling routines that call above routines ----- */ + +static void* +options_register (fclaw_app_t * app, void *package, sc_options_t * opt) +{ + user_options_t *user_opt; + + FCLAW_ASSERT (app != NULL); + FCLAW_ASSERT (package != NULL); + FCLAW_ASSERT (opt != NULL); + + user_opt = (user_options_t*) package; + + return latlong_register(user_opt,opt); +} + +static fclaw_exit_type_t +options_postprocess (fclaw_app_t * a, void *package, void *registered) +{ + FCLAW_ASSERT (a != NULL); + FCLAW_ASSERT (package != NULL); + FCLAW_ASSERT (registered == NULL); + + /* errors from the key-value options would have showed up in parsing */ + user_options_t *user = (user_options_t *) package; + + /* post-process this package */ + FCLAW_ASSERT(user->is_registered); + + /* Convert strings to arrays */ + return latlong_postprocess (user); +} + +static fclaw_exit_type_t +options_check(fclaw_app_t *app, void *package,void *registered) +{ + user_options_t *user; + + FCLAW_ASSERT (app != NULL); + FCLAW_ASSERT (package != NULL); + FCLAW_ASSERT(registered == NULL); + + user = (user_options_t*) package; + + return latlong_check(user); +} + + +static void +options_destroy (fclaw_app_t * app, void *package, void *registered) +{ + user_options_t *user; + + FCLAW_ASSERT (app != NULL); + FCLAW_ASSERT (package != NULL); + FCLAW_ASSERT (registered == NULL); + + user = (user_options_t*) package; + FCLAW_ASSERT (user->is_registered); + + latlong_destroy (user); + + FCLAW_FREE (user); +} + + +static const +fclaw_app_options_vtable_t options_vtable_user = +{ + options_register, + options_postprocess, + options_check, + options_destroy +}; + + +/* ------------- User options access functions --------------------- */ + +user_options_t* latlong_options_register (fclaw_app_t * app, + const char *configfile) +{ + user_options_t *user; + FCLAW_ASSERT (app != NULL); + + user = FCLAW_ALLOC (user_options_t, 1); + fclaw_app_options_register (app,"user", configfile, &options_vtable_user, + user); + + fclaw_app_set_attribute(app,"user",user); + return user; +} + +void latlong_options_store (fclaw2d_global_t* glob, user_options_t* user) +{ + FCLAW_ASSERT(s_user_options_package_id == -1); + int id = fclaw_package_container_add_pkg(glob,user); + s_user_options_package_id = id; +} + +const user_options_t* latlong_get_options(fclaw2d_global_t* glob) +{ + int id = s_user_options_package_id; + return (user_options_t*) + fclaw_package_get_options(glob, id); +} + + + + diff --git a/pool/shard008/C/0130410_inet_lnaof.c b/pool/shard008/C/0130410_inet_lnaof.c new file mode 100644 index 0000000000000000000000000000000000000000..99024d94643b14b3f27c1499df960dd7813e44ab --- /dev/null +++ b/pool/shard008/C/0130410_inet_lnaof.c @@ -0,0 +1,66 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)inet_lnaof.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ + +#include +#include +#include + +/* + * Return the local network address portion of an + * internet address; handles class a/b/c network + * number formats. + */ +u_long +inet_lnaof(in) + struct in_addr in; +{ + register u_long i = ntohl(in.s_addr); + + if (IN_CLASSA(i)) + return ((i)&IN_CLASSA_HOST); + else if (IN_CLASSB(i)) + return ((i)&IN_CLASSB_HOST); + else + return ((i)&IN_CLASSC_HOST); +} + +/* + * Weak aliases for applications that use certain private entry points, + * and fail to include . + */ +#undef inet_lnaof +__weak_reference(__inet_lnaof, inet_lnaof); diff --git a/pool/shard008/C/0130414_networkd-link-bus.c b/pool/shard008/C/0130414_networkd-link-bus.c new file mode 100644 index 0000000000000000000000000000000000000000..a28c93478e0f9c3c1b8b4c78a702d52e276194fe --- /dev/null +++ b/pool/shard008/C/0130414_networkd-link-bus.c @@ -0,0 +1,127 @@ +/* SPDX-License-Identifier: LGPL-2.1+ */ +/*** + This file is part of systemd. + + Copyright 2015 Tom Gundersen +***/ + +#include "alloc-util.h" +#include "bus-util.h" +#include "networkd-link.h" +#include "networkd-manager.h" +#include "parse-util.h" +#include "strv.h" + +static BUS_DEFINE_PROPERTY_GET_ENUM(property_get_operational_state, link_operstate, LinkOperationalState); +static BUS_DEFINE_PROPERTY_GET_ENUM(property_get_administrative_state, link_state, LinkState); + +const sd_bus_vtable link_vtable[] = { + SD_BUS_VTABLE_START(0), + + SD_BUS_PROPERTY("OperationalState", "s", property_get_operational_state, offsetof(Link, operstate), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE), + SD_BUS_PROPERTY("AdministrativeState", "s", property_get_administrative_state, offsetof(Link, state), SD_BUS_VTABLE_PROPERTY_EMITS_CHANGE), + + SD_BUS_VTABLE_END +}; + +static char *link_bus_path(Link *link) { + _cleanup_free_ char *ifindex = NULL; + char *p; + int r; + + assert(link); + assert(link->ifindex > 0); + + if (asprintf(&ifindex, "%d", link->ifindex) < 0) + return NULL; + + r = sd_bus_path_encode("/org/freedesktop/network1/link", ifindex, &p); + if (r < 0) + return NULL; + + return p; +} + +int link_node_enumerator(sd_bus *bus, const char *path, void *userdata, char ***nodes, sd_bus_error *error) { + _cleanup_strv_free_ char **l = NULL; + Manager *m = userdata; + unsigned c = 0; + Link *link; + Iterator i; + + assert(bus); + assert(path); + assert(m); + assert(nodes); + + l = new0(char*, hashmap_size(m->links) + 1); + if (!l) + return -ENOMEM; + + HASHMAP_FOREACH(link, m->links, i) { + char *p; + + p = link_bus_path(link); + if (!p) + return -ENOMEM; + + l[c++] = p; + } + + l[c] = NULL; + *nodes = TAKE_PTR(l); + + return 1; +} + +int link_object_find(sd_bus *bus, const char *path, const char *interface, void *userdata, void **found, sd_bus_error *error) { + _cleanup_free_ char *identifier = NULL; + Manager *m = userdata; + Link *link; + int ifindex, r; + + assert(bus); + assert(path); + assert(interface); + assert(m); + assert(found); + + r = sd_bus_path_decode(path, "/org/freedesktop/network1/link", &identifier); + if (r <= 0) + return 0; + + r = parse_ifindex(identifier, &ifindex); + if (r < 0) + return 0; + + r = link_get(m, ifindex, &link); + if (r < 0) + return 0; + + *found = link; + + return 1; +} + +int link_send_changed(Link *link, const char *property, ...) { + _cleanup_free_ char *p = NULL; + char **l; + + assert(link); + assert(link->manager); + + if (!link->manager->bus) + return 0; /* replace with assert when we have kdbus */ + + l = strv_from_stdarg_alloca(property); + + p = link_bus_path(link); + if (!p) + return -ENOMEM; + + return sd_bus_emit_properties_changed_strv( + link->manager->bus, + p, + "org.freedesktop.network1.Link", + l); +} diff --git a/pool/shard008/C/0130415_s2n_extensions_server_key_share_recv_test.c b/pool/shard008/C/0130415_s2n_extensions_server_key_share_recv_test.c new file mode 100644 index 0000000000000000000000000000000000000000..273bf3f52623dd69a4f7c0af2aa29df006869908 --- /dev/null +++ b/pool/shard008/C/0130415_s2n_extensions_server_key_share_recv_test.c @@ -0,0 +1,82 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file 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. + */ + +/* Target Functions: s2n_extensions_server_key_share_recv s2n_ecc_evp_read_params_point s2n_ecc_evp_parse_params_point */ + +#include + +#include +#include + +#include "tls/extensions/s2n_server_key_share.h" +#include "tls/s2n_security_policies.h" + +#include "api/s2n.h" +#include "stuffer/s2n_stuffer.h" +#include "tls/s2n_connection.h" +#include "tls/s2n_tls.h" +#include "utils/s2n_safety.h" +#include "s2n_test.h" +#include "testlib/s2n_testlib.h" +#include "tls/s2n_tls13.h" +#include "crypto/s2n_ecc_evp.h" + +/* This test is for TLS versions 1.3 and up only */ +static const uint8_t TLS_VERSIONS[] = {S2N_TLS13}; + +int s2n_fuzz_init(int *argc, char **argv[]) +{ + POSIX_GUARD(s2n_enable_tls13_in_test()); + return S2N_SUCCESS; +} + +int s2n_fuzz_test(const uint8_t *buf, size_t len) +{ + /* We need at least one byte of input to set parameters */ + S2N_FUZZ_ENSURE_MIN_LEN(len, 1); + + /* Setup */ + struct s2n_stuffer fuzz_stuffer = {0}; + POSIX_GUARD(s2n_stuffer_alloc(&fuzz_stuffer, len)); + POSIX_GUARD(s2n_stuffer_write_bytes(&fuzz_stuffer, buf, len)); + + struct s2n_connection *client_conn = s2n_connection_new(S2N_CLIENT); + EXPECT_NOT_NULL(client_conn); + + /* Pull a byte off the libfuzzer input and use it to set parameters */ + uint8_t randval = 0; + POSIX_GUARD(s2n_stuffer_read_uint8(&fuzz_stuffer, &randval)); + client_conn->actual_protocol_version = TLS_VERSIONS[randval % s2n_array_len(TLS_VERSIONS)]; + + const struct s2n_ecc_preferences *ecc_preferences = NULL; + POSIX_GUARD(s2n_connection_get_ecc_preferences(client_conn, &ecc_preferences)); + POSIX_ENSURE_REF(ecc_preferences); + + client_conn->kex_params.client_ecc_evp_params.negotiated_curve = ecc_preferences->ecc_curves[randval % ecc_preferences->count]; + POSIX_GUARD(s2n_ecc_evp_generate_ephemeral_key(&client_conn->kex_params.client_ecc_evp_params)); + + /* Run Test + * Do not use GUARD macro here since the connection memory hasn't been freed. + */ + s2n_extensions_server_key_share_recv(client_conn, &fuzz_stuffer); + + /* Cleanup */ + POSIX_GUARD(s2n_connection_free(client_conn)); + POSIX_GUARD(s2n_stuffer_free(&fuzz_stuffer)); + + return S2N_SUCCESS; +} + +S2N_FUZZ_TARGET(s2n_fuzz_init, s2n_fuzz_test, NULL) diff --git a/pool/shard008/C/0130416_sysctl.c b/pool/shard008/C/0130416_sysctl.c new file mode 100644 index 0000000000000000000000000000000000000000..ddd054758c7aeaa2bde62cf161a7c61d811b5594 --- /dev/null +++ b/pool/shard008/C/0130416_sysctl.c @@ -0,0 +1,185 @@ +/* + + + + + + + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "netns.h" + +/* + + */ +unsigned int rpc_debug; +EXPORT_SYMBOL_GPL(rpc_debug); + +unsigned int nfs_debug; +EXPORT_SYMBOL_GPL(nfs_debug); + +unsigned int nfsd_debug; +EXPORT_SYMBOL_GPL(nfsd_debug); + +unsigned int nlm_debug; +EXPORT_SYMBOL_GPL(nlm_debug); + +#ifdef RPC_DEBUG + +static struct ctl_table_header *sunrpc_table_header; +static ctl_table sunrpc_table[]; + +void +rpc_register_sysctl(void) +{ + if (!sunrpc_table_header) + sunrpc_table_header = register_sysctl_table(sunrpc_table); +} + +void +rpc_unregister_sysctl(void) +{ + if (sunrpc_table_header) { + unregister_sysctl_table(sunrpc_table_header); + sunrpc_table_header = NULL; + } +} + +static int proc_do_xprt(ctl_table *table, int write, + void __user *buffer, size_t *lenp, loff_t *ppos) +{ + char tmpbuf[256]; + size_t len; + + if ((*ppos && !write) || !*lenp) { + *lenp = 0; + return 0; + } + len = svc_print_xprts(tmpbuf, sizeof(tmpbuf)); + return simple_read_from_buffer(buffer, *lenp, ppos, tmpbuf, len); +} + +static int +proc_dodebug(ctl_table *table, int write, + void __user *buffer, size_t *lenp, loff_t *ppos) +{ + char tmpbuf[20], c, *s; + char __user *p; + unsigned int value; + size_t left, len; + + if ((*ppos && !write) || !*lenp) { + *lenp = 0; + return 0; + } + + left = *lenp; + + if (write) { + if (!access_ok(VERIFY_READ, buffer, left)) + return -EFAULT; + p = buffer; + while (left && __get_user(c, p) >= 0 && isspace(c)) + left--, p++; + if (!left) + goto done; + + if (left > sizeof(tmpbuf) - 1) + return -EINVAL; + if (copy_from_user(tmpbuf, p, left)) + return -EFAULT; + tmpbuf[left] = '\0'; + + for (s = tmpbuf, value = 0; '0' <= *s && *s <= '9'; s++, left--) + value = 10 * value + (*s - '0'); + if (*s && !isspace(*s)) + return -EINVAL; + while (left && isspace(*s)) + left--, s++; + *(unsigned int *) table->data = value; + /* */ + if (strcmp(table->procname, "rpc_debug") == 0) + rpc_show_tasks(&init_net); + } else { + if (!access_ok(VERIFY_WRITE, buffer, left)) + return -EFAULT; + len = sprintf(tmpbuf, "%d", *(unsigned int *) table->data); + if (len > left) + len = left; + if (__copy_to_user(buffer, tmpbuf, len)) + return -EFAULT; + if ((left -= len) > 0) { + if (put_user('\n', (char __user *)buffer + len)) + return -EFAULT; + left--; + } + } + +done: + *lenp -= left; + *ppos += *lenp; + return 0; +} + + +static ctl_table debug_table[] = { + { + .procname = "rpc_debug", + .data = &rpc_debug, + .maxlen = sizeof(int), + .mode = 0644, + .proc_handler = proc_dodebug + }, + { + .procname = "nfs_debug", + .data = &nfs_debug, + .maxlen = sizeof(int), + .mode = 0644, + .proc_handler = proc_dodebug + }, + { + .procname = "nfsd_debug", + .data = &nfsd_debug, + .maxlen = sizeof(int), + .mode = 0644, + .proc_handler = proc_dodebug + }, + { + .procname = "nlm_debug", + .data = &nlm_debug, + .maxlen = sizeof(int), + .mode = 0644, + .proc_handler = proc_dodebug + }, + { + .procname = "transports", + .maxlen = 256, + .mode = 0444, + .proc_handler = proc_do_xprt, + }, + { } +}; + +static ctl_table sunrpc_table[] = { + { + .procname = "sunrpc", + .mode = 0555, + .child = debug_table + }, + { } +}; + +#endif diff --git a/pool/shard008/C/0130417_stm32h7xx_hal_smartcard_ex.c b/pool/shard008/C/0130417_stm32h7xx_hal_smartcard_ex.c new file mode 100644 index 0000000000000000000000000000000000000000..16a483ab474a2b4f8b256ce44f3dd485d86839a0 --- /dev/null +++ b/pool/shard008/C/0130417_stm32h7xx_hal_smartcard_ex.c @@ -0,0 +1,208 @@ +/** + ****************************************************************************** + * @file stm32h7xx_hal_smartcard_ex.c + * @author MCD Application Team + * @version V1.2.0 + * @date 29-December-2017 + * @brief SMARTCARD HAL module driver. + * This file provides extended firmware functions to manage the following + * functionalities of the SmartCard. + * + Initialization and de-initialization functions + * + Peripheral Control functions + * + * + @verbatim + ============================================================================= + ##### SMARTCARD peripheral extended features ##### + ============================================================================= + [..] + The Extended SMARTCARD HAL driver can be used as follows: + + (#) After having configured the SMARTCARD basic features with HAL_SMARTCARD_Init(), + then program SMARTCARD advanced features if required (TX/RX pins swap, TimeOut, + auto-retry counter,...) in the hsmartcard AdvancedInit structure. + + + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2017 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32h7xx_hal.h" + +/** @addtogroup STM32H7xx_HAL_Driver + * @{ + */ + +/** @defgroup SMARTCARDEx SMARTCARDEx + * @brief SMARTCARD Extended HAL module driver + * @{ + */ +#ifdef HAL_SMARTCARD_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup SMARTCARDEx_Exported_Functions SMARTCARD Extended Exported Functions + * @{ + */ + +/** @defgroup SMARTCARDEx_Exported_Functions_Group1 Extended Peripheral Control functions + * @brief Extended control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the SMARTCARD. + (+) HAL_SMARTCARDEx_BlockLength_Config() API allows to configure the Block Length on the fly + (+) HAL_SMARTCARDEx_TimeOut_Config() API allows to configure the receiver timeout value on the fly + (+) HAL_SMARTCARDEx_EnableReceiverTimeOut() API enables the receiver timeout feature + (+) HAL_SMARTCARDEx_DisableReceiverTimeOut() API disables the receiver timeout feature + +@endverbatim + * @{ + */ + +/** + * @brief Update on the fly the SMARTCARD block length in RTOR register. + * @param hsmartcard: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @param BlockLength: SMARTCARD block length (8-bit long at most) + * @retval None + */ +void HAL_SMARTCARDEx_BlockLength_Config(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t BlockLength) +{ + MODIFY_REG(hsmartcard->Instance->RTOR, USART_RTOR_BLEN, ((uint32_t)BlockLength << SMARTCARD_RTOR_BLEN_LSB_POS)); +} + +/** + * @brief Update on the fly the receiver timeout value in RTOR register. + * @param hsmartcard: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @param TimeOutValue: receiver timeout value in number of baud blocks. The timeout + * value must be less or equal to 0x00FFFFFF. + * @retval None + */ +void HAL_SMARTCARDEx_TimeOut_Config(SMARTCARD_HandleTypeDef *hsmartcard, uint32_t TimeOutValue) +{ + assert_param(IS_SMARTCARD_TIMEOUT_VALUE(hsmartcard->Init.TimeOutValue)); + MODIFY_REG(hsmartcard->Instance->RTOR, USART_RTOR_RTO, TimeOutValue); +} + +/** + * @brief Enable the SMARTCARD receiver timeout feature. + * @param hsmartcard: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARDEx_EnableReceiverTimeOut(SMARTCARD_HandleTypeDef *hsmartcard) +{ + + if(hsmartcard->gState == HAL_SMARTCARD_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY; + + /* Set the USART RTOEN bit */ + SET_BIT(hsmartcard->Instance->CR2, USART_CR2_RTOEN); + + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Disable the SMARTCARD receiver timeout feature. + * @param hsmartcard: Pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARDEx_DisableReceiverTimeOut(SMARTCARD_HandleTypeDef *hsmartcard) +{ + + if(hsmartcard->gState == HAL_SMARTCARD_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->gState = HAL_SMARTCARD_STATE_BUSY; + + /* Clear the USART RTOEN bit */ + CLEAR_BIT(hsmartcard->Instance->CR2, USART_CR2_RTOEN); + + hsmartcard->gState = HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_SMARTCARD_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard008/C/0130422_sp_flop.c b/pool/shard008/C/0130422_sp_flop.c new file mode 100644 index 0000000000000000000000000000000000000000..cec246d40b916256c539d07c5f64b6ecad51b62f --- /dev/null +++ b/pool/shard008/C/0130422_sp_flop.c @@ -0,0 +1,365 @@ +/* + FreeRTOS V7.5.3 - Copyright (C) 2013 Real Time Engineers Ltd. + All rights reserved + + VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + *************************************************************************** + * * + * FreeRTOS provides completely free yet professionally developed, * + * robust, strictly quality controlled, supported, and cross * + * platform software that has become a de facto standard. * + * * + * Help yourself get started quickly and support the FreeRTOS * + * project by purchasing a FreeRTOS tutorial book, reference * + * manual, or both from: http://www.FreeRTOS.org/Documentation * + * * + * Thank you! * + * * + *************************************************************************** + + This file is part of the FreeRTOS distribution. + + FreeRTOS is free software; you can redistribute it and/or modify it under + the terms of the GNU General Public License (version 2) as published by the + Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception. + + >>! NOTE: The modification to the GPL is included to allow you to distribute + >>! a combined work that includes FreeRTOS without being obliged to provide + >>! the source code for proprietary components outside of the FreeRTOS + >>! kernel. + + FreeRTOS 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. Full license text is available from the following + link: http://www.freertos.org/a00114.html + + 1 tab == 4 spaces! + + *************************************************************************** + * * + * Having a problem? Start by reading the FAQ "My application does * + * not run, what could be wrong?" * + * * + * http://www.FreeRTOS.org/FAQHelp.html * + * * + *************************************************************************** + + http://www.FreeRTOS.org - Documentation, books, training, latest versions, + license and Real Time Engineers Ltd. contact details. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool, a DOS + compatible FAT file system, and our tiny thread aware UDP/IP stack. + + http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High + Integrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOS + licenses offer ticketed support, indemnification and middleware. + + http://www.SafeRTOS.com - High Integrity Systems also provide a safety + engineered and independently SIL3 certified version for use in safety and + mission critical applications that require provable dependability. + + 1 tab == 4 spaces! +*/ + +/* + * Creates eight tasks, each of which loops continuously performing a floating + * point calculation - using single precision variables. + * + * All the tasks run at the idle priority and never block or yield. This causes + * all eight tasks to time slice with the idle task. Running at the idle priority + * means that these tasks will get pre-empted any time another task is ready to run + * or a time slice occurs. More often than not the pre-emption will occur mid + * calculation, creating a good test of the schedulers context switch mechanism - a + * calculation producing an unexpected result could be a symptom of a corruption in + * the context of a task. + */ + +#include +#include + +/* Scheduler include files. */ +#include "FreeRTOS.h" +#include "task.h" + +/* Demo program include files. */ +#include "flop.h" + +#define mathSTACK_SIZE configMINIMAL_STACK_SIZE +#define mathNUMBER_OF_TASKS ( 8 ) + +/* Four tasks, each of which performs a different floating point calculation. +Each of the four is created twice. */ +static portTASK_FUNCTION_PROTO( vCompetingMathTask1, pvParameters ); +static portTASK_FUNCTION_PROTO( vCompetingMathTask2, pvParameters ); +static portTASK_FUNCTION_PROTO( vCompetingMathTask3, pvParameters ); +static portTASK_FUNCTION_PROTO( vCompetingMathTask4, pvParameters ); + +/* These variables are used to check that all the tasks are still running. If a +task gets a calculation wrong it will +stop incrementing its check variable. */ +static volatile unsigned short usTaskCheck[ mathNUMBER_OF_TASKS ] = { ( unsigned short ) 0 }; + +/*-----------------------------------------------------------*/ + +void vStartMathTasks( unsigned portBASE_TYPE uxPriority ) +{ + xTaskCreate( vCompetingMathTask1, ( signed char * ) "Math1", mathSTACK_SIZE, ( void * ) &( usTaskCheck[ 0 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask2, ( signed char * ) "Math2", mathSTACK_SIZE, ( void * ) &( usTaskCheck[ 1 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask3, ( signed char * ) "Math3", mathSTACK_SIZE, ( void * ) &( usTaskCheck[ 2 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask4, ( signed char * ) "Math4", mathSTACK_SIZE, ( void * ) &( usTaskCheck[ 3 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask1, ( signed char * ) "Math5", mathSTACK_SIZE, ( void * ) &( usTaskCheck[ 4 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask2, ( signed char * ) "Math6", mathSTACK_SIZE, ( void * ) &( usTaskCheck[ 5 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask3, ( signed char * ) "Math7", mathSTACK_SIZE, ( void * ) &( usTaskCheck[ 6 ] ), uxPriority, NULL ); + xTaskCreate( vCompetingMathTask4, ( signed char * ) "Math8", mathSTACK_SIZE, ( void * ) &( usTaskCheck[ 7 ] ), uxPriority, NULL ); +} +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( vCompetingMathTask1, pvParameters ) +{ +volatile float f1, f2, f3, f4; +volatile unsigned short *pusTaskCheckVariable; +volatile float fAnswer; +short sError = pdFALSE; + + f1 = 123.4567F; + f2 = 2345.6789F; + f3 = -918.222F; + + fAnswer = ( f1 + f2 ) * f3; + + /* The variable this task increments to show it is still running is passed in + as the parameter. */ + pusTaskCheckVariable = ( unsigned short * ) pvParameters; + + /* Keep performing a calculation and checking the result against a constant. */ + for(;;) + { + f1 = 123.4567F; + f2 = 2345.6789F; + f3 = -918.222F; + + f4 = ( f1 + f2 ) * f3; + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + /* If the calculation does not match the expected constant, stop the + increment of the check variable. */ + if( fabs( f4 - fAnswer ) > 0.001F ) + { + sError = pdTRUE; + } + + if( sError == pdFALSE ) + { + /* If the calculation has always been correct, increment the check + variable so we know this task is still running okay. */ + ( *pusTaskCheckVariable )++; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + } +} +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( vCompetingMathTask2, pvParameters ) +{ +volatile float f1, f2, f3, f4; +volatile unsigned short *pusTaskCheckVariable; +volatile float fAnswer; +short sError = pdFALSE; + + f1 = -389.38F; + f2 = 32498.2F; + f3 = -2.0001F; + + fAnswer = ( f1 / f2 ) * f3; + + + /* The variable this task increments to show it is still running is passed in + as the parameter. */ + pusTaskCheckVariable = ( unsigned short * ) pvParameters; + + /* Keep performing a calculation and checking the result against a constant. */ + for( ;; ) + { + f1 = -389.38F; + f2 = 32498.2F; + f3 = -2.0001F; + + f4 = ( f1 / f2 ) * f3; + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + /* If the calculation does not match the expected constant, stop the + increment of the check variable. */ + if( fabs( f4 - fAnswer ) > 0.001F ) + { + sError = pdTRUE; + } + + if( sError == pdFALSE ) + { + /* If the calculation has always been correct, increment the check + variable so we know + this task is still running okay. */ + ( *pusTaskCheckVariable )++; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + } +} +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( vCompetingMathTask3, pvParameters ) +{ +volatile float *pfArray, fTotal1, fTotal2, fDifference, fPosition; +volatile unsigned short *pusTaskCheckVariable; +const size_t xArraySize = 10; +size_t xPosition; +short sError = pdFALSE; + + /* The variable this task increments to show it is still running is passed in + as the parameter. */ + pusTaskCheckVariable = ( unsigned short * ) pvParameters; + + pfArray = ( float * ) pvPortMalloc( xArraySize * sizeof( float ) ); + + /* Keep filling an array, keeping a running total of the values placed in the + array. Then run through the array adding up all the values. If the two totals + do not match, stop the check variable from incrementing. */ + for( ;; ) + { + fTotal1 = 0.0F; + fTotal2 = 0.0F; + fPosition = 0.0F; + + for( xPosition = 0; xPosition < xArraySize; xPosition++ ) + { + pfArray[ xPosition ] = fPosition + 5.5F; + fTotal1 += fPosition + 5.5F; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + for( xPosition = 0; xPosition < xArraySize; xPosition++ ) + { + fTotal2 += pfArray[ xPosition ]; + } + + fDifference = fTotal1 - fTotal2; + if( fabs( fDifference ) > 0.001F ) + { + sError = pdTRUE; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + if( sError == pdFALSE ) + { + /* If the calculation has always been correct, increment the check + variable so we know this task is still running okay. */ + ( *pusTaskCheckVariable )++; + } + } +} +/*-----------------------------------------------------------*/ + +static portTASK_FUNCTION( vCompetingMathTask4, pvParameters ) +{ +volatile float *pfArray, fTotal1, fTotal2, fDifference, fPosition; +volatile unsigned short *pusTaskCheckVariable; +const size_t xArraySize = 10; +size_t xPosition; +short sError = pdFALSE; + + /* The variable this task increments to show it is still running is passed in + as the parameter. */ + pusTaskCheckVariable = ( unsigned short * ) pvParameters; + + pfArray = ( float * ) pvPortMalloc( xArraySize * sizeof( float ) ); + + /* Keep filling an array, keeping a running total of the values placed in the + array. Then run through the array adding up all the values. If the two totals + do not match, stop the check variable from incrementing. */ + for( ;; ) + { + fTotal1 = 0.0F; + fTotal2 = 0.0F; + fPosition = 0.0F; + + for( xPosition = 0; xPosition < xArraySize; xPosition++ ) + { + pfArray[ xPosition ] = fPosition * 12.123F; + fTotal1 += fPosition * 12.123F; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + for( xPosition = 0; xPosition < xArraySize; xPosition++ ) + { + fTotal2 += pfArray[ xPosition ]; + } + + fDifference = fTotal1 - fTotal2; + if( fabs( fDifference ) > 0.001F ) + { + sError = pdTRUE; + } + + #if configUSE_PREEMPTION == 0 + taskYIELD(); + #endif + + if( sError == pdFALSE ) + { + /* If the calculation has always been correct, increment the check + variable so we know this task is still running okay. */ + ( *pusTaskCheckVariable )++; + } + } +} +/*-----------------------------------------------------------*/ + +/* This is called to check that all the created tasks are still running. */ +portBASE_TYPE xAreMathsTaskStillRunning( void ) +{ +/* Keep a history of the check variables so we know if they have been incremented +since the last call. */ +static unsigned short usLastTaskCheck[ mathNUMBER_OF_TASKS ] = { ( unsigned short ) 0 }; +portBASE_TYPE xReturn = pdTRUE, xTask; + + /* Check the maths tasks are still running by ensuring their check variables + are still incrementing. */ + for( xTask = 0; xTask < mathNUMBER_OF_TASKS; xTask++ ) + { + if( usTaskCheck[ xTask ] == usLastTaskCheck[ xTask ] ) + { + /* The check has not incremented so an error exists. */ + xReturn = pdFALSE; + } + + usLastTaskCheck[ xTask ] = usTaskCheck[ xTask ]; + } + + return xReturn; +} + + + diff --git a/pool/shard008/C/0130424_nsseq.c b/pool/shard008/C/0130424_nsseq.c new file mode 100644 index 0000000000000000000000000000000000000000..8b39278692d38e648458468b9fe16991ef5b8dea --- /dev/null +++ b/pool/shard008/C/0130424_nsseq.c @@ -0,0 +1,129 @@ +/* $OpenBSD: nsseq.c,v 1.10 2015/02/11 04:00:39 jsing Exp $ */ +/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL + * project 1999. + */ +/* ==================================================================== + * Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include +#include +#include +#include +#include + +static int +nsseq_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) +{ + if (operation == ASN1_OP_NEW_POST) { + NETSCAPE_CERT_SEQUENCE *nsseq; + nsseq = (NETSCAPE_CERT_SEQUENCE *)*pval; + nsseq->type = OBJ_nid2obj(NID_netscape_cert_sequence); + } + return 1; +} + +/* Netscape certificate sequence structure */ + +static const ASN1_AUX NETSCAPE_CERT_SEQUENCE_aux = { + .asn1_cb = nsseq_cb, +}; +static const ASN1_TEMPLATE NETSCAPE_CERT_SEQUENCE_seq_tt[] = { + { + .offset = offsetof(NETSCAPE_CERT_SEQUENCE, type), + .field_name = "type", + .item = &ASN1_OBJECT_it, + }, + { + .flags = ASN1_TFLG_EXPLICIT | ASN1_TFLG_SEQUENCE_OF | ASN1_TFLG_OPTIONAL, + .offset = offsetof(NETSCAPE_CERT_SEQUENCE, certs), + .field_name = "certs", + .item = &X509_it, + }, +}; + +const ASN1_ITEM NETSCAPE_CERT_SEQUENCE_it = { + .itype = ASN1_ITYPE_SEQUENCE, + .utype = V_ASN1_SEQUENCE, + .templates = NETSCAPE_CERT_SEQUENCE_seq_tt, + .tcount = sizeof(NETSCAPE_CERT_SEQUENCE_seq_tt) / sizeof(ASN1_TEMPLATE), + .funcs = &NETSCAPE_CERT_SEQUENCE_aux, + .size = sizeof(NETSCAPE_CERT_SEQUENCE), + .sname = "NETSCAPE_CERT_SEQUENCE", +}; + + +NETSCAPE_CERT_SEQUENCE * +d2i_NETSCAPE_CERT_SEQUENCE(NETSCAPE_CERT_SEQUENCE **a, const unsigned char **in, long len) +{ + return (NETSCAPE_CERT_SEQUENCE *)ASN1_item_d2i((ASN1_VALUE **)a, in, len, + &NETSCAPE_CERT_SEQUENCE_it); +} + +int +i2d_NETSCAPE_CERT_SEQUENCE(NETSCAPE_CERT_SEQUENCE *a, unsigned char **out) +{ + return ASN1_item_i2d((ASN1_VALUE *)a, out, &NETSCAPE_CERT_SEQUENCE_it); +} + +NETSCAPE_CERT_SEQUENCE * +NETSCAPE_CERT_SEQUENCE_new(void) +{ + return (NETSCAPE_CERT_SEQUENCE *)ASN1_item_new(&NETSCAPE_CERT_SEQUENCE_it); +} + +void +NETSCAPE_CERT_SEQUENCE_free(NETSCAPE_CERT_SEQUENCE *a) +{ + ASN1_item_free((ASN1_VALUE *)a, &NETSCAPE_CERT_SEQUENCE_it); +} diff --git a/pool/shard008/C/0130425_rx.c b/pool/shard008/C/0130425_rx.c new file mode 100644 index 0000000000000000000000000000000000000000..974cf0d8519994a9496b11d5ce640315b90f1010 --- /dev/null +++ b/pool/shard008/C/0130425_rx.c @@ -0,0 +1,309 @@ +/* + * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2012 + * The ACX100 Open Source Project + * + * 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, see . + */ + +#include "acx_debug.h" + +#include "acx.h" +#include "pci.h" +#include "mem.h" +#include "merge.h" +#include "usb.h" +#include "utils.h" +#include "rx.h" + +/* + * Calculate level like the feb 2003 windows driver seems to do + * + * Note: the FreeBSD and DragonFlyBSD drivers seems to use different + * so-called correction constants depending on the chip. They will be + * defined for now, but as it is still unknown whether they are correct + * or not, only the original value will be used. Something else to take + * into account is that the OpenBSD driver uses another approach and + * defines the maximum RSSI value depending on the chip, rather than + * using a value of 100 for all of them, as it is currently done here. + */ +#define ACX100_RSSI_CORR 8 +#define ACX111_RSSI_CORR 5 +static u8 acx_signal_to_winlevel(u8 rawlevel) +{ + /* u8 winlevel = (u8) (0.5 + 0.625 * rawlevel); */ + u8 winlevel = (((ACX100_RSSI_CORR / 2) + (rawlevel * 5)) / + ACX100_RSSI_CORR); + + if (winlevel > 100) + winlevel = 100; + return winlevel; +} + +u8 acx_signal_determine_quality(u8 signal, u8 noise) +{ + int qual; + + qual = (((signal - 30) * 100 / 70) + (100 - noise * 4)) / 2; + + if (qual > 100) + return 100; + if (qual < 0) + return 0; + return qual; +} + +const char* acx_get_packet_type_string(u16 fc) +{ + static const char * const mgmt_arr[] = { + "MGMT/AssocReq", "MGMT/AssocResp", "MGMT/ReassocReq", + "MGMT/ReassocResp", "MGMT/ProbeReq", "MGMT/ProbeResp", + "MGMT/UNKNOWN", "MGMT/UNKNOWN", "MGMT/Beacon", "MGMT/ATIM", + "MGMT/Disassoc", "MGMT/Authen", "MGMT/Deauthen", + "MGMT/UNKNOWN" + }; + static const char * const ctl_arr[] = { + "CTL/PSPoll", "CTL/RTS", "CTL/CTS", "CTL/Ack", "CTL/CFEnd", + "CTL/CFEndCFAck", "CTL/UNKNOWN" + }; + static const char * const data_arr[] = { + "DATA/DataOnly", "DATA/Data CFAck", "DATA/Data CFPoll", + "DATA/Data CFAck/CFPoll", "DATA/Null", "DATA/CFAck", + "DATA/CFPoll", "DATA/CFAck/CFPoll", "DATA/UNKNOWN" + }; + const char *str; + u8 fstype = (IEEE80211_FCTL_STYPE & fc) >> 4; + u8 ctl; + + switch (IEEE80211_FCTL_FTYPE & fc) { + case IEEE80211_FTYPE_MGMT: + str = mgmt_arr[min((size_t)fstype, ARRAY_SIZE(mgmt_arr) - 1)]; + break; + case IEEE80211_FTYPE_CTL: + ctl = fstype - 0x0a; + str = ctl_arr[min((size_t)ctl, ARRAY_SIZE(ctl_arr) - 1)]; + break; + case IEEE80211_FTYPE_DATA: + str = data_arr[min((size_t)fstype, ARRAY_SIZE(data_arr) - 1)]; + break; + default: + str = "UNKNOWN"; + break; + } + return str; +} + + +/* + * acx_l_rx + * + * The end of the Rx path. Pulls data from a rxhostdesc into a socket + * buffer and feeds it to the network stack via netif_rx(). + */ +static void acx_rx(acx_device_t *adev, rxbuffer_t *rxbuf) +{ + struct ieee80211_rx_status *status; + + struct ieee80211_hdr *w_hdr; + struct sk_buff *skb; + int buflen; + int level; + + if (unlikely(!test_bit(ACX_FLAG_HW_UP, &adev->flags))) { + pr_info("asked to receive a packet while hw down\n"); + return; + } + + w_hdr = acx_get_wlan_hdr(adev, rxbuf); + buflen = RXBUF_BYTES_RCVD(adev, rxbuf); + + /* Allocate our skb */ + skb = dev_alloc_skb(buflen); + if (!skb) { + pr_info("skb allocation FAILED\n"); + return; + } + + skb_put(skb, buflen); + memcpy(skb->data, w_hdr, buflen); + + status = IEEE80211_SKB_RXCB(skb); + memset(status, 0, sizeof(*status)); + + status->mactime = rxbuf->time; + + level = acx_signal_to_winlevel(rxbuf->phy_level); + /* FIXME cleanup ?: noise = acx_signal_to_winlevel(rxbuf->phy_snr); */ + + /* status->signal = acx_signal_determine_quality(level, noise); + * TODO OW 20100619 On ACX100 seem to be always zero (seen during hx4700 tests ?!) + */ + status->signal = level; + + if(adev->hw_encrypt_enabled) + status->flag = RX_FLAG_DECRYPTED | RX_FLAG_IV_STRIPPED; + + status->freq = adev->rx_status.freq; + status->band = adev->rx_status.band; + + status->antenna = 1; + + /* TODO I'm not sure whether this is (currently) really required. In tests + * this didn't made a difference. Maybe compare what other drivers do. + * TODO Verify translation to rate_idx. + */ +#if 0 + if (rxbuf->phy_stat_baseband & (1 << 3)) /* Uses OFDM */ + status->rate_idx = + acx_plcp_get_bitrate_ofdm(rxbuf->phy_plcp_signal); + else + status->rate_idx = + acx_plcp_get_bitrate_cck(rxbuf->phy_plcp_signal); +#endif + + if (IS_PCI(adev)) { +#if CONFIG_ACX_MAC80211_VERSION <= KERNEL_VERSION(2, 6, 32) + local_bh_disable(); + ieee80211_rx(adev->hw, skb); + local_bh_enable(); +#else + ieee80211_rx_ni(adev->hw, skb); +#endif + } + /* Usb Rx is happening in_interupt() */ + else if (IS_USB(adev) || IS_MEM(adev)) + ieee80211_rx_irqsafe(adev->hw, skb); + else + logf0(L_ANY, "ERROR: Undefined device type !?\n"); + + adev->stats.rx_packets++; + adev->stats.rx_bytes += skb->len; + +} + +/* + * acx_l_process_rxbuf + * + * NB: used by USB code also + */ +void acx_process_rxbuf(acx_device_t *adev, rxbuffer_t *rxbuf) +{ + struct ieee80211_hdr *hdr; + u16 fc, buf_len; + + + + hdr = acx_get_wlan_hdr(adev, rxbuf); + fc = le16_to_cpu(hdr->frame_control); + /* length of frame from control field to first byte of FCS */ + buf_len = RXBUF_BYTES_RCVD(adev, rxbuf); + + /* For debugging */ + if (((IEEE80211_FCTL_STYPE & fc) != IEEE80211_STYPE_BEACON) + && (acx_debug & (L_XFER|L_DATA))) { + + printk_ratelimited( + "acx: rx: %s time:%u len:%u signal:%u,raw=%u" + "SNR:%u,raw=%u macstat:%02X " + "phystat:%02X phyrate:%u status:%u\n", + acx_get_packet_type_string(fc), + le32_to_cpu(rxbuf->time), buf_len, + acx_signal_to_winlevel(rxbuf->phy_level), + rxbuf->phy_level, + acx_signal_to_winlevel(rxbuf->phy_snr), + rxbuf->phy_snr, rxbuf->mac_status, + rxbuf->phy_stat_baseband, + rxbuf->phy_plcp_signal, + adev->status); + } + + if (unlikely(acx_debug & L_DATA)) { + pr_info("rx: 802.11 buf[%u]: \n", buf_len); + acx_dump_bytes(hdr, buf_len); + } + + acx_rx(adev, rxbuf); + + /* Now check Rx quality level, AFTER processing packet. I + * tried to figure out how to map these levels to dBm values, + * but for the life of me I really didn't manage to get + * it. Either these values are not meant to be expressed in + * dBm, or it's some pretty complicated calculation. */ + + /* FIXME OW 20100619 Is this still required. Only for adev local use. + * Mac80211 signal level is reported in acx_l_rx for each skb. + */ + /* TODO: only the RSSI seems to be reported */ + adev->rx_status.signal = acx_signal_to_winlevel(rxbuf->phy_level); + + +} + +/* TODO Verify these functions: translation rxbuffer.phy_plcp_signal to rate_idx */ +#if 0 + +/** Rate values **/ +#define ACX_CCK_RATE_1MB 0 +#define ACX_CCK_RATE_2MB 1 +#define ACX_CCK_RATE_5MB 2 +#define ACX_CCK_RATE_11MB 3 +#define ACX_OFDM_RATE_6MB 4 +#define ACX_OFDM_RATE_9MB 5 +#define ACX_OFDM_RATE_12MB 6 +#define ACX_OFDM_RATE_18MB 7 +#define ACX_OFDM_RATE_24MB 8 +#define ACX_OFDM_RATE_36MB 9 +#define ACX_OFDM_RATE_48MB 10 +#define ACX_OFDM_RATE_54MB 11 + +static u8 acx_plcp_get_bitrate_cck(u8 plcp) +{ + switch (plcp) { + case 0x0A: + return ACX_CCK_RATE_1MB; + case 0x14: + return ACX_CCK_RATE_2MB; + case 0x37: + return ACX_CCK_RATE_5MB; + case 0x6E: + return ACX_CCK_RATE_11MB; + } + return 0; +} + +/* Extract the bitrate out of an OFDM PLCP header. */ +static u8 acx_plcp_get_bitrate_ofdm(u8 plcp) +{ + switch (plcp & 0xF) { + case 0xB: + return ACX_OFDM_RATE_6MB; + case 0xF: + return ACX_OFDM_RATE_9MB; + case 0xA: + return ACX_OFDM_RATE_12MB; + case 0xE: + return ACX_OFDM_RATE_18MB; + case 0x9: + return ACX_OFDM_RATE_24MB; + case 0xD: + return ACX_OFDM_RATE_36MB; + case 0x8: + return ACX_OFDM_RATE_48MB; + case 0xC: + return ACX_OFDM_RATE_54MB; + } + return 0; +} +#endif + + diff --git a/pool/shard008/C/0130430_mmapTest.c b/pool/shard008/C/0130430_mmapTest.c new file mode 100644 index 0000000000000000000000000000000000000000..4bb1406e63391567ad7d1a2e77297283b1557dce --- /dev/null +++ b/pool/shard008/C/0130430_mmapTest.c @@ -0,0 +1,49 @@ +#include +#include +#include +#include +#include +#include +#include + +typedef struct { + int id; + char name[10]; +} RECORD; + +#define NRECORDS (100) + +int main() { + RECORD record, *maps; + int f; + FILE *fd; + const char *path = "record.dat"; + + fd = fopen(path, "w+"); + for(int i=0;i + +#define NAME_LEN 64 + +typedef struct { + char name[NAME_LEN]; + int height; + float weight; + long schols; +} Student; + +void hiroko(Student *std); + +int main(void) +{ + Student sanaka = {}; + + printf("请输入用户姓名: "); + scanf("%s", sanaka.name); + + printf("请输入用户身高: "); + scanf("%d", &sanaka.height); + + printf("请输入用户体重: "); + scanf("%f", &sanaka.weight); + + printf("请输入用户奖学金: "); + scanf("%ld", &sanaka.schols); + + hiroko(&sanaka); + + printf("姓名 = %s\n", sanaka.name); + printf("身高 = %d\n", sanaka.height); + printf("体重 = %.1f\n", sanaka.weight); + printf("奖学金 = %ld\n", sanaka.schols); + + return 0; +} + +void hiroko(Student *std) +{ + if (std->height < 180) { + std->height = 180; + } + if (std->weight > 80) { + std->weight = 80; + } +} diff --git a/pool/shard008/C/0130433_conntrack_delete.c b/pool/shard008/C/0130433_conntrack_delete.c new file mode 100644 index 0000000000000000000000000000000000000000..ae2fc35c5a11ad5d63da2eaeedb4b2268a4de55f --- /dev/null +++ b/pool/shard008/C/0130433_conntrack_delete.c @@ -0,0 +1,50 @@ +#include +#include +#include +#include +#include + +#include +#include + +int main(void) +{ + int ret; + struct nfct_handle *h; + struct nf_conntrack *ct; + + ct = nfct_new(); + if (!ct) { + perror("nfct_new"); + return 0; + } + + nfct_set_attr_u8(ct, ATTR_L3PROTO, AF_INET); + nfct_set_attr_u32(ct, ATTR_IPV4_SRC, inet_addr("1.1.1.1")); + nfct_set_attr_u32(ct, ATTR_IPV4_DST, inet_addr("2.2.2.2")); + + nfct_set_attr_u8(ct, ATTR_L4PROTO, IPPROTO_TCP); + nfct_set_attr_u16(ct, ATTR_PORT_SRC, htons(20)); + nfct_set_attr_u16(ct, ATTR_PORT_DST, htons(10)); + + h = nfct_open(CONNTRACK, 0); + if (!h) { + perror("nfct_open"); + nfct_destroy(ct); + return -1; + } + + ret = nfct_query(h, NFCT_Q_DESTROY, ct); + + printf("TEST: delete conntrack "); + if (ret == -1) + printf("(%d)(%s)\n", ret, strerror(errno)); + else + printf("(OK)\n"); + + nfct_close(h); + + nfct_destroy(ct); + + ret == -1 ? exit(EXIT_FAILURE) : exit(EXIT_SUCCESS); +} diff --git a/pool/shard008/C/0130444_ft_lstmap.c b/pool/shard008/C/0130444_ft_lstmap.c new file mode 100644 index 0000000000000000000000000000000000000000..93f82dfbe0abed70bcdc99e01e60bd0ed5dc4055 --- /dev/null +++ b/pool/shard008/C/0130444_ft_lstmap.c @@ -0,0 +1,44 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_lstmap.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: kdavis +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2016/09/29 15:48:02 by kdavis #+# #+# */ +/* Updated: 2016/10/07 13:19:34 by kdavis ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "libft.h" +#include + +/* +** Iterates a list and applies the function f resulting in a fresh list +** generated from the successive application of f. If an allocation fails +** return NULL. +*/ + +t_list *ft_lstmap(t_list *lst, t_list *(*f)(t_list *elem)) +{ + t_list *map; + t_list *tail; + + if (!lst || !f) + return (NULL); + if (!(map = f(lst))) + return (NULL); + lst = lst->next; + tail = map; + while (lst) + { + if (!(tail->next = f(lst))) + { + ft_lstdel(&map, ft_delcontent); + return (NULL); + } + tail = tail->next; + lst = lst->next; + } + return (map); +} diff --git a/pool/shard008/C/0130445_ext_log_upload_strategies.c b/pool/shard008/C/0130445_ext_log_upload_strategies.c new file mode 100644 index 0000000000000000000000000000000000000000..6897bba3d91185e23e17b6d107e95f3924ad7668 --- /dev/null +++ b/pool/shard008/C/0130445_ext_log_upload_strategies.c @@ -0,0 +1,260 @@ +/* + * Copyright 2014 CyberVision, Inc. + * + * 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. + */ + +#ifndef KAA_DISABLE_FEATURE_LOGGING + +#include "ext_log_upload_strategies.h" +#include "../../platform/ext_log_upload_strategy.h" +#include "../../platform/ext_transport_channel.h" +#include "../../platform/time.h" +#include "../../utilities/kaa_mem.h" +#include "../../kaa_context.h" + +/** + * @brief The default value (in seconds) for time to wait a log delivery response. + */ +#define KAA_DEFAULT_UPLOAD_TIMEOUT 2 * 60 + +/** + * @brief The default value (in seconds) for time to postpone log upload. + */ +#define KAA_DEFAULT_RETRY_PERIOD 5 * 60 + +/** + * @brief The default value (in bytes) for log volume to initiate the log upload. + */ +#define KAA_DEFAULT_UPLOAD_VOLUME_THRESHOLD 8 * 1024 + +/** + * @brief The default value for the log count to initiate the log upload. + */ +#define KAA_DEFAULT_UPLOAD_COUNT_THRESHOLD 64 + +/** + * @brief The default value (in bytes) for the maximum size of the report pack that + * will be delivered in a single request to the Operaions server. + */ +#define KAA_DEFAULT_BATCH_SIZE 8 * 1024 + +typedef struct { + uint8_t type; + size_t threshold_volume; + size_t threshold_count; + size_t upload_timeout; + size_t timeout; + + size_t log_batch_size; + size_t upload_retry_period; + + time_t upload_retry_ts; + + kaa_channel_manager_t *channel_manager; + kaa_bootstrap_manager_t *bootstrap_manager; +} ext_log_upload_strategy_t; + +extern kaa_transport_channel_interface_t *kaa_channel_manager_get_transport_channel(kaa_channel_manager_t *self + , kaa_service_t service_type); + +/* + * Strategy implementation. + */ + +kaa_error_t ext_log_upload_strategy_create(struct kaa_context_s *context, void **strategy_p, uint8_t type) +{ + KAA_RETURN_IF_NIL5(strategy_p, context, context->channel_manager, context->bootstrap_manager, type, KAA_ERR_BADPARAM); + + ext_log_upload_strategy_t *strategy = (ext_log_upload_strategy_t *) KAA_MALLOC(sizeof(ext_log_upload_strategy_t)); + KAA_RETURN_IF_NIL(strategy, KAA_ERR_NOMEM); + + KAA_RETURN_IF_ERR( ext_log_upload_strategy_set_threshold_volume(strategy, KAA_DEFAULT_UPLOAD_VOLUME_THRESHOLD) ); + KAA_RETURN_IF_ERR( ext_log_upload_strategy_set_threshold_count(strategy, KAA_DEFAULT_UPLOAD_COUNT_THRESHOLD) ); + KAA_RETURN_IF_ERR( ext_log_upload_strategy_set_upload_timeout(strategy, KAA_DEFAULT_UPLOAD_TIMEOUT) ); + KAA_RETURN_IF_ERR( ext_log_upload_strategy_set_upload_retry_period(strategy, KAA_DEFAULT_RETRY_PERIOD) ); + KAA_RETURN_IF_ERR( ext_log_upload_strategy_set_batch_size(strategy, KAA_DEFAULT_BATCH_SIZE) ); + + strategy->type = type; + strategy->upload_retry_ts = 0; + strategy->timeout = KAA_TIME() + strategy->upload_timeout; + + strategy->bootstrap_manager = context->bootstrap_manager; + strategy->channel_manager = context->channel_manager; + + *strategy_p = strategy; + + return KAA_ERR_NONE; +} + + + +void ext_log_upload_strategy_destroy(void *self) +{ + if (self) + KAA_FREE((ext_log_upload_strategy_t *)self); +} + + + +ext_log_upload_decision_t ext_log_upload_strategy_decide(void *context, const void *log_storage_context) +{ + KAA_RETURN_IF_NIL2(context, log_storage_context, NOOP); + + ext_log_upload_decision_t decision = NOOP; + ext_log_upload_strategy_t *self = (ext_log_upload_strategy_t *)context; + + if (self->upload_retry_ts) { + if (KAA_TIME() >= self->upload_retry_ts) { + // force upload after retry timeout has elapsed + self->upload_retry_ts = 0; + decision = UPLOAD; + } + return decision; + } + + if (self->type & 0x04 && KAA_TIME() >= self->timeout) { + decision = UPLOAD; + self->timeout = KAA_TIME() + self->upload_timeout; + } else if (self->type & 0x01 && ext_log_storage_get_total_size(log_storage_context) >= self->threshold_volume) { + decision = UPLOAD; + } else if (self->type & 0x02 && ext_log_storage_get_records_count(log_storage_context) >= self->threshold_count) { + decision = UPLOAD; + } + + return decision; +} + + + +size_t ext_log_upload_strategy_get_bucket_size(void *context) +{ + KAA_RETURN_IF_NIL(context, 0); + return ((ext_log_upload_strategy_t *)context)->log_batch_size; +} + + + +size_t ext_log_upload_strategy_get_timeout(void *context) +{ + KAA_RETURN_IF_NIL(context, 0); + return ((ext_log_upload_strategy_t *)context)->upload_timeout; +} + + + +kaa_error_t ext_log_upload_strategy_on_timeout(void *context) +{ + KAA_RETURN_IF_NIL(context, KAA_ERR_BADPARAM); + + ext_log_upload_strategy_t *self = (ext_log_upload_strategy_t *)context; + kaa_transport_channel_interface_t *channel = kaa_channel_manager_get_transport_channel(self->channel_manager + , KAA_SERVICE_LOGGING); + if (channel) { + self->upload_retry_ts = 0; + kaa_transport_protocol_id_t protocol_id; + kaa_error_t error_code = channel->get_protocol_id(channel->context, &protocol_id); + KAA_RETURN_IF_ERR(error_code); + error_code = kaa_bootstrap_manager_on_access_point_failed(self->bootstrap_manager + , &protocol_id + , KAA_SERVER_OPERATIONS); + return error_code; + } + + return KAA_ERR_NOT_FOUND; +} + + + +kaa_error_t ext_log_upload_strategy_on_failure(void *context, logging_delivery_error_code_t error_code) +{ + KAA_RETURN_IF_NIL(context, KAA_ERR_BADPARAM); + ext_log_upload_strategy_t *self = (ext_log_upload_strategy_t *)context; + + switch (error_code) { + case NO_APPENDERS_CONFIGURED: + case APPENDER_INTERNAL_ERROR: + case REMOTE_CONNECTION_ERROR: + case REMOTE_INTERNAL_ERROR: + self->upload_retry_ts = KAA_TIME() + self->upload_retry_period; + break; + default: + break; + } + + return KAA_ERR_NONE; +} + + + +kaa_error_t ext_log_upload_strategy_change_strategy(void *strategy, uint8_t type) +{ + KAA_RETURN_IF_NIL2(strategy, type, KAA_ERR_BADPARAM); + ((ext_log_upload_strategy_t *)strategy)->type = type; + return KAA_ERR_NONE; +} + +extern bool ext_log_upload_strategy_is_timeout_strategy(void *strategy) +{ + KAA_RETURN_IF_NIL(strategy, KAA_ERR_BADPARAM); + ext_log_upload_strategy_t *self = (ext_log_upload_strategy_t *)strategy; + if (self->type & TIMEOUT_FLAG) + return true; + return false; +} + +kaa_error_t ext_log_upload_strategy_set_threshold_volume(void *strategy, size_t threshold_volume) +{ + KAA_RETURN_IF_NIL2(strategy, threshold_volume, KAA_ERR_BADPARAM); + ((ext_log_upload_strategy_t *)strategy)->threshold_volume = threshold_volume; + return KAA_ERR_NONE; +} + + + +kaa_error_t ext_log_upload_strategy_set_threshold_count(void *strategy, size_t threshold_count) +{ + KAA_RETURN_IF_NIL2(strategy, threshold_count, KAA_ERR_BADPARAM); + ((ext_log_upload_strategy_t *)strategy)->threshold_count = threshold_count; + return KAA_ERR_NONE; +} + + + +kaa_error_t ext_log_upload_strategy_set_batch_size(void *strategy, size_t log_batch_size) +{ + KAA_RETURN_IF_NIL2(strategy, log_batch_size, KAA_ERR_BADPARAM); + ((ext_log_upload_strategy_t *)strategy)->log_batch_size = log_batch_size; + return KAA_ERR_NONE; +} + + + +kaa_error_t ext_log_upload_strategy_set_upload_timeout(void *strategy, size_t upload_timeout) +{ + KAA_RETURN_IF_NIL2(strategy, upload_timeout, KAA_ERR_BADPARAM); + ((ext_log_upload_strategy_t *)strategy)->upload_timeout = upload_timeout; + ((ext_log_upload_strategy_t *)strategy)->timeout = KAA_TIME() + upload_timeout; + return KAA_ERR_NONE; +} + + + +kaa_error_t ext_log_upload_strategy_set_upload_retry_period(void *strategy, size_t upload_retry_period) +{ + KAA_RETURN_IF_NIL2(strategy, upload_retry_period, KAA_ERR_BADPARAM); + ((ext_log_upload_strategy_t *)strategy)->upload_retry_period = upload_retry_period; + return KAA_ERR_NONE; +} + +#endif diff --git a/pool/shard008/C/0130448_policy_dummy.c b/pool/shard008/C/0130448_policy_dummy.c new file mode 100644 index 0000000000000000000000000000000000000000..a9b91d1ec8138c63b694826ebba7d8a7ffa08c07 --- /dev/null +++ b/pool/shard008/C/0130448_policy_dummy.c @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2018 Intel Corporation. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include +#include +#include "pm_policy.h" + +#include +LOG_MODULE_DECLARE(power, CONFIG_PM_LOG_LEVEL); + +#define STATE_ACTIVE \ + (struct pm_state_info){PM_STATE_ACTIVE, 0, 0} + +static const struct pm_state_info pm_dummy_states[] = + PM_STATE_INFO_DT_ITEMS_LIST(DT_NODELABEL(cpu0)); + +struct pm_state_info pm_policy_next_state(int32_t ticks) +{ + static struct pm_state_info cur_pm_state_info; + int i = (int)cur_pm_state_info.state; + uint8_t states_len = ARRAY_SIZE(pm_dummy_states); + + if (states_len == 0) { + /* No power states to go through. */ + return STATE_ACTIVE; + } + + do { + i = (i + 1) % states_len; + + if (!pm_constraint_get( + pm_dummy_states[i].state)) { + continue; + } + + cur_pm_state_info = pm_dummy_states[i]; + + LOG_DBG("Selected power state: %u", pm_dummy_states[i].state); + + return pm_dummy_states[i]; + } while (pm_dummy_states[i].state != cur_pm_state_info.state); + + LOG_DBG("No suitable power state found!"); + return STATE_ACTIVE; +} diff --git a/pool/shard008/C/0130450_powernow-k6.c b/pool/shard008/C/0130450_powernow-k6.c new file mode 100644 index 0000000000000000000000000000000000000000..5a30c0e727251132137d75f0d43ef52f416c4b2f --- /dev/null +++ b/pool/shard008/C/0130450_powernow-k6.c @@ -0,0 +1,213 @@ + + +#include +#include +#include +#include +#include +#include +#include + +#include + +#define POWERNOW_IOPORT 0xfff0 /* it doesn't matter where, as long + as it is unused */ + +#define PFX "powernow-k6: " +static unsigned int busfreq; /* FSB, in 10 kHz */ +static unsigned int max_multiplier; + + +/* Clock ratio multiplied by 10 - see table 27 in AMD#23446 */ +static struct cpufreq_frequency_table clock_ratio[] = { + {45, /* 000 -> 4.5x */ 0}, + {50, /* 001 -> 5.0x */ 0}, + {40, /* 010 -> 4.0x */ 0}, + {55, /* 011 -> 5.5x */ 0}, + {20, /* 100 -> 2.0x */ 0}, + {30, /* 101 -> 3.0x */ 0}, + {60, /* 110 -> 6.0x */ 0}, + {35, /* 111 -> 3.5x */ 0}, + {0, CPUFREQ_TABLE_END} +}; + + +static int powernow_k6_get_cpu_multiplier(void) +{ + u64 invalue = 0; + u32 msrval; + + msrval = POWERNOW_IOPORT + 0x1; + wrmsr(MSR_K6_EPMR, msrval, 0); /* enable the PowerNow port */ + invalue = inl(POWERNOW_IOPORT + 0x8); + msrval = POWERNOW_IOPORT + 0x0; + wrmsr(MSR_K6_EPMR, msrval, 0); /* disable it again */ + + return clock_ratio[(invalue >> 5)&7].index; +} + + +static void powernow_k6_set_state(unsigned int best_i) +{ + unsigned long outvalue = 0, invalue = 0; + unsigned long msrval; + struct cpufreq_freqs freqs; + + if (clock_ratio[best_i].index > max_multiplier) { + printk(KERN_ERR PFX "invalid target frequency\n"); + return; + } + + freqs.old = busfreq * powernow_k6_get_cpu_multiplier(); + freqs.new = busfreq * clock_ratio[best_i].index; + freqs.cpu = 0; /* powernow-k6.c is UP only driver */ + + cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE); + + /* we now need to transform best_i to the BVC format, see AMD#23446 */ + + outvalue = (1<<12) | (1<<10) | (1<<9) | (best_i<<5); + + msrval = POWERNOW_IOPORT + 0x1; + wrmsr(MSR_K6_EPMR, msrval, 0); /* enable the PowerNow port */ + invalue = inl(POWERNOW_IOPORT + 0x8); + invalue = invalue & 0xf; + outvalue = outvalue | invalue; + outl(outvalue , (POWERNOW_IOPORT + 0x8)); + msrval = POWERNOW_IOPORT + 0x0; + wrmsr(MSR_K6_EPMR, msrval, 0); /* disable it again */ + + cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE); + + return; +} + + +static int powernow_k6_verify(struct cpufreq_policy *policy) +{ + return cpufreq_frequency_table_verify(policy, &clock_ratio[0]); +} + + +static int powernow_k6_target(struct cpufreq_policy *policy, + unsigned int target_freq, + unsigned int relation) +{ + unsigned int newstate = 0; + + if (cpufreq_frequency_table_target(policy, &clock_ratio[0], + target_freq, relation, &newstate)) + return -EINVAL; + + powernow_k6_set_state(newstate); + + return 0; +} + + +static int powernow_k6_cpu_init(struct cpufreq_policy *policy) +{ + unsigned int i, f; + int result; + + if (policy->cpu != 0) + return -ENODEV; + + /* get frequencies */ + max_multiplier = powernow_k6_get_cpu_multiplier(); + busfreq = cpu_khz / max_multiplier; + + /* table init */ + for (i = 0; (clock_ratio[i].frequency != CPUFREQ_TABLE_END); i++) { + f = clock_ratio[i].index; + if (f > max_multiplier) + clock_ratio[i].frequency = CPUFREQ_ENTRY_INVALID; + else + clock_ratio[i].frequency = busfreq * f; + } + + /* cpuinfo and default policy values */ + policy->cpuinfo.transition_latency = 200000; + policy->cur = busfreq * max_multiplier; + + result = cpufreq_frequency_table_cpuinfo(policy, clock_ratio); + if (result) + return result; + + cpufreq_frequency_table_get_attr(clock_ratio, policy->cpu); + + return 0; +} + + +static int powernow_k6_cpu_exit(struct cpufreq_policy *policy) +{ + unsigned int i; + for (i = 0; i < 8; i++) { + if (i == max_multiplier) + powernow_k6_set_state(i); + } + cpufreq_frequency_table_put_attr(policy->cpu); + return 0; +} + +static unsigned int powernow_k6_get(unsigned int cpu) +{ + unsigned int ret; + ret = (busfreq * powernow_k6_get_cpu_multiplier()); + return ret; +} + +static struct freq_attr *powernow_k6_attr[] = { + &cpufreq_freq_attr_scaling_available_freqs, + NULL, +}; + +static struct cpufreq_driver powernow_k6_driver = { + .verify = powernow_k6_verify, + .target = powernow_k6_target, + .init = powernow_k6_cpu_init, + .exit = powernow_k6_cpu_exit, + .get = powernow_k6_get, + .name = "powernow-k6", + .owner = THIS_MODULE, + .attr = powernow_k6_attr, +}; + + +static int __init powernow_k6_init(void) +{ + struct cpuinfo_x86 *c = &cpu_data(0); + + if ((c->x86_vendor != X86_VENDOR_AMD) || (c->x86 != 5) || + ((c->x86_model != 12) && (c->x86_model != 13))) + return -ENODEV; + + if (!request_region(POWERNOW_IOPORT, 16, "PowerNow!")) { + printk(KERN_INFO PFX "PowerNow IOPORT region already used.\n"); + return -EIO; + } + + if (cpufreq_register_driver(&powernow_k6_driver)) { + release_region(POWERNOW_IOPORT, 16); + return -EINVAL; + } + + return 0; +} + + +static void __exit powernow_k6_exit(void) +{ + cpufreq_unregister_driver(&powernow_k6_driver); + release_region(POWERNOW_IOPORT, 16); +} + + +MODULE_AUTHOR("Arjan van de Ven, Dave Jones , " + "Dominik Brodowski "); +MODULE_DESCRIPTION("PowerNow! driver for AMD K6-2+ / K6-3+ processors."); +MODULE_LICENSE("GPL"); + +module_init(powernow_k6_init); +module_exit(powernow_k6_exit); diff --git a/pool/shard008/C/0130452_priotest.c b/pool/shard008/C/0130452_priotest.c new file mode 100644 index 0000000000000000000000000000000000000000..e08fb8afd05ef5b461884fd60e7b9f5f85a389b6 --- /dev/null +++ b/pool/shard008/C/0130452_priotest.c @@ -0,0 +1,226 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (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.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Netscape Portable Runtime (NSPR). + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998-2000 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +/* + * File: priotest.c + * Purpose: testing priorities + */ + +#include "prcmon.h" +#include "prinit.h" +#include "prinrval.h" +#include "prlock.h" +#include "prlog.h" +#include "prmon.h" +#include "prprf.h" +#include "prthread.h" +#include "prtypes.h" + +#include "plerror.h" +#include "plgetopt.h" + +#include +#include + +#define DEFAULT_DURATION 5 + +static PRBool failed = PR_FALSE; +static PRIntervalTime oneSecond; +static PRFileDesc *debug_out = NULL; +static PRBool debug_mode = PR_FALSE; + +static PRUint32 PerSecond(PRIntervalTime timein) +{ + PRUint32 loop = 0; + while (((PRIntervalTime)(PR_IntervalNow()) - timein) < oneSecond) + loop += 1; + return loop; +} /* PerSecond */ + +static void PR_CALLBACK Low(void *arg) +{ + PRUint32 t3 = 0, t2 = 0, t1 = 0, t0, *tn = (PRUint32*)arg; + while (1) + { + t0 = PerSecond(PR_IntervalNow()); + *tn = (t3 + 3 * t2 + 3 * t1 + t0) / 8; + t3 = t2; t2 = t1; t1 = t0; + } +} /* Low */ + +static void PR_CALLBACK High(void *arg) +{ + PRUint32 t3 = 0, t2 = 0, t1 = 0, t0, *tn = (PRUint32*)arg; + while (1) + { + PRIntervalTime timein = PR_IntervalNow(); + PR_Sleep(oneSecond >> 2); /* 0.25 seconds */ + t0 = PerSecond(timein); + *tn = (t3 + 3 * t2 + 3 * t1 + t0) / 8; + t3 = t2; t2 = t1; t1 = t0; + } +} /* High */ + +static void Help(void) +{ + PR_fprintf( + debug_out, "Usage: priotest [-d] [-c n]\n"); + PR_fprintf( + debug_out, "-c n\tduration of test in seconds (default: %d)\n", DEFAULT_DURATION); + PR_fprintf( + debug_out, "-d\tturn on debugging output (default: FALSE)\n"); +} /* Help */ + +static void RudimentaryTests(void) +{ + /* + ** Try some rudimentary tests like setting valid priority and + ** getting it back, or setting invalid priorities and getting + ** back a valid answer. + */ + PRThreadPriority priority; + PR_SetThreadPriority(PR_GetCurrentThread(), PR_PRIORITY_URGENT); + priority = PR_GetThreadPriority(PR_GetCurrentThread()); + failed = ((PR_TRUE == failed) || (PR_PRIORITY_URGENT != priority)) + ? PR_TRUE : PR_FALSE; + if (debug_mode && (PR_PRIORITY_URGENT != priority)) + { + PR_fprintf(debug_out, "PR_[S/G]etThreadPriority() failed\n"); + } + + + PR_SetThreadPriority( + PR_GetCurrentThread(), (PRThreadPriority)(PR_PRIORITY_FIRST - 1)); + priority = PR_GetThreadPriority(PR_GetCurrentThread()); + failed = ((PR_TRUE == failed) || (PR_PRIORITY_FIRST != priority)) + ? PR_TRUE : PR_FALSE; + if (debug_mode && (PR_PRIORITY_FIRST != priority)) + { + PR_fprintf(debug_out, "PR_SetThreadPriority(-1) failed\n"); + } + + PR_SetThreadPriority( + PR_GetCurrentThread(), (PRThreadPriority)(PR_PRIORITY_LAST + 1)); + priority = PR_GetThreadPriority(PR_GetCurrentThread()); + failed = ((PR_TRUE == failed) || (PR_PRIORITY_LAST != priority)) + ? PR_TRUE : PR_FALSE; + if (debug_mode && (PR_PRIORITY_LAST != priority)) + { + PR_fprintf(debug_out, "PR_SetThreadPriority(+1) failed\n"); + } + +} /* RudimentataryTests */ + +static void CreateThreads(PRUint32 *lowCount, PRUint32 *highCount) +{ + (void)PR_CreateThread( + PR_USER_THREAD, Low, lowCount, PR_PRIORITY_LOW, + PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); + (void)PR_CreateThread( + PR_USER_THREAD, High, highCount, PR_PRIORITY_HIGH, + PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); +} /* CreateThreads */ + +int main(int argc, char **argv) +{ + PLOptStatus os; + PRIntn duration = DEFAULT_DURATION; + PRUint32 totalCount, highCount = 0, lowCount = 0; + PLOptState *opt = PL_CreateOptState(argc, argv, "hdc:"); + + debug_out = PR_STDOUT; + oneSecond = PR_SecondsToInterval(1); + + while (PL_OPT_EOL != (os = PL_GetNextOpt(opt))) + { + if (PL_OPT_BAD == os) continue; + switch (opt->option) + { + case 'd': /* debug mode */ + debug_mode = PR_TRUE; + break; + case 'c': /* test duration */ + duration = atoi(opt->value); + break; + case 'h': /* help message */ + default: + Help(); + return 2; + } + } + PL_DestroyOptState(opt); + PR_STDIO_INIT(); + + if (duration == 0) duration = DEFAULT_DURATION; + + RudimentaryTests(); + + printf("Priority test: running for %d seconds\n\n", duration); + + (void)PerSecond(PR_IntervalNow()); + totalCount = PerSecond(PR_IntervalNow()); + + PR_SetThreadPriority(PR_GetCurrentThread(), PR_PRIORITY_URGENT); + + if (debug_mode) + { + PR_fprintf(debug_out, + "The high priority thread should get approximately three\n"); + PR_fprintf( debug_out, + "times what the low priority thread manages. A maximum of \n"); + PR_fprintf( debug_out, "%d cycles are available.\n\n", totalCount); + } + + duration = (duration + 4) / 5; + CreateThreads(&lowCount, &highCount); + while (duration--) + { + PRIntn loop = 5; + while (loop--) PR_Sleep(oneSecond); + if (debug_mode) + PR_fprintf(debug_out, "high : low :: %d : %d\n", highCount, lowCount); + } + + + PR_ProcessExit((failed) ? 1 : 0); + + PR_ASSERT(!"You can't get here -- but you did!"); + return 1; /* or here */ + +} /* main */ + +/* priotest.c */ diff --git a/pool/shard008/C/0130453_devices.c b/pool/shard008/C/0130453_devices.c new file mode 100644 index 0000000000000000000000000000000000000000..f04e9eed4eb5352f43aa951aa1e67651ea699afe --- /dev/null +++ b/pool/shard008/C/0130453_devices.c @@ -0,0 +1,80 @@ +/* devices.c: Initial scan of the prom device tree for important + * Sparc device nodes which we need to find. + * + * Copyright (C) 1996 David S. Miller (davem@caip.rutgers.edu) + */ + +#include +#include +#include + +#include +#include +#include +#include + +struct prom_cpuinfo linux_cpus[NCPUS]; +int linux_num_cpus; + +extern void cpu_probe(void); +extern void clock_stop_probe(void); /* tadpole.c */ + +unsigned long +device_scan(unsigned long mem_start) +{ + char node_str[128]; + int nd, prom_node_cpu, thismid; + int cpu_nds[NCPUS]; /* One node for each cpu */ + int cpu_ctr = 0; + +#if CONFIG_AP1000 + printk("Not scanning device list for CPUs\n"); + linux_num_cpus = 1; + return; +#endif + + prom_getstring(prom_root_node, "device_type", node_str, sizeof(node_str)); + + if(strcmp(node_str, "cpu") == 0) { + cpu_nds[0] = prom_root_node; + cpu_ctr++; + } else { + int scan; + scan = prom_getchild(prom_root_node); + prom_printf("root child is %08lx\n", (unsigned long) scan); + nd = 0; + while((scan = prom_getsibling(scan)) != 0) { + prom_getstring(scan, "device_type", node_str, sizeof(node_str)); + if(strcmp(node_str, "cpu") == 0) { + cpu_nds[cpu_ctr] = scan; + linux_cpus[cpu_ctr].prom_node = scan; + prom_getproperty(scan, "mid", (char *) &thismid, sizeof(thismid)); + linux_cpus[cpu_ctr].mid = thismid; + prom_printf("Found CPU %d \n", + cpu_ctr, (unsigned long) scan, + thismid); + cpu_ctr++; + } + }; + if(cpu_ctr == 0) { + printk("No CPU nodes found, cannot continue.\n"); + /* Probably a sun4d or sun4e, Sun is trying to trick us ;-) */ + halt(); + } + printk("Found %d CPU prom device tree node(s).\n", cpu_ctr); + }; + prom_node_cpu = cpu_nds[0]; + + linux_num_cpus = cpu_ctr; + + cpu_probe(); +#if CONFIG_SUN_AUXIO + { + extern void auxio_probe(void); + auxio_probe(); + } +#endif + clock_stop_probe(); + + return mem_start; +} diff --git a/pool/shard008/C/0130456_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_ncat_51b.c b/pool/shard008/C/0130456_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_ncat_51b.c new file mode 100644 index 0000000000000000000000000000000000000000..8f138d6ca10c2194012e72e9260af26b448bc6ea --- /dev/null +++ b/pool/shard008/C/0130456_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_ncat_51b.c @@ -0,0 +1,56 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_ncat_51b.c +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.string.label.xml +Template File: sources-sink-51b.tmpl.c +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Allocate using malloc() and set data pointer to a small buffer + * GoodSource: Allocate using malloc() and set data pointer to a large buffer + * Sink: ncat + * BadSink : Copy string to data using wcsncat + * Flow Variant: 51 Data flow: data passed as an argument from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include + +/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */ + +#ifndef OMITBAD + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_ncat_51b_badSink(wchar_t * data) +{ + { + wchar_t source[100]; + wmemset(source, L'C', 100-1); /* fill with L'C's */ + source[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: Possible buffer overflow if source is larger than sizeof(data)-strlen(data) */ + wcsncat(data, source, 100); + printWLine(data); + free(data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_wchar_t_ncat_51b_goodG2BSink(wchar_t * data) +{ + { + wchar_t source[100]; + wmemset(source, L'C', 100-1); /* fill with L'C's */ + source[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: Possible buffer overflow if source is larger than sizeof(data)-strlen(data) */ + wcsncat(data, source, 100); + printWLine(data); + free(data); + } +} + +#endif /* OMITGOOD */ diff --git a/pool/shard008/C/0130461_main.c b/pool/shard008/C/0130461_main.c new file mode 100644 index 0000000000000000000000000000000000000000..a0bc3a2f380e070062819f99533c31970da2f2ab --- /dev/null +++ b/pool/shard008/C/0130461_main.c @@ -0,0 +1,118 @@ +#include "types.h" +#include "defs.h" +#include "param.h" +#include "memlayout.h" +#include "mmu.h" +#include "proc.h" +#include "x86.h" + +static void startothers(void); +static void mpmain(void) __attribute__((noreturn)); +extern pde_t *kpgdir; +extern char end[]; // first address after kernel loaded from ELF file + +// Bootstrap processor starts running C code here. +// Allocate a real stack and switch to it, first +// doing some setup required for memory allocator to work. +int +main(void) +{ + kinit1(end, P2V(4*1024*1024)); // phys page allocator + kvmalloc(); // kernel page table + mpinit(); // collect info about this machine + lapicinit(); + seginit(); // set up segments + consoleclear(); + cprintf("\ncpu%d: starting xv6\n\n", cpu->id); + picinit(); // interrupt controller + ioapicinit(); // another interrupt controller + consoleinit(); // I/O devices & their interrupts + uartinit(); // serial port + pinit(); // process table + tvinit(); // trap vectors + binit(); // buffer cache + fileinit(); // file table + iinit(); // inode cache + ideinit(); // disk + if(!ismp) + timerinit(); // uniprocessor timer + startothers(); // start other processors + kinit2(P2V(4*1024*1024), P2V(PHYSTOP)); // must come after startothers() + userinit(); // first user process + // Finish setting up this processor in mpmain. + mpmain(); +} + +// Other CPUs jump here from entryother.S. +static void +mpenter(void) +{ + switchkvm(); + seginit(); + lapicinit(); + mpmain(); +} + +// Common CPU setup code. +static void +mpmain(void) +{ + cprintf("cpu%d: starting\n", cpu->id); + idtinit(); // load idt register + xchg(&cpu->started, 1); // tell startothers() we're up + scheduler(); // start running processes +} + +pde_t entrypgdir[]; // For entry.S + +// Start the non-boot (AP) processors. +static void +startothers(void) +{ + extern uchar _binary_entryother_start[], _binary_entryother_size[]; + uchar *code; + struct cpu *c; + char *stack; + + return; + // Write entry code to unused memory at 0x7000. + // The linker has placed the image of entryother.S in + // _binary_entryother_start. + code = p2v(0x7000); + memmove(code, _binary_entryother_start, (uint)_binary_entryother_size); + + for(c = cpus; c < cpus+ncpu; c++){ + if(c == cpus+cpunum()) // We've started already. + continue; + + // Tell entryother.S what stack to use, where to enter, and what + // pgdir to use. We cannot use kpgdir yet, because the AP processor + // is running in low memory, so we use entrypgdir for the APs too. + stack = kalloc(); + *(void**)(code-4) = stack + KSTACKSIZE; + *(void**)(code-8) = mpenter; + *(int**)(code-12) = (void *) v2p(entrypgdir); + + lapicstartap(c->id, v2p(code)); + + // wait for cpu to finish mpmain() + while(c->started == 0) + ; + } +} + +// Boot page table used in entry.S and entryother.S. +// Page directories (and page tables), must start on a page boundary, +// hence the "__aligned__" attribute. +// Use PTE_PS in page directory entry to enable 4Mbyte pages. +__attribute__((__aligned__(PGSIZE))) +pde_t entrypgdir[NPDENTRIES] = { + // Map VA's [0, 4MB) to PA's [0, 4MB) + [0] = (0) | PTE_P | PTE_W | PTE_PS, + // Map VA's [KERNBASE, KERNBASE+4MB) to PA's [0, 4MB) + [KERNBASE>>PDXSHIFT] = (0) | PTE_P | PTE_W | PTE_PS, +}; + +//PAGEBREAK! +// Blank page. + diff --git a/pool/shard008/C/0130462_bjm.c b/pool/shard008/C/0130462_bjm.c new file mode 100644 index 0000000000000000000000000000000000000000..606e9c07f138b6638d3795ae6dacd589ff509b4c --- /dev/null +++ b/pool/shard008/C/0130462_bjm.c @@ -0,0 +1,208 @@ +/* + * Copyright (c) 1991, 1992 Paul Kranenburg + * Copyright (c) 1993 Branko Lankester + * Copyright (c) 1993, 1994, 1995, 1996 Rick Sladkey + * Copyright (c) 1996-1999 Wichert Akkerman + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * $Id: bjm.c,v 1.15 2005/06/01 19:02:37 roland Exp $ + */ +#include "defs.h" + +#if defined(LINUX) + +#include +#include +#include +#include +#include +#include +#ifndef HAVE_ANDROID_OS +#include +#endif +#include +#include + +/* Bits of module.flags. */ + +#define MOD_UNINITIALIZED 0 +#define MOD_RUNNING 1 +#define MOD_DELETED 2 +#define MOD_AUTOCLEAN 4 +#define MOD_VISITED 8 +#define MOD_USED_ONCE 16 +#define MOD_JUST_FREED 32 +#define MOD_INITIALIZING 64 + +/* Values for query_module's which. */ + +#define QM_MODULES 1 +#define QM_DEPS 2 +#define QM_REFS 3 +#define QM_SYMBOLS 4 +#define QM_INFO 5 + +struct module_symbol +{ + unsigned long value; + const char *name; +}; + +struct module_info +{ + unsigned long addr; + unsigned long size; + unsigned long flags; + long usecount; +}; + +static const struct xlat which[] = { + { 0, "0" }, + { QM_MODULES, "QM_MODULES" }, + { QM_DEPS, "QM_DEPS" }, + { QM_REFS, "QM_REFS" }, + { QM_SYMBOLS, "QM_SYMBOLS" }, + { QM_INFO, "QM_INFO" }, + { 0, NULL }, +}; + +static const struct xlat modflags[] = { + { MOD_UNINITIALIZED, "MOD_UNINITIALIZED" }, + { MOD_RUNNING, "MOD_RUNNING" }, + { MOD_DELETED, "MOD_DELETED" }, + { MOD_AUTOCLEAN, "MOD_AUTOCLEAN" }, + { MOD_VISITED, "MOD_VISITED" }, + { MOD_USED_ONCE, "MOD_USED_ONCE" }, + { MOD_JUST_FREED, "MOD_JUST_FREED" }, + { 0, NULL }, +}; + +int +sys_query_module(tcp) +struct tcb *tcp; +{ + + if (exiting(tcp)) { + printstr(tcp, tcp->u_arg[0], -1); + tprintf(", "); + printxval(which, tcp->u_arg[1], "QM_???"); + tprintf(", "); + if (!verbose(tcp)) { + tprintf("%#lx, %lu, %#lx", tcp->u_arg[2], tcp->u_arg[3], tcp->u_arg[4]); + } else if (tcp->u_rval!=0) { + size_t ret; + umove(tcp, tcp->u_arg[4], &ret); + tprintf("%#lx, %lu, %Zu", tcp->u_arg[2], tcp->u_arg[3], ret); + } else if (tcp->u_arg[1]==QM_INFO) { + struct module_info mi; + size_t ret; + umove(tcp, tcp->u_arg[2], &mi); + tprintf("{address=%#lx, size=%lu, flags=", mi.addr, mi.size); + printflags(modflags, mi.flags, "MOD_???"); + tprintf(", usecount=%lu}", mi.usecount); + umove(tcp, tcp->u_arg[4], &ret); + tprintf(", %Zu", ret); + } else if ((tcp->u_arg[1]==QM_MODULES) || + (tcp->u_arg[1]==QM_DEPS) || + (tcp->u_arg[1]==QM_REFS)) { + size_t ret; + + umove(tcp, tcp->u_arg[4], &ret); + tprintf("{"); + if (!abbrev(tcp)) { + char* data = (char*)malloc(tcp->u_arg[3]); + char* mod = data; + size_t idx; + + if (data==NULL) { + fprintf(stderr, "out of memory\n"); + tprintf(" /* %Zu entries */ ", ret); + } else { + umoven(tcp, tcp->u_arg[2], tcp->u_arg[3], data); + for (idx=0; idxu_arg[1]==QM_SYMBOLS) { + size_t ret; + umove(tcp, tcp->u_arg[4], &ret); + tprintf("{"); + if (!abbrev(tcp)) { + char* data = (char *)malloc(tcp->u_arg[3]); + struct module_symbol* sym = (struct module_symbol*)data; + size_t idx; + + if (data==NULL) { + fprintf(stderr, "out of memory\n"); + tprintf(" /* %Zu entries */ ", ret); + } else { + umoven(tcp, tcp->u_arg[2], tcp->u_arg[3], data); + for (idx=0; idxname, sym->value); + sym++; + } + free(data); + } + } else + tprintf(" /* %Zu entries */ ", ret); + tprintf("}, %Zd", ret); + } else { + printstr(tcp, tcp->u_arg[2], tcp->u_arg[3]); + tprintf(", %#lx", tcp->u_arg[4]); + } + } + return 0; +} + +int +sys_create_module(tcp) +struct tcb *tcp; +{ + if (entering(tcp)) { + printpath(tcp, tcp->u_arg[0]); + tprintf(", %lu", tcp->u_arg[1]); + } + return RVAL_HEX; +} + +int +sys_init_module(tcp) +struct tcb *tcp; +{ + if (entering(tcp)) { + tprintf("%#lx, ", tcp->u_arg[0]); + tprintf("%lu, ", tcp->u_arg[1]); + printstr(tcp, tcp->u_arg[2], -1); + } + return 0; +} +#endif /* LINUX */ diff --git a/pool/shard008/C/0130463_subr_disklabel.c b/pool/shard008/C/0130463_subr_disklabel.c new file mode 100644 index 0000000000000000000000000000000000000000..4bb655489d28e2ab8c300e814277f95e7ff629b5 --- /dev/null +++ b/pool/shard008/C/0130463_subr_disklabel.c @@ -0,0 +1,277 @@ +/* + * Copyright (c) 1982, 1986, 1988, 1993 + * The Regents of the University of California. All rights reserved. + * (c) UNIX System Laboratories, Inc. + * All or some portions of this file are derived from material licensed + * to the University of California by American Telephone and Telegraph + * Co. or Unix System Laboratories, Inc. and are reproduced herein with + * the permission of UNIX System Laboratories, Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * This product includes software developed by the University of + * California, Berkeley and its contributors. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @(#)ufs_disksubr.c 8.5 (Berkeley) 1/21/94 + * $FreeBSD: src/sys/kern/subr_disklabel.c,v 1.72 2002/09/20 19:36:04 phk Exp $ + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * Attempt to read a disk label from a device using the indicated strategy + * routine. The label must be partly set up before this: secpercyl, secsize + * and anything required in the strategy routine (e.g., dummy bounds for the + * partition containing the label) must be filled in before calling us. + * Returns NULL on success and an error string on failure. + */ +char * +readdisklabel(dev, lp) + dev_t dev; + register struct disklabel *lp; +{ + register struct buf *bp; + struct disklabel *dlp; + char *msg = NULL; + + bp = geteblk((int)lp->d_secsize); + bp->b_dev = dev; + bp->b_blkno = LABELSECTOR * ((int)lp->d_secsize/DEV_BSIZE); + bp->b_bcount = lp->d_secsize; + bp->b_flags &= ~B_INVAL; + bp->b_iocmd = BIO_READ; + DEV_STRATEGY(bp, 1); + if (bufwait(bp)) + msg = "I/O error"; + else if (bp->b_resid != 0) + msg = "disk too small for a label"; + else for (dlp = (struct disklabel *)bp->b_data; + dlp <= (struct disklabel *)((char *)bp->b_data + + lp->d_secsize - sizeof(*dlp)); + dlp = (struct disklabel *)((char *)dlp + sizeof(long))) { + if (dlp->d_magic != DISKMAGIC || dlp->d_magic2 != DISKMAGIC) { + if (msg == NULL) + msg = "no disk label"; + } else if (dlp->d_npartitions > MAXPARTITIONS || + dkcksum(dlp) != 0) + msg = "disk label corrupted"; + else { + *lp = *dlp; + msg = NULL; + break; + } + } + bp->b_flags |= B_INVAL | B_AGE; + brelse(bp); + return (msg); +} + +/* + * Check new disk label for sensibility before setting it. + */ +int +setdisklabel(olp, nlp, openmask) + register struct disklabel *olp, *nlp; + u_long openmask; +{ + register int i; + register struct partition *opp, *npp; + + /* + * Check it is actually a disklabel we are looking at. + */ + if (nlp->d_magic != DISKMAGIC || nlp->d_magic2 != DISKMAGIC || + dkcksum(nlp) != 0) + return (EINVAL); + /* + * For each partition that we think is open, + */ + while ((i = ffs((long)openmask)) != 0) { + i--; + /* + * Check it is not changing.... + */ + openmask &= ~(1 << i); + if (nlp->d_npartitions <= i) + return (EBUSY); + opp = &olp->d_partitions[i]; + npp = &nlp->d_partitions[i]; + if (npp->p_offset != opp->p_offset || npp->p_size < opp->p_size) + return (EBUSY); + /* + * Copy internally-set partition information + * if new label doesn't include it. XXX + * (If we are using it then we had better stay the same type) + * This is possibly dubious, as someone else noted (XXX) + */ + if (npp->p_fstype == FS_UNUSED && opp->p_fstype != FS_UNUSED) { + npp->p_fstype = opp->p_fstype; + npp->p_fsize = opp->p_fsize; + npp->p_frag = opp->p_frag; + npp->p_cpg = opp->p_cpg; + } + } + nlp->d_checksum = 0; + nlp->d_checksum = dkcksum(nlp); + *olp = *nlp; + return (0); +} + +/* + * Write disk label back to device after modification. + */ +int +writedisklabel(dev, lp) + dev_t dev; + register struct disklabel *lp; +{ + struct buf *bp; + struct disklabel *dlp; + int error = 0; + + if (lp->d_partitions[RAW_PART].p_offset != 0) + return (EXDEV); /* not quite right */ + bp = geteblk((int)lp->d_secsize); + bp->b_dev = dkmodpart(dev, RAW_PART); + bp->b_blkno = LABELSECTOR * ((int)lp->d_secsize/DEV_BSIZE); + bp->b_bcount = lp->d_secsize; +#if 1 + /* + * We read the label first to see if it's there, + * in which case we will put ours at the same offset into the block.. + * (I think this is stupid [Julian]) + * Note that you can't write a label out over a corrupted label! + * (also stupid.. how do you write the first one? by raw writes?) + */ + bp->b_flags &= ~B_INVAL; + bp->b_iocmd = BIO_READ; + DEV_STRATEGY(bp, 1); + error = bufwait(bp); + if (error) + goto done; + if (bp->b_resid != 0) { + error = ENOSPC; + goto done; + } + for (dlp = (struct disklabel *)bp->b_data; + dlp <= (struct disklabel *) + ((char *)bp->b_data + lp->d_secsize - sizeof(*dlp)); + dlp = (struct disklabel *)((char *)dlp + sizeof(long))) { + if (dlp->d_magic == DISKMAGIC && dlp->d_magic2 == DISKMAGIC && + dkcksum(dlp) == 0) { + *dlp = *lp; + bp->b_flags &= ~B_DONE; + bp->b_iocmd = BIO_WRITE; +#ifdef __alpha__ + alpha_fix_srm_checksum(bp); +#endif + DEV_STRATEGY(bp, 1); + error = bufwait(bp); + goto done; + } + } + error = ESRCH; +done: +#else + bzero(bp->b_data, lp->d_secsize); + dlp = (struct disklabel *)bp->b_data; + *dlp = *lp; + bp->b_flags &= ~B_INVAL; + bp->b_iocmd = BIO_WRITE; + DEV_STRATEGY(bp, 1); + error = bufwait(bp); +#endif + bp->b_flags |= B_INVAL | B_AGE; + brelse(bp); + return (error); +} + +/* + * Determine the size of the transfer, and make sure it is + * within the boundaries of the partition. Adjust transfer + * if needed, and signal errors or early completion. + */ +int +bounds_check_with_label(struct bio *bp, struct disklabel *lp, int wlabel) +{ + struct partition *p = lp->d_partitions + dkpart(bp->bio_dev); + int labelsect = lp->d_partitions[0].p_offset; + int maxsz = p->p_size, + sz = (bp->bio_bcount + DEV_BSIZE - 1) >> DEV_BSHIFT; + + /* overwriting disk label ? */ + /* XXX should also protect bootstrap in first 8K */ + if (bp->bio_blkno + p->p_offset <= LABELSECTOR + labelsect && +#if LABELSECTOR != 0 + bp->bio_blkno + p->p_offset + sz > LABELSECTOR + labelsect && +#endif + (bp->bio_cmd == BIO_WRITE) && wlabel == 0) { + bp->bio_error = EROFS; + goto bad; + } + +#if defined(DOSBBSECTOR) && defined(notyet) + /* overwriting master boot record? */ + if (bp->bio_blkno + p->p_offset <= DOSBBSECTOR && + (bp->bio_cmd == BIO_WRITE) && wlabel == 0) { + bp->bio_error = EROFS; + goto bad; + } +#endif + + /* beyond partition? */ + if (bp->bio_blkno < 0 || bp->bio_blkno + sz > maxsz) { + /* if exactly at end of disk, return an EOF */ + if (bp->bio_blkno == maxsz) { + bp->bio_resid = bp->bio_bcount; + return(0); + } + /* or truncate if part of it fits */ + sz = maxsz - bp->bio_blkno; + if (sz <= 0) { + bp->bio_error = EINVAL; + goto bad; + } + bp->bio_bcount = sz << DEV_BSHIFT; + } + + bp->bio_pblkno = bp->bio_blkno + p->p_offset; + return(1); + +bad: + bp->bio_flags |= BIO_ERROR; + return(-1); +} + diff --git a/pool/shard008/C/0130464_edb93xx.c b/pool/shard008/C/0130464_edb93xx.c new file mode 100644 index 0000000000000000000000000000000000000000..cbed98b0e36882ef663ea76b780e6c31a0895db5 --- /dev/null +++ b/pool/shard008/C/0130464_edb93xx.c @@ -0,0 +1,291 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * Board initialization for EP93xx + * + * Copyright (C) 2013 + * Sergey Kostanbaev fairwaves.ru> + * + * Copyright (C) 2009 + * Matthias Kaehlcke kaehlcke.net> + * + * (C) Copyright 2002 2003 + * Network Audio Technologies, Inc. + * Adam Bezanson netaudiotech.com> + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +DECLARE_GLOBAL_DATA_PTR; + +/* + * usb_div: 4, nbyp2: 1, pll2_en: 1 + * pll2_x1: 368640000.000000, pll2_x2ip: 15360000.000000, + * pll2_x2: 384000000.000000, pll2_out: 192000000.000000 + */ +#define CLKSET2_VAL (23 << SYSCON_CLKSET_PLL_X2IPD_SHIFT | \ + 24 << SYSCON_CLKSET_PLL_X2FBD2_SHIFT | \ + 24 << SYSCON_CLKSET_PLL_X1FBD1_SHIFT | \ + 1 << SYSCON_CLKSET_PLL_PS_SHIFT | \ + SYSCON_CLKSET2_PLL2_EN | \ + SYSCON_CLKSET2_NBYP2 | \ + 3 << SYSCON_CLKSET2_USB_DIV_SHIFT) + +#define SMC_BCR6_VALUE (2 << SMC_BCR_IDCY_SHIFT | 5 << SMC_BCR_WST1_SHIFT | \ + SMC_BCR_BLE | 2 << SMC_BCR_WST2_SHIFT | \ + 1 << SMC_BCR_MW_SHIFT) + +/* delay execution before timers are initialized */ +static inline void early_udelay(uint32_t usecs) +{ + /* loop takes 4 cycles at 5.0ns (fastest case, running at 200MHz) */ + register uint32_t loops = (usecs * 1000) / 20; + + __asm__ volatile ("1:\n" + "subs %0, %1, #1\n" + "bne 1b" : "=r" (loops) : "0" (loops)); +} + +#ifndef CONFIG_EP93XX_NO_FLASH_CFG +static void flash_cfg(void) +{ + struct smc_regs *smc = (struct smc_regs *)SMC_BASE; + + writel(SMC_BCR6_VALUE, &smc->bcr6); +} +#else +#define flash_cfg() +#endif + +int board_init(void) +{ + /* + * Setup PLL2, PPL1 has been set during lowlevel init + */ + struct syscon_regs *syscon = (struct syscon_regs *)SYSCON_BASE; + writel(CLKSET2_VAL, &syscon->clkset2); + + /* + * the user's guide recommends to wait at least 1 ms for PLL2 to + * stabilize + */ + early_udelay(1000); + + /* Go to Async mode */ + __asm__ volatile ("mrc p15, 0, r0, c1, c0, 0"); + __asm__ volatile ("orr r0, r0, #0xc0000000"); + __asm__ volatile ("mcr p15, 0, r0, c1, c0, 0"); + + icache_enable(); + +#ifdef USE_920T_MMU + dcache_enable(); +#endif + + /* Machine number, as defined in linux/arch/arm/tools/mach-types */ + gd->bd->bi_arch_number = CONFIG_MACH_TYPE; + + /* adress of boot parameters */ + gd->bd->bi_boot_params = LINUX_BOOT_PARAM_ADDR; + + /* We have a console */ + gd->have_console = 1; + + enable_interrupts(); + + flash_cfg(); + + green_led_on(); + red_led_off(); + + return 0; +} + +int board_early_init_f(void) +{ + /* + * set UARTBAUD bit to drive UARTs with 14.7456MHz instead of + * 14.7456/2 MHz + */ + struct syscon_regs *syscon = (struct syscon_regs *)SYSCON_BASE; + writel(SYSCON_PWRCNT_UART_BAUD, &syscon->pwrcnt); + return 0; +} + +int board_eth_init(struct bd_info *bd) +{ + return ep93xx_eth_initialize(0, MAC_BASE); +} + +static void dram_fill_bank_addr(unsigned dram_addr_mask, unsigned dram_bank_cnt, + unsigned dram_bank_base[CONFIG_NR_DRAM_BANKS]) +{ + if (dram_bank_cnt == 1) { + dram_bank_base[0] = PHYS_SDRAM_1; + } else { + /* Table lookup for holes in address space. Maximum memory + * for the single SDCS may be up to 256Mb. We start scanning + * banks from 1Mb, so it could be up to 128 banks theoretically. + * We need at maximum 7 bits for the loockup, 8 slots is + * enough for the worst case. + */ + unsigned tbl[8]; + unsigned i = dram_bank_cnt / 2; + unsigned j = 0x00100000; /* 1 Mb */ + unsigned *ptbl = tbl; + do { + while (!(dram_addr_mask & j)) { + j <<= 1; + } + *ptbl++ = j; + j <<= 1; + i >>= 1; + } while (i != 0); + + for (i = dram_bank_cnt, j = 0; + (i != 0) && (j < CONFIG_NR_DRAM_BANKS); --i, ++j) { + unsigned addr = PHYS_SDRAM_1; + unsigned k; + unsigned bit; + + for (k = 0, bit = 1; k < 8; k++, bit <<= 1) { + if (bit & j) + addr |= tbl[k]; + } + + dram_bank_base[j] = addr; + } + } +} + +/* called in board_init_f (before relocation) */ +static unsigned dram_init_banksize_int(int print) +{ + /* + * Collect information of banks that has been filled during lowlevel + * initialization + */ + unsigned i; + unsigned dram_bank_base[CONFIG_NR_DRAM_BANKS]; + unsigned dram_total = 0; + unsigned dram_bank_size = *(unsigned *) + (PHYS_SDRAM_1 | UBOOT_MEMORYCNF_BANK_SIZE); + unsigned dram_addr_mask = *(unsigned *) + (PHYS_SDRAM_1 | UBOOT_MEMORYCNF_BANK_MASK); + unsigned dram_bank_cnt = *(unsigned *) + (PHYS_SDRAM_1 | UBOOT_MEMORYCNF_BANK_COUNT); + + dram_fill_bank_addr(dram_addr_mask, dram_bank_cnt, dram_bank_base); + + for (i = 0; i < dram_bank_cnt; i++) { + gd->bd->bi_dram[i].start = dram_bank_base[i]; + gd->bd->bi_dram[i].size = dram_bank_size; + dram_total += dram_bank_size; + } + for (; i < CONFIG_NR_DRAM_BANKS; i++) { + gd->bd->bi_dram[i].start = 0; + gd->bd->bi_dram[i].size = 0; + } + + if (print) { + printf("DRAM mask: %08x\n", dram_addr_mask); + printf("DRAM total %u banks:\n", dram_bank_cnt); + printf("bank base-address size\n"); + + if (dram_bank_cnt > CONFIG_NR_DRAM_BANKS) { + printf("WARNING! UBoot was configured for %u banks,\n" + "but %u has been found. " + "Supressing extra memory banks\n", + CONFIG_NR_DRAM_BANKS, dram_bank_cnt); + dram_bank_cnt = CONFIG_NR_DRAM_BANKS; + } + + for (i = 0; i < dram_bank_cnt; i++) { + printf(" %u %08x %08x\n", + i, dram_bank_base[i], dram_bank_size); + } + printf(" ------------------------------------------\n" + "Total %9d\n\n", + dram_total); + } + + return dram_total; +} + +int dram_init_banksize(void) +{ + dram_init_banksize_int(0); + + return 0; +} + +/* called in board_init_f (before relocation) */ +int dram_init(void) +{ + struct syscon_regs *syscon = (struct syscon_regs *)SYSCON_BASE; + unsigned sec_id = readl(SECURITY_EXTENSIONID); + unsigned chip_id = readl(&syscon->chipid); + + printf("CPU: Cirrus Logic "); + switch (sec_id & 0x000001FE) { + case 0x00000008: + printf("EP9301"); + break; + case 0x00000004: + printf("EP9307"); + break; + case 0x00000002: + printf("EP931x"); + break; + case 0x00000000: + printf("EP9315"); + break; + default: + printf(""); + break; + } + + printf(" - Rev. "); + switch (chip_id & 0xF0000000) { + case 0x00000000: + printf("A"); + break; + case 0x10000000: + printf("B"); + break; + case 0x20000000: + printf("C"); + break; + case 0x30000000: + printf("D0"); + break; + case 0x40000000: + printf("D1"); + break; + case 0x50000000: + printf("E0"); + break; + case 0x60000000: + printf("E1"); + break; + case 0x70000000: + printf("E2"); + break; + default: + printf("?"); + break; + } + printf(" (SecExtID=%.8x/ChipID=%.8x)\n", sec_id, chip_id); + + gd->ram_size = dram_init_banksize_int(1); + return 0; +} diff --git a/pool/shard008/C/0130469_patest_sine8.c b/pool/shard008/C/0130469_patest_sine8.c new file mode 100644 index 0000000000000000000000000000000000000000..7a4982c604bc726338000c064390a1b59becf54c --- /dev/null +++ b/pool/shard008/C/0130469_patest_sine8.c @@ -0,0 +1,184 @@ +/* + * $Id: patest_sine8.c 90 2002-01-22 00:51:49Z phil $ + * patest_sine8.c + * Play a sine wave using the Portable Audio api for several seconds. + * Test 8 bit data. + * + * Author: Ross Bencina + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.audiomulch.com/portaudio/ + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files + * (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, + * publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR + * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#include +#include +#include "portaudio.h" +#define NUM_SECONDS (8) +#define SAMPLE_RATE (44100) +#define TEST_UNSIGNED (1) +#if TEST_UNSIGNED +#define TEST_FORMAT paUInt8 +#else +#define TEST_FORMAT paInt8 +#endif +#ifndef M_PI +#define M_PI (3.14159265) +#endif +#define TABLE_SIZE (200) +typedef struct +{ +#if TEST_UNSIGNED + unsigned char sine[TABLE_SIZE]; +#else + char sine[TABLE_SIZE]; +#endif + int left_phase; + int right_phase; + unsigned int framesToGo; +} +paTestData; +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + char *out = (char*)outputBuffer; + int i; + int framesToCalc; + int finished = 0; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + if( data->framesToGo < framesPerBuffer ) + { + framesToCalc = data->framesToGo; + data->framesToGo = 0; + finished = 1; + } + else + { + framesToCalc = framesPerBuffer; + data->framesToGo -= framesPerBuffer; + } + + for( i=0; isine[data->left_phase]; /* left */ + *out++ = data->sine[data->right_phase]; /* right */ + data->left_phase += 1; + if( data->left_phase >= TABLE_SIZE ) data->left_phase -= TABLE_SIZE; + data->right_phase += 3; /* higher pitch so we can distinguish left and right. */ + if( data->right_phase >= TABLE_SIZE ) data->right_phase -= TABLE_SIZE; + } + /* zero remainder of final buffer */ + for( ; i<(int)framesPerBuffer; i++ ) + { +#if TEST_UNSIGNED + *out++ = (unsigned char) 0x80; /* left */ + *out++ = (unsigned char) 0x80; /* right */ +#else + *out++ = 0; /* left */ + *out++ = 0; /* right */ +#endif + + } + return finished; +} +/*******************************************************************/ +int main(void); +int main(void) +{ + PortAudioStream *stream; + PaError err; + paTestData data; + int i; + int totalSamps; +#if TEST_UNSIGNED + printf("PortAudio Test: output UNsigned 8 bit sine wave.\n"); +#else + printf("PortAudio Test: output signed 8 bit sine wave.\n"); +#endif + /* initialise sinusoidal wavetable */ + for( i=0; i + * + * See http://www.asterisk.org for more information about + * the Asterisk project. Please do not directly contact + * any of the maintainers of this project for assistance; + * the project provides a web site, mailing lists and IRC + * channels for your use. + * + * This program is free software, distributed under the terms of + * the GNU General Public License Version 2. See the LICENSE file + * at the top of the source tree. + */ + +/*! \file + * + * \brief Debugging routines for file descriptor leaks + * + * \author Tilghman Lesher + */ + +#include "asterisk.h" + +#ifdef DEBUG_FD_LEAKS + +ASTERISK_FILE_VERSION(__FILE__, "$Revision: 228338 $") + +#include +#include +#include +#include +#include +#include + +#include "asterisk/cli.h" +#include "asterisk/logger.h" +#include "asterisk/options.h" +#include "asterisk/lock.h" +#include "asterisk/strings.h" +#include "asterisk/unaligned.h" + +static struct fdleaks { + char file[40]; + int line; + char function[25]; + char callname[10]; + char callargs[60]; + unsigned int isopen:1; +} fdleaks[1024] = { { "", }, }; + +#define COPY(dst, src) \ + do { \ + int dlen = sizeof(dst), slen = strlen(src); \ + if (slen + 1 > dlen) { \ + char *slash = strrchr(src, '/'); \ + if (slash) { \ + ast_copy_string(dst, slash + 1, dlen); \ + } else { \ + ast_copy_string(dst, src + slen - dlen + 1, dlen); \ + } \ + } else { \ + ast_copy_string(dst, src, dlen); \ + } \ + } while (0) + +#define STORE_COMMON(offset, name, ...) \ + COPY(fdleaks[offset].file, file); \ + fdleaks[offset].line = line; \ + COPY(fdleaks[offset].function, func); \ + strcpy(fdleaks[offset].callname, name); \ + snprintf(fdleaks[offset].callargs, sizeof(fdleaks[offset].callargs), __VA_ARGS__); \ + fdleaks[offset].isopen = 1; + +#undef open +int __ast_fdleak_open(const char *file, int line, const char *func, const char *path, int flags, ...) +{ + int res; + va_list ap; + int mode; + + if (flags & O_CREAT) { + va_start(ap, flags); + mode = va_arg(ap, int); + va_end(ap); + res = open(path, flags, mode); + if (res > -1 && res < (sizeof(fdleaks) / sizeof(fdleaks[0]))) { + char sflags[80]; + snprintf(sflags, sizeof(sflags), "O_CREAT%s%s%s%s%s%s%s%s", + flags & O_APPEND ? "|O_APPEND" : "", + flags & O_EXCL ? "|O_EXCL" : "", + flags & O_NONBLOCK ? "|O_NONBLOCK" : "", + flags & O_TRUNC ? "|O_TRUNC" : "", + flags & O_RDWR ? "|O_RDWR" : "", + flags & O_RDONLY ? "|O_RDONLY" : "", + flags & O_WRONLY ? "|O_WRONLY" : "", + ""); + flags &= ~(O_CREAT | O_APPEND | O_EXCL | O_NONBLOCK | O_TRUNC | O_RDWR | O_RDONLY | O_WRONLY); + if (flags) { + STORE_COMMON(res, "open", "\"%s\",%s|%d,%04o", path, sflags, flags, mode); + } else { + STORE_COMMON(res, "open", "\"%s\",%s,%04o", path, sflags, mode); + } + } + } else { + res = open(path, flags); + if (res > -1 && res < (sizeof(fdleaks) / sizeof(fdleaks[0]))) { + STORE_COMMON(res, "open", "\"%s\",%d", path, flags); + } + } + return res; +} + +#undef pipe +int __ast_fdleak_pipe(int *fds, const char *file, int line, const char *func) +{ + int i, res = pipe(fds); + if (res) { + return res; + } + for (i = 0; i < 2; i++) { + STORE_COMMON(fds[i], "pipe", "{%d,%d}", fds[0], fds[1]); + } + return 0; +} + +#undef socket +int __ast_fdleak_socket(int domain, int type, int protocol, const char *file, int line, const char *func) +{ + char sdomain[20], stype[20], *sproto = NULL; + struct protoent *pe; + int res = socket(domain, type, protocol); + if (res < 0 || res > 1023) { + return res; + } + + if ((pe = getprotobynumber(protocol))) { + sproto = pe->p_name; + } + + if (domain == PF_UNIX) { + ast_copy_string(sdomain, "PF_UNIX", sizeof(sdomain)); + } else if (domain == PF_INET) { + ast_copy_string(sdomain, "PF_INET", sizeof(sdomain)); + } else { + snprintf(sdomain, sizeof(sdomain), "%d", domain); + } + + if (type == SOCK_DGRAM) { + ast_copy_string(stype, "SOCK_DGRAM", sizeof(stype)); + if (protocol == 0) { + sproto = "udp"; + } + } else if (type == SOCK_STREAM) { + ast_copy_string(stype, "SOCK_STREAM", sizeof(stype)); + if (protocol == 0) { + sproto = "tcp"; + } + } else { + snprintf(stype, sizeof(stype), "%d", type); + } + + if (sproto) { + STORE_COMMON(res, "socket", "%s,%s,\"%s\"", sdomain, stype, sproto); + } else { + STORE_COMMON(res, "socket", "%s,%s,\"%d\"", sdomain, stype, protocol); + } + return res; +} + +#undef close +int __ast_fdleak_close(int fd) +{ + int res = close(fd); + if (!res && fd > -1 && fd < 1024) { + fdleaks[fd].isopen = 0; + } + return res; +} + +#undef fopen +FILE *__ast_fdleak_fopen(const char *path, const char *mode, const char *file, int line, const char *func) +{ + FILE *res = fopen(path, mode); + int fd; + if (!res) { + return res; + } + fd = fileno(res); + STORE_COMMON(fd, "fopen", "\"%s\",\"%s\"", path, mode); + return res; +} + +#undef fclose +int __ast_fdleak_fclose(FILE *ptr) +{ + int fd, res; + if (!ptr) { + return fclose(ptr); + } + + fd = fileno(ptr); + if ((res = fclose(ptr)) || fd < 0 || fd > 1023) { + return res; + } + fdleaks[fd].isopen = 0; + return res; +} + +#undef dup2 +int __ast_fdleak_dup2(int oldfd, int newfd, const char *file, int line, const char *func) +{ + int res = dup2(oldfd, newfd); + if (res < 0 || res > 1023) { + return res; + } + STORE_COMMON(res, "dup2", "%d,%d", oldfd, newfd); + return res; +} + +#undef dup +int __ast_fdleak_dup(int oldfd, const char *file, int line, const char *func) +{ + int res = dup(oldfd); + if (res < 0 || res > 1023) { + return res; + } + STORE_COMMON(res, "dup2", "%d", oldfd); + return res; +} + +static int handle_show_fd(int fd, int argc, char *argv[]) +{ + int i; + char line[24]; + struct rlimit rl; + getrlimit(RLIMIT_FSIZE, &rl); + if (rl.rlim_cur == RLIM_INFINITY || rl.rlim_max == RLIM_INFINITY) { + ast_copy_string(line, "unlimited", sizeof(line)); + } else { + snprintf(line, sizeof(line), "%d/%d", (int) rl.rlim_cur, (int) rl.rlim_max); + } + ast_cli(fd, "Current maxfiles: %s\n", line); + for (i = 0; i < 1024; i++) { + if (fdleaks[i].isopen) { + snprintf(line, sizeof(line), "%d", fdleaks[i].line); + ast_cli(fd, "%5d %15s:%-7.7s (%-25s): %s(%s)\n", i, fdleaks[i].file, line, fdleaks[i].function, fdleaks[i].callname, fdleaks[i].callargs); + } + } + return RESULT_SUCCESS; +} + +static struct ast_cli_entry cli_show_fd = + { { "core", "show", "fd", NULL }, + handle_show_fd, "Show open file descriptors" }; + +int ast_fd_init(void) +{ + return ast_cli_register(&cli_show_fd); +} + +#else /* !defined(DEBUG_FD_LEAKS) */ +int ast_fd_init(void) +{ + return 0; +} +#endif /* defined(DEBUG_FD_LEAKS) */ + diff --git a/pool/shard008/C/0130471_pm.c b/pool/shard008/C/0130471_pm.c new file mode 100644 index 0000000000000000000000000000000000000000..065b09e6f1eb73660eca3cd077700073d291b475 --- /dev/null +++ b/pool/shard008/C/0130471_pm.c @@ -0,0 +1,335 @@ +/* + * Copyright (c) 2014, Fuzhou Rockchip Electronics Co., Ltd + * Author: Tony Xie + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope 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. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "pm.h" + +/* These enum are option of low power mode */ +enum { + ROCKCHIP_ARM_OFF_LOGIC_NORMAL = 0, + ROCKCHIP_ARM_OFF_LOGIC_DEEP = 1, +}; + +struct rockchip_pm_data { + const struct platform_suspend_ops *ops; + int (*init)(struct device_node *np); +}; + +static void __iomem *rk3288_bootram_base; +static phys_addr_t rk3288_bootram_phy; + +static struct regmap *pmu_regmap; +static struct regmap *sgrf_regmap; +static struct regmap *grf_regmap; + +static u32 rk3288_pmu_pwr_mode_con; +static u32 rk3288_sgrf_soc_con0; +static u32 rk3288_sgrf_cpu_con0; + +static inline u32 rk3288_l2_config(void) +{ + u32 l2ctlr; + + asm("mrc p15, 1, %0, c9, c0, 2" : "=r" (l2ctlr)); + return l2ctlr; +} + +static void __init rk3288_config_bootdata(void) +{ + rkpm_bootdata_cpusp = rk3288_bootram_phy + (SZ_4K - 8); + rkpm_bootdata_cpu_code = __pa_symbol(cpu_resume); + + rkpm_bootdata_l2ctlr_f = 1; + rkpm_bootdata_l2ctlr = rk3288_l2_config(); +} + +#define GRF_UOC0_CON0 0x320 +#define GRF_UOC1_CON0 0x334 +#define GRF_UOC2_CON0 0x348 +#define GRF_SIDDQ BIT(13) + +static bool rk3288_slp_disable_osc(void) +{ + static const u32 reg_offset[] = { GRF_UOC0_CON0, GRF_UOC1_CON0, + GRF_UOC2_CON0 }; + u32 reg, i; + + /* + * if any usb phy is still on(GRF_SIDDQ==0), that means we need the + * function of usb wakeup, so do not switch to 32khz, since the usb phy + * clk does not connect to 32khz osc + */ + for (i = 0; i < ARRAY_SIZE(reg_offset); i++) { + regmap_read(grf_regmap, reg_offset[i], ®); + if (!(reg & GRF_SIDDQ)) + return false; + } + + return true; +} + +static void rk3288_slp_mode_set(int level) +{ + u32 mode_set, mode_set1; + bool osc_disable = rk3288_slp_disable_osc(); + + regmap_read(sgrf_regmap, RK3288_SGRF_CPU_CON0, &rk3288_sgrf_cpu_con0); + regmap_read(sgrf_regmap, RK3288_SGRF_SOC_CON0, &rk3288_sgrf_soc_con0); + + regmap_read(pmu_regmap, RK3288_PMU_PWRMODE_CON, + &rk3288_pmu_pwr_mode_con); + + /* + * SGRF_FAST_BOOT_EN - system to boot from FAST_BOOT_ADDR + * PCLK_WDT_GATE - disable WDT during suspend. + */ + regmap_write(sgrf_regmap, RK3288_SGRF_SOC_CON0, + SGRF_PCLK_WDT_GATE | SGRF_FAST_BOOT_EN + | SGRF_PCLK_WDT_GATE_WRITE | SGRF_FAST_BOOT_EN_WRITE); + + /* + * The dapswjdp can not auto reset before resume, that cause it may + * access some illegal address during resume. Let's disable it before + * suspend, and the MASKROM will enable it back. + */ + regmap_write(sgrf_regmap, RK3288_SGRF_CPU_CON0, SGRF_DAPDEVICEEN_WRITE); + + /* booting address of resuming system is from this register value */ + regmap_write(sgrf_regmap, RK3288_SGRF_FAST_BOOT_ADDR, + rk3288_bootram_phy); + + mode_set = BIT(PMU_GLOBAL_INT_DISABLE) | BIT(PMU_L2FLUSH_EN) | + BIT(PMU_SREF0_ENTER_EN) | BIT(PMU_SREF1_ENTER_EN) | + BIT(PMU_DDR0_GATING_EN) | BIT(PMU_DDR1_GATING_EN) | + BIT(PMU_PWR_MODE_EN) | BIT(PMU_CHIP_PD_EN) | + BIT(PMU_SCU_EN); + + mode_set1 = BIT(PMU_CLR_CORE) | BIT(PMU_CLR_CPUP); + + if (level == ROCKCHIP_ARM_OFF_LOGIC_DEEP) { + /* arm off, logic deep sleep */ + mode_set |= BIT(PMU_BUS_PD_EN) | BIT(PMU_PMU_USE_LF) | + BIT(PMU_DDR1IO_RET_EN) | BIT(PMU_DDR0IO_RET_EN) | + BIT(PMU_ALIVE_USE_LF) | BIT(PMU_PLL_PD_EN); + + if (osc_disable) + mode_set |= BIT(PMU_OSC_24M_DIS); + + mode_set1 |= BIT(PMU_CLR_ALIVE) | BIT(PMU_CLR_BUS) | + BIT(PMU_CLR_PERI) | BIT(PMU_CLR_DMA); + + regmap_write(pmu_regmap, RK3288_PMU_WAKEUP_CFG1, + PMU_ARMINT_WAKEUP_EN); + + /* + * In deep suspend we use PMU_PMU_USE_LF to let the rk3288 + * switch its main clock supply to the alternative 32kHz + * source. Therefore set 30ms on a 32kHz clock for pmic + * stabilization. Similar 30ms on 24MHz for the other + * mode below. + */ + regmap_write(pmu_regmap, RK3288_PMU_STABL_CNT, 32 * 30); + + /* only wait for stabilization, if we turned the osc off */ + regmap_write(pmu_regmap, RK3288_PMU_OSC_CNT, + osc_disable ? 32 * 30 : 0); + } else { + /* + * arm off, logic normal + * if pmu_clk_core_src_gate_en is not set, + * wakeup will be error + */ + mode_set |= BIT(PMU_CLK_CORE_SRC_GATE_EN); + + regmap_write(pmu_regmap, RK3288_PMU_WAKEUP_CFG1, + PMU_ARMINT_WAKEUP_EN | PMU_GPIOINT_WAKEUP_EN); + + /* 30ms on a 24MHz clock for pmic stabilization */ + regmap_write(pmu_regmap, RK3288_PMU_STABL_CNT, 24000 * 30); + + /* oscillator is still running, so no need to wait */ + regmap_write(pmu_regmap, RK3288_PMU_OSC_CNT, 0); + } + + regmap_write(pmu_regmap, RK3288_PMU_PWRMODE_CON, mode_set); + regmap_write(pmu_regmap, RK3288_PMU_PWRMODE_CON1, mode_set1); +} + +static void rk3288_slp_mode_set_resume(void) +{ + regmap_write(sgrf_regmap, RK3288_SGRF_CPU_CON0, + rk3288_sgrf_cpu_con0 | SGRF_DAPDEVICEEN_WRITE); + + regmap_write(pmu_regmap, RK3288_PMU_PWRMODE_CON, + rk3288_pmu_pwr_mode_con); + + regmap_write(sgrf_regmap, RK3288_SGRF_SOC_CON0, + rk3288_sgrf_soc_con0 | SGRF_PCLK_WDT_GATE_WRITE + | SGRF_FAST_BOOT_EN_WRITE); +} + +static int rockchip_lpmode_enter(unsigned long arg) +{ + flush_cache_all(); + + cpu_do_idle(); + + pr_err("%s: Failed to suspend\n", __func__); + + return 1; +} + +static int rk3288_suspend_enter(suspend_state_t state) +{ + local_fiq_disable(); + + rk3288_slp_mode_set(ROCKCHIP_ARM_OFF_LOGIC_NORMAL); + + cpu_suspend(0, rockchip_lpmode_enter); + + rk3288_slp_mode_set_resume(); + + local_fiq_enable(); + + return 0; +} + +static int rk3288_suspend_prepare(void) +{ + return regulator_suspend_prepare(PM_SUSPEND_MEM); +} + +static void rk3288_suspend_finish(void) +{ + if (regulator_suspend_finish()) + pr_err("%s: Suspend finish failed\n", __func__); +} + +static int __init rk3288_suspend_init(struct device_node *np) +{ + struct device_node *sram_np; + struct resource res; + int ret; + + pmu_regmap = syscon_node_to_regmap(np); + if (IS_ERR(pmu_regmap)) { + pr_err("%s: could not find pmu regmap\n", __func__); + return PTR_ERR(pmu_regmap); + } + + sgrf_regmap = syscon_regmap_lookup_by_compatible( + "rockchip,rk3288-sgrf"); + if (IS_ERR(sgrf_regmap)) { + pr_err("%s: could not find sgrf regmap\n", __func__); + return PTR_ERR(sgrf_regmap); + } + + grf_regmap = syscon_regmap_lookup_by_compatible( + "rockchip,rk3288-grf"); + if (IS_ERR(grf_regmap)) { + pr_err("%s: could not find grf regmap\n", __func__); + return PTR_ERR(grf_regmap); + } + + sram_np = of_find_compatible_node(NULL, NULL, + "rockchip,rk3288-pmu-sram"); + if (!sram_np) { + pr_err("%s: could not find bootram dt node\n", __func__); + return -ENODEV; + } + + rk3288_bootram_base = of_iomap(sram_np, 0); + if (!rk3288_bootram_base) { + pr_err("%s: could not map bootram base\n", __func__); + return -ENOMEM; + } + + ret = of_address_to_resource(sram_np, 0, &res); + if (ret) { + pr_err("%s: could not get bootram phy addr\n", __func__); + return ret; + } + rk3288_bootram_phy = res.start; + + of_node_put(sram_np); + + rk3288_config_bootdata(); + + /* copy resume code and data to bootsram */ + memcpy(rk3288_bootram_base, rockchip_slp_cpu_resume, + rk3288_bootram_sz); + + return 0; +} + +static const struct platform_suspend_ops rk3288_suspend_ops = { + .enter = rk3288_suspend_enter, + .valid = suspend_valid_only_mem, + .prepare = rk3288_suspend_prepare, + .finish = rk3288_suspend_finish, +}; + +static const struct rockchip_pm_data rk3288_pm_data __initconst = { + .ops = &rk3288_suspend_ops, + .init = rk3288_suspend_init, +}; + +static const struct of_device_id rockchip_pmu_of_device_ids[] __initconst = { + { + .compatible = "rockchip,rk3288-pmu", + .data = &rk3288_pm_data, + }, + { /* sentinel */ }, +}; + +void __init rockchip_suspend_init(void) +{ + const struct rockchip_pm_data *pm_data; + const struct of_device_id *match; + struct device_node *np; + int ret; + + np = of_find_matching_node_and_match(NULL, rockchip_pmu_of_device_ids, + &match); + if (!match) { + pr_err("Failed to find PMU node\n"); + return; + } + pm_data = (struct rockchip_pm_data *) match->data; + + if (pm_data->init) { + ret = pm_data->init(np); + + if (ret) { + pr_err("%s: matches init error %d\n", __func__, ret); + return; + } + } + + suspend_set_ops(pm_data->ops); +} diff --git a/pool/shard008/C/0130482_timer.c b/pool/shard008/C/0130482_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..6977409438b2174b85df9947341260ec7eccfa01 --- /dev/null +++ b/pool/shard008/C/0130482_timer.c @@ -0,0 +1,157 @@ +/* + * $Id: timer.c,v 1.6 2001/11/14 19:58:11 lutchann Exp $ + * + * Authors: + * Pedro Roque + * Lars Fenneberg + * + * This software is Copyright 1996-2000 by the above mentioned author(s), + * All Rights Reserved. + * + * The license which is distributed with this software in the file COPYRIGHT + * applies to this software. If your distribution is missing this file, you + * may request it from . + * + */ + +#include +#include +#include + +static struct timer_lst timers_head = { + {LONG_MAX, LONG_MAX}, + NULL, NULL, + &timers_head, &timers_head +}; + +static void alarm_handler(int sig); + +static void +schedule_timer(void) +{ + struct timer_lst *tm = timers_head.next; + struct timeval tv; + + gettimeofday(&tv, NULL); + + if (tm != &timers_head) + { + struct itimerval next; + + memset(&next, 0, sizeof(next)); + + timersub(&tm->expires, &tv, &next.it_value); + + signal(SIGALRM, alarm_handler); + + if ((next.it_value.tv_sec > 0) || + ((next.it_value.tv_sec == 0) && (next.it_value.tv_usec > 0))) + { + dlog(LOG_DEBUG, 4, "calling alarm: %ld secs, %ld usecs", + next.it_value.tv_sec, next.it_value.tv_usec); + setitimer(ITIMER_REAL, &next, NULL); + } + else + { + dlog(LOG_DEBUG, 4, "next timer has already expired, queueing signal"); + kill(getpid(), SIGALRM); + } + } +} + +void +set_timer(struct timer_lst *tm, double secs) +{ + struct timeval tv; + struct timer_lst *lst; + sigset_t bmask, oldmask; + struct timeval firein; + + dlog(LOG_DEBUG, 3, "setting timer: %.2f secs", secs); + + firein.tv_sec = (long)secs; + firein.tv_usec = (long)((secs - (double)firein.tv_sec) * 1000000); + + dlog(LOG_DEBUG, 5, "setting timer: %ld secs %ld usecs", firein.tv_sec, firein.tv_usec); + + gettimeofday(&tv, NULL); + timeradd(&tv, &firein, &tm->expires); + + sigemptyset(&bmask); + sigaddset(&bmask, SIGALRM); + sigprocmask(SIG_BLOCK, &bmask, &oldmask); + + lst = &timers_head; + + do { + lst = lst->next; + } while ((tm->expires.tv_sec > lst->expires.tv_sec) || + ((tm->expires.tv_sec == lst->expires.tv_sec) && + (tm->expires.tv_usec > lst->expires.tv_usec))); + + tm->next = lst; + tm->prev = lst->prev; + lst->prev = tm; + tm->prev->next = tm; + + dlog(LOG_DEBUG, 5, "calling schedule_timer from set_timer context"); + schedule_timer(); + + sigprocmask(SIG_SETMASK, &oldmask, NULL); +} + +void +clear_timer(struct timer_lst *tm) +{ + sigset_t bmask, oldmask; + + sigemptyset(&bmask); + sigaddset(&bmask, SIGALRM); + sigprocmask(SIG_BLOCK, &bmask, &oldmask); + + tm->prev->next = tm->next; + tm->next->prev = tm->prev; + + tm->prev = tm->next = NULL; + + dlog(LOG_DEBUG, 5, "calling schedule_timer from clear_timer context"); + schedule_timer(); + + sigprocmask(SIG_SETMASK, &oldmask, NULL); +} + +static void +alarm_handler(int sig) +{ + struct timer_lst *tm, *back; + struct timeval tv; + + gettimeofday(&tv, NULL); + tm = timers_head.next; + + while ((tm->expires.tv_sec < tv.tv_sec) + || ((tm->expires.tv_sec == tv.tv_sec) + && (tm->expires.tv_usec <= tv.tv_usec))) + { + tm->prev->next = tm->next; + tm->next->prev = tm->prev; + + back = tm; + tm = tm->next; + back->prev = back->next = NULL; + + (*back->handler)(back->data); + } + + dlog(LOG_DEBUG, 5, "calling schedule_timer from alarm_handler context"); + schedule_timer(); +} + + +void +init_timer(struct timer_lst *tm, void (*handler)(void *), void *data) +{ + memset(tm, 0, sizeof(struct timer_lst)); + tm->handler = handler; + tm->data = data; +} diff --git a/pool/shard008/C/0130488_list.c b/pool/shard008/C/0130488_list.c new file mode 100644 index 0000000000000000000000000000000000000000..2acced95c0a44251b9a1fae50bb5df7875a79be1 --- /dev/null +++ b/pool/shard008/C/0130488_list.c @@ -0,0 +1,52 @@ +#include +#include +#include "list.h" + +static void *list_node_base(struct list_node *node, ptrdiff_t base_offset) { + return (void *)((intptr_t)node - base_offset); +} + +static inline void list_insert(struct list_node *prev, struct list_node *next, struct list_node *new_node) { + new_node->next = next; + new_node->prev = prev; + next->prev = new_node; + prev->next = new_node; +} + +void list_head_init(struct list_node *head) { + head->next = head; + head->prev = head; +} + +void list_append(struct list_node *head, struct list_node *node) { + list_insert(head, head->next, node); +} + +void list_prepend(struct list_node *head, struct list_node *node) { + list_insert(head->prev, head, node); +} + +void list_remove(struct list_node *node) { + node->prev->next = node->next; + node->next->prev = node->prev; + node->prev = NULL; + node->next = NULL; +} + +void list_iterate(struct list_node *head, void (*f)(void *), ptrdiff_t base_offset) { + for (struct list_node *curr = head->next; curr != head; curr = curr->next) { + f(list_node_base(curr, base_offset)); + } +} + +bool list_empty(struct list_node *head) { + return head->next == head; +} + +size_t list_length(struct list_node *head) { + size_t length = 0; + for (struct list_node *curr = head->next; curr != head; curr = curr->next) { + length++; + } + return length; +} diff --git a/pool/shard008/C/0130491_xp_dl.c b/pool/shard008/C/0130491_xp_dl.c new file mode 100644 index 0000000000000000000000000000000000000000..fe95a7f82a44d39e57af73c1abcecdb4c39d44d1 --- /dev/null +++ b/pool/shard008/C/0130491_xp_dl.c @@ -0,0 +1,76 @@ +#include +#include "dirwrap.h" +#include "xp_dl.h" + +#ifndef STATIC_LINK +#if defined(__unix__) + +DLLEXPORT dll_handle DLLCALL xp_dlopen(const char **names, int mode, int major) +{ + const char *name; + char fname[MAX_PATH+1]; + dll_handle ret=NULL; + int i; + + for(; *names && (*names)[0]; names++) { + name=*names; + /* Try for version match */ + sprintf(fname, "lib%s.so.%d", name, major); + if((ret=dlopen(fname, mode))!=NULL) + return(ret); + + /* Try for name match */ + sprintf(fname, "lib%s.so", name); + if((ret=dlopen(fname, mode))!=NULL) + return(ret); + + /* Try for name match without the prefix */ + sprintf(fname, "%s.so", name); + if((ret=dlopen(fname, mode))!=NULL) + return(ret); + + /* Try all previous major versions */ + for(i=major-1; i>=0; i--) { + sprintf(fname, "lib%s.so.%d", name, i); + if((ret=dlopen(fname, mode))!=NULL) + return(ret); + } + +#if defined(__APPLE__) && defined(__MACH__) + /* Try for version match */ + sprintf(fname, "lib%s.%d.dylib", name, major); + if((ret=dlopen(fname, mode))!=NULL) + return(ret); + + /* Try for name match */ + sprintf(fname, "lib%s.dylib", name, major); + if((ret=dlopen(fname, mode))!=NULL) + return(ret); + + /* Try all previous major versions */ + for(i=major-1; i>=0; i--) { + sprintf(fname, "lib%s.%d.dylib", name, i); + if((ret=dlopen(fname, mode))!=NULL) + return(ret); + } +#endif /* OS X */ + } + + return(NULL); +} +#elif defined(_WIN32) +DLLEXPORT dll_handle DLLCALL xp_dlopen(const char **names, int mode, int major) +{ + char fname[MAX_PATH+1]; + dll_handle ret=NULL; + + for(; *names && (*names)[0]; names++) { + sprintf(fname, "%s.dll", *names); + if((ret=LoadLibrary(fname))!=NULL) + return(ret); + } + return(NULL); +} +#endif /* __unix__,_WIN32 */ + +#endif /* STATIC_LINK */ diff --git a/pool/shard008/C/0130493_ux_screen.c b/pool/shard008/C/0130493_ux_screen.c new file mode 100644 index 0000000000000000000000000000000000000000..1b903793eaf010da0755bfd4d8be71c4b9219694 --- /dev/null +++ b/pool/shard008/C/0130493_ux_screen.c @@ -0,0 +1,128 @@ +/* + * ux_screen.c - Unix interface, screen manipulation + * + * This file is part of Frotz. + * + * Frotz 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. + * + * Frotz 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + */ + +#define __UNIX_PORT_FILE + +#include +#include +#include + +#ifdef USE_NCURSES_H +#include +#else +#include +#endif + +#include "ux_frotz.h" + +/* + * os_erase_area + * + * Fill a rectangular area of the screen with the current background + * colour. Top left coordinates are (1,1). The cursor does not move. + * + */ + +void os_erase_area (int top, int left, int bottom, int right) +{ + int y, x, i, j; + + /* Catch the most common situation and do things the easy way */ + if ((top == 1) && (bottom == h_screen_rows) && + (left == 1) && (right == h_screen_cols)) { +#ifdef COLOR_SUPPORT + /* Only set the curses background when doing an erase, so it won't + * interfere with the copying we do in os_scroll_area. + */ + bkgdset(u_setup.current_color | ' '); + erase(); + bkgdset(0); +#else + erase(); +#endif + } else { + /* Sigh... */ + int saved_style = u_setup.current_text_style; + os_set_text_style(u_setup.current_color); + getyx(stdscr, y, x); + top--; left--; bottom--; right--; + for (i = top; i <= bottom; i++) { + move(i, left); + for (j = left; j <= right; j++) + addch(' '); + } + move(y, x); + os_set_text_style(saved_style); + } +}/* os_erase_area */ + +/* + * os_scroll_area + * + * Scroll a rectangular area of the screen up (units > 0) or down + * (units < 0) and fill the empty space with the current background + * colour. Top left coordinates are (1,1). The cursor stays put. + * + */ + +void os_scroll_area (int top, int left, int bottom, int right, int units) +{ + top--; left--; bottom--; right--; + + if ((left == 0) && (right == h_screen_cols - 1)) { + static int old_scroll_top = 0; + static int old_scroll_bottom = 0; + + if (!((old_scroll_top == top) && (old_scroll_bottom == bottom))) { + old_scroll_top = top; old_scroll_bottom = bottom; + setscrreg(top, bottom); + } + scrollok(stdscr, TRUE); + scrl(units); + scrollok(stdscr, FALSE); + } else { + int row, col, x, y; + chtype ch; + + getyx(stdscr, y, x); + /* Must turn off attributes during copying. */ + attrset(0); + if (units > 0) { + for (row = top; row <= bottom - units; row++) + for (col = left; col <= right; col++) { + ch = mvinch(row + units, col); + mvaddch(row, col, ch); + } + } else if (units < 0) { + for (row = bottom; row >= top - units; row--) + for (col = left; col <= right; col++) { + ch = mvinch(row + units, col); + mvaddch(row, col, ch); + } + } + /* Restore attributes. */ + os_set_text_style(u_setup.current_text_style); + move(y, x); + } + if (units > 0) + os_erase_area(bottom - units + 2, left + 1, bottom + 1, right + 1); + else if (units < 0) + os_erase_area(top + 1, left + 1, top - units, right + 1); +}/* os_scroll_area */ diff --git a/pool/shard008/C/0130497_testencoder.c b/pool/shard008/C/0130497_testencoder.c new file mode 100644 index 0000000000000000000000000000000000000000..b142ff49f14bef62ae6b704472ccba2baceb4709 --- /dev/null +++ b/pool/shard008/C/0130497_testencoder.c @@ -0,0 +1,114 @@ +/* RLE encoder for minimOS * + * investigates optimum threshold * + * (c) 2021-2022 Carlos J. Santisteban * + * last modified 20211031-1752 */ + +#include + +/* function declarations */ +void send_u(void); // go backwards and send uncompressed chunk + +/* global variables, WTF */ + char src[32768]; // just in case, read whole input file + FILE* f; // file handler, both source and output as not simultaneous + int i; // source index + int base; // pivot index for comparisons + int thres; // compressed encoding threshold + int siz, unc, count, output; + int clocks; // estimated 6502 decompression time! + +/* main code */ +int main(void) { + char base; // repeated character + char name[80]; // input filename + +/* read source file into memory */ + printf("File to compress: "); + scanf("%s", name); // does this put terminator? I think so + f = fopen(name, "rb"); // open source file + if (f==NULL) { + printf("\n*** No input file ***\n"); + return -1; + } + fseek(f, 0, SEEK_END); // go to the end for a moment + siz = ftell(f); // get length + fseek(f, 0, SEEK_SET); // back to start + if (siz>32768) { + printf("\n*** File is too large ***\n"); + return -2; + } + fread(src, 1, siz, f); // read file into memory + fclose(f); // all done with input + printf("original: %d bytes\n", siz); + +/* prepare output file */ +// f = fopen("source.rle", "wb"); // get ready for output file +// if (f==NULL) { +// printf("\n*** Cannot create output file ***\n"); +// return -3; +// } + for (thres=1; thres<127; thres++) { // NOTE ANOMALOUS INDENT +/* compress array */ +//printf("t=%d:\n",thres); + i = 0; // cursor reset, normally after last repetition + unc = 0; // this gets reset every time but first + clocks = output = 0; // needed here for estimation + while (i < siz) { +//printf("(%d)\n",i); + base = src[i++]; // read this first byte and point to following one + count = 1; // assume not yet repeated + while (src[i]==base && count<127 && ithres) { // any actual repetition? +//printf("T\n"); + if (unc) { +//printf("u\n"); + send_u(); // send previous uncompressed chunk, if any! + } +// fputc(count, f); // first goes 'command', positive means repeat following byte +// fputc(base, f); // this was the repeated value + output += 2; + clocks += 47+13*count; + } else { +//printf("-%d\n",count); + unc+=count; // different, thus more for the uncompressed chunk EEEEK + if (unc>=128) { +//printf("U\n"); + send_u(); // cannot add more to chunk (check limits!) + } + } + } +/* input stream ended, but check for anything in progress! */ + count=0; // EEEEEEEEEEEK + if (unc) + send_u(); // send uncompressed chunk in progress! + +/* end output stream and cleanout */ +// fputc(0, f); // end of stream + output++; +// fclose(f); + printf("Threshold %d encodes into %d (%d%%), 6502 timing: %d clock cycles\n", thres, output, 100*output/siz, clocks); + } // NOTE ANOMALOUS INDENT + + return 0; +} + +/* function definitions */ +void send_u(void) { // go backwards and send uncompressed chunk + int x, y; // x = uncompressed chunk index, y = min(unc,128) + + x = i - unc - count; // compute start of chunk, is this OK? + y = (unc<128)?unc:128; // cannot sent more than 128 in a chunk +//printf("Chunk %d\n",y); + clocks += 46+18*y; +// fputc(-y, f); // negative 'command' means length of uncompressed chunk + output++; + while (y--) { +// fputc(src[x++], f); // send uncompressed byte + output++; + unc--; // may not finish as 0! + } +} diff --git a/pool/shard008/C/0130498_mapcon.c b/pool/shard008/C/0130498_mapcon.c new file mode 100644 index 0000000000000000000000000000000000000000..6af6a3dbcae3d6e94162a56f4e505d504191f17a --- /dev/null +++ b/pool/shard008/C/0130498_mapcon.c @@ -0,0 +1,94 @@ +/* This file "mapcon.c" contains the definitions of the operations + * declared in the file "mapcon.h". */ + +#include "mapcon.h" + +int mapcon_solve_system ( int puretopdim ) +{ + int *b,fail; + double *c; + fail = _ada_use_c2phc4c(430,&puretopdim,b,c,0); + return fail; +} + +int mapcon_write_maps ( void ) +{ + int *a,*b,fail; + double *c; + fail = _ada_use_c2phc4c(431,a,b,c,0); + return fail; +} + +int mapcon_clear_maps ( void ) +{ + int *a,*b,fail; + double *c; + fail = _ada_use_c2phc4c(432,a,b,c,0); + return fail; +} + +int mapcon_top_dimension ( int *dim ) +{ + int *b,fail; + double *c; + fail = _ada_use_c2phc4c(433,dim,b,c,0); + return fail; +} + +int mapcon_number_of_maps ( int dim, int *nbmaps ) +{ + int fail; + double *c; + fail = _ada_use_c2phc4c(434,&dim,nbmaps,c,0); + return fail; +} + +int mapcon_degree_of_map ( int dim, int ind, int *deg ) +{ + int a[2], fail; + double *c; + + a[0] = dim; + a[1] = ind; + fail = _ada_use_c2phc4c(435,a,deg,c,0); + + return fail; +} + +int mapcon_coefficients_of_map ( int dim, int ind, int nvr, double *cff ) +{ + int a[3], *b, fail; + + a[0] = dim; + a[1] = ind; + a[2] = nvr; + fail = _ada_use_c2phc4c(436,a,b,cff,0); + + return fail; +} + +int mapcon_exponents_of_map ( int dim, int ind, int nvr, int *exp ) +{ + int a[3], fail; + double *c; + + a[0] = dim; + a[1] = ind; + a[2] = nvr; + fail = _ada_use_c2phc4c(437,a,exp,c,0); + + return fail; +} + +int mapcon_coefficients_and_exponents_of_map + ( int dim, int ind, int nvr, double *cff, int *exp ) +{ + int a[3], fail; + + a[0] = dim; + a[1] = ind; + a[2] = nvr; + fail = _ada_use_c2phc4c(438,a,exp,cff,0); + + return fail; +} diff --git a/pool/shard008/C/0130499_redboot.c b/pool/shard008/C/0130499_redboot.c new file mode 100644 index 0000000000000000000000000000000000000000..2349366c5fd18f1c195d10568b1441a9acd5ed06 --- /dev/null +++ b/pool/shard008/C/0130499_redboot.c @@ -0,0 +1,272 @@ +/* + * $Id: redboot.c,v 1.21 2006/03/30 18:34:37 bjd Exp $ + * + * Parse RedBoot-style Flash Image System (FIS) tables and + * produce a Linux partition array to match. + */ + +#include +#include +#include +#include + +#include +#include + +struct fis_image_desc { + unsigned char name[16]; // Null terminated name + uint32_t flash_base; // Address within FLASH of image + uint32_t mem_base; // Address in memory where it executes + uint32_t size; // Length of image + uint32_t entry_point; // Execution entry point + uint32_t data_length; // Length of actual data + unsigned char _pad[256-(16+7*sizeof(uint32_t))]; + uint32_t desc_cksum; // Checksum over image descriptor + uint32_t file_cksum; // Checksum over image data +}; + +struct fis_list { + struct fis_image_desc *img; + struct fis_list *next; +}; + +static int directory = CONFIG_MTD_REDBOOT_DIRECTORY_BLOCK; +module_param(directory, int, 0); + +static inline int redboot_checksum(struct fis_image_desc *img) +{ + /* RedBoot doesn't actually write the desc_cksum field yet AFAICT */ + return 1; +} + +static int parse_redboot_partitions(struct mtd_info *master, + struct mtd_partition **pparts, + unsigned long fis_origin) +{ + int nrparts = 0; + struct fis_image_desc *buf; + struct mtd_partition *parts; + struct fis_list *fl = NULL, *tmp_fl; + int ret, i; + size_t retlen; + char *names; + char *nullname; + int namelen = 0; + int nulllen = 0; + int numslots; + unsigned long offset; +#ifdef CONFIG_MTD_REDBOOT_PARTS_UNALLOCATED + static char nullstring[] = "unallocated"; +#endif + + buf = vmalloc(master->erasesize); + + if (!buf) + return -ENOMEM; + + if ( directory < 0 ) + offset = master->size + directory*master->erasesize; + else + offset = directory*master->erasesize; + + printk(KERN_NOTICE "Searching for RedBoot partition table in %s at offset 0x%lx\n", + master->name, offset); + + ret = master->read(master, offset, + master->erasesize, &retlen, (void *)buf); + + if (ret) + goto out; + + if (retlen != master->erasesize) { + ret = -EIO; + goto out; + } + + numslots = (master->erasesize / sizeof(struct fis_image_desc)); + for (i = 0; i < numslots; i++) { + if (!memcmp(buf[i].name, "FIS directory", 14)) { + /* This is apparently the FIS directory entry for the + * FIS directory itself. The FIS directory size is + * one erase block; if the buf[i].size field is + * swab32(erasesize) then we know we are looking at + * a byte swapped FIS directory - swap all the entries! + * (NOTE: this is 'size' not 'data_length'; size is + * the full size of the entry.) + */ + if (swab32(buf[i].size) == master->erasesize) { + int j; + for (j = 0; j < numslots; ++j) { + + /* A single 0xff denotes a deleted entry. + * Two of them in a row is the end of the table. + */ + if (buf[j].name[0] == 0xff) { + if (buf[j].name[1] == 0xff) { + break; + } else { + continue; + } + } + + /* The unsigned long fields were written with the + * wrong byte sex, name and pad have no byte sex. + */ + swab32s(&buf[j].flash_base); + swab32s(&buf[j].mem_base); + swab32s(&buf[j].size); + swab32s(&buf[j].entry_point); + swab32s(&buf[j].data_length); + swab32s(&buf[j].desc_cksum); + swab32s(&buf[j].file_cksum); + } + } + break; + } + } + if (i == numslots) { + /* Didn't find it */ + printk(KERN_NOTICE "No RedBoot partition table detected in %s\n", + master->name); + ret = 0; + goto out; + } + + for (i = 0; i < numslots; i++) { + struct fis_list *new_fl, **prev; + + if (buf[i].name[0] == 0xff) { + if (buf[i].name[1] == 0xff) { + break; + } else { + continue; + } + } + if (!redboot_checksum(&buf[i])) + break; + + new_fl = kmalloc(sizeof(struct fis_list), GFP_KERNEL); + namelen += strlen(buf[i].name)+1; + if (!new_fl) { + ret = -ENOMEM; + goto out; + } + new_fl->img = &buf[i]; + if (fis_origin) { + buf[i].flash_base -= fis_origin; + } else { + buf[i].flash_base &= master->size-1; + } + + /* I'm sure the JFFS2 code has done me permanent damage. + * I now think the following is _normal_ + */ + prev = &fl; + while(*prev && (*prev)->img->flash_base < new_fl->img->flash_base) + prev = &(*prev)->next; + new_fl->next = *prev; + *prev = new_fl; + + nrparts++; + } +#ifdef CONFIG_MTD_REDBOOT_PARTS_UNALLOCATED + if (fl->img->flash_base) { + nrparts++; + nulllen = sizeof(nullstring); + } + + for (tmp_fl = fl; tmp_fl->next; tmp_fl = tmp_fl->next) { + if (tmp_fl->img->flash_base + tmp_fl->img->size + master->erasesize <= tmp_fl->next->img->flash_base) { + nrparts++; + nulllen = sizeof(nullstring); + } + } +#endif + parts = kmalloc(sizeof(*parts)*nrparts + nulllen + namelen, GFP_KERNEL); + + if (!parts) { + ret = -ENOMEM; + goto out; + } + + memset(parts, 0, sizeof(*parts)*nrparts + nulllen + namelen); + + nullname = (char *)&parts[nrparts]; +#ifdef CONFIG_MTD_REDBOOT_PARTS_UNALLOCATED + if (nulllen > 0) { + strcpy(nullname, nullstring); + } +#endif + names = nullname + nulllen; + + i=0; + +#ifdef CONFIG_MTD_REDBOOT_PARTS_UNALLOCATED + if (fl->img->flash_base) { + parts[0].name = nullname; + parts[0].size = fl->img->flash_base; + parts[0].offset = 0; + i++; + } +#endif + for ( ; iimg->size; + parts[i].offset = fl->img->flash_base; + parts[i].name = names; + + strcpy(names, fl->img->name); +#ifdef CONFIG_MTD_REDBOOT_PARTS_READONLY + if (!memcmp(names, "RedBoot", 8) || + !memcmp(names, "RedBoot config", 15) || + !memcmp(names, "FIS directory", 14)) { + parts[i].mask_flags = MTD_WRITEABLE; + } +#endif + names += strlen(names)+1; + +#ifdef CONFIG_MTD_REDBOOT_PARTS_UNALLOCATED + if(fl->next && fl->img->flash_base + fl->img->size + master->erasesize <= fl->next->img->flash_base) { + i++; + parts[i].offset = parts[i-1].size + parts[i-1].offset; + parts[i].size = fl->next->img->flash_base - parts[i].offset; + parts[i].name = nullname; + } +#endif + tmp_fl = fl; + fl = fl->next; + kfree(tmp_fl); + } + ret = nrparts; + *pparts = parts; + out: + while (fl) { + struct fis_list *old = fl; + fl = fl->next; + kfree(old); + } + vfree(buf); + return ret; +} + +static struct mtd_part_parser redboot_parser = { + .owner = THIS_MODULE, + .parse_fn = parse_redboot_partitions, + .name = "RedBoot", +}; + +static int __init redboot_parser_init(void) +{ + return register_mtd_parser(&redboot_parser); +} + +static void __exit redboot_parser_exit(void) +{ + deregister_mtd_parser(&redboot_parser); +} + +module_init(redboot_parser_init); +module_exit(redboot_parser_exit); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Red Hat, Inc. - David Woodhouse "); +MODULE_DESCRIPTION("Parsing code for RedBoot Flash Image System (FIS) tables"); diff --git a/pool/shard008/C/0130501_symtab.c b/pool/shard008/C/0130501_symtab.c new file mode 100644 index 0000000000000000000000000000000000000000..6aca4850f4da89adb4282bc3d721cf465dc12bd8 --- /dev/null +++ b/pool/shard008/C/0130501_symtab.c @@ -0,0 +1,278 @@ +/* + * Portions Copyright (C) 2004 Internet Systems Consortium, Inc. ("ISC") + * Portions Copyright (C) 2001 Internet Software Consortium. + * Portions Copyright (C) 2001 Nominum, Inc. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND ISC AND NOMINUM DISCLAIMS ALL + * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY + * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +/* $Id: symtab.c,v 1.3.12.3 2004/03/08 09:05:04 marka Exp $ */ + +#include + +#include +#include +#include + +#include +#include + +#include +#include +#include + +typedef struct elt { + char * key; + unsigned int type; + isccc_symvalue_t value; + ISC_LINK(struct elt) link; +} elt_t; + +typedef ISC_LIST(elt_t) eltlist_t; + +#define SYMTAB_MAGIC ISC_MAGIC('S', 'y', 'm', 'T') +#define VALID_SYMTAB(st) ISC_MAGIC_VALID(st, SYMTAB_MAGIC) + +struct isccc_symtab { + unsigned int magic; + unsigned int size; + eltlist_t * table; + isccc_symtabundefaction_t undefine_action; + void * undefine_arg; + isc_boolean_t case_sensitive; +}; + +isc_result_t +isccc_symtab_create(unsigned int size, + isccc_symtabundefaction_t undefine_action, + void *undefine_arg, + isc_boolean_t case_sensitive, + isccc_symtab_t **symtabp) +{ + isccc_symtab_t *symtab; + unsigned int i; + + REQUIRE(symtabp != NULL && *symtabp == NULL); + REQUIRE(size > 0); /* Should be prime. */ + + symtab = malloc(sizeof(*symtab)); + if (symtab == NULL) + return (ISC_R_NOMEMORY); + symtab->table = malloc(size * sizeof(eltlist_t)); + if (symtab->table == NULL) { + free(symtab); + return (ISC_R_NOMEMORY); + } + for (i = 0; i < size; i++) + ISC_LIST_INIT(symtab->table[i]); + symtab->size = size; + symtab->undefine_action = undefine_action; + symtab->undefine_arg = undefine_arg; + symtab->case_sensitive = case_sensitive; + symtab->magic = SYMTAB_MAGIC; + + *symtabp = symtab; + + return (ISC_R_SUCCESS); +} + +static inline void +free_elt(isccc_symtab_t *symtab, unsigned int bucket, elt_t *elt) { + ISC_LIST_UNLINK(symtab->table[bucket], elt, link); + if (symtab->undefine_action != NULL) + (symtab->undefine_action)(elt->key, elt->type, elt->value, + symtab->undefine_arg); + free(elt); +} + +void +isccc_symtab_destroy(isccc_symtab_t **symtabp) { + isccc_symtab_t *symtab; + unsigned int i; + elt_t *elt, *nelt; + + REQUIRE(symtabp != NULL); + symtab = *symtabp; + REQUIRE(VALID_SYMTAB(symtab)); + + for (i = 0; i < symtab->size; i++) { + for (elt = ISC_LIST_HEAD(symtab->table[i]); + elt != NULL; + elt = nelt) { + nelt = ISC_LIST_NEXT(elt, link); + free_elt(symtab, i, elt); + } + } + free(symtab->table); + symtab->magic = 0; + free(symtab); + + *symtabp = NULL; +} + +static inline unsigned int +hash(const char *key, isc_boolean_t case_sensitive) { + const char *s; + unsigned int h = 0; + unsigned int g; + int c; + + /* + * P. J. Weinberger's hash function, adapted from p. 436 of + * _Compilers: Principles, Techniques, and Tools_, Aho, Sethi + * and Ullman, Addison-Wesley, 1986, ISBN 0-201-10088-6. + */ + + if (case_sensitive) { + for (s = key; *s != '\0'; s++) { + h = ( h << 4 ) + *s; + if ((g = ( h & 0xf0000000 )) != 0) { + h = h ^ (g >> 24); + h = h ^ g; + } + } + } else { + for (s = key; *s != '\0'; s++) { + c = *s; + c = tolower((unsigned char)c); + h = ( h << 4 ) + c; + if ((g = ( h & 0xf0000000 )) != 0) { + h = h ^ (g >> 24); + h = h ^ g; + } + } + } + + return (h); +} + +#define FIND(s, k, t, b, e) \ + b = hash((k), (s)->case_sensitive) % (s)->size; \ + if ((s)->case_sensitive) { \ + for (e = ISC_LIST_HEAD((s)->table[b]); \ + e != NULL; \ + e = ISC_LIST_NEXT(e, link)) { \ + if (((t) == 0 || e->type == (t)) && \ + strcmp(e->key, (k)) == 0) \ + break; \ + } \ + } else { \ + for (e = ISC_LIST_HEAD((s)->table[b]); \ + e != NULL; \ + e = ISC_LIST_NEXT(e, link)) { \ + if (((t) == 0 || e->type == (t)) && \ + strcasecmp(e->key, (k)) == 0) \ + break; \ + } \ + } + +isc_result_t +isccc_symtab_lookup(isccc_symtab_t *symtab, const char *key, unsigned int type, + isccc_symvalue_t *value) +{ + unsigned int bucket; + elt_t *elt; + + REQUIRE(VALID_SYMTAB(symtab)); + REQUIRE(key != NULL); + + FIND(symtab, key, type, bucket, elt); + + if (elt == NULL) + return (ISC_R_NOTFOUND); + + if (value != NULL) + *value = elt->value; + + return (ISC_R_SUCCESS); +} + +isc_result_t +isccc_symtab_define(isccc_symtab_t *symtab, char *key, unsigned int type, + isccc_symvalue_t value, isccc_symexists_t exists_policy) +{ + unsigned int bucket; + elt_t *elt; + + REQUIRE(VALID_SYMTAB(symtab)); + REQUIRE(key != NULL); + REQUIRE(type != 0); + + FIND(symtab, key, type, bucket, elt); + + if (exists_policy != isccc_symexists_add && elt != NULL) { + if (exists_policy == isccc_symexists_reject) + return (ISC_R_EXISTS); + INSIST(exists_policy == isccc_symexists_replace); + ISC_LIST_UNLINK(symtab->table[bucket], elt, link); + if (symtab->undefine_action != NULL) + (symtab->undefine_action)(elt->key, elt->type, + elt->value, + symtab->undefine_arg); + } else { + elt = malloc(sizeof(*elt)); + if (elt == NULL) + return (ISC_R_NOMEMORY); + ISC_LINK_INIT(elt, link); + } + + elt->key = key; + elt->type = type; + elt->value = value; + + /* + * We prepend so that the most recent definition will be found. + */ + ISC_LIST_PREPEND(symtab->table[bucket], elt, link); + + return (ISC_R_SUCCESS); +} + +isc_result_t +isccc_symtab_undefine(isccc_symtab_t *symtab, const char *key, unsigned int type) { + unsigned int bucket; + elt_t *elt; + + REQUIRE(VALID_SYMTAB(symtab)); + REQUIRE(key != NULL); + + FIND(symtab, key, type, bucket, elt); + + if (elt == NULL) + return (ISC_R_NOTFOUND); + + free_elt(symtab, bucket, elt); + + return (ISC_R_SUCCESS); +} + +void +isccc_symtab_foreach(isccc_symtab_t *symtab, isccc_symtabforeachaction_t action, + void *arg) +{ + unsigned int i; + elt_t *elt, *nelt; + + REQUIRE(VALID_SYMTAB(symtab)); + REQUIRE(action != NULL); + + for (i = 0; i < symtab->size; i++) { + for (elt = ISC_LIST_HEAD(symtab->table[i]); + elt != NULL; + elt = nelt) { + nelt = ISC_LIST_NEXT(elt, link); + if ((action)(elt->key, elt->type, elt->value, arg)) + free_elt(symtab, i, elt); + } + } +} diff --git a/pool/shard008/C/0130503_lqr_progress.c b/pool/shard008/C/0130503_lqr_progress.c new file mode 100644 index 0000000000000000000000000000000000000000..a9a68f4b21ba8a4b7d24aa898617664165248a68 --- /dev/null +++ b/pool/shard008/C/0130503_lqr_progress.c @@ -0,0 +1,147 @@ +/* LiquidRescaling Library + * Copyright (C) 2007-2009 Carlo Baldassi (the "Author") . + * All Rights Reserved. + * + * This library implements the algorithm described in the paper + * "Seam Carving for Content-Aware Image Resizing" + * by Shai Avidan and Ariel Shamir + * which can be found at http://www.faculty.idc.ac.il/arik/imret.pdf + * + * 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; version 3 dated June, 2007. + + * 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 + */ + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include + +#include +#include + +/* LQR_PUBLIC */ +LqrProgress * +lqr_progress_new(void) +{ + LqrProgress *progress; + LQR_TRY_N_N(progress = g_try_new0(LqrProgress, 1)); + + lqr_progress_set_init_width_message(progress, "Resizing width..."); + lqr_progress_set_init_height_message(progress, "Resizing height..."); + lqr_progress_set_end_width_message(progress, "done"); + lqr_progress_set_end_height_message(progress, "done"); + lqr_progress_set_update_step(progress, (float) 0.02); + + return progress; +} + +LqrRetVal +lqr_progress_init(LqrProgress * p, const gchar *message) +{ + LQR_CATCH_F(p != NULL); + if (p->init) { + return p->init(message); + } else { + return LQR_OK; + } +} + +LqrRetVal +lqr_progress_update(LqrProgress * p, gdouble percentage) +{ + LQR_CATCH_F(p != NULL); + if (p->update) { + return p->update(percentage); + } else { + return LQR_OK; + } +} + +LqrRetVal +lqr_progress_end(LqrProgress * p, const gchar *message) +{ + LQR_CATCH_F(p != NULL); + if (p->end) { + return p->end(message); + } else { + return LQR_OK; + } +} + +/* LQR_PUBLIC */ +LqrRetVal +lqr_progress_set_init(LqrProgress * p, LqrProgressFuncInit init_func) +{ + p->init = init_func; + return LQR_OK; +} + +/* LQR_PUBLIC */ +LqrRetVal +lqr_progress_set_update(LqrProgress * p, LqrProgressFuncUpdate update_func) +{ + p->update = update_func; + return LQR_OK; +} + +/* LQR_PUBLIC */ +LqrRetVal +lqr_progress_set_end(LqrProgress * p, LqrProgressFuncEnd end_func) +{ + p->end = end_func; + return LQR_OK; +} + +/* LQR_PUBLIC */ +LqrRetVal +lqr_progress_set_update_step(LqrProgress * p, gfloat update_step) +{ + p->update_step = update_step; + return LQR_OK; +} + +/* LQR_PUBLIC */ +LqrRetVal +lqr_progress_set_init_width_message(LqrProgress * p, const gchar *message) +{ + LQR_CATCH_F(p); + g_strlcpy(p->init_width_message, message, LQR_PROGRESS_MAX_MESSAGE_LENGTH); + return LQR_OK; +} + +/* LQR_PUBLIC */ +LqrRetVal +lqr_progress_set_init_height_message(LqrProgress * p, const gchar *message) +{ + LQR_CATCH_F(p != NULL); + g_strlcpy(p->init_height_message, message, LQR_PROGRESS_MAX_MESSAGE_LENGTH); + return LQR_OK; +} + +/* LQR_PUBLIC */ +LqrRetVal +lqr_progress_set_end_width_message(LqrProgress * p, const gchar *message) +{ + LQR_CATCH_F(p != NULL); + g_strlcpy(p->end_width_message, message, LQR_PROGRESS_MAX_MESSAGE_LENGTH); + return LQR_OK; +} + +/* LQR_PUBLIC */ +LqrRetVal +lqr_progress_set_end_height_message(LqrProgress * p, const gchar *message) +{ + LQR_CATCH_F(p != NULL); + g_strlcpy(p->end_height_message, message, LQR_PROGRESS_MAX_MESSAGE_LENGTH); + return LQR_OK; +} diff --git a/pool/shard008/C/0130504_buttons.c b/pool/shard008/C/0130504_buttons.c new file mode 100644 index 0000000000000000000000000000000000000000..43c0820afee003be712fb07a24b0e409a2a65ae3 --- /dev/null +++ b/pool/shard008/C/0130504_buttons.c @@ -0,0 +1,163 @@ +// Report on user interface buttons +// +// Copyright (C) 2018 Kevin O'Connor +// +// This file may be distributed under the terms of the GNU GPLv3 license. + +#include "basecmd.h" // oid_alloc +#include "board/gpio.h" // struct gpio_in +#include "board/irq.h" // irq_disable +#include "command.h" // DECL_COMMAND +#include "sched.h" // struct timer + +struct buttons { + struct timer time; + uint32_t rest_ticks; + uint8_t pressed, last_pressed; + uint8_t report_count, reports[8]; + uint8_t ack_count, retransmit_state, retransmit_count; + uint8_t button_count; + struct gpio_in pins[0]; +}; + +enum { BF_NO_RETRANSMIT = 0x80, BF_PENDING = 0xff, BF_ACKED = 0xfe }; + +static struct task_wake buttons_wake; + +static uint_fast8_t +buttons_event(struct timer *t) +{ + struct buttons *b = container_of(t, struct buttons, time); + + // Read pins + uint8_t i, bit, status = 0; + for (i = 0, bit = 1; i < b->button_count; i++, bit <<= 1) { + uint8_t val = gpio_in_read(b->pins[i]); + if (val) + status |= bit; + } + + // Check if any pins have changed since last time + uint8_t diff = status ^ b->pressed; + if (diff) { + // At least one pin has changed - do button debouncing + uint8_t debounced = ~(status ^ b->last_pressed); + if (diff & debounced) { + // Pin has been consistently different - report it + b->pressed = (b->pressed & ~debounced) | (status & debounced); + if (b->report_count < sizeof(b->reports)) { + b->reports[b->report_count++] = b->pressed; + sched_wake_task(&buttons_wake); + b->retransmit_state = BF_PENDING; + } + } + } + b->last_pressed = status; + + // Check if a retransmit is needed + uint8_t retransmit_state = b->retransmit_state; + if (!(retransmit_state & BF_NO_RETRANSMIT)) { + retransmit_state--; + if (retransmit_state & BF_NO_RETRANSMIT) + // timeout - do retransmit + sched_wake_task(&buttons_wake); + b->retransmit_state = retransmit_state; + } + + // Reschedule timer + b->time.waketime += b->rest_ticks; + return SF_RESCHEDULE; +} + +void +command_config_buttons(uint32_t *args) +{ + uint8_t button_count = args[1]; + if (button_count > 8) + shutdown("Max of 8 buttons"); + struct buttons *b = oid_alloc( + args[0], command_config_buttons + , sizeof(*b) + sizeof(b->pins[0]) * button_count); + b->button_count = button_count; + b->time.func = buttons_event; +} +DECL_COMMAND(command_config_buttons, "config_buttons oid=%c button_count=%c"); + +void +command_buttons_add(uint32_t *args) +{ + struct buttons *b = oid_lookup(args[0], command_config_buttons); + uint8_t pos = args[1]; + if (pos >= b->button_count) + shutdown("Set button past maximum button count"); + b->pins[pos] = gpio_in_setup(args[2], args[3]); +} +DECL_COMMAND(command_buttons_add, + "buttons_add oid=%c pos=%c pin=%u pull_up=%c"); + +void +command_buttons_query(uint32_t *args) +{ + struct buttons *b = oid_lookup(args[0], command_config_buttons); + sched_del_timer(&b->time); + b->time.waketime = args[1]; + b->rest_ticks = args[2]; + b->pressed = b->last_pressed = args[4]; + b->ack_count = b->report_count = 0; + b->retransmit_state = BF_ACKED; + b->retransmit_count = args[3]; + if (b->retransmit_count >= BF_NO_RETRANSMIT) + shutdown("Invalid buttons retransmit count"); + if (! b->rest_ticks) + return; + sched_add_timer(&b->time); +} +DECL_COMMAND(command_buttons_query, + "buttons_query oid=%c clock=%u rest_ticks=%u retransmit_count=%c" + " invert=%c"); + +void +command_buttons_ack(uint32_t *args) +{ + struct buttons *b = oid_lookup(args[0], command_config_buttons); + uint8_t count = args[1]; + b->ack_count += count; + irq_disable(); + if (count >= b->report_count) { + b->report_count = 0; + b->retransmit_state = BF_ACKED; + } else { + uint8_t pending = b->report_count - count, i; + for (i=0; ireports[i] = b->reports[i+count]; + b->report_count = pending; + } + irq_enable(); +} +DECL_COMMAND(command_buttons_ack, "buttons_ack oid=%c count=%c"); + +void +buttons_task(void) +{ + if (!sched_check_wake(&buttons_wake)) + return; + uint8_t oid; + struct buttons *b; + foreach_oid(oid, b, command_config_buttons) { + // See if need to transmit buttons_state + if (b->retransmit_state != BF_PENDING) + continue; + // Generate message + irq_disable(); + uint8_t report_count = b->report_count; + if (!report_count) { + irq_enable(); + continue; + } + b->retransmit_state = b->retransmit_count; + irq_enable(); + sendf("buttons_state oid=%c ack_count=%c state=%*s" + , oid, b->ack_count, report_count, b->reports); + } +} +DECL_TASK(buttons_task); diff --git a/pool/shard008/C/0130506_bluetooth.c b/pool/shard008/C/0130506_bluetooth.c new file mode 100644 index 0000000000000000000000000000000000000000..c5ee86b308f96688c6c4798abc2d126dad187b41 --- /dev/null +++ b/pool/shard008/C/0130506_bluetooth.c @@ -0,0 +1,209 @@ +/* + * This file is part of the Soletta™ Project + * + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#define SOL_LOG_DOMAIN &_log_domain +#include "sol-log-internal.h" +SOL_LOG_INTERNAL_DECLARE_STATIC(_log_domain, "linux-micro-bluetooth"); + +#include "sol-mainloop.h" +#include "sol-platform-linux-micro.h" +#include "sol-util-internal.h" + +static struct sol_platform_linux_fork_run *fork_run; +static const char *name; + +static void on_dbus_service_state_changed(void *data, + const char *service, + enum sol_platform_service_state state); + +static void +on_fork(void *data) +{ + unsigned i; + + static const char *daemon_possible_paths[] = { + "/usr/libexec/bluetooth/bluetoothd", // fedora/yocto-style + "/usr/lib/bluetooth/bluetoothd", // arch-style + "/usr/sbin/bluetoothd" // debian-style + }; + + const char *argv[] = { + NULL, // waiting to be set + "--nodetach", + NULL + }; + + static const char *envp[] = { + "BLUETOOTH_SYSTEM_BUS_ADDRESS=unix:path=/run/dbus/system_bus_socket", + NULL + }; + + for (i = 0; i < sol_util_array_size(daemon_possible_paths); i++) { + argv[0] = daemon_possible_paths[i]; + SOL_INF("attempting to exec %s", daemon_possible_paths[i]); + execvpe(argv[0], (char *const *)argv, (char *const *)envp); + } + + SOL_INF("bluetooth daemon executable not found, aborting"); + sol_platform_linux_fork_run_exit(EXIT_FAILURE); +} + +static void +on_fork_exit(void *data, uint64_t pid, int status) +{ + SOL_DBG("bluetooth-daemon pid=%" PRIu64 " exited with status=%d", + pid, status); + + if (status) + sol_platform_linux_micro_inform_service_state + (name, SOL_PLATFORM_SERVICE_STATE_FAILED); + else + sol_platform_linux_micro_inform_service_state + (name, SOL_PLATFORM_SERVICE_STATE_INACTIVE); +} + +static int +fork_run_do(void) +{ + if (fork_run) + return 0; + + fork_run = sol_platform_linux_fork_run(on_fork, on_fork_exit, NULL); + if (!fork_run) { + sol_platform_linux_micro_inform_service_state + (name, SOL_PLATFORM_SERVICE_STATE_FAILED); + return -errno; + } + + SOL_DBG("bluetooth-daemon started as pid=%" PRIu64, + (uint64_t)sol_platform_linux_fork_run_get_pid(fork_run)); + + sol_platform_linux_micro_inform_service_state + (name, SOL_PLATFORM_SERVICE_STATE_ACTIVE); + + return 0; +} + +static int +bluetooth_stop(const struct sol_platform_linux_micro_module *mod, + const char *service, + bool force_immediate) +{ + static const char *DBUS = "dbus"; + int err = 0; + + if (!fork_run) + return 0; + + if (!force_immediate) + err = sol_platform_linux_fork_run_send_signal(fork_run, SIGTERM); + else { + sol_platform_linux_fork_run_stop(fork_run); + fork_run = NULL; + } + + sol_platform_del_service_monitor + (on_dbus_service_state_changed, DBUS, NULL); + + return err; +} + +static void +on_dbus_service_state_changed(void *data, + const char *service, + enum sol_platform_service_state state) +{ + if (state == SOL_PLATFORM_SERVICE_STATE_ACTIVE) + fork_run_do(); + else if (state == SOL_PLATFORM_SERVICE_STATE_INACTIVE + || state == SOL_PLATFORM_SERVICE_STATE_FAILED) + bluetooth_stop(data, name, true); +} + +static int +bluetooth_start(const struct sol_platform_linux_micro_module *mod, + const char *service) +{ + int ret = 0; + static const char *DBUS = "dbus"; + enum sol_platform_service_state state = SOL_PLATFORM_SERVICE_STATE_ACTIVE; + + name = service; + + if (fork_run) + return 0; + + ret = sol_platform_add_service_monitor + (on_dbus_service_state_changed, DBUS, mod); + SOL_INT_CHECK_GOTO(ret, < 0, err); + + ret = sol_platform_start_service(DBUS); + if (ret < 0) { + SOL_WRN("D-Bus service is a dependency for bluetooth and could" + " not be started"); + sol_platform_del_service_monitor + (on_dbus_service_state_changed, DBUS, NULL); + goto err; + } + + state = sol_platform_get_service_state(DBUS); + if (state == SOL_PLATFORM_SERVICE_STATE_ACTIVE) + return fork_run_do(); + + return 0; /* wait for dep to activate */ + +err: + sol_platform_linux_micro_inform_service_state + (service, SOL_PLATFORM_SERVICE_STATE_FAILED); + return ret; +} + +static int +bluetooth_restart(const struct sol_platform_linux_micro_module *mod, + const char *service) +{ + if (!fork_run) + return bluetooth_start(mod, service); + + return sol_platform_linux_fork_run_send_signal(fork_run, SIGHUP); +} + +static int +bluetooth_init(const struct sol_platform_linux_micro_module *module, + const char *service) +{ + SOL_LOG_INTERNAL_INIT_ONCE; + return 0; +} + +SOL_PLATFORM_LINUX_MICRO_MODULE(BLUETOOTH, + .name = "bluetooth", + .init = bluetooth_init, + .start = bluetooth_start, + .stop = bluetooth_stop, + .restart = bluetooth_restart, + ); diff --git a/pool/shard008/C/0130508_heap_conv.c b/pool/shard008/C/0130508_heap_conv.c new file mode 100644 index 0000000000000000000000000000000000000000..dbf059a424417bb38680812c571b01997cda4871 --- /dev/null +++ b/pool/shard008/C/0130508_heap_conv.c @@ -0,0 +1,96 @@ +/*- + * See the file LICENSE for redistribution information. + * + * Copyright (c) 2010, 2015 Oracle and/or its affiliates. All rights reserved. + */ + +#include "db_config.h" + +#include "db_int.h" +#include "dbinc/db_page.h" +#include "dbinc/db_swap.h" +#include "dbinc/heap.h" + +/* + * __heap_pgin -- + * Convert host-specific page layout from the host-independent format + * stored on disk. + * + * PUBLIC: int __heap_pgin __P((DB *, db_pgno_t, void *, DBT *)); + */ +int +__heap_pgin(dbp, pg, pp, cookie) + DB *dbp; + db_pgno_t pg; + void *pp; + DBT *cookie; +{ + DB_PGINFO *pginfo; + PAGE *h; + + pginfo = (DB_PGINFO *)cookie->data; + if (!F_ISSET(pginfo, DB_AM_SWAP)) + return (0); + + h = pp; + return (TYPE(h) == P_HEAPMETA ? __heap_mswap(dbp->env, pp) : + __db_byteswap(dbp, pg, pp, pginfo->db_pagesize, 1)); +} + +/* + * __heap_pgout -- + * Convert host-specific page layout from the host-independent format + * stored on disk. + * + * PUBLIC: int __heap_pgout __P((DB *, db_pgno_t, void *, DBT *)); + */ +int +__heap_pgout(dbp, pg, pp, cookie) + DB *dbp; + db_pgno_t pg; + void *pp; + DBT *cookie; +{ + DB_PGINFO *pginfo; + PAGE *h; + + pginfo = (DB_PGINFO *)cookie->data; + if (!F_ISSET(pginfo, DB_AM_SWAP)) + return (0); + + h = pp; + return (TYPE(h) == P_HEAPMETA ? __heap_mswap(dbp->env, pp) : + __db_byteswap(dbp, pg, pp, pginfo->db_pagesize, 0)); +} + +/* + * __heap_mswap -- + * Swap the bytes on the heap metadata page. + * + * PUBLIC: int __heap_mswap __P((ENV *, PAGE *)); + */ +int +__heap_mswap(env, pg) + ENV *env; + PAGE *pg; +{ + u_int8_t *p; + + COMPQUIET(env, NULL); + + __db_metaswap(pg); + p = (u_int8_t *)pg + sizeof(DBMETA); + + SWAP32(p); /* curregion */ + SWAP32(p); /* nregions */ + SWAP32(p); /* gbytes */ + SWAP32(p); /* bytes */ + SWAP32(p); /* region_size */ + SWAP32(p); /* threshold */ + SWAP32(p); /* file id lo */ + SWAP32(p); /* file id hi */ + p += 89 * sizeof(u_int32_t); /* unused */ + SWAP32(p); /* crypto_magic */ + + return (0); +} diff --git a/pool/shard008/C/0130510_il_val.c b/pool/shard008/C/0130510_il_val.c new file mode 100644 index 0000000000000000000000000000000000000000..d62b0bb301d03fe3fe29721b3b061fa84aea1fe6 --- /dev/null +++ b/pool/shard008/C/0130510_il_val.c @@ -0,0 +1,64 @@ +/****************************************************************************** + * Automatically generated file. Please don't change anything. * + *****************************************************************************/ + +#include + +#include +#include + +#include "iup.h" +#include "iuplua.h" +#include "il.h" + + +static int val_button_press_cb(Ihandle *self, double p0) +{ + lua_State *L = iuplua_call_start(self, "button_press_cb"); + lua_pushnumber(L, p0); + return iuplua_call(L, 1); +} + +static int val_mousemove_cb(Ihandle *self, double p0) +{ + lua_State *L = iuplua_call_start(self, "mousemove_cb"); + lua_pushnumber(L, p0); + return iuplua_call(L, 1); +} + +static int val_button_release_cb(Ihandle *self, double p0) +{ + lua_State *L = iuplua_call_start(self, "button_release_cb"); + lua_pushnumber(L, p0); + return iuplua_call(L, 1); +} + +static int Val(lua_State *L) +{ + Ihandle *ih = IupVal((char *)luaL_optstring(L, 1, NULL)); + iuplua_plugstate(L, ih); + iuplua_pushihandle_raw(L, ih); + return 1; +} + +int iupvallua_open(lua_State * L) +{ + iuplua_register(L, Val, "Val"); + + iuplua_register_cb(L, "BUTTON_PRESS_CB", (lua_CFunction)val_button_press_cb, NULL); + iuplua_register_cb(L, "MOUSEMOVE_CB", (lua_CFunction)val_mousemove_cb, "val"); + iuplua_register_cb(L, "BUTTON_RELEASE_CB", (lua_CFunction)val_button_release_cb, NULL); + +#ifdef IUPLUA_USELOH +#include "val.loh" +#else +#ifdef IUPLUA_USELH +#include "val.lh" +#else + iuplua_dofile(L, "val.lua"); +#endif +#endif + + return 0; +} + diff --git a/pool/shard008/C/0130513_latticetune.c b/pool/shard008/C/0130513_latticetune.c new file mode 100644 index 0000000000000000000000000000000000000000..96c40ac5fac94db5038826e98f768e422502aacf --- /dev/null +++ b/pool/shard008/C/0130513_latticetune.c @@ -0,0 +1,164 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2001 * + * by the Xiph.Org Foundation http://www.xiph.org/ * + * * + ******************************************************************** + + function: utility main for setting entropy encoding parameters + for lattice codebooks + last mod: $Id: latticetune.c,v 1.7 2008-02-02 15:54:08 richardash1981 Exp $ + + ********************************************************************/ + +#include +#include +#include +#include +#include +#include "bookutil.h" + +static int strrcmp_i(char *s,char *cmp){ + return(strncmp(s+strlen(s)-strlen(cmp),cmp,strlen(cmp))); +} + +/* This util takes a training-collected file listing codewords used in + LSP fitting, then generates new codeword lengths for maximally + efficient integer-bits entropy encoding. + + command line: + latticetune book.vqh input.vqd [unused_entriesp] + + latticetune produces book.vqh on stdout */ + +int main(int argc,char *argv[]){ + codebook *b; + static_codebook *c; + long *lengths; + long *hits; + + int entries=-1,dim=-1,guard=1; + FILE *in=NULL; + char *line,*name; + long j; + + if(argv[1]==NULL){ + fprintf(stderr,"Need a lattice codebook on the command line.\n"); + exit(1); + } + if(argv[2]==NULL){ + fprintf(stderr,"Need a codeword data file on the command line.\n"); + exit(1); + } + if(argv[3]!=NULL)guard=0; + + { + char *ptr; + char *filename=strdup(argv[1]); + + b=codebook_load(filename); + c=(static_codebook *)(b->c); + + ptr=strrchr(filename,'.'); + if(ptr){ + *ptr='\0'; + name=strdup(filename); + }else{ + name=strdup(filename); + } + } + + if(c->maptype!=1){ + fprintf(stderr,"Provided book is not a latticebook.\n"); + exit(1); + } + + entries=b->entries; + dim=b->dim; + + hits=_ogg_malloc(entries*sizeof(long)); + lengths=_ogg_calloc(entries,sizeof(long)); + for(j=0;jlengthlist=lengths; + write_codebook(stdout,name,c); + + { + long bins=_book_maptype1_quantvals(c); + long i,k,base=c->lengthlist[0]; + for(i=0;ilengthlist[i]>base)base=c->lengthlist[i]; + + for(j=0;jlengthlist[j]){ + int indexdiv=1; + fprintf(stderr,"%4ld: ",j); + for(k=0;kdim;k++){ + int index= (j/indexdiv)%bins; + fprintf(stderr,"%+3.1f,", c->quantlist[index]*_float32_unpack(c->q_delta)+ + _float32_unpack(c->q_min)); + indexdiv*=bins; + } + fprintf(stderr,"\t|"); + for(k=0;klengthlist[j];k++)fprintf(stderr,"*"); + fprintf(stderr,"\n"); + } + } + } + + fprintf(stderr,"\r " + "\nDone.\n"); + exit(0); +} diff --git a/pool/shard008/C/0130514_php_http_client_response.c b/pool/shard008/C/0130514_php_http_client_response.c new file mode 100644 index 0000000000000000000000000000000000000000..722b4e03ac1b58494593f0a35430098f76be3b72 --- /dev/null +++ b/pool/shard008/C/0130514_php_http_client_response.c @@ -0,0 +1,150 @@ +/* + +--------------------------------------------------------------------+ + | PECL :: http | + +--------------------------------------------------------------------+ + | Redistribution and use in source and binary forms, with or without | + | modification, are permitted provided that the conditions mentioned | + | in the accompanying LICENSE file are met. | + +--------------------------------------------------------------------+ + | Copyright (c) 2004-2014, Michael Wallner | + +--------------------------------------------------------------------+ +*/ + +#include "php_http_api.h" + +static zend_class_entry *php_http_client_response_class_entry; +zend_class_entry *php_http_get_client_response_class_entry(void) +{ + return php_http_client_response_class_entry; +} + +ZEND_BEGIN_ARG_INFO_EX(ai_HttpClientResponse_getCookies, 0, 0, 0) + ZEND_ARG_INFO(0, flags) + ZEND_ARG_INFO(0, allowed_extras) +ZEND_END_ARG_INFO(); +static PHP_METHOD(HttpClientResponse, getCookies) +{ + zend_long flags = 0; + zval *allowed_extras_array = NULL; + int i = 0; + char **allowed_extras = NULL; + zval *header = NULL, *entry = NULL; + php_http_message_object_t *msg; + + if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "|la!/", &flags, &allowed_extras_array)) { + return; + } + + msg = PHP_HTTP_OBJ(NULL, getThis()); + array_init(return_value); + + if (allowed_extras_array) { + /* FIXME: use zend_string** instead of char** */ + allowed_extras = ecalloc(zend_hash_num_elements(Z_ARRVAL_P(allowed_extras_array)) + 1, sizeof(char *)); + ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(allowed_extras_array), entry) + { + zend_string *zs = zval_get_string(entry); + allowed_extras[i++] = estrndup(zs->val, zs->len); + zend_string_release(zs); + } + ZEND_HASH_FOREACH_END(); + } + + if ((header = php_http_message_header(msg->message, ZEND_STRL("Set-Cookie")))) { + php_http_cookie_list_t *list; + + if (Z_TYPE_P(header) == IS_ARRAY) { + zval *single_header; + + ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(header), single_header) + { + zend_string *zs = zval_get_string(single_header); + + if ((list = php_http_cookie_list_parse(NULL, zs->val, zs->len, flags, allowed_extras))) { + zval cookie; + + ZVAL_OBJ(&cookie, &php_http_cookie_object_new_ex(php_http_cookie_get_class_entry(), list)->zo); + add_next_index_zval(return_value, &cookie); + } + zend_string_release(zs); + } + ZEND_HASH_FOREACH_END(); + } else { + zend_string *zs = zval_get_string(header); + + if ((list = php_http_cookie_list_parse(NULL, zs->val, zs->len, flags, allowed_extras))) { + zval cookie; + + ZVAL_OBJ(&cookie, &php_http_cookie_object_new_ex(php_http_cookie_get_class_entry(), list)->zo); + add_next_index_zval(return_value, &cookie); + } + zend_string_release(zs); + } + } + + if (allowed_extras) { + for (i = 0; allowed_extras[i]; ++i) { + efree(allowed_extras[i]); + } + efree(allowed_extras); + } +} + +ZEND_BEGIN_ARG_INFO_EX(ai_HttpClientResponse_getTransferInfo, 0, 0, 0) + ZEND_ARG_INFO(0, element) +ZEND_END_ARG_INFO(); +static PHP_METHOD(HttpClientResponse, getTransferInfo) +{ + char *info_name = NULL; + size_t info_len = 0; + zval info_tmp, info_name_tmp, *info; + + php_http_expect(SUCCESS == zend_parse_parameters(ZEND_NUM_ARGS(), "|s", &info_name, &info_len), invalid_arg, return); + + info = zend_read_property(php_http_client_response_class_entry, Z_OBJ_P(ZEND_THIS), ZEND_STRL("transferInfo"), 0, &info_tmp); + + /* request completed? */ + if (Z_TYPE_P(info) != IS_OBJECT) { + php_http_throw(bad_method_call, "Incomplete state"); + return; + } + + if (info_len && info_name) { + info = zend_read_property(NULL, Z_OBJ_P(info), php_http_pretty_key(info_name, info_len, 0, 0), info_len, 0, &info_name_tmp); + + if (!info) { + php_http_throw(unexpected_val, "Could not find transfer info with name '%s'", info_name); + return; + } + } + + RETURN_ZVAL(info, 1, 0); +} + +static zend_function_entry php_http_client_response_methods[] = { + PHP_ME(HttpClientResponse, getCookies, ai_HttpClientResponse_getCookies, ZEND_ACC_PUBLIC) + PHP_ME(HttpClientResponse, getTransferInfo, ai_HttpClientResponse_getTransferInfo, ZEND_ACC_PUBLIC) + EMPTY_FUNCTION_ENTRY +}; + +PHP_MINIT_FUNCTION(http_client_response) +{ + zend_class_entry ce = {0}; + + INIT_NS_CLASS_ENTRY(ce, "http\\Client", "Response", php_http_client_response_methods); + php_http_client_response_class_entry = zend_register_internal_class_ex(&ce, php_http_message_get_class_entry()); + + zend_declare_property_null(php_http_client_response_class_entry, ZEND_STRL("transferInfo"), ZEND_ACC_PROTECTED); + + return SUCCESS; +} + +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: noet sw=4 ts=4 fdm=marker + * vim<600: noet sw=4 ts=4 + */ + diff --git a/pool/shard008/C/0130517_cpuinfo.c b/pool/shard008/C/0130517_cpuinfo.c new file mode 100644 index 0000000000000000000000000000000000000000..5379e13e2b26b385deb2ad85f57e575d9402019b --- /dev/null +++ b/pool/shard008/C/0130517_cpuinfo.c @@ -0,0 +1,144 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * PXA CPU information display + * + * Copyright (C) 2011 Marek Vasut + */ + +#include +#include +#include +#include + +#ifdef CONFIG_CPU_PXA25X +#if ((CONFIG_SYS_INIT_SP_ADDR) != 0xfffff800) +#error "Init SP address must be set to 0xfffff800 for PXA250" +#endif +#endif + +#define CPU_MASK_PXA_PRODID 0x000003f0 +#define CPU_MASK_PXA_REVID 0x0000000f + +#define CPU_MASK_PRODREV (CPU_MASK_PXA_PRODID | CPU_MASK_PXA_REVID) + +#define CPU_VALUE_PXA25X 0x100 +#define CPU_VALUE_PXA27X 0x110 + +static uint32_t pxa_get_cpuid(void) +{ + uint32_t cpuid; + asm volatile("mrc p15, 0, %0, c0, c0, 0" : "=r"(cpuid)); + return cpuid; +} + +int cpu_is_pxa25x(void) +{ + uint32_t id = pxa_get_cpuid(); + id &= CPU_MASK_PXA_PRODID; + return id == CPU_VALUE_PXA25X; +} + +int cpu_is_pxa27x(void) +{ + uint32_t id = pxa_get_cpuid(); + id &= CPU_MASK_PXA_PRODID; + return id == CPU_VALUE_PXA27X; +} + +int cpu_is_pxa27xm(void) +{ + uint32_t id = pxa_get_cpuid(); + return ((id & CPU_MASK_PXA_PRODID) == CPU_VALUE_PXA27X) && + ((id & CPU_MASK_PXA_REVID) == 8); +} + +uint32_t pxa_get_cpu_revision(void) +{ + return pxa_get_cpuid() & CPU_MASK_PRODREV; +} + +#ifdef CONFIG_DISPLAY_CPUINFO +static const char *pxa25x_get_revision(void) +{ + static __maybe_unused const char * const revs_25x[] = { "A0" }; + static __maybe_unused const char * const revs_26x[] = { + "A0", "B0", "B1" + }; + static const char *unknown = "Unknown"; + uint32_t id; + + if (!cpu_is_pxa25x()) + return unknown; + + id = pxa_get_cpuid() & CPU_MASK_PXA_REVID; + +/* PXA26x is a sick special case as it can't be told apart from PXA25x :-( */ +#ifdef CONFIG_CPU_PXA26X + switch (id) { + case 3: return revs_26x[0]; + case 5: return revs_26x[1]; + case 6: return revs_26x[2]; + } +#else + if (id == 6) + return revs_25x[0]; +#endif + return unknown; +} + +static const char *pxa27x_get_revision(void) +{ + static const char *const rev[] = { "A0", "A1", "B0", "B1", "C0", "C5" }; + static const char *unknown = "Unknown"; + uint32_t id; + + if (!cpu_is_pxa27x()) + return unknown; + + id = pxa_get_cpuid() & CPU_MASK_PXA_REVID; + + if ((id == 5) || (id == 6) || (id > 8)) + return unknown; + + /* Cap the special PXA270 C5 case. */ + if (id == 7) + id = 5; + + /* Cap the special PXA270M A1 case. */ + if (id == 8) + id = 1; + + return rev[id]; +} + +static int print_cpuinfo_pxa2xx(void) +{ + if (cpu_is_pxa25x()) { + puts("Marvell PXA25x rev. "); + puts(pxa25x_get_revision()); + } else if (cpu_is_pxa27x()) { + puts("Marvell PXA27x"); + if (cpu_is_pxa27xm()) puts("M"); + puts(" rev. "); + puts(pxa27x_get_revision()); + } else + return -EINVAL; + + puts("\n"); + + return 0; +} + +int print_cpuinfo(void) +{ + int ret; + + puts("CPU: "); + + ret = print_cpuinfo_pxa2xx(); + if (!ret) + return ret; + + return ret; +} +#endif diff --git a/pool/shard008/C/0130518_cr-num.c b/pool/shard008/C/0130518_cr-num.c new file mode 100644 index 0000000000000000000000000000000000000000..6cc5150a16d6ac0df4a001d563d1fa8735c0edf1 --- /dev/null +++ b/pool/shard008/C/0130518_cr-num.c @@ -0,0 +1,315 @@ +/* -*- Mode: C; indent-tabs-mode:nil; c-basic-offset: 8-*- */ + +/* + * This file is part of The Croco Library + * + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of version 2.1 of the GNU Lesser General Public + * License as published by the Free Software Foundation. + * + * 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 Lesser General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * Author: Dodji Seketeli + * See COPYRIGHTS file for copyrights information. + */ + +/** + *@CRNum: + * + *The definition + *of the #CRNum class. + */ + +#include "cr-num.h" +#include "string.h" + +/** + * cr_num_new: + * + *#CRNum. + * + *Returns the newly built instance of + *#CRNum. + */ +CRNum * +cr_num_new (void) +{ + CRNum *result = NULL; + + result = g_try_malloc (sizeof (CRNum)); + + if (result == NULL) { + cr_utils_trace_info ("Out of memory"); + return NULL; + } + + memset (result, 0, sizeof (CRNum)); + + return result; +} + +/** + * cr_num_new_with_val: + * @a_val: the numerical value of the number. + * @a_type: the type of number. + * + * A constructor of #CRNum. + * + * Returns the newly built instance of #CRNum or + * NULL if an error arises. + */ +CRNum * +cr_num_new_with_val (gdouble a_val, enum CRNumType a_type) +{ + CRNum *result = NULL; + + result = cr_num_new (); + + g_return_val_if_fail (result, NULL); + + result->val = a_val; + result->type = a_type; + + return result; +} + +/** + * cr_num_to_string: + *@a_this: the current instance of #CRNum. + * + *Returns the newly built string representation + *of the current instance of #CRNum. The returned + *string is NULL terminated. The caller *must* + *free the returned string. + */ +guchar * +cr_num_to_string (CRNum const * a_this) +{ + gdouble test_val = 0.0; + + guchar *tmp_char1 = NULL, + *tmp_char2 = NULL, + *result = NULL; + + g_return_val_if_fail (a_this, NULL); + + test_val = a_this->val - (glong) a_this->val; + + if (!test_val) { + tmp_char1 = (guchar *) g_strdup_printf ("%ld", (glong) a_this->val); + } else { + /* We can't use g_ascii_dtostr, because that sometimes uses + e notation (which wouldn't be a valid number in CSS). */ + size_t const buflen = 35; /* fairly arbitrary. */ + tmp_char1 = (guchar *)g_malloc (buflen); + g_ascii_formatd ((gchar *)tmp_char1, buflen, "%.17f", a_this->val); + } + + g_return_val_if_fail (tmp_char1, NULL); + + switch (a_this->type) { + case NUM_LENGTH_EM: + tmp_char2 = (guchar *) "em"; + break; + + case NUM_LENGTH_EX: + tmp_char2 = (guchar *) "ex"; + break; + + case NUM_LENGTH_PX: + tmp_char2 = (guchar *) "px"; + break; + + case NUM_LENGTH_IN: + tmp_char2 = (guchar *) "in"; + break; + + case NUM_LENGTH_CM: + tmp_char2 = (guchar *) "cm"; + break; + + case NUM_LENGTH_MM: + tmp_char2 = (guchar *) "mm"; + break; + + case NUM_LENGTH_PT: + tmp_char2 = (guchar *) "pt"; + break; + + case NUM_LENGTH_PC: + tmp_char2 = (guchar *) "pc"; + break; + + case NUM_ANGLE_DEG: + tmp_char2 = (guchar *) "deg"; + break; + + case NUM_ANGLE_RAD: + tmp_char2 = (guchar *) "rad"; + break; + + case NUM_ANGLE_GRAD: + tmp_char2 = (guchar *) "grad"; + break; + + case NUM_TIME_MS: + tmp_char2 = (guchar *) "ms"; + break; + + case NUM_TIME_S: + tmp_char2 = (guchar *) "s"; + break; + + case NUM_FREQ_HZ: + tmp_char2 = (guchar *) "Hz"; + break; + + case NUM_FREQ_KHZ: + tmp_char2 = (guchar *) "KHz"; + break; + + case NUM_PERCENTAGE: + tmp_char2 = (guchar *) "%"; + break; + case NUM_INHERIT: + tmp_char2 = (guchar *) "inherit"; + break ; + case NUM_AUTO: + tmp_char2 = (guchar *) "auto"; + break ; + case NUM_GENERIC: + tmp_char2 = NULL ; + break ; + default: + tmp_char2 = (guchar *) "unknown"; + break; + } + + if (tmp_char2) { + result = (guchar *) g_strconcat ((gchar *) tmp_char1, tmp_char2, NULL); + g_free (tmp_char1); + } else { + result = tmp_char1; + } + + return result; +} + +/** + * cr_num_copy: + *@a_src: the instance of #CRNum to copy. + *Must be non NULL. + *@a_dest: the destination of the copy. + *Must be non NULL + * + *Copies an instance of #CRNum. + * + *Returns CR_OK upon successful completion, an + *error code otherwise. + */ +enum CRStatus +cr_num_copy (CRNum * a_dest, CRNum const * a_src) +{ + g_return_val_if_fail (a_dest && a_src, CR_BAD_PARAM_ERROR); + + memcpy (a_dest, a_src, sizeof (CRNum)); + + return CR_OK; +} + +/** + * cr_num_dup: + *@a_this: the instance of #CRNum to duplicate. + * + *Duplicates an instance of #CRNum + * + *Returns the newly created (duplicated) instance of #CRNum. + *Must be freed by cr_num_destroy(). + */ +CRNum * +cr_num_dup (CRNum const * a_this) +{ + CRNum *result = NULL; + enum CRStatus status = CR_OK; + + g_return_val_if_fail (a_this, NULL); + + result = cr_num_new (); + g_return_val_if_fail (result, NULL); + + status = cr_num_copy (result, a_this); + g_return_val_if_fail (status == CR_OK, NULL); + + return result; +} + +/** + * cr_num_set: + *Sets an instance of #CRNum. + *@a_this: the current instance of #CRNum to be set. + *@a_val: the new numerical value to be hold by the current + *instance of #CRNum + *@a_type: the new type of #CRNum. + * + * Returns CR_OK upon succesful completion, an error code otherwise. + */ +enum CRStatus +cr_num_set (CRNum * a_this, gdouble a_val, enum CRNumType a_type) +{ + g_return_val_if_fail (a_this, CR_BAD_PARAM_ERROR); + + a_this->val = a_val; + a_this->type = a_type; + + return CR_OK; +} + +/** + * cr_num_is_fixed_length: + * @a_this: the current instance of #CRNum . + * + *Tests if the current instance of #CRNum is a fixed + *length value or not. Typically a fixed length value + *is anything from NUM_LENGTH_EM to NUM_LENGTH_PC. + *See the definition of #CRNumType to see what we mean. + * + *Returns TRUE if the instance of #CRNum is a fixed length number, + *FALSE otherwise. + */ +gboolean +cr_num_is_fixed_length (CRNum const * a_this) +{ + gboolean result = FALSE; + + g_return_val_if_fail (a_this, FALSE); + + if (a_this->type >= NUM_LENGTH_EM + && a_this->type <= NUM_LENGTH_PC) { + result = TRUE ; + } + return result ; +} + +/** + * cr_num_destroy: + *@a_this: the this pointer of + *the current instance of #CRNum. + * + *The destructor of #CRNum. + */ +void +cr_num_destroy (CRNum * a_this) +{ + g_return_if_fail (a_this); + + g_free (a_this); +} diff --git a/pool/shard008/C/0130524_filecache.c b/pool/shard008/C/0130524_filecache.c new file mode 100644 index 0000000000000000000000000000000000000000..be03c1e5afd7f5b77b345e7cac52ef7c2318048c --- /dev/null +++ b/pool/shard008/C/0130524_filecache.c @@ -0,0 +1,196 @@ +/* + * Copyright (c) 2010, 2018, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#include +#include +#include +#include +#include + +#define DEFAULT_BUFFER_SIZE 4096 +static const char *tempDir = NULL; + +struct _Cache +{ + char* filename; + int readHandle; + int writeHandle; + + gint64 read_position; + gint64 write_position; +}; + +void cache_static_init(void) +{ + tempDir = g_get_tmp_dir(); +} + +Cache* create_cache() +{ + Cache* result= (Cache*)g_try_malloc(sizeof(Cache)); + if (result) + { + result->filename = g_build_filename(tempDir, "jfxmpbXXXXXX", NULL); + if (result->filename == NULL) + goto _error_exit; + else + { + result->writeHandle = g_mkstemp_full(result->filename, O_RDWR, S_IRUSR|S_IWUSR); + result->readHandle = open(result->filename, O_RDONLY, 0); + + if(result->writeHandle < 0 || result->readHandle < 0) + goto _error_exit; + + if (unlink(result->filename) < 0) + { + close (result->writeHandle); + close (result->readHandle); + goto _error_exit; + } + + result->read_position = result->write_position = 0; + } + } + return result; + +_error_exit: + g_free(result); + return NULL; +} + +void destroy_cache(Cache* instance) +{ + close(instance->writeHandle); + close(instance->readHandle); + g_free(instance->filename); + + g_free(instance); +} + +void cache_write_buffer(Cache* cache, GstBuffer* buffer) +{ + GstMapInfo info; + if (gst_buffer_map(buffer, &info, GST_MAP_READ)) + { + ssize_t written = write(cache->writeHandle, info.data, info.size); + if (written > 0) + cache->write_position += written; + gst_buffer_unmap(buffer, &info); + } +} + +gint64 cache_read_buffer(Cache* cache, GstBuffer** buffer) +{ + guint8 *data = (guint8*)g_try_malloc(DEFAULT_BUFFER_SIZE); + *buffer = NULL; + + if (data) + { + ssize_t size = 0; + if ((cache->write_position - cache->read_position) > 0 && + (cache->write_position - cache->read_position) < DEFAULT_BUFFER_SIZE) + size = cache->write_position - cache->read_position; + else + size = DEFAULT_BUFFER_SIZE; + + ssize_t read_bytes = read(cache->readHandle, data, size); + if (read_bytes > 0) + { + *buffer = gst_buffer_new_wrapped_full(0, data, DEFAULT_BUFFER_SIZE, 0, read_bytes, data, g_free); + if (*buffer != NULL) + GST_BUFFER_OFFSET(*buffer) = cache->read_position; + + cache->read_position += read_bytes; + return cache->read_position; + } + else // read error, deleting buffer to avoid leaking. + g_free(data); + } + + return 0; +} + +GstFlowReturn cache_read_buffer_from_position(Cache* cache, gint64 start_position, guint size, GstBuffer** buffer) +{ + GstFlowReturn result = GST_FLOW_ERROR; + *buffer = NULL; + + if (cache_set_read_position(cache, start_position)) + { + guint8 *data = (guint8*)g_try_malloc(size); + if (data) + { + ssize_t read_bytes = read(cache->readHandle, data, size); + if (read_bytes == size) + { + *buffer = gst_buffer_new_wrapped_full(0, data, size, 0, read_bytes, data, g_free); + if (*buffer != NULL) + { + GST_BUFFER_OFFSET(*buffer) = cache->read_position; + result = GST_FLOW_OK; + } + } + else + g_free(data); // Wrong size, deleting buffer to avoid leaking. + + cache->read_position += read_bytes; + } + } + return result; +} + +static inline gboolean cache_set_handler_position(int handle, guint64 position) +{ + return lseek(handle, position, SEEK_SET) >= 0; +} + +gboolean cache_set_write_position(Cache* cache, gint64 position) +{ + gboolean result = (position == cache->write_position); + if (!result) + { + result = cache_set_handler_position(cache->writeHandle, position); + if (result) + cache->write_position = position; + } + return result; +} + +gboolean cache_set_read_position(Cache* cache, gint64 position) +{ + gboolean result = (position == cache->read_position); + if (!result) + { + result = cache_set_handler_position(cache->readHandle, position); + if (result) + cache->read_position = position; + } + return result; +} + +gboolean cache_has_enough_data(Cache* cache) +{ + return cache->read_position < cache->write_position; +} diff --git a/pool/shard008/C/0130525_timesyncd.c b/pool/shard008/C/0130525_timesyncd.c new file mode 100644 index 0000000000000000000000000000000000000000..1f59bf14e1aa59bc03dfe5bd74344d61c85a1ae7 --- /dev/null +++ b/pool/shard008/C/0130525_timesyncd.c @@ -0,0 +1,178 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include +#include + +#include "sd-daemon.h" +#include "sd-event.h" + +#include "capability-util.h" +#include "clock-util.h" +#include "daemon-util.h" +#include "fd-util.h" +#include "fs-util.h" +#include "main-func.h" +#include "mkdir.h" +#include "network-util.h" +#include "process-util.h" +#include "signal-util.h" +#include "timesyncd-bus.h" +#include "timesyncd-conf.h" +#include "timesyncd-manager.h" +#include "user-util.h" + +#define STATE_DIR "/var/lib/systemd/timesync" +#define CLOCK_FILE STATE_DIR "/clock" + +static int load_clock_timestamp(uid_t uid, gid_t gid) { + _cleanup_close_ int fd = -1; + usec_t min = TIME_EPOCH * USEC_PER_SEC; + usec_t ct; + int r; + + /* Let's try to make sure that the clock is always + * monotonically increasing, by saving the clock whenever we + * have a new NTP time, or when we shut down, and restoring it + * when we start again. This is particularly helpful on + * systems lacking a battery backed RTC. We also will adjust + * the time to at least the build time of systemd. */ + + fd = open(CLOCK_FILE, O_RDWR|O_CLOEXEC, 0644); + if (fd >= 0) { + struct stat st; + usec_t stamp; + + /* check if the recorded time is later than the compiled-in one */ + r = fstat(fd, &st); + if (r >= 0) { + stamp = timespec_load(&st.st_mtim); + if (stamp > min) + min = stamp; + } + + if (geteuid() == 0) { + /* Try to fix the access mode, so that we can still + touch the file after dropping privileges */ + r = fchmod_and_chown(fd, 0644, uid, gid); + if (r < 0) + log_warning_errno(r, "Failed to chmod or chown %s, ignoring: %m", CLOCK_FILE); + } + + } else { + r = mkdir_safe_label(STATE_DIR, 0755, uid, gid, + MKDIR_FOLLOW_SYMLINK | MKDIR_WARN_MODE); + if (r < 0) { + log_debug_errno(r, "Failed to create state directory, ignoring: %m"); + goto settime; + } + + /* create stamp file with the compiled-in date */ + r = touch_file(CLOCK_FILE, false, min, uid, gid, 0644); + if (r < 0) + log_debug_errno(r, "Failed to create %s, ignoring: %m", CLOCK_FILE); + } + +settime: + ct = now(CLOCK_REALTIME); + if (ct < min) { + struct timespec ts; + char date[FORMAT_TIMESTAMP_MAX]; + + log_info("System clock time unset or jumped backwards, restoring from recorded timestamp: %s", + format_timestamp(date, sizeof(date), min)); + + if (clock_settime(CLOCK_REALTIME, timespec_store(&ts, min)) < 0) + log_error_errno(errno, "Failed to restore system clock, ignoring: %m"); + } + + return 0; +} + +static int run(int argc, char *argv[]) { + _cleanup_(manager_freep) Manager *m = NULL; + _cleanup_(notify_on_cleanup) const char *notify_message = NULL; + const char *user = "systemd-timesync"; + uid_t uid, uid_current; + gid_t gid; + int r; + + log_set_facility(LOG_CRON); + log_setup_service(); + + umask(0022); + + if (argc != 1) + return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program does not take arguments."); + + uid = uid_current = geteuid(); + gid = getegid(); + + if (uid_current == 0) { + r = get_user_creds(&user, &uid, &gid, NULL, NULL, 0); + if (r < 0) + return log_error_errno(r, "Cannot resolve user name %s: %m", user); + } + + r = load_clock_timestamp(uid, gid); + if (r < 0) + return r; + + /* Drop privileges, but only if we have been started as root. If we are not running as root we assume all + * privileges are already dropped. */ + if (uid_current == 0) { + r = drop_privileges(uid, gid, (1ULL << CAP_SYS_TIME)); + if (r < 0) + return log_error_errno(r, "Failed to drop privileges: %m"); + } + + assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, -1) >= 0); + + r = manager_new(&m); + if (r < 0) + return log_error_errno(r, "Failed to allocate manager: %m"); + + r = manager_connect_bus(m); + if (r < 0) + return log_error_errno(r, "Could not connect to bus: %m"); + + if (clock_is_localtime(NULL) > 0) { + log_info("The system is configured to read the RTC time in the local time zone. " + "This mode cannot be fully supported. All system time to RTC updates are disabled."); + m->rtc_local_time = true; + } + + r = manager_parse_config_file(m); + if (r < 0) + log_warning_errno(r, "Failed to parse configuration file: %m"); + + r = manager_parse_fallback_string(m, NTP_SERVERS); + if (r < 0) + return log_error_errno(r, "Failed to parse fallback server strings: %m"); + + log_debug("systemd-timesyncd running as pid " PID_FMT, getpid_cached()); + + notify_message = notify_start("READY=1\n" + "STATUS=Daemon is running", + NOTIFY_STOPPING); + + if (network_is_online()) { + r = manager_connect(m); + if (r < 0) + return r; + } + + r = sd_event_loop(m->event); + if (r < 0) + return log_error_errno(r, "Failed to run event loop: %m"); + + /* if we got an authoritative time, store it in the file system */ + if (m->sync) { + r = touch(CLOCK_FILE); + if (r < 0) + log_debug_errno(r, "Failed to touch %s, ignoring: %m", CLOCK_FILE); + } + + return 0; +} + +DEFINE_MAIN_FUNCTION(run); diff --git a/pool/shard008/C/0130526_sso-11.c b/pool/shard008/C/0130526_sso-11.c new file mode 100644 index 0000000000000000000000000000000000000000..6b50a25485813f679efd59e4a90b9dbcb2953a0c --- /dev/null +++ b/pool/shard008/C/0130526_sso-11.c @@ -0,0 +1,36 @@ +/* Test support of scalar_storage_order attribute */ + +/* { dg-do compile } */ + +struct __attribute__((scalar_storage_order("big-endian"))) S1 +{ + int i; +}; + +struct __attribute__((scalar_storage_order("little-endian"))) S2 +{ + int i; +}; + +extern int foo (void *); + +int incompatible_call (int which, struct S1 *s1, struct S2 *s2) +{ + if (which == 1) return foo (s1); else foo (s2); /* { dg-warning "incompatible scalar storage order" } */ +} + +void incompatible_assign (struct S1 *s1, struct S2 *s2) +{ + void *p1, *p2; + p1 = s1, p2 = s2; /* { dg-warning "incompatible scalar storage order" } */ +} + +void incompatible_init (struct S1 *s1, struct S2 *s2) +{ + void *p1 = s1, *p2 = s2; /* { dg-warning "incompatible scalar storage order" } */ +} + +void *incompatible_return (int which, struct S1 *s1, struct S2 *s2) +{ + if (which == 1) return s1; else return s2; /* { dg-warning "incompatible scalar storage order" } */ +} diff --git a/pool/shard008/C/0130527_board.c b/pool/shard008/C/0130527_board.c new file mode 100644 index 0000000000000000000000000000000000000000..b9dc9f9f30ba5e336482d76c411a9b796c90742b --- /dev/null +++ b/pool/shard008/C/0130527_board.c @@ -0,0 +1,58 @@ +/* + ChibiOS/RT - Copyright (C) 2006-2014 Giovanni Di Sirio + + 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. +*/ + +#include "hal.h" + +/** + * @brief PAL setup. + * @details Digital I/O ports static configuration as defined in @p board.h. + * This variable is used by the HAL when initializing the PAL driver. + */ +#if HAL_USE_PAL || defined(__DOXYGEN__) +const PALConfig pal_default_config = { + {VAL_GPIO0DATA, VAL_GPIO0DIR}, + {VAL_GPIO1DATA, VAL_GPIO1DIR}, + {VAL_GPIO2DATA, VAL_GPIO2DIR}, + {VAL_GPIO3DATA, VAL_GPIO3DIR}, +}; +#endif + +/* + * Early initialization code. + * This initialization must be performed just after stack setup and before + * any other initialization. + */ +void __early_init(void) { + + lpc111x_clock_init(); +} + +/* + * Board-specific initialization code. + */ +void boardInit(void) { + + /* + * Extra, board-specific, initializations. + * NOTE: PIO1_2 is associated also to the JTAG, if you need to use JTAG + * you must comment that line first. + */ + LPC_IOCON->PIO0_7 = 0xC0; /* Disables pull-up on LED2 output. */ + LPC_IOCON->R_PIO1_2 = 0xC1; /* Disables pull-up on LED3B output + and makes it GPIO1_2. */ + LPC_IOCON->PIO1_9 = 0xC0; /* Disables pull-up on LED3R output.*/ + LPC_IOCON->PIO1_10 = 0xC0; /* Disables pull-up on LED3G output.*/ +} diff --git a/pool/shard008/C/0130529_libatomic.c b/pool/shard008/C/0130529_libatomic.c new file mode 100644 index 0000000000000000000000000000000000000000..b2f2379ff318fa2756bff2b487534576651a0511 --- /dev/null +++ b/pool/shard008/C/0130529_libatomic.c @@ -0,0 +1,85 @@ +/** \copyright + * Copyright (c) 2019, Balazs Racz + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * - Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * \file libatomic.c + * + * A partial implementation of libatomic for Cortex-M0 for the necessary + * operations in OpenMRN. + * + * @author Balazs Racz + * @date 30 Dec 2019 + */ + +#include + +#if defined(STM32F0xx) || (!defined(ARDUINO) && !defined(ESP32)) +// On Cortex-M0 the only way to do atomic operation is to disable interrupts. + +/// Disables interrupts and saves the interrupt enable flag in a register. +#define ACQ_LOCK() \ + int _pastlock; \ + __asm volatile(" mrs %0, PRIMASK \n cpsid i\n" : "=r"(_pastlock)); + +/// Restores the interrupte enable flag from a register. +#define REL_LOCK() __asm volatile(" msr PRIMASK, %0\n " : : "r"(_pastlock)); + +uint16_t __atomic_fetch_sub_2(uint16_t *ptr, uint16_t val, int memorder) +{ + ACQ_LOCK(); + uint16_t ret = *ptr; + *ptr -= val; + REL_LOCK(); + return ret; +} + +uint8_t __atomic_exchange_1(uint8_t *ptr, uint8_t val, int memorder) +{ + ACQ_LOCK(); + uint8_t ret = *ptr; + *ptr = val; + REL_LOCK(); + return ret; +} + +uint8_t __atomic_fetch_or_1(uint8_t *ptr, uint8_t val, int memorder) +{ + ACQ_LOCK(); + uint8_t ret = *ptr; + *ptr = ret | val; + REL_LOCK(); + return ret; +} + +uint8_t __atomic_fetch_and_1(uint8_t *ptr, uint8_t val, int memorder) +{ + ACQ_LOCK(); + uint8_t ret = *ptr; + *ptr = ret & val; + REL_LOCK(); + return ret; +} + +#endif // guard for arduino compilation diff --git a/pool/shard008/C/0130532_msm_vibrator.c b/pool/shard008/C/0130532_msm_vibrator.c new file mode 100644 index 0000000000000000000000000000000000000000..c24a3fbdf796bd1cefb27de94675673ee9b14c9f --- /dev/null +++ b/pool/shard008/C/0130532_msm_vibrator.c @@ -0,0 +1,208 @@ +/* include/asm/mach-msm/htc_pwrsink.h + * + * Copyright (C) 2008 HTC Corporation. + * Copyright (C) 2007 Google, Inc. + * Copyright (c) 2011 Code Aurora Forum. All rights reserved. + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * 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. + * + */ +#include +#include +#include +#include +#include +#include "pmic.h" +#include "timed_output.h" + +#include + +#ifdef CONFIG_HUAWEI_EVALUATE_POWER_CONSUMPTION +#include +#endif +#include +#define VIBRATOR_DELAY 20 +#define VIBRATOR_MIN 50 +#define PM_LIBPROG 0x30000061 +#ifndef CONFIG_HUAWEI_FEATURE_VIBRATOR +#if (CONFIG_MSM_AMSS_VERSION == 6220) || (CONFIG_MSM_AMSS_VERSION == 6225) +#define PM_LIBVERS 0xfb837d0b +#else +#define PM_LIBVERS 0x10001 +#endif +#else +#ifdef CONFIG_ARCH_MSM7X27 +#define PM_LIBVERS 0x60001 +#else +#define PM_LIBVERS 0x00030005 +#endif +#endif +#ifndef CONFIG_HUAWEI_FEATURE_VIBRATOR +#define HTC_PROCEDURE_SET_VIB_ON_OFF 21 +#define PMIC_VIBRATOR_LEVEL (3000) +#else +#define HW_PROCEDURE_SET_VIB_ON_OFF 22 +#define PMIC_VIBRATOR_LEVEL (3000) +#endif +static struct work_struct work_vibrator_on; +static struct work_struct work_vibrator_off; +static struct hrtimer vibe_timer; +#ifdef CONFIG_HUAWEI_SETTING_TIMER_FOR_VIBRATOR_OFF +static int time_value = 0; +#endif + +static void set_pmic_vibrator(int on) +{ + static struct msm_rpc_endpoint *vib_endpoint; + struct set_vib_on_off_req { + struct rpc_request_hdr hdr; + #ifndef CONFIG_HUAWEI_SETTING_TIMER_FOR_VIBRATOR_OFF + uint32_t data; + #else + uint32_t vib_volt; + uint32_t vib_time;//vibratting time pass to modem . + #endif + } req; + + if (!vib_endpoint) { + vib_endpoint = msm_rpc_connect(PM_LIBPROG, PM_LIBVERS, 0); + if (IS_ERR(vib_endpoint)) { + printk(KERN_ERR "init vib rpc failed!\n"); + vib_endpoint = 0; + return; + } + } + + if (on) + { + #ifndef CONFIG_HUAWEI_SETTING_TIMER_FOR_VIBRATOR_OFF + req.data = cpu_to_be32(PMIC_VIBRATOR_LEVEL); + #else + req.vib_volt = cpu_to_be32(PMIC_VIBRATOR_LEVEL); + req.vib_time = cpu_to_be32(time_value); + #endif + } + else + { + #ifndef CONFIG_HUAWEI_SETTING_TIMER_FOR_VIBRATOR_OFF + req.data = cpu_to_be32(0); + #else + req.vib_volt = cpu_to_be32(0); + req.vib_time = cpu_to_be32(0); + #endif + } +#ifndef CONFIG_HUAWEI_FEATURE_VIBRATOR + msm_rpc_call(vib_endpoint, HTC_PROCEDURE_SET_VIB_ON_OFF, &req, + sizeof(req), 5 * HZ); +#else + msm_rpc_call(vib_endpoint, HW_PROCEDURE_SET_VIB_ON_OFF, &req, + sizeof(req), 5 * HZ); +#endif +} + +static void pmic_vibrator_on(struct work_struct *work) +{ + set_pmic_vibrator(1); +} + +static void pmic_vibrator_off(struct work_struct *work) +{ + set_pmic_vibrator(0); +} + +#ifndef CONFIG_HUAWEI_SETTING_TIMER_FOR_VIBRATOR_OFF +static void timed_vibrator_on(struct timed_output_dev *sdev) +{ + schedule_work(&work_vibrator_on); +} + +#endif +static void timed_vibrator_off(struct timed_output_dev *sdev) +{ + schedule_work(&work_vibrator_off); +} +#ifndef CONFIG_HUAWEI_SETTING_TIMER_FOR_VIBRATOR_OFF +static void vibrator_enable(struct timed_output_dev *dev, int value) +{ + hrtimer_cancel(&vibe_timer); + + if (value == 0) + timed_vibrator_off(dev); + else { + value = (value > 15000 ? 15000 : value); + + timed_vibrator_on(dev); + + hrtimer_start(&vibe_timer, + ktime_set(value / 1000, (value % 1000) * 1000000), + HRTIMER_MODE_REL); + } +} +#else +static void vibrator_enable(struct timed_output_dev *dev, int value) +{ + time_value = value;//save this value as vibratting time + hrtimer_cancel(&vibe_timer); + + if (value == 0) + { + mdelay(VIBRATOR_DELAY); + //timed_vibrator_off(dev); + pmic_vibrator_off(NULL); + } + else { + value = (value > 15000 ? 15000 : value); + value = (value < VIBRATOR_MIN ? VIBRATOR_MIN : value); + + //timed_vibrator_on(dev); + pmic_vibrator_on(NULL);//use this function instead of timed_vibrator_on. + hrtimer_start(&vibe_timer, + ktime_set(value / 1000, (value % 1000) * 1000000), + HRTIMER_MODE_REL); + } +} +#endif + +static int vibrator_get_time(struct timed_output_dev *dev) +{ + if (hrtimer_active(&vibe_timer)) { + ktime_t r = hrtimer_get_remaining(&vibe_timer); + struct timeval t = ktime_to_timeval(r); + return t.tv_sec * 1000 + t.tv_usec / 1000; + } + return 0; +} + +static enum hrtimer_restart vibrator_timer_func(struct hrtimer *timer) +{ + timed_vibrator_off(NULL); + return HRTIMER_NORESTART; +} + +static struct timed_output_dev pmic_vibrator = { + .name = "vibrator", + .get_time = vibrator_get_time, + .enable = vibrator_enable, +}; + +void __init msm_init_pmic_vibrator(void) +{ + INIT_WORK(&work_vibrator_on, pmic_vibrator_on); + INIT_WORK(&work_vibrator_off, pmic_vibrator_off); + + hrtimer_init(&vibe_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); + vibe_timer.function = vibrator_timer_func; + + timed_output_dev_register(&pmic_vibrator); +} + +MODULE_DESCRIPTION("timed output pmic vibrator device"); +MODULE_LICENSE("GPL"); + diff --git a/pool/shard008/C/0130535_cdn_create_timestamp_url.c b/pool/shard008/C/0130535_cdn_create_timestamp_url.c new file mode 100644 index 0000000000000000000000000000000000000000..4e907ed5f560e57625022a25eda6cbb1f01601b7 --- /dev/null +++ b/pool/shard008/C/0130535_cdn_create_timestamp_url.c @@ -0,0 +1,17 @@ +#include "qiniu/cdn.h" +#include "qiniu/tm.h" +#include + +void cdn_create_timestamp_url() { + char *host = "http://v1.cdn.example.com"; + char *fileName = "video/caipu/201708/0600/s/5985f37b37025.mp4/eGgxMDgwcA.m3u8"; + char *cryptKey = "xxx"; + char *queryStr = "name=七牛&age=27"; + + char *finalUrl; + Qiniu_Uint64 deadline = Qiniu_Tm_LocalTime() + 3600; + + finalUrl = Qiniu_CDN_CreateTimestampAntiLeechURL(host, fileName, queryStr, deadline, cryptKey); + printf("%s\n", finalUrl); + Qiniu_Free(finalUrl); +} diff --git a/pool/shard008/C/0130539_ppm.c b/pool/shard008/C/0130539_ppm.c new file mode 100644 index 0000000000000000000000000000000000000000..fd9864f51937b22e0cdc8275bc245ba4e0e2fdd7 --- /dev/null +++ b/pool/shard008/C/0130539_ppm.c @@ -0,0 +1,132 @@ +// https://en.wikipedia.org/wiki/Netpbm_format + +#define S 800 // video size +#define R0 (S / 400.0f) // dot inner radius +#define R1 (S / 200.0f) // dot outer radius +#define FONT_W 16 +#define FONT_H 33 +#define PAD (S / 128) // message padding + + +pub void ppm_dot(uint8_t *buf, float x, y, uint32_t fgc) +{ + float fr = 0; + float fg = 0; + float fb = 0; + rgb_split(fgc, &fr, &fg, &fb); + + int miny = floorf(y - R1 - 1); + int maxy = ceilf(y + R1 + 1); + int minx = floorf(x - R1 - 1); + int maxx = ceilf(x + R1 + 1); + + for (int py = miny; py <= maxy; py++) { + float dy = py - y; + for (int px = minx; px <= maxx; px++) { + float dx = px - x; + float d = sqrtf(dy * dy + dx * dx); + float a = smoothstep(R1, R0, d); + + uint32_t bgc = ppm_get(buf, px, py); + float br = 0; + float bg = 0; + float bb = 0; + rgb_split(bgc, &br, &bg, &bb); + + float r = a * fr + (1 - a) * br; + float g = a * fg + (1 - a) * bg; + float b = a * fb + (1 - a) * bb; + ppm_set(buf, px, py, rgb_join(r, g, b)); + } + } +} + +pub void ppm_char(uint8_t *buf, int c, int x, int y, uint32_t fgc) +{ + float fr = 0; + float fg = 0; + float fb = 0; + rgb_split(fgc, &fr, &fg, &fb); + for (int dy = 0; dy < FONT_H; dy++) { + for (int dx = 0; dx < FONT_W; dx++) { + float a = font_value(c, dx, dy); + if (a > 0.0f) { + uint32_t bgc = ppm_get(buf, x + dx, y + dy); + float br = 0; + float bg = 0; + float bb = 0; + rgb_split(bgc, &br, &bg, &bb); + + float r = a * fr + (a - 1) * br; + float g = a * fg + (a - 1) * bg; + float b = a * fb + (a - 1) * bb; + ppm_set(buf, x + dx, y + dy, rgb_join(r, g, b)); + } + } + } +} + +pub void ppm_string(uint8_t *buf, const char *message) +{ + for (int c = 0; message[c]; c++) { + ppm_char(buf, message[c], c * FONT_W + PAD, PAD, 0xffffffUL); + } +} + +pub void ppm_write(const uint8_t *buf, FILE *f) +{ + fprintf(f, "P6\n%d %d\n255\n", S, S); + fwrite(buf, S * 3, S, f); + fflush(f); +} + +void +ppm_set(uint8_t *buf, int x, int y, uint32_t color) +{ + buf[y * S * 3 + x * 3 + 0] = color >> 16; + buf[y * S * 3 + x * 3 + 1] = color >> 8; + buf[y * S * 3 + x * 3 + 2] = color >> 0; +} + +uint32_t +ppm_get(uint8_t *buf, int x, int y) +{ + uint32_t r = buf[y * S * 3 + x * 3 + 0]; + uint32_t g = buf[y * S * 3 + x * 3 + 1]; + uint32_t b = buf[y * S * 3 + x * 3 + 2]; + return (r << 16) | (g << 8) | b; +} + +/* Convert 24-bit color to RGB. */ +void +rgb_split(uint32_t c, float *r, float *g, float *b) +{ + *r = ((c >> 16) / 255.0f); + *g = (((c >> 8) & 0xff) / 255.0f); + *b = ((c & 0xff) / 255.0f); +} + +/* Convert RGB to 24-bit color. */ +uint32_t +rgb_join(float r, float g, float b) +{ + uint32_t ir = roundf(r * 255.0f); + uint32_t ig = roundf(g * 255.0f); + uint32_t ib = roundf(b * 255.0f); + return (ir << 16) | (ig << 8) | ib; +} + +float clamp(float x, float lower, float upper) +{ + if (x < lower) + return lower; + if (x > upper) + return upper; + return x; +} + +float smoothstep(float lower, float upper, float x) +{ + x = clamp((x - lower) / (upper - lower), 0.0f, 1.0f); + return x * x * (3.0f - 2.0f * x); +} diff --git a/pool/shard008/C/0130540_memory.c b/pool/shard008/C/0130540_memory.c new file mode 100644 index 0000000000000000000000000000000000000000..5eb0c7114a1f09f65c3920cabce06528030bb9ef --- /dev/null +++ b/pool/shard008/C/0130540_memory.c @@ -0,0 +1,160 @@ +/* The LibVMI Library is an introspection library that simplifies access to + * memory in a target virtual machine or in a file containing a dump of + * a system's physical memory. LibVMI is based on the XenAccess Library. + * + * Copyright (C) 2011 Sandia National Laboratories + * Author: Bryan D. Payne (bdpayne@acm.org) + * + * This file is part of LibVMI. + * + * LibVMI 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. + * + * LibVMI 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 LibVMI. If not, see . + */ + +#include "private.h" +#define _GNU_SOURCE +#include +#include +#include +#include "driver/driver_wrapper.h" + +status_t +windows_kernel_symbol_to_address( + vmi_instance_t vmi, + const char *symbol, + addr_t *kernel_base_address, + addr_t *address) +{ + status_t ret = VMI_FAILURE; + addr_t rva = 0; + windows_instance_t windows = vmi->os_data; + + if (windows == NULL || !windows->ntoskrnl_va) { + goto exit; + } + + dbprint(VMI_DEBUG_MISC, "--windows symbol lookup (%s)\n", symbol); + + if (windows->sysmap) { + dbprint(VMI_DEBUG_MISC, "--trying kernel sysmap\n"); + + if (VMI_SUCCESS == windows_system_map_symbol_to_address(vmi, symbol, NULL, &rva)) { + *address = windows->ntoskrnl_va + rva; + dbprint(VMI_DEBUG_MISC, "--got symbol from kernel sysmap (%s --> 0x%.16"PRIx64").\n", + symbol, *address); + ret = VMI_SUCCESS; + goto success; + } + + dbprint(VMI_DEBUG_MISC, "--kernel sysmap lookup failed\n"); + } + + if (VMI_SUCCESS == windows_kdbg_lookup(vmi, symbol, address)) { + dbprint(VMI_DEBUG_MISC, "--got symbol from kdbg (%s --> 0x%"PRIx64").\n", symbol, *address); + ret = VMI_SUCCESS; + goto success; + } + + dbprint(VMI_DEBUG_MISC, "--kdbg lookup failed\n"); + dbprint(VMI_DEBUG_MISC, "--trying kernel PE export table\n"); + + /* check exports */ + if (VMI_SUCCESS == windows_export_to_rva(vmi, windows->ntoskrnl_va, 0, symbol, &rva)) { + *address = windows->ntoskrnl_va + rva; + dbprint(VMI_DEBUG_MISC, "--got symbol from PE export table (%s --> 0x%.16"PRIx64").\n", + symbol, *address); + ret = VMI_SUCCESS; + goto success; + } + + dbprint(VMI_DEBUG_MISC, "--kernel PE export table failed\n"); + + goto exit; + +success: + if (kernel_base_address) { + *kernel_base_address = windows->ntoskrnl_va; + } + +exit: + return ret; +} + +/* finds the address of the page global directory for a given pid */ +addr_t +windows_pid_to_pgd( + vmi_instance_t vmi, + vmi_pid_t pid) +{ + addr_t pgd = 0; + addr_t eprocess = 0; + int pid_offset = 0; + int tasks_offset = 0; + int pdbase_offset = 0; + windows_instance_t windows = vmi->os_data; + + if (vmi->os_data == NULL) { + return VMI_FAILURE; + } + + pid_offset = windows->pid_offset; + tasks_offset = windows->tasks_offset; + pdbase_offset = windows->pdbase_offset; + + /* first we need a pointer to this pid's EPROCESS struct */ + eprocess = windows_find_eprocess_list_pid(vmi, pid); + if (!eprocess) { + errprint("Could not find EPROCESS struct for pid = %d.\n", pid); + goto error_exit; + } + + /* now follow the pointer to the memory descriptor and grab the pgd value */ + vmi_read_addr_va(vmi, eprocess + pdbase_offset - tasks_offset, 0, + &pgd); + +error_exit: + return pgd; +} + +vmi_pid_t +windows_pgd_to_pid( + vmi_instance_t vmi, + addr_t pgd) +{ + vmi_pid_t pid = -1; + addr_t eprocess = 0; + int tasks_offset = 0; + int pid_offset = 0; + windows_instance_t windows = vmi->os_data; + + if (vmi->os_data == NULL) { + return VMI_FAILURE; + } + + tasks_offset = windows->tasks_offset; + pid_offset = windows->pid_offset; + + /* first we need a pointer to this pgd's EPROCESS struct */ + eprocess = windows_find_eprocess_list_pgd(vmi, pgd); + if (!eprocess) { + errprint("Could not find EPROCESS struct for pgd = 0x%"PRIx64".\n", pgd); + goto error_exit; + } + + /* now follow the pointer to the memory descriptor and grab the pgd value */ + vmi_read_32_va(vmi, eprocess + pid_offset - tasks_offset, 0, + (uint32_t*)&pid); + +error_exit: + return pid; +} diff --git a/pool/shard008/C/0130541_read_all.c b/pool/shard008/C/0130541_read_all.c new file mode 100644 index 0000000000000000000000000000000000000000..2ce9f22d40928ec2b807d369341aa5dc3712159d --- /dev/null +++ b/pool/shard008/C/0130541_read_all.c @@ -0,0 +1,119 @@ +/* -*- Mode: C; c-basic-offset:4 ; -*- */ +/* + * Copyright (C) 1997 University of Chicago. + * See COPYRIGHT notice in top-level directory. + */ + +#include "mpioimpl.h" + +#ifdef HAVE_WEAK_SYMBOLS + +#if defined(HAVE_PRAGMA_WEAK) +#pragma weak MPI_File_read_all = PMPI_File_read_all +#elif defined(HAVE_PRAGMA_HP_SEC_DEF) +#pragma _HP_SECONDARY_DEF PMPI_File_read_all MPI_File_read_all +#elif defined(HAVE_PRAGMA_CRI_DUP) +#pragma _CRI duplicate MPI_File_read_all as PMPI_File_read_all +/* end of weak pragmas */ +#endif + +/* Include mapping from MPI->PMPI */ +#define MPIO_BUILD_PROFILING +#include "mpioprof.h" +#endif + +/* status object not filled currently */ + +/*@ + MPI_File_read_all - Collective read using individual file pointer + +Input Parameters: +. fh - file handle (handle) +. count - number of elements in buffer (nonnegative integer) +. datatype - datatype of each buffer element (handle) + +Output Parameters: +. buf - initial address of buffer (choice) +. status - status object (Status) + +.N fortran +@*/ +int MPI_File_read_all(MPI_File mpi_fh, void *buf, int count, + MPI_Datatype datatype, MPI_Status *status) +{ + int error_code; + static char myname[] = "MPI_FILE_READ_ALL"; +#ifdef MPI_hpux + int fl_xmpi; + + HPMP_IO_START(fl_xmpi, BLKMPIFILEREADALL, TRDTBLOCK, fh, datatype, count); +#endif /* MPI_hpux */ + + error_code = MPIOI_File_read_all(mpi_fh, (MPI_Offset) 0, + ADIO_INDIVIDUAL, buf, + count, datatype, myname, status); + +#ifdef MPI_hpux + HPMP_IO_END(fl_xmpi, fh, datatype, count); +#endif /* MPI_hpux */ + + return error_code; +} + +/* Note: MPIOI_File_read_all also used by MPI_File_read_at_all */ +/* prevent multiple definitions of this routine */ +#ifdef MPIO_BUILD_PROFILING +int MPIOI_File_read_all(MPI_File mpi_fh, + MPI_Offset offset, + int file_ptr_type, + void *buf, + int count, + MPI_Datatype datatype, + char *myname, + MPI_Status *status) +{ + int error_code, datatype_size; + ADIO_File fh; + + MPIU_THREAD_CS_ENTER(ALLFUNC,); + + fh = MPIO_File_resolve(mpi_fh); + + /* --BEGIN ERROR HANDLING-- */ + MPIO_CHECK_FILE_HANDLE(fh, myname, error_code); + MPIO_CHECK_COUNT(fh, count, myname, error_code); + MPIO_CHECK_DATATYPE(fh, datatype, myname, error_code); + + if (file_ptr_type == ADIO_EXPLICIT_OFFSET && offset < 0) + { + error_code = MPIO_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE, + myname, __LINE__, MPI_ERR_ARG, + "**iobadoffset", 0); + error_code = MPIO_Err_return_file(fh, error_code); + goto fn_exit; + } + /* --END ERROR HANDLING-- */ + + MPI_Type_size(datatype, &datatype_size); + + /* --BEGIN ERROR HANDLING-- */ + MPIO_CHECK_INTEGRAL_ETYPE(fh, count, datatype_size, myname, error_code); + MPIO_CHECK_READABLE(fh, myname, error_code); + MPIO_CHECK_NOT_SEQUENTIAL_MODE(fh, myname, error_code); + MPIO_CHECK_COUNT_SIZE(fh, count, datatype_size, myname, error_code); + /* --END ERROR HANDLING-- */ + + ADIO_ReadStridedColl(fh, buf, count, datatype, file_ptr_type, + offset, status, &error_code); + + /* --BEGIN ERROR HANDLING-- */ + if (error_code != MPI_SUCCESS) + error_code = MPIO_Err_return_file(fh, error_code); + /* --END ERROR HANDLING-- */ + +fn_exit: + MPIU_THREAD_CS_EXIT(ALLFUNC,); + + return error_code; +} +#endif diff --git a/pool/shard008/C/0130546_rcr_main.c b/pool/shard008/C/0130546_rcr_main.c new file mode 100644 index 0000000000000000000000000000000000000000..1b79f501081ae2649f83133d33b667e477c11e0f --- /dev/null +++ b/pool/shard008/C/0130546_rcr_main.c @@ -0,0 +1,196 @@ +#include +#include +#include +#include +#include +#include +#include "rcr_priv.h" + + +static int +rcr_open(struct inode *inode, struct file *file) +{ + return 0; +} + + +static int +rcr_release(struct inode * inode, struct file *file) +{ + return 0; +} + + +static long +rcr_ioctl(struct file *file, unsigned int cmd, unsigned long arg) +{ + return 0; +} + + +static int +rcr_mmap(struct file *file, struct vm_area_struct *vma) +{ + size_t blackboard_size = RCRblackboard_size(); + kaddr_t blackboard_kvaddr = (kaddr_t) RCRblackboard_base(); + paddr_t blackboard_paddr = __pa(blackboard_kvaddr); + + int status = aspace_map_pmem(current->aspace->id, blackboard_paddr, vma->vm_start, blackboard_size); + if (status) { + printk(KERN_ERR "Failed to map RCR blackboard into user-space.\n"); + return -1; + } + + return 0; +} + + +static struct kfs_fops +rcr_fops = { + .open = rcr_open, + .release = rcr_release, + .unlocked_ioctl = rcr_ioctl, + .compat_ioctl = rcr_ioctl, + .mmap = rcr_mmap, +}; + + +/* + * This is the kernel thread that periodically updates the blackboard. + * The set of performance counters monitoried is currently hard-coded. + * At some point down the road, it may make sense to make the set of + * counters monitored and the polling interval configurable via + * ioctl's on /dev/rcr. + */ +static int +rcr_poller(void *data) +{ + int status; + + /* **************************************************************** */ + + uint64_t msr_rapl_power_unit = 0; + uint64_t rapl_time_unit = 0; + uint64_t rapl_energy_unit = 0; + uint64_t rapl_power_unit = 0; + + uint64_t rapl_s0_energy = 0; + uint64_t rapl_s0_energy_prev = 0; + uint64_t rapl_s0_energy_wrap_count = 0; + + /* **************************************************************** */ + + /* Pointers into the blackboard where to store the performance + * counter values that are read by this kthread. */ + uint64_t *bb_s0_energy_ptr; + uint64_t *bb_s0_timestamp_ptr; + + /* **************************************************************** */ + + status = rdmsrl_safe(MSR_RAPL_POWER_UNIT, &msr_rapl_power_unit); + BUG_ON(status); + + rapl_time_unit = (msr_rapl_power_unit >> 16) & 0xF; + rapl_energy_unit = (msr_rapl_power_unit >> 8) & 0xF; + rapl_power_unit = (msr_rapl_power_unit >> 0) & 0xF; + + printk(KERN_INFO "MSR RAPL Power Unit: 0x%lx (time=%lx energy=%lx power=%lx)\n", + (unsigned long) msr_rapl_power_unit, + (unsigned long) rapl_time_unit, + (unsigned long) rapl_energy_unit, + (unsigned long) rapl_power_unit + ); + + /* **************************************************************** */ + + /* Allocate a slot in the blackboard for 'Socket 0 RAPL Energy' */ + status = RCRblackboard_assignSocketMeter(0, 0, ENERGY_STATUS); + BUG_ON(status == false); + + /* Allocate a slot in the blackboard for 'Socket 0 Timestamp Counter' */ + status = RCRblackboard_assignSocketMeter(0, 0, TSC); + BUG_ON(status == false); + + /* **************************************************************** */ + + /* Get the address of the 'Socket 0 RAPL Energy' slot */ + bb_s0_energy_ptr = (uint64_t *)RCRblackboard_getSocketMeter(ENERGY_STATUS, 0, 0); + BUG_ON(bb_s0_energy_ptr == NULL); + printk(KERN_INFO "RCRd: bb_s0_energy_ptr = %p\n", bb_s0_energy_ptr); + + /* Get the address of the 'Socket 0 Timestamp Counter' slot */ + bb_s0_timestamp_ptr = (uint64_t *)RCRblackboard_getSocketMeter(TSC, 0, 0); + BUG_ON(bb_s0_timestamp_ptr == NULL); + printk(KERN_INFO "RCRd: bb_s0_timestamp_ptr = %p\n", bb_s0_timestamp_ptr); + + /* **************************************************************** */ + + /* Loop forever, updating the blackboard each time through the loop */ + while (1) { + + /* ************** Socket 0 Energy Counter ***************** */ + + status = rdmsrl_safe(MSR_PKG_ENERGY_STATUS, &rapl_s0_energy); + BUG_ON(status); + + /* Detect wrap around */ + if (rapl_s0_energy < rapl_s0_energy_prev) + ++rapl_s0_energy_wrap_count; + rapl_s0_energy_prev = rapl_s0_energy; + + /* Update the blackboard. Return (1/1024)'ths of a Joule. */ + *bb_s0_energy_ptr = ((rapl_s0_energy + (rapl_s0_energy_wrap_count << 32))) / (1 << (rapl_energy_unit - 10)); + + /* ************** Socket 0 Timestamp Counter ************** */ + + status = rdmsrl_safe(MSR_IA32_TSC, bb_s0_timestamp_ptr); + BUG_ON(status); + + /* ******************************************************** */ + + //printk("RCRd: bb_s0_energy = %lu\n", (unsigned long) *bb_s0_energy_ptr); + //printk("RCRd: bb_s0_timestamp = %lu\n", (unsigned long) *bb_s0_timestamp_ptr); + + /* ******************************************************** */ + + /* Go to sleep for awhile */ + schedule_timeout(NSEC_PER_SEC/10); + } + + return 0; +} + + +/* + * Called with RCR driver is loaded at LWK boot. + * This initializes RCR. + */ +static int +rcr_init(void) +{ + kfs_create(RCR_DEV_PATH, NULL, &rcr_fops, 0777, NULL, 0); + + /* Setup the blackboard. + * There is one blackboard for the entire node. + * All user-level processes share the same blackboard. */ + RCRblackboard_buildSharedMemoryBlackBoard( + /* num system meters */ 0, + /* num of nodes */ 1, + /* num node meters */ 0, + /* num sockets */ 1, + /* num socket meters */ 2, + /* num cores */ 60, + /* num core meters */ 0, + /* num threads */ 4, + /* num thread meters */ 0 + ); + + /* Kick-off the kthread that updates the blackboard */ + kthread_run(rcr_poller, NULL, "RCR"); + + printk("RCR Driver Loaded\n"); + return 0; +} + + +DRIVER_INIT("kfs", rcr_init); diff --git a/pool/shard008/C/0130548_lwip_eth.c b/pool/shard008/C/0130548_lwip_eth.c new file mode 100644 index 0000000000000000000000000000000000000000..c8eb80aa638a663fb2e535462ff04e3847feb9a1 --- /dev/null +++ b/pool/shard008/C/0130548_lwip_eth.c @@ -0,0 +1,335 @@ +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "FreeRTOSConfig.h" +#include +#include +#include +#include +#include + +#include "lwip_eth.h" +#include +#include +#include +#include +#if LWIP_IPV6 +#include +#endif +#include + +#include "hal/hal.h" +#include "hal/lwip_eth.h" +#include "xbh.h" +#include "util.h" + + +#define LINK_POLL_MSEC 2000 +#define ETH_INT_STACK 256 + + +// Global Variables /*{{{*/ +/** Mac address */ +uint8_t mac_addr[6]; +/*}}}*/ + +// Static Variables /*{{{*/ + +/** Handle for ethernet interrupt task */ +static TaskHandle_t eth_int_task_handle; + +/** Queue handle for status register passed between ISR and task */ +static QueueHandle_t eth_int_q_handle; + +/** NetIF struct for lwIP */ +static struct netif lwip_netif; +/*}}}*/ + +// Forward Declarations *//*{{{*/ +void init_ethernet(void); +void lwIP_eth_isr(void); +static void eth_int_task(void *arg); +static void tcpip_init_cb(void *args); +static void link_status(struct netif *arg); +/*}}}*/ + + +/** + * Creates task to feed data from interrupt to lwIP, + * initializes EMAC0, then initializes lwIP + */ +void init_ethernet(void){/*{{{*/ + + { // Enable Ethernet hardware/*{{{*/ + uint32_t user0, user1; + /** + * Enable ethernet + * See page 160 of spmu298a + */ + MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_EMAC0); + MAP_SysCtlPeripheralReset(SYSCTL_PERIPH_EMAC0); + + //Enable internal PHY + MAP_SysCtlPeripheralEnable(SYSCTL_PERIPH_EPHY0); + MAP_SysCtlPeripheralReset(SYSCTL_PERIPH_EPHY0); + + // Set Ethernet LED pinouts + // See Page 269 of spmu298a.pdf + MAP_GPIOPinConfigure(GPIO_PF0_EN0LED0); + MAP_GPIOPinConfigure(GPIO_PF4_EN0LED1); + GPIOPinTypeEthernetLED(GPIO_PORTF_BASE, GPIO_PIN_0|GPIO_PIN_4); + + + // Busy wait until MAC ready + while(MAP_SysCtlPeripheralReady(SYSCTL_PERIPH_EMAC0) == 0); + + //Using builtin PHY, so don't need to call GPIOPinTypeEthernetMII() + MAP_EMACPHYConfigSet(EMAC0_BASE, EMAC_PHY_TYPE_INTERNAL|EMAC_PHY_INT_MDIX_EN|EMAC_PHY_AN_100B_T_FULL_DUPLEX); + + + // Initialize MAC (see spmu363a.pdf) + // Maybe should optimize burst size + MAP_EMACInit(EMAC0_BASE, g_syshz, EMAC_BCONFIG_MIXED_BURST|EMAC_BCONFIG_PRIORITY_FIXED, 4, 4, 0); + + // Set options + // Tune parameters + MAP_EMACConfigSet(EMAC0_BASE, (EMAC_CONFIG_FULL_DUPLEX | + EMAC_CONFIG_CHECKSUM_OFFLOAD | + EMAC_CONFIG_7BYTE_PREAMBLE | + EMAC_CONFIG_IF_GAP_96BITS | + EMAC_CONFIG_USE_MACADDR0 | + EMAC_CONFIG_SA_FROM_DESCRIPTOR | + EMAC_CONFIG_100MBPS| + EMAC_CONFIG_BO_LIMIT_1024), + (EMAC_MODE_RX_STORE_FORWARD | + EMAC_MODE_TX_STORE_FORWARD | + EMAC_MODE_TX_THRESHOLD_64_BYTES | + EMAC_MODE_RX_THRESHOLD_64_BYTES), 0); + + //Mac Address saved in user0 and user1 by default + MAP_FlashUserGet(&user0, &user1); + mac_addr[0] = user0 & 0xFF; + mac_addr[1] = user0 >> 8 & 0xFF; + mac_addr[2] = user0 >> 16 & 0xFF; + mac_addr[3] = user1 & 0xFF; + mac_addr[4] = user1 >> 8 & 0xFF; + mac_addr[5] = user1 >> 16 & 0xFF; + + MAP_EMACAddrSet(EMAC0_BASE, 0, mac_addr ); + + //Explicitly Disable PTP + EMACTimestampDisable(EMAC0_BASE); + }/*}}}*/ + + // Lower priority of ISR so *FromISR functions can be safely called + MAP_IntPrioritySet(INT_EMAC0, ETH_ISR_PRIO); + + tcpip_init(tcpip_init_cb, NULL); +}/*}}}*/ + +/** + * Callback for tcpip_init() + */ +static void tcpip_init_cb(void *args){/*{{{*/ + ip_addr_t ip_addr; + ip_addr_t netmask; + ip_addr_t gw_addr; + BaseType_t retval; + eth_int_q_handle = xQueueCreate(1, sizeof(uint32_t)); + + retval = xTaskCreate( eth_int_task, + "eth_int", + ETH_INT_STACK, + NULL, + tskIDLE_PRIORITY+ETH_PRIO, + ð_int_task_handle); + LOOP_ERRMSG(retval != pdPASS, "Could not start lwip eth_int task\n" ); + + +#if XBH_IP4_STATIC + ip_addr.addr = htonl(XBH_IP4_ADDR); + netmask.addr = htonl(XBH_IP4_NETMASK); + gw_addr.addr = 0; +#else + ip_addr.addr = 0; + netmask.addr = 0; + gw_addr.addr = 0; +#endif + netif_add(&lwip_netif, &ip_addr, &netmask, &gw_addr, NULL, tivaif_init, + tcpip_input); + + //netif_add sets everything to defaults, so run after netif_add + netif_set_hostname(&lwip_netif, XBH_HOSTNAME); + netif_set_status_callback(&lwip_netif, link_status); + netif_set_default(&lwip_netif); + +#if LWIP_IPV6 + lwip_netif.ip6_autoconfig_enabled = 1; + lwip_netif.output_ip6 = ethip6_output; + //IPv6, enable linklocal addresses and SLAAC + netif_create_ip6_linklocal_address(&lwip_netif, 1); + netif_ip6_addr_set_state((&lwip_netif), 0, IP6_ADDR_TENTATIVE); +#endif +#if XBH_IP4_STATIC + netif_set_up(&lwip_netif); +#else + dhcp_start(&lwip_netif); +#endif + +#if DEBUG_STACK + DEBUG_OUT("Stack Usage: %s: %d\n", __PRETTY_FUNCTION__, uxTaskGetStackHighWaterMark(NULL)); +#endif +}/*}}}*/ + +#if LWIP_IPV6 +static void poll_ip6_addr(TimerHandle_t pxTimer){ + struct netif *netif_arg = (struct netif *) pvTimerGetTimerID( pxTimer ); + bool slaac_done = false; + + //0th address is link local, assume 1th address is SLAAC + for(int i = 0; i < 4; i++){ + if(netif_arg->ip6_addr[1].addr[i] != 0){ + slaac_done = true; + break; + } + } + if(slaac_done){ + for(int i = 0; i < LWIP_IPV6_NUM_ADDRESSES; i++){ + uart_printf("IPv6 Address %d of interface %c%c set " + "to %04hx:%04hx:%04hx:%04hx:%04hx:%04hx:%04hx:%04hx\n", + i, + netif_arg->name[0], netif_arg->name[1], + IP6_ADDR_BLOCK1(&netif_arg->ip6_addr[i]), + IP6_ADDR_BLOCK2(&netif_arg->ip6_addr[i]), + IP6_ADDR_BLOCK3(&netif_arg->ip6_addr[i]), + IP6_ADDR_BLOCK4(&netif_arg->ip6_addr[i]), + IP6_ADDR_BLOCK5(&netif_arg->ip6_addr[i]), + IP6_ADDR_BLOCK6(&netif_arg->ip6_addr[i]), + IP6_ADDR_BLOCK7(&netif_arg->ip6_addr[i]), + IP6_ADDR_BLOCK8(&netif_arg->ip6_addr[i])); + } + xTimerStop( pxTimer, 0 ); + } +} +#endif + +/** + * Outputs link status on serial console + */ +static void link_status(struct netif *arg){/*{{{*/ +#if LWIP_IPV6 + TimerHandle_t poll_timer; +#endif + uart_printf("IP address of interface %c%c set to %hd.%hd.%hd.%hd\n", + arg->name[0], arg->name[1], + ip4_addr1_16(&arg->ip_addr), + ip4_addr2_16(&arg->ip_addr), + ip4_addr3_16(&arg->ip_addr), + ip4_addr4_16(&arg->ip_addr)); + uart_printf("Netmask of interface %c%c set to %hd.%hd.%hd.%hd\n", + arg->name[0], arg->name[1], + ip4_addr1_16(&arg->netmask), + ip4_addr2_16(&arg->netmask), + ip4_addr3_16(&arg->netmask), + ip4_addr4_16(&arg->netmask)); + uart_printf("Gateway of interface %c%c set to %hd.%hd.%hd.%hd\n", + arg->name[0], arg->name[1], + ip4_addr1_16(&arg->gw), + ip4_addr2_16(&arg->gw), + ip4_addr3_16(&arg->gw), + ip4_addr4_16(&arg->gw)); + uart_printf("Hostname of interface %c%c set to %s\n", + arg->name[0], arg->name[1], arg->hostname); +#if LWIP_IPV6 + poll_timer = xTimerCreate + ( "poll_ipv6_addr", + 1000 / portTICK_PERIOD_MS, + pdTRUE, + arg, + poll_ip6_addr); + xTimerStart(poll_timer, 0); +#endif +}/*}}}*/ + + + +/** + * ISR for handling interrupts from Ethernet MAC (ISR 56) + */ +void lwIP_eth_isr(void){/*{{{*/ + uint32_t status; + BaseType_t wake; + + status = MAP_EMACIntStatus(EMAC0_BASE, true); + + // If PTP implemented like lwiplib: + // Check if from timer + // clear timer interrupt + // However, we have already run EMACTimestampDisable() so we don't need to + // worry about MAC timer interrupts + + //Clear interrupt + if(status) { + MAP_EMACIntClear(EMAC0_BASE, status); + } + + // Disable ethernet interrupts here, reenable in task, as we don't want + // ethernet interrupts while already processing ethernet interrupts See + // tivaif_hwinit() for list of interrupts + MAP_EMACIntDisable(EMAC0_BASE, + (EMAC_INT_RECEIVE | EMAC_INT_TRANSMIT | + EMAC_INT_TX_STOPPED | EMAC_INT_RX_NO_BUFFER | + EMAC_INT_RX_STOPPED | EMAC_INT_PHY)); + + + // Enqueue status to eth_int_task + // If sending to queue unblocks task, wake should equal true, + // This freeRTOS function copies status by value, so status going out of + // scope after yielding is not a problem. + // We could use semaphore instead of queue by making status a global var + xQueueSendToBackFromISR(eth_int_q_handle, &status, &wake); + + //Yield to eth_int_task + portYIELD_FROM_ISR((pdTRUE == wake)); +}/*}}}*/ + +/** + * Task for feeding packets from ISR to lwIP + * Loops forever blocking on queue waiting for next status from ISR + * @param arg Unused + */ +static void eth_int_task(void* arg){/*{{{*/ + uint32_t status; + while(1){ + + //Loop waiting max time between loops until queue item received + while(xQueueReceive(eth_int_q_handle, &status, portMAX_DELAY)!=pdPASS); + + tivaif_interrupt(&lwip_netif, status); + // Reenable interrupts disabled in lwIP_eth_isr() + MAP_EMACIntEnable(EMAC0_BASE, (EMAC_INT_PHY| + EMAC_INT_RECEIVE| + EMAC_INT_RX_NO_BUFFER| + EMAC_INT_RX_STOPPED| + EMAC_INT_TRANSMIT| + EMAC_INT_TX_STOPPED)); + +#if DEBUG_STACK + DEBUG_OUT("Stack Usage: %s: %d\n", __PRETTY_FUNCTION__, uxTaskGetStackHighWaterMark(NULL)); +#endif + } +}/*}}}*/ diff --git a/pool/shard008/C/0130549_fputc.c b/pool/shard008/C/0130549_fputc.c new file mode 100644 index 0000000000000000000000000000000000000000..c0e6f01cf814c749294cb805c5b165d9d0de3fcd --- /dev/null +++ b/pool/shard008/C/0130549_fputc.c @@ -0,0 +1,46 @@ +/* + * ETA/OS - STDIO fputc + * Copyright (C) 2014 Michel Megens + * + * 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 . + */ + +/** @file fputc.c */ + +#include +#include +#include +#include + +/** + * @addtogroup libcio + * @{ + */ + +/** + * @brief Write one character to a stream. + * @param c Character to write. + * @param stream Stream to write \p c to. + */ +int fputc(int c, struct vfile * stream) +{ + int rc = -1; + + if(test_bit(STREAM_WRITE_FLAG, &stream->flags)) + rc = stream->put(c, stream); + return rc; +} + +/** @} */ + diff --git a/pool/shard008/C/0130550_empty-Seed4-RandomFuns-Type_long-ControlStructures_8-BB2-ForBound_constant-Operators_PlusA_MinusA_Lt_Gt_Le_Ge_Eq_Ne_Mult_Div_Mod.c b/pool/shard008/C/0130550_empty-Seed4-RandomFuns-Type_long-ControlStructures_8-BB2-ForBound_constant-Operators_PlusA_MinusA_Lt_Gt_Le_Ge_Eq_Ne_Mult_Div_Mod.c new file mode 100644 index 0000000000000000000000000000000000000000..480bac26f13b535ee907173fe7f83198285163a3 --- /dev/null +++ b/pool/shard008/C/0130550_empty-Seed4-RandomFuns-Type_long-ControlStructures_8-BB2-ForBound_constant-Operators_PlusA_MinusA_Lt_Gt_Le_Ge_Eq_Ne_Mult_Div_Mod.c @@ -0,0 +1,93 @@ +/* Generated by CIL v. 1.7.0 */ +/* print_CIL_Input is false */ + +struct _IO_FILE; +struct timeval; +extern float strtof(char const *str , char const *endptr ) ; +extern void signal(int sig , void *func ) ; +typedef struct _IO_FILE FILE; +extern int atoi(char const *s ) ; +extern double strtod(char const *str , char const *endptr ) ; +extern int fclose(void *stream ) ; +extern void *fopen(char const *filename , char const *mode ) ; +extern void abort() ; +extern void exit(int status ) ; +extern int raise(int sig ) ; +extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; +extern int strcmp(char const *a , char const *b ) ; +extern int rand() ; +extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; +void RandomFunc(unsigned long input[1] , unsigned long output[1] ) ; +extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; +extern int gettimeofday(struct timeval *tv , void *tz , ...) ; +extern int printf(char const *format , ...) ; +int main(int argc , char *argv[] ) ; +void megaInit(void) ; +extern unsigned long strlen(char const *s ) ; +extern long strtol(char const *str , char const *endptr , int base ) ; +extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; +extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; +struct timeval { + long tv_sec ; + long tv_usec ; +}; +extern void *malloc(unsigned long size ) ; +extern int scanf(char const *format , ...) ; +void megaInit(void) +{ + + + { + +} +} +int main(int argc , char *argv[] ) +{ + unsigned long input[1] ; + unsigned long output[1] ; + int randomFuns_i5 ; + unsigned long randomFuns_value6 ; + int randomFuns_main_i7 ; + + { + megaInit(); + if (argc != 2) { + printf("Call this program with %i arguments\n", 1); + exit(-1); + } else { + + } + randomFuns_i5 = 0; + while (randomFuns_i5 < 1) { + randomFuns_value6 = strtoul(argv[randomFuns_i5 + 1], 0, 10); + input[randomFuns_i5] = randomFuns_value6; + randomFuns_i5 ++; + } + RandomFunc(input, output); + if (output[0] == 4242424242UL) { + printf("You win!\n"); + } else { + + } + randomFuns_main_i7 = 0; + while (randomFuns_main_i7 < 1) { + printf("%lu\n", output[randomFuns_main_i7]); + randomFuns_main_i7 ++; + } +} +} +void RandomFunc(unsigned long input[1] , unsigned long output[1] ) +{ + unsigned long state[1] ; + unsigned long local1 ; + + { + state[0UL] = (input[0UL] + 914778474UL) * 67330564296145686UL; + local1 = 0UL; + while (local1 < 1UL) { + state[0UL] = state[local1] + state[0UL]; + local1 ++; + } + output[0UL] = (state[0UL] + 238420169UL) * 1151155071UL; +} +} diff --git a/pool/shard008/C/0130559_test_log.c b/pool/shard008/C/0130559_test_log.c new file mode 100644 index 0000000000000000000000000000000000000000..8633ff0ad91c954758ac004eeabd3e522a0a881b --- /dev/null +++ b/pool/shard008/C/0130559_test_log.c @@ -0,0 +1,94 @@ +#include +#include + +#include + +void writefile (double **x, double **y, double **z, int line, int row) +{ + int i, j; + FILE * f; + f = fopen("scan05log.dat", "w+"); + for (i=0 ; i1 && nrow==0){nline++;} + if (read==1){nrow++;} + } + fclose(fr); + printf("nline=%i\n",nline); + printf("nrow=%i\n",nrow); + + double ** x=NULL; + double ** y=NULL; + double ** z=NULL; + x=(double **)malloc(nrow*sizeof(double *)); + y=(double **)malloc(nrow*sizeof(double *)); + z=(double **)malloc(nrow*sizeof(double *)); + int temp=0; + float tempx=0.0, tempy=0.0; + + for (i=0 ; i +#include +#include + +#include "Platform/Event.h" +#include "Platform/NvmSettings.h" +#include "ApplicationNvmSettings.h" +#include "Door.h" + +#include "DoorFixture.h" + +#include "../Fixture.h" +#include "../NonDeterminism.h" +#include "../NvmSettingsFixture.h" + +TEST_FILE("Door/DoorInitialise.c") +TEST_FILE("Door/DoorGetState.c") +TEST_FILE("Door/DoorCalibrate.c") +TEST_FILE("Door/DoorOnAborted.c") +TEST_FILE("Door/DoorOnOpenScheduleActioned.c") +TEST_FILE("Door/DoorOnCloseScheduleActioned.c") +TEST_FILE("Door/DoorOnMotorStopped.c") +TEST_FILE("Door/DoorOnMotorEnabled.c") + +void onBeforeTest(void) +{ + doorFixtureInitialise(); +} + +void onAfterTest(void) +{ + doorFixtureShutdown(); +} + +void test_doorOpenScheduleActioned_onPublishedWhenStateIsClosing_expectSameStateWithOpenTransition(void) +{ + struct DoorStateWithContext state = + { + .current = DoorState_Closing, + .transition = anyByteExcept(DoorTransition_Open) + }; + + stubDoorWithState(state.current, state.transition); + publishDoorOpenScheduleActioned(); + dispatchAllEvents(); + doorGetState(&state); + + TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorState_Closing, state.current, "A"); + TEST_ASSERT_EQUAL_UINT8_MESSAGE(DoorTransition_Open, state.transition, "T"); +} + +void test_doorOpenScheduleActioned_onPublishedWhenStateIsClosing_expectMotorIsNotEnabled(void) +{ + struct DoorStateWithContext state = + { + .current = DoorState_Closing, + .transition = anyByte() + }; + + stubDoorWithState(state.current, state.transition); + publishDoorOpenScheduleActioned(); + dispatchAllEvents(); + doorGetState(&state); + + TEST_ASSERT_EQUAL_UINT8(0, motorEnableCalls); +} + +void test_doorOpenScheduleActioned_onPublishedWhenStateIsClosing_expectMotorIsNotTurnedOn(void) +{ + struct DoorStateWithContext state = + { + .current = DoorState_Closing, + .transition = anyByte() + }; + + stubDoorWithState(state.current, state.transition); + publishDoorOpenScheduleActioned(); + dispatchAllEvents(); + doorGetState(&state); + + TEST_ASSERT_EQUAL_UINT8(0, motorOnCalls); +} + +void test_doorOpenScheduleActioned_onPublishedWhenStateIsClosing_expectMotorCurrentLimitIsNotChanged(void) +{ + struct DoorStateWithContext state = + { + .current = DoorState_Closing, + .transition = anyByte() + }; + + stubDoorWithState(state.current, state.transition); + publishDoorOpenScheduleActioned(); + dispatchAllEvents(); + doorGetState(&state); + + TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, motorLimitIsNoLoadCalls, "N"); + TEST_ASSERT_EQUAL_UINT8_MESSAGE(0, motorLimitIsMaximumLoadCalls, "M"); +} diff --git a/pool/shard008/C/0130565_t-newton_to_monomial.c b/pool/shard008/C/0130565_t-newton_to_monomial.c new file mode 100644 index 0000000000000000000000000000000000000000..339503667ef1cbad29e1a752836ce79b46e6fa82 --- /dev/null +++ b/pool/shard008/C/0130565_t-newton_to_monomial.c @@ -0,0 +1,71 @@ +/* + Copyright (C) 2012 Fredrik Johansson + + This file is part of FLINT. + + FLINT is free software: you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License (LGPL) as published + by the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. See . +*/ + +#include +#include +#include +#include "flint.h" +#include "fmpz.h" +#include "fmpz_poly.h" +#include "ulong_extras.h" + +int +main(void) +{ + int i; + FLINT_TEST_INIT(state); + + flint_printf("newton_to_monomial...."); + fflush(stdout); + + + + for (i = 0; i < 1000 * flint_test_multiplier(); i++) + { + fmpz_poly_t f, g; + fmpz * r; + slong k, n; + + fmpz_poly_init(f); + fmpz_poly_init(g); + + fmpz_poly_randtest(f, state, 1 + n_randint(state, 20), + 1 + n_randint(state, 200)); + + n = fmpz_poly_length(f); + r = _fmpz_vec_init(n); + + for (k = 0; k < n; k++) + fmpz_randtest(r + k, state, n_randint(state, 200)); + + fmpz_poly_set(g, f); + + _fmpz_poly_newton_to_monomial(g->coeffs, r, n); + _fmpz_poly_monomial_to_newton(g->coeffs, r, n); + + if (!fmpz_poly_equal(f, g)) + { + flint_printf("FAIL: roundtrip\n"); + fmpz_poly_print(f); flint_printf("\n"); + fmpz_poly_print(g); flint_printf("\n"); + abort(); + } + + fmpz_poly_clear(f); + fmpz_poly_clear(g); + _fmpz_vec_clear(r, n); + } + + FLINT_TEST_CLEANUP(state); + + flint_printf("PASS\n"); + return 0; +} diff --git a/pool/shard008/C/0130566_qe_common.c b/pool/shard008/C/0130566_qe_common.c new file mode 100644 index 0000000000000000000000000000000000000000..75075591f6308d15d0c250285d601dd02644b677 --- /dev/null +++ b/pool/shard008/C/0130566_qe_common.c @@ -0,0 +1,240 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Common CPM code + * + * Author: Scott Wood + * + * Copyright 2007-2008,2010 Freescale Semiconductor, Inc. + * + * Some parts derived from commproc.c/cpm2_common.c, which is: + * Copyright (c) 1997 Dan error_act (dmalek@jlc.net) + * Copyright (c) 1999-2001 Dan Malek + * Copyright (c) 2000 MontaVista Software, Inc (source@mvista.com) + * 2006 (c) MontaVista Software, Inc. + * Vitaly Bordug + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static struct gen_pool *muram_pool; +static spinlock_t cpm_muram_lock; +static u8 __iomem *muram_vbase; +static phys_addr_t muram_pbase; + +struct muram_block { + struct list_head head; + s32 start; + int size; +}; + +static LIST_HEAD(muram_block_list); + +/* max address size we deal with */ +#define OF_MAX_ADDR_CELLS 4 +#define GENPOOL_OFFSET (4096 * 8) + +int cpm_muram_init(void) +{ + struct device_node *np; + struct resource r; + __be32 zero[OF_MAX_ADDR_CELLS] = {}; + resource_size_t max = 0; + int i = 0; + int ret = 0; + + if (muram_pbase) + return 0; + + spin_lock_init(&cpm_muram_lock); + np = of_find_compatible_node(NULL, NULL, "fsl,cpm-muram-data"); + if (!np) { + /* try legacy bindings */ + np = of_find_node_by_name(NULL, "data-only"); + if (!np) { + pr_err("Cannot find CPM muram data node"); + ret = -ENODEV; + goto out_muram; + } + } + + muram_pool = gen_pool_create(0, -1); + if (!muram_pool) { + pr_err("Cannot allocate memory pool for CPM/QE muram"); + ret = -ENOMEM; + goto out_muram; + } + muram_pbase = of_translate_address(np, zero); + if (muram_pbase == (phys_addr_t)OF_BAD_ADDR) { + pr_err("Cannot translate zero through CPM muram node"); + ret = -ENODEV; + goto out_pool; + } + + while (of_address_to_resource(np, i++, &r) == 0) { + if (r.end > max) + max = r.end; + ret = gen_pool_add(muram_pool, r.start - muram_pbase + + GENPOOL_OFFSET, resource_size(&r), -1); + if (ret) { + pr_err("QE: couldn't add muram to pool!\n"); + goto out_pool; + } + } + + muram_vbase = ioremap(muram_pbase, max - muram_pbase + 1); + if (!muram_vbase) { + pr_err("Cannot map QE muram"); + ret = -ENOMEM; + goto out_pool; + } + goto out_muram; +out_pool: + gen_pool_destroy(muram_pool); +out_muram: + of_node_put(np); + return ret; +} + +/* + * cpm_muram_alloc_common - cpm_muram_alloc common code + * @size: number of bytes to allocate + * @algo: algorithm for alloc. + * @data: data for genalloc's algorithm. + * + * This function returns a non-negative offset into the muram area, or + * a negative errno on failure. + */ +static s32 cpm_muram_alloc_common(unsigned long size, + genpool_algo_t algo, void *data) +{ + struct muram_block *entry; + s32 start; + + entry = kmalloc(sizeof(*entry), GFP_ATOMIC); + if (!entry) + return -ENOMEM; + start = gen_pool_alloc_algo(muram_pool, size, algo, data); + if (!start) { + kfree(entry); + return -ENOMEM; + } + start = start - GENPOOL_OFFSET; + memset_io(cpm_muram_addr(start), 0, size); + entry->start = start; + entry->size = size; + list_add(&entry->head, &muram_block_list); + + return start; +} + +/* + * cpm_muram_alloc - allocate the requested size worth of multi-user ram + * @size: number of bytes to allocate + * @align: requested alignment, in bytes + * + * This function returns a non-negative offset into the muram area, or + * a negative errno on failure. + * Use cpm_dpram_addr() to get the virtual address of the area. + * Use cpm_muram_free() to free the allocation. + */ +s32 cpm_muram_alloc(unsigned long size, unsigned long align) +{ + s32 start; + unsigned long flags; + struct genpool_data_align muram_pool_data; + + spin_lock_irqsave(&cpm_muram_lock, flags); + muram_pool_data.align = align; + start = cpm_muram_alloc_common(size, gen_pool_first_fit_align, + &muram_pool_data); + spin_unlock_irqrestore(&cpm_muram_lock, flags); + return start; +} +EXPORT_SYMBOL(cpm_muram_alloc); + +/** + * cpm_muram_free - free a chunk of multi-user ram + * @offset: The beginning of the chunk as returned by cpm_muram_alloc(). + */ +void cpm_muram_free(s32 offset) +{ + unsigned long flags; + int size; + struct muram_block *tmp; + + if (offset < 0) + return; + + size = 0; + spin_lock_irqsave(&cpm_muram_lock, flags); + list_for_each_entry(tmp, &muram_block_list, head) { + if (tmp->start == offset) { + size = tmp->size; + list_del(&tmp->head); + kfree(tmp); + break; + } + } + gen_pool_free(muram_pool, offset + GENPOOL_OFFSET, size); + spin_unlock_irqrestore(&cpm_muram_lock, flags); +} +EXPORT_SYMBOL(cpm_muram_free); + +/* + * cpm_muram_alloc_fixed - reserve a specific region of multi-user ram + * @offset: offset of allocation start address + * @size: number of bytes to allocate + * This function returns @offset if the area was available, a negative + * errno otherwise. + * Use cpm_dpram_addr() to get the virtual address of the area. + * Use cpm_muram_free() to free the allocation. + */ +s32 cpm_muram_alloc_fixed(unsigned long offset, unsigned long size) +{ + s32 start; + unsigned long flags; + struct genpool_data_fixed muram_pool_data_fixed; + + spin_lock_irqsave(&cpm_muram_lock, flags); + muram_pool_data_fixed.offset = offset + GENPOOL_OFFSET; + start = cpm_muram_alloc_common(size, gen_pool_fixed_alloc, + &muram_pool_data_fixed); + spin_unlock_irqrestore(&cpm_muram_lock, flags); + return start; +} +EXPORT_SYMBOL(cpm_muram_alloc_fixed); + +/** + * cpm_muram_addr - turn a muram offset into a virtual address + * @offset: muram offset to convert + */ +void __iomem *cpm_muram_addr(unsigned long offset) +{ + return muram_vbase + offset; +} +EXPORT_SYMBOL(cpm_muram_addr); + +unsigned long cpm_muram_offset(void __iomem *addr) +{ + return addr - (void __iomem *)muram_vbase; +} +EXPORT_SYMBOL(cpm_muram_offset); + +/** + * cpm_muram_dma - turn a muram virtual address into a DMA address + * @offset: virtual address from cpm_muram_addr() to convert + */ +dma_addr_t cpm_muram_dma(void __iomem *addr) +{ + return muram_pbase + ((u8 __iomem *)addr - muram_vbase); +} +EXPORT_SYMBOL(cpm_muram_dma); diff --git a/pool/shard008/C/0130568_vibrator.c b/pool/shard008/C/0130568_vibrator.c new file mode 100644 index 0000000000000000000000000000000000000000..bb043efccb26001fd5ef903340a8de344eaa2559 --- /dev/null +++ b/pool/shard008/C/0130568_vibrator.c @@ -0,0 +1,273 @@ + + +#include +#include +#include +#include +#include +#include + +#include "timed_output.h" +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#define VERSION "v 0.1" +#define VIB_DEVICE "mt6573_vibrator" + +#define COUNT_DOWN_TIME 50 + +#define VIBR_HRTIMER + +#ifndef VIBR_HRTIMER +XGPT_NUM Vibrator_XGPT = XGPT7; +#endif + +#define RSUCCESS 0 + + +/* Debug message event */ +#define DBG_EVT_NONE 0x00000000 /* No event */ +#define DBG_EVT_INT 0x00000001 /* Interrupt related event */ +#define DBG_EVT_TASKLET 0x00000002 /* Tasklet related event */ + +#define DBG_EVT_ALL 0xffffffff + +#define DBG_EVT_MASK (DBG_EVT_TASKLET) + +#if 1 +#define MSG(evt, fmt, args...) \ +do { \ + if ((DBG_EVT_##evt) & DBG_EVT_MASK) { \ + printk(fmt, ##args); \ + } \ +} while(0) + +#define MSG_FUNC_ENTRY(f) MSG(FUC, ": %s\n", __FUNCTION__) +#else +#define MSG(evt, fmt, args...) do{}while(0) +#define MSG_FUNC_ENTRY(f) do{}while(0) +#endif + +#define VIBR_CON0 ((volatile unsigned long*)(0xF702F7B0)) + +static int vibr_Enable(void) +{ + printk("[vibrator]vibr_Enable \n"); + hwPowerOn(MT65XX_POWER_LDO_VIBR, VOL_2800 , "VIBR"); + return 0; +} + +static int vibr_Disable(void) +{ + while((INREG32(VIBR_CON0)&1)) + { + printk("[vibrator]vibr_Disable \n"); + hwPowerDown(MT65XX_POWER_LDO_VIBR , "VIBR"); + //printk("[vibrator]vibr_Disable:VIBR_CON0=0x%x \r\n", INREG32(VIBR_CON0)); + } + + return 0; +} + + +//static struct work_struct vibrator_work; +static struct hrtimer vibe_timer; +static spinlock_t vibe_lock; + + +static int vibrator_get_time(struct timed_output_dev *dev) +{ + if (hrtimer_active(&vibe_timer)) + { + ktime_t r = hrtimer_get_remaining(&vibe_timer); + return r.tv.sec * 1000 + r.tv.nsec / 1000000; + } + else + return 0; +} + +static void vibrator_enable(struct timed_output_dev *dev, int value) +{ + unsigned long flags; + + spin_lock_irqsave(&vibe_lock, flags); + + #ifdef VIBR_HRTIMER + while(hrtimer_cancel(&vibe_timer)) + { + printk("[vibrator]vibrator_enable: try to cancel hrtimer \n"); + } + #else + XGPT_Reset(Vibrator_XGPT); + #endif + + if (value == 0) + { + printk("[vibrator]vibrator_enable: disable \n"); + vibr_Disable(); + + } + else + { + value = ((value > 15000) ? 15000 : value); + printk("[vibrator]vibrator_enable: vibrator start: %d \n", value); + + #ifdef VIBR_HRTIMER + hrtimer_start(&vibe_timer, + ktime_set(value / 1000, (value % 1000) * 1000000), + HRTIMER_MODE_REL); + + #else + XGPT_CONFIG config; + config.num = Vibrator_XGPT; + config.clkDiv = 0; + config.mode = XGPT_ONE_SHOT; + config.bIrqEnable = TRUE; + config.u4Compare = value*32768/1000; + + if(!XGPT_Config(config)) + { + printk("[vibrator]vibrator_enable: config XGPT: %d fail!\n", value); + } + + XGPT_Start(Vibrator_XGPT); + #endif + + vibr_Enable(); + + } + spin_unlock_irqrestore(&vibe_lock, flags); + +} + + +#ifdef VIBR_HRTIMER +static enum hrtimer_restart vibrator_timer_func(struct hrtimer *timer) +{ + printk("[vibrator]vibrator_timer_func: vibrator will disable \n"); + + vibr_Disable(); + + return HRTIMER_NORESTART; +} + +#else +void vibrator_timer_func(UINT16 temp) +{ + printk("[vibrator]vibrator_timer_func: vibrator will disable \n"); + + vibr_Disable(); +} +#endif + + +static struct timed_output_dev mt6573_vibrator = +{ + .name = "vibrator", + .get_time = vibrator_get_time, + .enable = vibrator_enable, +}; + +static int vib_probe(struct platform_device *pdev) +{ + return 0; +} + +static int vib_remove(struct platform_device *pdev) +{ + return 0; +} + +static void vib_shutdown(struct platform_device *pdev) +{ + vibr_Disable(); + +} +static struct platform_driver vibrator_driver = +{ + .probe = vib_probe, + .remove = vib_remove, + .shutdown = vib_shutdown, + .driver = { + .name = VIB_DEVICE, + }, +}; + +static ssize_t store_vibr_on(struct device *dev,struct device_attribute *attr, const char *buf, size_t size) +{ + if(buf != NULL && size != 0) + { + printk("[vibrator]buf is %s and size is %d \n",buf,size); + if(buf[0]== '0') + { + vibr_Disable(); + }else + { + vibr_Enable(); + } + } + return size; +} + +static DEVICE_ATTR(vibr_on, 0664, NULL, store_vibr_on); + + +static s32 __devinit vib_mod_init(void) +{ + s32 ret; + + printk("MediaTek MT6573 vibrator driver register, version %s\n", VERSION); + + spin_lock_init(&vibe_lock); + + #ifdef VIBR_HRTIMER + hrtimer_init(&vibe_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); + vibe_timer.function = vibrator_timer_func; + + #else + XGPT_Init(Vibrator_XGPT, vibrator_timer_func); + #endif + + timed_output_dev_register(&mt6573_vibrator); + + ret = platform_driver_register(&vibrator_driver); + + if(ret) + { + printk("[vibrator]Unable to register vibrator driver (%d)\n", ret); + return ret; + } + + ret = device_create_file(mt6573_vibrator.dev,&dev_attr_vibr_on); + if(ret) + { + printk("[vibrator]device_create_file vibr_on fail! \n"); + } + + printk("[vibrator]vib_mod_init Done \n"); + + return RSUCCESS; +} + + +static void __exit vib_mod_exit(void) +{ + printk("MediaTek MT6573 vibrator driver unregister, version %s \n", VERSION); + printk("[vibrator]vib_mod_exit Done \n"); +} + +module_init(vib_mod_init); +module_exit(vib_mod_exit); +MODULE_AUTHOR("MediaTek Inc."); +MODULE_DESCRIPTION("MT6573 Vibrator Driver (VIB)"); +MODULE_LICENSE("GPL"); + diff --git a/pool/shard008/C/0130574_twolame.c b/pool/shard008/C/0130574_twolame.c new file mode 100644 index 0000000000000000000000000000000000000000..9fe366592b913f68bc8c686a0357fd5d05dd9642 --- /dev/null +++ b/pool/shard008/C/0130574_twolame.c @@ -0,0 +1,314 @@ +/***************************************************************************** + * twolame.c: libtwolame encoder (MPEG-1/2 layer II) module + * (using libtwolame from http://www.twolame.org/) + ***************************************************************************** + * Copyright (C) 2004-2005 the VideoLAN team + * $Id$ + * + * Authors: Christophe Massiot + * Gildas Bazin + * + * 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. + *****************************************************************************/ + +/***************************************************************************** + * Preamble + *****************************************************************************/ +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include +#include + +#include + +#define MPEG_FRAME_SIZE 1152 +#define MAX_CODED_FRAME_SIZE 1792 + +/**************************************************************************** + * Local prototypes + ****************************************************************************/ +static int OpenEncoder ( vlc_object_t * ); +static void CloseEncoder ( vlc_object_t * ); +static block_t *Encode ( encoder_t *, block_t * ); + +/***************************************************************************** + * Module descriptor + *****************************************************************************/ +#define ENC_CFG_PREFIX "sout-twolame-" + +#define ENC_QUALITY_TEXT N_("Encoding quality") +#define ENC_QUALITY_LONGTEXT N_( \ + "Force a specific encoding quality between 0.0 (high) and 50.0 (low), " \ + "instead of specifying a particular bitrate. " \ + "This will produce a VBR stream." ) +#define ENC_MODE_TEXT N_("Stereo mode") +#define ENC_MODE_LONGTEXT N_( "Handling mode for stereo streams" ) +#define ENC_VBR_TEXT N_("VBR mode") +#define ENC_VBR_LONGTEXT N_( \ + "Use Variable BitRate. Default is to use Constant BitRate (CBR)." ) +#define ENC_PSY_TEXT N_("Psycho-acoustic model") +#define ENC_PSY_LONGTEXT N_( \ + "Integer from -1 (no model) to 4." ) + +static const int pi_stereo_values[] = { 0, 1, 2 }; +static const char *const ppsz_stereo_descriptions[] = +{ N_("Stereo"), N_("Dual mono"), N_("Joint stereo") }; + + +vlc_module_begin () + set_shortname( "Twolame") + set_description( N_("Libtwolame audio encoder") ) + set_capability( "encoder", 120 ) + set_callbacks( OpenEncoder, CloseEncoder ) + set_category( CAT_INPUT ) + set_subcategory( SUBCAT_INPUT_ACODEC ) + + add_float( ENC_CFG_PREFIX "quality", 0.0, ENC_QUALITY_TEXT, + ENC_QUALITY_LONGTEXT, false ) + add_integer( ENC_CFG_PREFIX "mode", 0, ENC_MODE_TEXT, + ENC_MODE_LONGTEXT, false ) + change_integer_list( pi_stereo_values, ppsz_stereo_descriptions ); + add_bool( ENC_CFG_PREFIX "vbr", false, ENC_VBR_TEXT, + ENC_VBR_LONGTEXT, false ) + add_integer( ENC_CFG_PREFIX "psy", 3, ENC_PSY_TEXT, + ENC_PSY_LONGTEXT, false ) +vlc_module_end () + +static const char *const ppsz_enc_options[] = { + "quality", "mode", "vbr", "psy", NULL +}; + +/***************************************************************************** + * encoder_sys_t : twolame encoder descriptor + *****************************************************************************/ +struct encoder_sys_t +{ + /* + * Input properties + */ + int16_t p_buffer[MPEG_FRAME_SIZE * 2]; + int i_nb_samples; + mtime_t i_pts; + + /* + * libtwolame properties + */ + twolame_options *p_twolame; + unsigned char p_out_buffer[MAX_CODED_FRAME_SIZE]; +}; + +/***************************************************************************** + * OpenEncoder: probe the encoder and return score + *****************************************************************************/ +static const uint16_t mpa_bitrate_tab[2][15] = +{ + {0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384}, + {0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160} +}; + +static const uint16_t mpa_freq_tab[6] = +{ 44100, 48000, 32000, 22050, 24000, 16000 }; + +static int OpenEncoder( vlc_object_t *p_this ) +{ + encoder_t *p_enc = (encoder_t *)p_this; + encoder_sys_t *p_sys; + int i_frequency; + + if( p_enc->fmt_out.i_codec != VLC_CODEC_MP2 && + p_enc->fmt_out.i_codec != VLC_CODEC_MPGA && + p_enc->fmt_out.i_codec != VLC_FOURCC( 'm', 'p', '2', 'a' ) && + !p_enc->b_force ) + { + return VLC_EGENERIC; + } + + if( p_enc->fmt_in.audio.i_channels > 2 ) + { + msg_Err( p_enc, "doesn't support > 2 channels" ); + return VLC_EGENERIC; + } + + for ( i_frequency = 0; i_frequency < 6; i_frequency++ ) + { + if ( p_enc->fmt_out.audio.i_rate == mpa_freq_tab[i_frequency] ) + break; + } + if ( i_frequency == 6 ) + { + msg_Err( p_enc, "MPEG audio doesn't support frequency=%d", + p_enc->fmt_out.audio.i_rate ); + return VLC_EGENERIC; + } + + /* Allocate the memory needed to store the decoder's structure */ + if( ( p_sys = (encoder_sys_t *)malloc(sizeof(encoder_sys_t)) ) == NULL ) + return VLC_ENOMEM; + p_enc->p_sys = p_sys; + + p_enc->pf_encode_audio = Encode; + p_enc->fmt_in.i_codec = VLC_CODEC_S16N; + + p_enc->fmt_out.i_cat = AUDIO_ES; + p_enc->fmt_out.i_codec = VLC_CODEC_MPGA; + + config_ChainParse( p_enc, ENC_CFG_PREFIX, ppsz_enc_options, p_enc->p_cfg ); + + p_sys->p_twolame = twolame_init(); + + /* Set options */ + twolame_set_in_samplerate( p_sys->p_twolame, p_enc->fmt_out.audio.i_rate ); + twolame_set_out_samplerate( p_sys->p_twolame, p_enc->fmt_out.audio.i_rate ); + + if( var_GetBool( p_enc, ENC_CFG_PREFIX "vbr" ) ) + { + float f_quality = var_GetFloat( p_enc, ENC_CFG_PREFIX "quality" ); + if ( f_quality > 50.0 ) f_quality = 50.0; + if ( f_quality < 0.0 ) f_quality = 0.0; + twolame_set_VBR( p_sys->p_twolame, 1 ); + twolame_set_VBR_q( p_sys->p_twolame, f_quality ); + } + else + { + int i; + for ( i = 1; i < 14; i++ ) + { + if ( p_enc->fmt_out.i_bitrate / 1000 + <= mpa_bitrate_tab[i_frequency / 3][i] ) + break; + } + if ( p_enc->fmt_out.i_bitrate / 1000 + != mpa_bitrate_tab[i_frequency / 3][i] ) + { + msg_Warn( p_enc, "MPEG audio doesn't support bitrate=%d, using %d", + p_enc->fmt_out.i_bitrate, + mpa_bitrate_tab[i_frequency / 3][i] * 1000 ); + p_enc->fmt_out.i_bitrate = mpa_bitrate_tab[i_frequency / 3][i] + * 1000; + } + + twolame_set_bitrate( p_sys->p_twolame, + p_enc->fmt_out.i_bitrate / 1000 ); + } + + if ( p_enc->fmt_in.audio.i_channels == 1 ) + { + twolame_set_num_channels( p_sys->p_twolame, 1 ); + twolame_set_mode( p_sys->p_twolame, TWOLAME_MONO ); + } + else + { + twolame_set_num_channels( p_sys->p_twolame, 2 ); + switch( var_GetInteger( p_enc, ENC_CFG_PREFIX "mode" ) ) + { + case 1: + twolame_set_mode( p_sys->p_twolame, TWOLAME_DUAL_CHANNEL ); + break; + case 2: + twolame_set_mode( p_sys->p_twolame, TWOLAME_JOINT_STEREO ); + break; + case 0: + default: + twolame_set_mode( p_sys->p_twolame, TWOLAME_STEREO ); + break; + } + } + + twolame_set_psymodel( p_sys->p_twolame, + var_GetInteger( p_enc, ENC_CFG_PREFIX "psy" ) ); + + if ( twolame_init_params( p_sys->p_twolame ) ) + { + msg_Err( p_enc, "twolame initialization failed" ); + return -VLC_EGENERIC; + } + + p_sys->i_nb_samples = 0; + + return VLC_SUCCESS; +} + +/**************************************************************************** + * Encode: the whole thing + **************************************************************************** + * This function spits out MPEG packets. + ****************************************************************************/ +static void Bufferize( encoder_t *p_enc, int16_t *p_in, int i_nb_samples ) +{ + int16_t *p_buffer = p_enc->p_sys->p_buffer + + (p_enc->p_sys->i_nb_samples + * p_enc->fmt_in.audio.i_channels); + + memcpy( p_buffer, p_in, i_nb_samples * p_enc->fmt_in.audio.i_channels + * sizeof(int16_t) ); +} + +static block_t *Encode( encoder_t *p_enc, block_t *p_aout_buf ) +{ + encoder_sys_t *p_sys = p_enc->p_sys; + int16_t *p_buffer = (int16_t *)p_aout_buf->p_buffer; + int i_nb_samples = p_aout_buf->i_nb_samples; + block_t *p_chain = NULL; + + p_sys->i_pts = p_aout_buf->i_pts - + (mtime_t)1000000 * (mtime_t)p_sys->i_nb_samples / + (mtime_t)p_enc->fmt_out.audio.i_rate; + + while ( p_sys->i_nb_samples + i_nb_samples >= MPEG_FRAME_SIZE ) + { + int i_used; + block_t *p_block; + + Bufferize( p_enc, p_buffer, MPEG_FRAME_SIZE - p_sys->i_nb_samples ); + i_nb_samples -= MPEG_FRAME_SIZE - p_sys->i_nb_samples; + p_buffer += (MPEG_FRAME_SIZE - p_sys->i_nb_samples) * 2; + + i_used = twolame_encode_buffer_interleaved( p_sys->p_twolame, + p_sys->p_buffer, MPEG_FRAME_SIZE, + p_sys->p_out_buffer, MAX_CODED_FRAME_SIZE ); + p_sys->i_nb_samples = 0; + p_block = block_New( p_enc, i_used ); + memcpy( p_block->p_buffer, p_sys->p_out_buffer, i_used ); + p_block->i_length = (mtime_t)1000000 * + (mtime_t)MPEG_FRAME_SIZE / (mtime_t)p_enc->fmt_out.audio.i_rate; + p_block->i_dts = p_block->i_pts = p_sys->i_pts; + p_sys->i_pts += p_block->i_length; + block_ChainAppend( &p_chain, p_block ); + } + + if ( i_nb_samples ) + { + Bufferize( p_enc, p_buffer, i_nb_samples ); + p_sys->i_nb_samples += i_nb_samples; + } + + return p_chain; +} + +/***************************************************************************** + * CloseEncoder: twolame encoder destruction + *****************************************************************************/ +static void CloseEncoder( vlc_object_t *p_this ) +{ + encoder_t *p_enc = (encoder_t *)p_this; + encoder_sys_t *p_sys = p_enc->p_sys; + + twolame_close( &p_sys->p_twolame ); + + free( p_sys ); +} diff --git a/pool/shard008/C/0130576_main.c b/pool/shard008/C/0130576_main.c new file mode 100644 index 0000000000000000000000000000000000000000..62190973b23ef6d304847c06f6adef4c64fb47bc --- /dev/null +++ b/pool/shard008/C/0130576_main.c @@ -0,0 +1,141 @@ +/* + ChibiOS/RT - Copyright (C) 2006,2007,2008,2009,2010, + 2011,2012 Giovanni Di Sirio. + + This file is part of ChibiOS/RT. + + ChibiOS/RT 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. + + ChibiOS/RT 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 . +*/ + +#include "ch.h" +#include "hal.h" +#include "test.h" + +/* + * Conversion table from hex digit to 7 segments encoding, bit 5 controls the + * dot. + * 8 = LU, 4 = RL, 2 = D, 1 = RU, 8 = U, 4 = M, 2 = LL, 1 = L. + */ +static uint8_t digits[32] = { + 0x24, 0xAF, 0xE0, 0xA2, 0x2B, 0x32, 0x30, 0xA7, + 0x20, 0x22, 0x21, 0x38, 0x74, 0xA8, 0x70, 0x71, + 0x04, 0x8F, 0xC0, 0x82, 0x0B, 0x12, 0x10, 0x87, + 0x00, 0x02, 0x01, 0x18, 0x54, 0x88, 0x50, 0x51 +}; + +/* + * SPI configuration (1MHz, CPHA=0, CPOL=0). + */ +static SPIConfig spicfg = { + NULL, + GPIO1, + GPIO1_SPI0SEL, + CR0_DSS8BIT | CR0_FRFSPI | CR0_CLOCKRATE(0), + 48 +}; + +/* + * Red LED blinker thread, times are in milliseconds. + */ +static WORKING_AREA(waThread1, 128); +static msg_t Thread1(void *arg) { + + (void)arg; + chRegSetThreadName("blinker1"); + while (TRUE) { + palClearPad(GPIO0, GPIO0_LED2); + chThdSleepMilliseconds(500); + palSetPad(GPIO0, GPIO0_LED2); + chThdSleepMilliseconds(500); + } +} + +/* + * RGB LED blinker thread, times are in milliseconds. + */ +static WORKING_AREA(waThread2, 128); +static msg_t Thread2(void *arg) { + + (void)arg; + chRegSetThreadName("blinker2"); + while (TRUE) { + palClearPort(GPIO1, PAL_PORT_BIT(GPIO1_LED3B) | + PAL_PORT_BIT(GPIO1_LED3R) | + PAL_PORT_BIT(GPIO1_LED3G)); + chThdSleepMilliseconds(250); + palClearPort(GPIO1, PAL_PORT_BIT(GPIO1_LED3B) | + PAL_PORT_BIT(GPIO1_LED3R) | + PAL_PORT_BIT(GPIO1_LED3G)); + palSetPort(GPIO1, PAL_PORT_BIT(GPIO1_LED3B)); + chThdSleepMilliseconds(250); + palClearPort(GPIO1, PAL_PORT_BIT(GPIO1_LED3B) | + PAL_PORT_BIT(GPIO1_LED3R) | + PAL_PORT_BIT(GPIO1_LED3G)); + palSetPort(GPIO1, PAL_PORT_BIT(GPIO1_LED3R)); + chThdSleepMilliseconds(250); + palClearPort(GPIO1, PAL_PORT_BIT(GPIO1_LED3B) | + PAL_PORT_BIT(GPIO1_LED3R) | + PAL_PORT_BIT(GPIO1_LED3G)); + palSetPort(GPIO1, PAL_PORT_BIT(GPIO1_LED3G)); + chThdSleepMilliseconds(250); + } +} + +/* + * Application entry point. + */ +int main(void) { + uint8_t i; + + /* + * System initializations. + * - HAL initialization, this also initializes the configured device drivers + * and performs the board-specific initializations. + * - Kernel initialization, the main() function becomes a thread and the + * RTOS is active. + */ + halInit(); + chSysInit(); + + /* + * Activates the SD1 and SPI1 drivers. + */ + sdStart(&SD1, NULL); /* Default: 38400,8,N,1. */ + spiStart(&SPID1, &spicfg); + + /* + * Creates the blinker threads. + */ + chThdCreateStatic(waThread1, sizeof(waThread1), NORMALPRIO, Thread1, NULL); + chThdCreateStatic(waThread2, sizeof(waThread2), NORMALPRIO, Thread2, NULL); + + /* + * Normal main() thread activity, in this demo it updates the 7-segments + * display on the LPCXpresso main board using the SPI driver. + */ + i = 0; + while (TRUE) { + if (!palReadPad(GPIO0, GPIO0_SW3)) + TestThread(&SD1); + spiSelect(&SPID1); + spiSend(&SPID1, 1, &digits[i]); /* Non polled method. */ + spiUnselect(&SPID1); + chThdSleepMilliseconds(500); + spiSelect(&SPID1); + spiPolledExchange(&SPID1, digits[i | 0x10]); /* Polled method. */ + spiUnselect(&SPID1); + chThdSleepMilliseconds(500); + i = (i + 1) & 15; + } +} diff --git a/pool/shard008/C/0130577_ssl_sock_dump.c b/pool/shard008/C/0130577_ssl_sock_dump.c new file mode 100644 index 0000000000000000000000000000000000000000..0734004c5123c9d347d958ba3816dc236c82a0fb --- /dev/null +++ b/pool/shard008/C/0130577_ssl_sock_dump.c @@ -0,0 +1,146 @@ +/* $Id: ssl_sock_dump.c 5659 2017-09-25 02:58:42Z riza $ */ +/* + * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.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 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#include +#include +#include +#include + + +/* Only build when PJ_HAS_SSL_SOCK is enabled */ +#if defined(PJ_HAS_SSL_SOCK) && PJ_HAS_SSL_SOCK!=0 + +#define THIS_FILE "ssl_sock_dump.c" + +#define CHECK_BUF_LEN() \ + if ((len < 0) || (len >= end-p)) { \ + *p = '\0'; \ + return -1; \ + } \ + p += len; + +PJ_DEF(pj_ssize_t) pj_ssl_cert_info_dump(const pj_ssl_cert_info *ci, + const char *indent, + char *buf, + pj_size_t buf_size) +{ + const char *wdays[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; + pj_parsed_time pt1; + pj_parsed_time pt2; + unsigned i; + int len = 0; + char *p, *end; + + p = buf; + end = buf + buf_size; + + pj_time_decode(&ci->validity.start, &pt1); + pj_time_decode(&ci->validity.end, &pt2); + + /* Version */ + len = pj_ansi_snprintf(p, end-p, "%sVersion : v%d\n", + indent, ci->version); + CHECK_BUF_LEN(); + + /* Serial number */ + len = pj_ansi_snprintf(p, end-p, "%sSerial : ", indent); + CHECK_BUF_LEN(); + + for (i = 0; i < sizeof(ci->serial_no) && !ci->serial_no[i]; ++i); + for (; i < sizeof(ci->serial_no); ++i) { + len = pj_ansi_snprintf(p, end-p, "%02X ", ci->serial_no[i] & 0xFF); + CHECK_BUF_LEN(); + } + *(p-1) = '\n'; + + /* Subject */ + len = pj_ansi_snprintf( p, end-p, "%sSubject : %.*s\n", indent, + (int)ci->subject.cn.slen, + ci->subject.cn.ptr); + CHECK_BUF_LEN(); + len = pj_ansi_snprintf( p, end-p, "%s %.*s\n", indent, + (int)ci->subject.info.slen, + ci->subject.info.ptr); + CHECK_BUF_LEN(); + + /* Issuer */ + len = pj_ansi_snprintf( p, end-p, "%sIssuer : %.*s\n", indent, + (int)ci->issuer.cn.slen, + ci->issuer.cn.ptr); + CHECK_BUF_LEN(); + len = pj_ansi_snprintf( p, end-p, "%s %.*s\n", indent, + (int)ci->issuer.info.slen, + ci->issuer.info.ptr); + CHECK_BUF_LEN(); + + /* Validity period */ + len = pj_ansi_snprintf( p, end-p, "%sValid from : %s %4d-%02d-%02d " + "%02d:%02d:%02d.%03d %s\n", indent, + wdays[pt1.wday], pt1.year, pt1.mon+1, pt1.day, + pt1.hour, pt1.min, pt1.sec, pt1.msec, + (ci->validity.gmt? "GMT":"")); + CHECK_BUF_LEN(); + + len = pj_ansi_snprintf( p, end-p, "%sValid to : %s %4d-%02d-%02d " + "%02d:%02d:%02d.%03d %s\n", indent, + wdays[pt2.wday], pt2.year, pt2.mon+1, pt2.day, + pt2.hour, pt2.min, pt2.sec, pt2.msec, + (ci->validity.gmt? "GMT":"")); + CHECK_BUF_LEN(); + + /* Subject alternative name extension */ + if (ci->subj_alt_name.cnt) { + len = pj_ansi_snprintf(p, end-p, "%ssubjectAltName extension\n", + indent); + CHECK_BUF_LEN(); + + for (i = 0; i < ci->subj_alt_name.cnt; ++i) { + const char *type = NULL; + + switch(ci->subj_alt_name.entry[i].type) { + case PJ_SSL_CERT_NAME_RFC822: + type = "MAIL"; + break; + case PJ_SSL_CERT_NAME_DNS: + type = " DNS"; + break; + case PJ_SSL_CERT_NAME_URI: + type = " URI"; + break; + case PJ_SSL_CERT_NAME_IP: + type = " IP"; + break; + default: + break; + } + if (type) { + len = pj_ansi_snprintf( p, end-p, "%s %s : %.*s\n", indent, + type, + (int)ci->subj_alt_name.entry[i].name.slen, + ci->subj_alt_name.entry[i].name.ptr); + CHECK_BUF_LEN(); + } + } + } + + return (p-buf); +} + + +#endif /* PJ_HAS_SSL_SOCK */ + diff --git a/pool/shard008/C/0130580_hotplug.c b/pool/shard008/C/0130580_hotplug.c new file mode 100644 index 0000000000000000000000000000000000000000..46e835ff7b05b4d007276e0fd0cd1d9789fa3785 --- /dev/null +++ b/pool/shard008/C/0130580_hotplug.c @@ -0,0 +1,178 @@ +/* + * Copyright (C) 2002 ARM Ltd. + * All Rights Reserved + * Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +#include "pm.h" +#include "spm.h" + +extern volatile int pen_release; + +struct msm_hotplug_device { + struct completion cpu_killed; + unsigned int warm_boot; +}; + +static DEFINE_PER_CPU_SHARED_ALIGNED(struct msm_hotplug_device, + msm_hotplug_devices); + +static inline void cpu_enter_lowpower(void) +{ + /* Just flush the cache. Changing the coherency is not yet + * available on msm. */ + flush_cache_all(); +} + +static inline void cpu_leave_lowpower(void) +{ +} + +static inline void platform_do_lowpower(unsigned int cpu) +{ + /* Just enter wfi for now. TODO: Properly shut off the cpu. */ + for (;;) { + + msm_pm_cpu_enter_lowpower(cpu); + if (pen_release == cpu_logical_map(cpu)) { + /* + * OK, proper wakeup, we're done + */ + pen_release = -1; + dmac_flush_range((void *)&pen_release, + (void *)(&pen_release + sizeof(pen_release))); + break; + } + + /* + * getting here, means that we have come out of WFI without + * having been woken up - this shouldn't happen + * + * The trouble is, letting people know about this is not really + * possible, since we are currently running incoherently, and + * therefore cannot safely call printk() or anything else + */ + dmac_inv_range((void *)&pen_release, + (void *)(&pen_release + sizeof(pen_release))); + pr_debug("CPU%u: spurious wakeup call\n", cpu); + } +} + +int platform_cpu_kill(unsigned int cpu) +{ + return 1; +} + +/* + * platform-specific code to shutdown a CPU + * + * Called with IRQs disabled + */ +void platform_cpu_die(unsigned int cpu) +{ + if (unlikely(cpu != smp_processor_id())) { + pr_crit("%s: running on %u, should be %u\n", + __func__, smp_processor_id(), cpu); + BUG(); + } + complete(&__get_cpu_var(msm_hotplug_devices).cpu_killed); + /* + * we're ready for shutdown now, so do it + */ + cpu_enter_lowpower(); + platform_do_lowpower(cpu); + + pr_debug("CPU%u: %s: normal wakeup\n", cpu, __func__); + cpu_leave_lowpower(); +} + +int platform_cpu_disable(unsigned int cpu) +{ + /* + * we don't allow CPU 0 to be shutdown (it is still too special + * e.g. clock tick interrupts) + */ + return cpu == 0 ? -EPERM : 0; +} + +#define CPU_SHIFT 0 +#define CPU_MASK 0xF +#define CPU_OF(n) (((n) & CPU_MASK) << CPU_SHIFT) +#define CPUSET_SHIFT 4 +#define CPUSET_MASK 0xFFFF +#define CPUSET_OF(n) (((n) & CPUSET_MASK) << CPUSET_SHIFT) + +static int hotplug_rtb_callback(struct notifier_block *nfb, + unsigned long action, void *hcpu) +{ + /* + * Bits [19:4] of the data are the online mask, lower 4 bits are the + * cpu number that is being changed. Additionally, changes to the + * online_mask that will be done by the current hotplug will be made + * even though they aren't necessarily in the online mask yet. + * + * XXX: This design is limited to supporting at most 16 cpus + */ + int this_cpumask = CPUSET_OF(1 << (int)hcpu); + int cpumask = CPUSET_OF(cpumask_bits(cpu_online_mask)[0]); + int cpudata = CPU_OF((int)hcpu) | cpumask; + + switch (action & (~CPU_TASKS_FROZEN)) { + case CPU_STARTING: + uncached_logk(LOGK_HOTPLUG, (void *)(cpudata | this_cpumask)); + break; + case CPU_DYING: + uncached_logk(LOGK_HOTPLUG, (void *)(cpudata & ~this_cpumask)); + break; + default: + break; + } + + return NOTIFY_OK; +} +static struct notifier_block hotplug_rtb_notifier = { + .notifier_call = hotplug_rtb_callback, +}; + +int msm_platform_secondary_init(unsigned int cpu) +{ + int ret; + struct msm_hotplug_device *dev = &__get_cpu_var(msm_hotplug_devices); + + if (!dev->warm_boot) { + dev->warm_boot = 1; + init_completion(&dev->cpu_killed); + return 0; + } + msm_jtag_restore_state(); +#if defined(CONFIG_VFP) && defined (CONFIG_CPU_PM) + vfp_pm_resume(); +#endif + ret = msm_spm_set_low_power_mode(MSM_SPM_MODE_CLOCK_GATING, false); + + return ret; +} + +static int __init init_hotplug(void) +{ + + struct msm_hotplug_device *dev = &__get_cpu_var(msm_hotplug_devices); + init_completion(&dev->cpu_killed); + return register_hotcpu_notifier(&hotplug_rtb_notifier); +} +early_initcall(init_hotplug); diff --git a/pool/shard008/C/0130581_concat2.c b/pool/shard008/C/0130581_concat2.c new file mode 100644 index 0000000000000000000000000000000000000000..34ac2b30460d5c6d91ce15c3dc640daaa00862a0 --- /dev/null +++ b/pool/shard008/C/0130581_concat2.c @@ -0,0 +1,34 @@ +//Revising the concatenation program using character array initialization and printing with %c + +#include + +int main (void) +{ + + void concat (char result[], const char str1[], const char str2[]); + const char s1[] = { "Test " }; + const char s2[] = { "works." }; + char s3[20]; + + concat(s3, s1, s2); + + printf("%s\n", s3); + + return 0; +} + +//Function to concatenate 2 strings into one array + +void concat (char result[], const char str1[], const char str2[]) +{ + int i, j; + + for ( i = 0; str1[i] != '\0'; ++i ) + result[i] = str1[i]; + + for ( j = 0; str2[j] != '\0'; ++j) + result[i+j] = str2[j]; + + result[i+j] = '\0'; + +} diff --git a/pool/shard008/C/0130585_addmul_1.c b/pool/shard008/C/0130585_addmul_1.c new file mode 100644 index 0000000000000000000000000000000000000000..e1d52e4a5f435028f700d43c86b45c7f6378521c --- /dev/null +++ b/pool/shard008/C/0130585_addmul_1.c @@ -0,0 +1,49 @@ +/* mpn_addmul_1 for Cray PVP. + +Copyright 1996, 2000, 2001 Free Software Foundation, Inc. + +This file is part of the GNU MP Library. + +The GNU MP Library is free software; you can redistribute it and/or modify +it under the terms of either: + + * 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. + +or + + * 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. + +or both in parallel, as here. + +The GNU MP 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 General Public License +for more details. + +You should have received copies of the GNU General Public License and the +GNU Lesser General Public License along with the GNU MP Library. If not, +see https://www.gnu.org/licenses/. */ + + +#include "gmp.h" +#include "gmp-impl.h" + +mp_limb_t +mpn_addmul_1 (mp_ptr rp, mp_srcptr up, mp_size_t n, mp_limb_t limb) +{ + mp_limb_t p0[n], p1[n], tp[n]; + mp_limb_t cy_limb; + + GMPN_MULWW (p1, p0, up, &n, &limb); + cy_limb = mpn_add_n (tp, rp, p0, n); + rp[0] = tp[0]; + if (n != 1) + cy_limb += mpn_add_n (rp + 1, tp + 1, p1, n - 1); + cy_limb += p1[n - 1]; + + return cy_limb; +} diff --git a/pool/shard008/C/0130586_pj_auth.c b/pool/shard008/C/0130586_pj_auth.c new file mode 100644 index 0000000000000000000000000000000000000000..9d62cd7d37f6f6f68fa0c13398265b0b6f01a1fb --- /dev/null +++ b/pool/shard008/C/0130586_pj_auth.c @@ -0,0 +1,30 @@ +/* determine latitude from authalic latitude */ +#include +# define P00 .33333333333333333333 +# define P01 .17222222222222222222 +# define P02 .10257936507936507936 +# define P10 .06388888888888888888 +# define P11 .06640211640211640211 +# define P20 .01641501294219154443 +#define APA_SIZE 3 + double * +pj_authset(double es) { + double t, *APA; + + if ((APA = (double *)pj_malloc(APA_SIZE * sizeof(double)))) { + APA[0] = es * P00; + t = es * es; + APA[0] += t * P01; + APA[1] = t * P10; + t *= es; + APA[0] += t * P02; + APA[1] += t * P11; + APA[2] = t * P20; + } + return APA; +} + double +pj_authlat(double beta, double *APA) { + double t = beta+beta; + return(beta + APA[0] * sin(t) + APA[1] * sin(t+t) + APA[2] * sin(t+t+t)); +} diff --git a/pool/shard008/C/0130587_88pm860x-i2c.c b/pool/shard008/C/0130587_88pm860x-i2c.c new file mode 100644 index 0000000000000000000000000000000000000000..c37e12bf3004b943cdbcd9d9d7b58936cd9c5687 --- /dev/null +++ b/pool/shard008/C/0130587_88pm860x-i2c.c @@ -0,0 +1,236 @@ +/* + * I2C driver for Marvell 88PM860x + * + * Copyright (C) 2009 Marvell International Ltd. + * Haojian Zhuang + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ +#include +#include +#include +#include +#include + +static inline int pm860x_read_device(struct i2c_client *i2c, + int reg, int bytes, void *dest) +{ + unsigned char data; + int ret; + + data = (unsigned char)reg; + ret = i2c_master_send(i2c, &data, 1); + if (ret < 0) + return ret; + + ret = i2c_master_recv(i2c, dest, bytes); + if (ret < 0) + return ret; + return 0; +} + +static inline int pm860x_write_device(struct i2c_client *i2c, + int reg, int bytes, void *src) +{ + unsigned char buf[bytes + 1]; + int ret; + + buf[0] = (unsigned char)reg; + memcpy(&buf[1], src, bytes); + + ret = i2c_master_send(i2c, buf, bytes + 1); + if (ret < 0) + return ret; + return 0; +} + +int pm860x_reg_read(struct i2c_client *i2c, int reg) +{ + struct pm860x_chip *chip = i2c_get_clientdata(i2c); + unsigned char data; + int ret; + + mutex_lock(&chip->io_lock); + ret = pm860x_read_device(i2c, reg, 1, &data); + mutex_unlock(&chip->io_lock); + + if (ret < 0) + return ret; + else + return (int)data; +} +EXPORT_SYMBOL(pm860x_reg_read); + +int pm860x_reg_write(struct i2c_client *i2c, int reg, + unsigned char data) +{ + struct pm860x_chip *chip = i2c_get_clientdata(i2c); + int ret; + + mutex_lock(&chip->io_lock); + ret = pm860x_write_device(i2c, reg, 1, &data); + mutex_unlock(&chip->io_lock); + + return ret; +} +EXPORT_SYMBOL(pm860x_reg_write); + +int pm860x_bulk_read(struct i2c_client *i2c, int reg, + int count, unsigned char *buf) +{ + struct pm860x_chip *chip = i2c_get_clientdata(i2c); + int ret; + + mutex_lock(&chip->io_lock); + ret = pm860x_read_device(i2c, reg, count, buf); + mutex_unlock(&chip->io_lock); + + return ret; +} +EXPORT_SYMBOL(pm860x_bulk_read); + +int pm860x_bulk_write(struct i2c_client *i2c, int reg, + int count, unsigned char *buf) +{ + struct pm860x_chip *chip = i2c_get_clientdata(i2c); + int ret; + + mutex_lock(&chip->io_lock); + ret = pm860x_write_device(i2c, reg, count, buf); + mutex_unlock(&chip->io_lock); + + return ret; +} +EXPORT_SYMBOL(pm860x_bulk_write); + +int pm860x_set_bits(struct i2c_client *i2c, int reg, + unsigned char mask, unsigned char data) +{ + struct pm860x_chip *chip = i2c_get_clientdata(i2c); + unsigned char value; + int ret; + + mutex_lock(&chip->io_lock); + ret = pm860x_read_device(i2c, reg, 1, &value); + if (ret < 0) + goto out; + value &= ~mask; + value |= data; + ret = pm860x_write_device(i2c, reg, 1, &value); +out: + mutex_unlock(&chip->io_lock); + return ret; +} +EXPORT_SYMBOL(pm860x_set_bits); + + +static const struct i2c_device_id pm860x_id_table[] = { + { "88PM860x", 0 }, + {} +}; +MODULE_DEVICE_TABLE(i2c, pm860x_id_table); + +static int verify_addr(struct i2c_client *i2c) +{ + unsigned short addr_8607[] = {0x30, 0x34}; + unsigned short addr_8606[] = {0x10, 0x11}; + int size, i; + + if (i2c == NULL) + return 0; + size = ARRAY_SIZE(addr_8606); + for (i = 0; i < size; i++) { + if (i2c->addr == *(addr_8606 + i)) + return CHIP_PM8606; + } + size = ARRAY_SIZE(addr_8607); + for (i = 0; i < size; i++) { + if (i2c->addr == *(addr_8607 + i)) + return CHIP_PM8607; + } + return 0; +} + +static int __devinit pm860x_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + struct pm860x_platform_data *pdata = client->dev.platform_data; + struct pm860x_chip *chip; + + if (!pdata) { + pr_info("No platform data in %s!\n", __func__); + return -EINVAL; + } + + chip = kzalloc(sizeof(struct pm860x_chip), GFP_KERNEL); + if (chip == NULL) + return -ENOMEM; + + chip->id = verify_addr(client); + chip->client = client; + i2c_set_clientdata(client, chip); + chip->dev = &client->dev; + mutex_init(&chip->io_lock); + dev_set_drvdata(chip->dev, chip); + + /* + * Both client and companion client shares same platform driver. + * Driver distinguishes them by pdata->companion_addr. + * pdata->companion_addr is only assigned if companion chip exists. + * At the same time, the companion_addr shouldn't equal to client + * address. + */ + if (pdata->companion_addr && (pdata->companion_addr != client->addr)) { + chip->companion_addr = pdata->companion_addr; + chip->companion = i2c_new_dummy(chip->client->adapter, + chip->companion_addr); + i2c_set_clientdata(chip->companion, chip); + } + + pm860x_device_init(chip, pdata); + return 0; +} + +static int __devexit pm860x_remove(struct i2c_client *client) +{ + struct pm860x_chip *chip = i2c_get_clientdata(client); + + pm860x_device_exit(chip); + i2c_unregister_device(chip->companion); + i2c_set_clientdata(chip->companion, NULL); + i2c_set_clientdata(chip->client, NULL); + kfree(chip); + return 0; +} + +static struct i2c_driver pm860x_driver = { + .driver = { + .name = "88PM860x", + .owner = THIS_MODULE, + }, + .probe = pm860x_probe, + .remove = __devexit_p(pm860x_remove), + .id_table = pm860x_id_table, +}; + +static int __init pm860x_i2c_init(void) +{ + int ret; + ret = i2c_add_driver(&pm860x_driver); + if (ret != 0) + pr_err("Failed to register 88PM860x I2C driver: %d\n", ret); + return ret; +} +subsys_initcall(pm860x_i2c_init); + +static void __exit pm860x_i2c_exit(void) +{ + i2c_del_driver(&pm860x_driver); +} +module_exit(pm860x_i2c_exit); + +MODULE_DESCRIPTION("I2C Driver for Marvell 88PM860x"); +MODULE_AUTHOR("Haojian Zhuang "); +MODULE_LICENSE("GPL"); diff --git a/pool/shard008/C/0130589_fptask.c b/pool/shard008/C/0130589_fptask.c new file mode 100644 index 0000000000000000000000000000000000000000..d3fdbeb9a4f5ee8602eefa905e3c1f9300732eb8 --- /dev/null +++ b/pool/shard008/C/0130589_fptask.c @@ -0,0 +1,97 @@ +/* FP_task + * + * This routine serves as a floating point test task. It verifies the + * basic task switching capabilities of the executive when floating + * point is configured. + * + * Input parameters: + * argument - task argument + * + * Output parameters: NONE + * + * COPYRIGHT (c) 1989-2009. + * On-Line Applications Research Corporation (OAR). + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rtems.com/license/LICENSE. + * + * $Id$ + */ + +#include "system.h" +#include "fptest.h" +#include "inttest.h" + +rtems_task FP_task( + rtems_task_argument argument +) +{ + rtems_status_code status; + rtems_id tid; + rtems_time_of_day time; + uint32_t task_index; + uint32_t previous_seconds; + INTEGER_DECLARE; + FP_DECLARE; + + status = rtems_task_ident( RTEMS_SELF, RTEMS_SEARCH_ALL_NODES, &tid ); + directive_failed( status, "rtems_task_ident of self" ); + + task_index = task_number( tid ); + + INTEGER_LOAD( INTEGER_factors[ task_index ] ); + FP_LOAD( FP_factors[ task_index ] ); + + put_name( Task_name[ task_index ], FALSE ); + printf( " - integer base = (0x%" PRIx32 ")\n", INTEGER_factors[ task_index ] ); + put_name( Task_name[ task_index ], FALSE ); +#if ( RTEMS_HAS_HARDWARE_FP == 1 ) + printf( " - float base = (%g)\n", FP_factors[ task_index ] ); +#else + printf( " - float base = (NA)\n" ); +#endif + + previous_seconds = (uint32_t)-1; + + while( FOREVER ) { + + status = rtems_clock_get_tod( &time ); + directive_failed( status, "rtems_clock_get_tod" ); + + if ( time.second >= 16 ) { + + if ( task_number( tid ) == 4 ) { + puts( "TA4 - rtems_task_delete - self" ); + status = rtems_task_delete( RTEMS_SELF ); + directive_failed( status, "rtems_task_delete of TA4" ); + } + puts( "TA5 - rtems_task_delete - TA3" ); + status = rtems_task_delete( Task_id[ 3 ] ); + directive_failed( status, "rtems_task_delete of TA3" ); + + puts( "*** END OF TEST 19 *** " ); + rtems_test_exit( 0 ); + } + + if (previous_seconds != time.second) + { + put_name( Task_name[ task_index ], FALSE ); + print_time( " - rtems_clock_get_tod - ", &time, "\n" ); + previous_seconds = time.second; + } + + INTEGER_CHECK( INTEGER_factors[ task_index ] ); + FP_CHECK( FP_factors[ task_index ] ); + + /* for the first 4 seconds we spin as fast as possible + * so that we likely are interrupted + * After that, we go to sleep for a second at a time + */ + if (time.second >= 4) + { + status = rtems_task_wake_after( rtems_clock_get_ticks_per_second() ); + directive_failed( status, "rtems_task_wake_after" ); + } + } +} diff --git a/pool/shard008/C/0130590_memory.c b/pool/shard008/C/0130590_memory.c new file mode 100644 index 0000000000000000000000000000000000000000..df529c6d9f2d3ce8b8bc11804f08f21f788a0d22 --- /dev/null +++ b/pool/shard008/C/0130590_memory.c @@ -0,0 +1,161 @@ +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% M M EEEEE M M OOO RRRR Y Y % +% MM MM E MM MM O O R R Y Y % +% M M M EEE M M M O O RRRR Y % +% M M E M M O O R R Y % +% M M EEEEE M M OOO R R Y % +% % +% % +% ImageMagick Memory Allocation Methods % +% % +% % +% Software Design % +% John Cristy % +% July 1998 % +% % +% % +% Copyright 1999 E. I. du Pont de Nemours and Company % +% % +% Permission is hereby granted, free of charge, to any person obtaining a % +% copy of this software and associated documentation files ("ImageMagick"), % +% to deal in ImageMagick without restriction, including without limitation % +% the rights to use, copy, modify, merge, publish, distribute, sublicense, % +% and/or sell copies of ImageMagick, and to permit persons to whom the % +% ImageMagick is furnished to do so, subject to the following conditions: % +% % +% The above copyright notice and this permission notice shall be included in % +% all copies or substantial portions of ImageMagick. % +% % +% The software is provided "as is", without warranty of any kind, express or % +% implied, including but not limited to the warranties of merchantability, % +% fitness for a particular purpose and noninfringement. In no event shall % +% E. I. du Pont de Nemours and Company be liable for any claim, damages or % +% other liability, whether in an action of contract, tort or otherwise, % +% arising from, out of or in connection with ImageMagick or the use or other % +% dealings in ImageMagick. % +% % +% Except as contained in this notice, the name of the E. I. du Pont de % +% Nemours and Company shall not be used in advertising or otherwise to % +% promote the sale, use or other dealings in ImageMagick without prior % +% written authorization from the E. I. du Pont de Nemours and Company. % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% +% +*/ + +/* + Include declarations. +*/ +#include "magick.h" +#include "defines.h" + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% A l l o c a t e M e m o r y % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% Method AllocateMemory returns a pointer to a block of at least size bytes +% suitably aligned for any use. +% +% The format of the AllocateMemory method is: +% +% void *AllocateMemory(const size_t size) +% +% A description of each parameter follows: +% +% o memory: Method AllocateMemory returns a pointer to a block of at +% least size bytes suitably aligned for any use. +% +% o size: Specifies the size of the memory to return. +% +% +*/ +Export void *AllocateMemory(const size_t size) +{ + assert(size > 0); + return(malloc(size)); +} + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% F r e e M e m o r y % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% Method FreeMemory frees memory that has already been allocated. +% +% The format of the FreeMemory method is: +% +% void FreeMemory(void *memory) +% +% A description of each parameter follows: +% +% o span: Specifies the pointer to a block memory to free for reuse. +% +% +*/ +Export void FreeMemory(void *memory) +{ + if (memory == (void *) NULL) + return; + free(memory); + memory=(void *)NULL; +} + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% R e a l l o c a t e M e m o r y % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% Method ReallocateMemory changes the size of the memory and returns a +% pointer to the (possibly moved) block. The contents will be unchanged up +% to the lesser of the new and old sizes. +% +% The format of the ReallocateMemory method is: +% +% void *ReallocateMemory(void *memory,const size_t size) +% +% A description of each parameter follows: +% +% o memory: Method ReallocateMemory returns a pointer to a block of at +% least size bytes suitably aligned for any use. +% +% o size: Specifies the size of the memory to return. +% +% +*/ +Export void *ReallocateMemory(void *memory,const size_t size) +{ + void + *new_memory; + + new_memory=(void *) NULL; + if (size) + new_memory=realloc(memory,size); + if (new_memory == (void *) NULL) + FreeMemory(memory); + return(new_memory); +} diff --git a/pool/shard008/C/0130591_st5481_init.c b/pool/shard008/C/0130591_st5481_init.c new file mode 100644 index 0000000000000000000000000000000000000000..517d01cff6c0c73cd53bc65725ecc54cc1e0e584 --- /dev/null +++ b/pool/shard008/C/0130591_st5481_init.c @@ -0,0 +1,224 @@ +/* + * Driver for ST5481 USB ISDN modem + * + * Author Frode Isaksen + * Copyright 2001 by Frode Isaksen + * 2001 by Kai Germaschewski + * + * This software may be used and distributed according to the terms + * of the GNU General Public License, incorporated herein by reference. + * + */ + +/* + * TODO: + * + * b layer1 delay? + * hotplug / unregister issues + * mod_inc/dec_use_count + * unify parts of d/b channel usb handling + * file header + * avoid copy to isoc buffer? + * improve usb delay? + * merge l1 state machines? + * clean up debug + */ + +#include +#include +#include +#include +#include "st5481.h" + +MODULE_DESCRIPTION("ISDN4Linux: driver for ST5481 USB ISDN adapter"); +MODULE_AUTHOR("Frode Isaksen"); +MODULE_LICENSE("GPL"); + +static int protocol = 2; /* EURO-ISDN Default */ +module_param(protocol, int, 0); + +static int number_of_leds = 2; /* 2 LEDs on the adpater default */ +module_param(number_of_leds, int, 0); + +#ifdef CONFIG_HISAX_DEBUG +static int debug = 0; +module_param(debug, int, 0); +#endif +int st5481_debug; + +static LIST_HEAD(adapter_list); + +/* ====================================================================== + * registration/deregistration with the USB layer + */ + +/* + * This function will be called when the adapter is plugged + * into the USB bus. + */ +static int probe_st5481(struct usb_interface *intf, + const struct usb_device_id *id) +{ + struct usb_device *dev = interface_to_usbdev(intf); + struct st5481_adapter *adapter; + struct hisax_b_if *b_if[2]; + int retval, i; + + printk(KERN_INFO "st541: found adapter VendorId %04x, ProductId %04x, LEDs %d\n", + le16_to_cpu(dev->descriptor.idVendor), + le16_to_cpu(dev->descriptor.idProduct), + number_of_leds); + + adapter = kzalloc(sizeof(struct st5481_adapter), GFP_KERNEL); + if (!adapter) + return -ENOMEM; + + adapter->number_of_leds = number_of_leds; + adapter->usb_dev = dev; + + adapter->hisax_d_if.owner = THIS_MODULE; + adapter->hisax_d_if.ifc.priv = adapter; + adapter->hisax_d_if.ifc.l2l1 = st5481_d_l2l1; + + for (i = 0; i < 2; i++) { + adapter->bcs[i].adapter = adapter; + adapter->bcs[i].channel = i; + adapter->bcs[i].b_if.ifc.priv = &adapter->bcs[i]; + adapter->bcs[i].b_if.ifc.l2l1 = st5481_b_l2l1; + } + list_add(&adapter->list, &adapter_list); + + retval = st5481_setup_usb(adapter); + if (retval < 0) + goto err; + + retval = st5481_setup_d(adapter); + if (retval < 0) + goto err_usb; + + retval = st5481_setup_b(&adapter->bcs[0]); + if (retval < 0) + goto err_d; + + retval = st5481_setup_b(&adapter->bcs[1]); + if (retval < 0) + goto err_b; + + for (i = 0; i < 2; i++) + b_if[i] = &adapter->bcs[i].b_if; + + if (hisax_register(&adapter->hisax_d_if, b_if, "st5481_usb", + protocol) != 0) + goto err_b1; + + st5481_start(adapter); + + usb_set_intfdata(intf, adapter); + return 0; + + err_b1: + st5481_release_b(&adapter->bcs[1]); + err_b: + st5481_release_b(&adapter->bcs[0]); + err_d: + st5481_release_d(adapter); + err_usb: + st5481_release_usb(adapter); + err: + return -EIO; +} + +/* + * This function will be called when the adapter is removed + * from the USB bus. + */ +static void disconnect_st5481(struct usb_interface *intf) +{ + struct st5481_adapter *adapter = usb_get_intfdata(intf); + + DBG(1,""); + + usb_set_intfdata(intf, NULL); + if (!adapter) + return; + + list_del(&adapter->list); + + st5481_stop(adapter); + st5481_release_b(&adapter->bcs[1]); + st5481_release_b(&adapter->bcs[0]); + st5481_release_d(adapter); + // we would actually better wait for completion of outstanding urbs + mdelay(2); + st5481_release_usb(adapter); + + hisax_unregister(&adapter->hisax_d_if); + + kfree(adapter); +} + +/* + * The last 4 bits in the Product Id is set with 4 pins on the chip. + */ +static struct usb_device_id st5481_ids[] = { + { USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID+0x0) }, + { USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID+0x1) }, + { USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID+0x2) }, + { USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID+0x3) }, + { USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID+0x4) }, + { USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID+0x5) }, + { USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID+0x6) }, + { USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID+0x7) }, + { USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID+0x8) }, + { USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID+0x9) }, + { USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID+0xA) }, + { USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID+0xB) }, + { USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID+0xC) }, + { USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID+0xD) }, + { USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID+0xE) }, + { USB_DEVICE(ST_VENDOR_ID, ST5481_PRODUCT_ID+0xF) }, + { } +}; +MODULE_DEVICE_TABLE (usb, st5481_ids); + +static struct usb_driver st5481_usb_driver = { + .name = "st5481_usb", + .probe = probe_st5481, + .disconnect = disconnect_st5481, + .id_table = st5481_ids, +}; + +static int __init st5481_usb_init(void) +{ + int retval; + +#ifdef CONFIG_HISAX_DEBUG + st5481_debug = debug; +#endif + + printk(KERN_INFO "hisax_st5481: ST5481 USB ISDN driver $Revision: 1.1.1.1 $\n"); + + retval = st5481_d_init(); + if (retval < 0) + goto out; + + retval = usb_register(&st5481_usb_driver); + if (retval < 0) + goto out_d_exit; + + return 0; + + out_d_exit: + st5481_d_exit(); + out: + return retval; +} + +static void __exit st5481_usb_exit(void) +{ + usb_deregister(&st5481_usb_driver); + st5481_d_exit(); +} + +module_init(st5481_usb_init); +module_exit(st5481_usb_exit); diff --git a/pool/shard008/C/0130593_us_ticker.c b/pool/shard008/C/0130593_us_ticker.c new file mode 100644 index 0000000000000000000000000000000000000000..90db88cd7b1e97c97cd1b51e10e652106fbb4305 --- /dev/null +++ b/pool/shard008/C/0130593_us_ticker.c @@ -0,0 +1,116 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2018 ARM Limited + * + * 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. + */ +#include +#include "us_ticker_api.h" +#include "PeripheralNames.h" +#define US_TICKER_TIMER1 CMSDK_DUALTIMER1 +#define US_TICKER_TIMER2 CMSDK_DUALTIMER2 +#define US_TICKER_TIMER_IRQn DUALTIMER_IRQn + +/** mbed OS HAL API defined us_ticker as an increment ticker + * MPS2 platform provided in SSE-200 are decrement tickers + * with interrupt fired counter reaches 0. + * + * So 2 Timers are used to construct mbed OS HAL ticker. + * + * TIMER1 is for counting, and returns inverted binary when read from it + * TIMER1 will be kept in free-running mode (default, and not generate interrupts) + * + * TIMER2 is for generating interrupts + * So TIMER2 is set to periodic mode, which start decrement counting form LOADVALUE generates interrupts at 0 + * and TIMER2 also set into one-shot mode, which counter halts when is reaches 0 + */ + +static int us_ticker_inited = 0; + +void us_ticker_init(void) +{ + if (us_ticker_inited) { + us_ticker_disable_interrupt(); + return; + } + + US_TICKER_TIMER1->TimerControl = 0x0ul; // disable TIMER1 and reset all control + US_TICKER_TIMER2->TimerControl = 0x0ul; // disable TIMER2 and reset all control + + US_TICKER_TIMER1->TimerLoad = 0xFFFFFFFFul; + US_TICKER_TIMER2->TimerLoad = 0xFFFFFFFFul; + + US_TICKER_TIMER1->TimerControl |= CMSDK_DUALTIMER1_CTRL_SIZE_Msk; // set TIMER1 to 32 bit counter + US_TICKER_TIMER2->TimerControl |= CMSDK_DUALTIMER2_CTRL_SIZE_Msk; // set TIMER2 to 32 bit counter + + US_TICKER_TIMER1->TimerControl |= 0x1 << CMSDK_DUALTIMER1_CTRL_PRESCALE_Pos; // set TIMER1 with 4 stages prescale + US_TICKER_TIMER2->TimerControl |= 0x1 << CMSDK_DUALTIMER2_CTRL_PRESCALE_Pos; // set TIMER2 with 4 stages prescale + + US_TICKER_TIMER2->TimerControl |= CMSDK_DUALTIMER2_CTRL_MODE_Msk; // set TIMER2 periodic mode + US_TICKER_TIMER2->TimerControl |= CMSDK_DUALTIMER2_CTRL_ONESHOOT_Msk; // set TIMER2 one-shot mode + + US_TICKER_TIMER1->TimerControl |= CMSDK_DUALTIMER1_CTRL_EN_Msk; // enable TIMER1 counter + + NVIC_SetVector(US_TICKER_TIMER_IRQn, (uint32_t)us_ticker_irq_handler); + us_ticker_inited = 1; +} + +void us_ticker_free(void) +{ + US_TICKER_TIMER1->TimerControl &= ~CMSDK_DUALTIMER1_CTRL_EN_Msk; // disable TIMER1 + US_TICKER_TIMER2->TimerControl &= ~CMSDK_DUALTIMER2_CTRL_EN_Msk; // disable TIMER2 + us_ticker_disable_interrupt(); + us_ticker_inited = 0; +} + +uint32_t us_ticker_read() +{ + return ~US_TICKER_TIMER1->TimerValue; +} + +void us_ticker_set_interrupt(timestamp_t timestamp) +{ + uint32_t delta = timestamp - us_ticker_read(); + US_TICKER_TIMER2->TimerControl &= ~CMSDK_DUALTIMER2_CTRL_EN_Msk; // disable TIMER2 + US_TICKER_TIMER2->TimerLoad = delta; // Set TIMER2 load value + US_TICKER_TIMER2->TimerControl |= CMSDK_DUALTIMER2_CTRL_INTEN_Msk; // enable TIMER2 interrupt + US_TICKER_TIMER2->TimerControl |= CMSDK_DUALTIMER2_CTRL_EN_Msk; // enable TIMER2 counter + NVIC_EnableIRQ(US_TICKER_TIMER_IRQn); +} + +void us_ticker_fire_interrupt(void) +{ + NVIC_EnableIRQ(US_TICKER_TIMER_IRQn); + NVIC_SetPendingIRQ(US_TICKER_TIMER_IRQn); +} + + +void us_ticker_disable_interrupt(void) +{ + US_TICKER_TIMER2->TimerControl &= ~CMSDK_DUALTIMER2_CTRL_INTEN_Msk; + US_TICKER_TIMER2->TimerControl &= ~CMSDK_DUALTIMER2_CTRL_EN_Msk; // disable TIMER2 + NVIC_DisableIRQ(US_TICKER_TIMER_IRQn); +} + +void us_ticker_clear_interrupt(void) +{ + US_TICKER_TIMER2->TimerIntClr = CMSDK_DUALTIMER2_INTCLR_Msk; +} + +const ticker_info_t *us_ticker_get_info(void) +{ + static const ticker_info_t info = { + 1562500, // 4 stages prescaled from 25MHz (dived by 16) + 32 // 32 bit counter + }; + return &info; +} diff --git a/pool/shard008/C/0130596_WriteBack.c b/pool/shard008/C/0130596_WriteBack.c new file mode 100644 index 0000000000000000000000000000000000000000..e1d025f482804e6db2130a3970b724b00ca1c2d3 --- /dev/null +++ b/pool/shard008/C/0130596_WriteBack.c @@ -0,0 +1,23 @@ +#include "WriteBack.h" + +#include + +void write_back(const mem_result_t * const in) +{ + if (in == NULL) + return; + + const uint8_t opcode = instruction_decode_opcode(in->inst); + const uint8_t type = instruction_decode_type(in->inst); + + if (type == BINARY_ARITHMETIC || type == UNARY_ARITHMETIC) + { + // decode destination + const uint32_t dest = instruction_decode_destination(in->inst); + registers[dest] = in->result; + } else if (opcode == OPCODE_LOAD) { + registers[in->io_op] = in->result; + } + + free((void *)in); +} diff --git a/pool/shard008/C/0130599_addNodeBegin.c b/pool/shard008/C/0130599_addNodeBegin.c new file mode 100644 index 0000000000000000000000000000000000000000..a0e52438058044d01aa3ce2c82a59692e38b108c --- /dev/null +++ b/pool/shard008/C/0130599_addNodeBegin.c @@ -0,0 +1,35 @@ +#include +#include "listHelper.h" + +void makeNode(struct linkList **head, struct linkList **tail, int dat) +{ + struct linkList *curr; + curr = (struct linkList*)malloc(sizeof(struct linkList)); + curr->data = dat; + curr->next = NULL; + + if(*head == NULL) { + *head = *tail = curr; + } + else { + curr->next = *head; + *head = curr; + } + +} + +void +main() { + + int dat; + struct linkList *head, *tail; + + tail = head = NULL; + + for (dat = 1; dat <= 21; dat++) + makeNode(&head, &tail, dat); + + displayList(head); + displayList(head); + free(head); +} diff --git a/pool/shard008/C/0130602_abstractformatter.zep.c b/pool/shard008/C/0130602_abstractformatter.zep.c new file mode 100644 index 0000000000000000000000000000000000000000..cb3945c4f47c68923245803db7b377cf8b09c6ff --- /dev/null +++ b/pool/shard008/C/0130602_abstractformatter.zep.c @@ -0,0 +1,106 @@ + +#ifdef HAVE_CONFIG_H +#include "../../ext_config.h" +#endif + +#include +#include "../../php_ext.h" +#include "../../ext.h" + +#include +#include +#include + +#include "kernel/main.h" +#include "kernel/memory.h" +#include "kernel/hash.h" +#include "kernel/concat.h" +#include "kernel/array.h" +#include "kernel/fcall.h" +#include "kernel/operators.h" + + +ZEPHIR_INIT_CLASS(Owl_Log_AbstractFormatter) { + + ZEPHIR_REGISTER_CLASS(Owl\\Log, AbstractFormatter, owl, log_abstractformatter, owl_log_abstractformatter_method_entry, 0); + + zend_class_implements(owl_log_abstractformatter_ce TSRMLS_CC, 1, owl_log_formatterinterface_ce); + return SUCCESS; + +} + +/** + * Interpolates context values into the message placeholders. + * + * @see http://www.php-fig.org/psr/psr-3/ + */ +PHP_METHOD(Owl_Log_AbstractFormatter, interpolate) { + + int ZEPHIR_LAST_CALL_STATUS; + zephir_nts_static zephir_fcall_cache_entry *_4 = NULL; + HashTable *_1; + HashPosition _0; + zval *context = NULL; + zval *message_param = NULL, *context_param = NULL, *replace, *key = NULL, *value = NULL, **_2, *_3 = NULL; + zval *message = NULL; + + ZEPHIR_MM_GROW(); + zephir_fetch_params(1, 1, 1, &message_param, &context_param); + + zephir_get_strval(message, message_param); + if (!context_param) { + ZEPHIR_INIT_VAR(context); + array_init(context); + } else { + zephir_get_arrval(context, context_param); + } + + + if (zephir_fast_count_int(context TSRMLS_CC) > 0) { + ZEPHIR_INIT_VAR(replace); + array_init(replace); + zephir_is_iterable(context, &_1, &_0, 0, 0, "owl/Log/AbstractFormatter.zep", 20); + for ( + ; zephir_hash_get_current_data_ex(_1, (void**) &_2, &_0) == SUCCESS + ; zephir_hash_move_forward_ex(_1, &_0) + ) { + ZEPHIR_GET_HMKEY(key, _1, _0); + ZEPHIR_GET_HVALUE(value, _2); + ZEPHIR_INIT_LNVAR(_3); + ZEPHIR_CONCAT_SVS(_3, "{", key, "}"); + zephir_array_update_zval(&replace, _3, &value, PH_COPY | PH_SEPARATE); + } + ZEPHIR_RETURN_CALL_FUNCTION("strtr", &_4, message, replace); + zephir_check_call_status(); + RETURN_MM(); + } + RETURN_CTOR(message); + +} + +/** + * @inheritdoc + */ +PHP_METHOD(Owl_Log_AbstractFormatter, format) { + + zval *context = NULL; + zval *message = NULL; + double timestamp; + zval *level, *timestamp_param = NULL, *message_param = NULL, *context_param = NULL; + + ZEPHIR_MM_GROW(); + zephir_fetch_params(1, 3, 1, &level, ×tamp_param, &message_param, &context_param); + + timestamp = zephir_get_doubleval(timestamp_param); + zephir_get_strval(message, message_param); + if (!context_param) { + ZEPHIR_INIT_VAR(context); + array_init(context); + } else { + zephir_get_arrval(context, context_param); + } + + + +} + diff --git a/pool/shard008/C/0130603_SystemRandomSeed.c b/pool/shard008/C/0130603_SystemRandomSeed.c new file mode 100644 index 0000000000000000000000000000000000000000..c8f3a5fec6589a1a9ec014e3e1d8762b1b23b477 --- /dev/null +++ b/pool/shard008/C/0130603_SystemRandomSeed.c @@ -0,0 +1,45 @@ +/* vim: set expandtab ts=4 sw=4: */ +/* + * You may redistribute this program 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 . + */ +#include "crypto/random/seed/RandomSeed.h" +#include "util/log/Log.h" + +#include "crypto/random/seed/RandomSeedProvider.h" +#include "crypto/random/seed/RtlGenRandomSeed.h" +#include "crypto/random/seed/BsdKernArndSysctlRandomSeed.h" +#include "crypto/random/seed/DevUrandomRandomSeed.h" +#include "crypto/random/seed/LinuxRandomUuidSysctlRandomSeed.h" +#include "crypto/random/seed/ProcSysKernelRandomUuidRandomSeed.h" + +static RandomSeed_Provider PROVIDERS[] = { RandomSeedProvider_list() }; +#define PROVIDERS_COUNT ((int)(sizeof(PROVIDERS) / sizeof(RandomSeed_Provider))) + +struct RandomSeed* SystemRandomSeed_new(RandomSeed_Provider* additionalProviders, + int additionalProviderCount, + struct Log* logger, + struct Allocator* alloc) +{ + int providerCount = PROVIDERS_COUNT + additionalProviderCount; + + RandomSeed_Provider* allProviders = + Allocator_calloc(alloc, sizeof(RandomSeed_Provider), providerCount+1); + int i = 0; + for (int j = 0; j < additionalProviderCount; j++) { + allProviders[i++] = additionalProviders[j]; + } + for (int j = 0; j < PROVIDERS_COUNT; j++) { + allProviders[i++] = PROVIDERS[j]; + } + return RandomSeed_new(allProviders, providerCount, logger, alloc); +} diff --git a/pool/shard008/C/0130604_initsrv2.c b/pool/shard008/C/0130604_initsrv2.c new file mode 100644 index 0000000000000000000000000000000000000000..5ab6a0d1bafb9f774d396adb7625aba4886dfb57 --- /dev/null +++ b/pool/shard008/C/0130604_initsrv2.c @@ -0,0 +1,35 @@ +#include "apue.h" +#include +#include + +int +initserver(int type, const struct sockaddr *addr, socklen_t alen, + int qlen) +{ + int fd, err; + int reuse = 1; + + if ((fd = socket(addr->sa_family, type, 0)) < 0) + return(-1); + if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, + sizeof(int)) < 0) { + err = errno; + goto errout; + } + if (bind(fd, addr, alen) < 0) { + err = errno; + goto errout; + } + if (type == SOCK_STREAM || type == SOCK_SEQPACKET) { + if (listen(fd, qlen) < 0) { + err = errno; + goto errout; + } + } + return(fd); + +errout: + close(fd); + errno = err; + return(-1); +} diff --git a/pool/shard008/C/0130608_CWE195_Signed_to_Unsigned_Conversion_Error__rand_malloc_05.c b/pool/shard008/C/0130608_CWE195_Signed_to_Unsigned_Conversion_Error__rand_malloc_05.c new file mode 100644 index 0000000000000000000000000000000000000000..0f6e078c8231eae609f90931003ee8199781192c --- /dev/null +++ b/pool/shard008/C/0130608_CWE195_Signed_to_Unsigned_Conversion_Error__rand_malloc_05.c @@ -0,0 +1,144 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE195_Signed_to_Unsigned_Conversion_Error__rand_malloc_05.c +Label Definition File: CWE195_Signed_to_Unsigned_Conversion_Error.label.xml +Template File: sources-sink-05.tmpl.c +*/ +/* + * @description + * CWE: 195 Signed to Unsigned Conversion Error + * BadSource: rand Set data to result of rand(), which may be zero + * GoodSource: Positive integer + * Sink: malloc + * BadSink : Allocate memory using malloc() with the size of data + * Flow Variant: 05 Control flow: if(staticTrue) and if(staticFalse) + * + * */ + +#include "std_testcase.h" + +/* The two variables below are not defined as "const", but are never + * assigned any other value, so a tool should be able to identify that + * reads of these will always return their initialized values. + */ +static int staticTrue = 1; /* true */ +static int staticFalse = 0; /* false */ + +#ifndef OMITBAD + +void CWE195_Signed_to_Unsigned_Conversion_Error__rand_malloc_05_bad() +{ + int data; + /* Initialize data */ + data = -1; + if(staticTrue) + { + /* POTENTIAL FLAW: Set data to a random value */ + data = RAND32(); + } + /* Assume we want to allocate a relatively small buffer */ + if (data < 100) + { + /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative, + * the conversion will cause malloc() to allocate a very large amount of data or fail */ + char * dataBuffer = (char *)malloc(data); + /* Do something with dataBuffer */ + memset(dataBuffer, 'A', data-1); + dataBuffer[data-1] = '\0'; + printLine(dataBuffer); + free(dataBuffer); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the staticTrue to staticFalse */ +static void goodG2B1() +{ + int data; + /* Initialize data */ + data = -1; + if(staticFalse) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Use a positive integer less than &InitialDataSize&*/ + data = 100-1; + } + /* Assume we want to allocate a relatively small buffer */ + if (data < 100) + { + /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative, + * the conversion will cause malloc() to allocate a very large amount of data or fail */ + char * dataBuffer = (char *)malloc(data); + /* Do something with dataBuffer */ + memset(dataBuffer, 'A', data-1); + dataBuffer[data-1] = '\0'; + printLine(dataBuffer); + free(dataBuffer); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + int data; + /* Initialize data */ + data = -1; + if(staticTrue) + { + /* FIX: Use a positive integer less than &InitialDataSize&*/ + data = 100-1; + } + /* Assume we want to allocate a relatively small buffer */ + if (data < 100) + { + /* POTENTIAL FLAW: malloc() takes a size_t (unsigned int) as input and therefore if it is negative, + * the conversion will cause malloc() to allocate a very large amount of data or fail */ + char * dataBuffer = (char *)malloc(data); + /* Do something with dataBuffer */ + memset(dataBuffer, 'A', data-1); + dataBuffer[data-1] = '\0'; + printLine(dataBuffer); + free(dataBuffer); + } +} + +void CWE195_Signed_to_Unsigned_Conversion_Error__rand_malloc_05_good() +{ + goodG2B1(); + goodG2B2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE195_Signed_to_Unsigned_Conversion_Error__rand_malloc_05_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE195_Signed_to_Unsigned_Conversion_Error__rand_malloc_05_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard008/C/0130611_formats.c b/pool/shard008/C/0130611_formats.c new file mode 100644 index 0000000000000000000000000000000000000000..c1f7aed62f927d1fcf8cf80e3d342251afb084ba --- /dev/null +++ b/pool/shard008/C/0130611_formats.c @@ -0,0 +1,129 @@ +#include +#include +#include + +#include "formats.h" +#include "common.h" + + +// TODO: write_num in lp format + +// private: macros for reading/printing lp_t +#define _lp_scan "%"lp_t_fmt1 +#define _lp_bg_out "%.*"lp_t_fmt2 +#define _lp_lpsolve_out "%+.*"lp_t_fmt2 +#define _lp_lpsolve_out_var _lp_lpsolve_out" x%d " + + +lp_t * new_lp(const int m, const int n) { + return (lp_t *) malloc(m * n * sizeof(lp_t)); +} + + +lp_t * new_lp_zero(const int m, const int n) { + return (lp_t *) calloc(m * n * sizeof(lp_t), 1); +} + + +void free_lp(lp_t * lp) { + free(lp); +} + + +int precision = 2; + +void set_precision(const int digits) { + precision = digits; +} + + +void write_num(FILE * fp, const lp_t num) { + char buf[32]; + int last = sprintf(buf, "%"lp_t_fmt1, num) - 1; + if (strstr(buf, ".") != NULL) { + while (buf[last] == '0') last--; + if (buf[last] == '.') last--; + buf[last + 1] = 0; + } + fprintf(fp, "%s", buf); +} + + +void write_bg(FILE * fp, const int m, const int n, const lp_t * lp) { + fprintf(fp, "%i %i\n", m, n); + for (int i = 0; i < m; i++) { + for (int j = 0; j < n; j++) { + write_num(fp, lp[i * n + j]); +// fprintf(fp, _lp_bg_out, precision, lp[i * n + j]); + fputc(j < n - 1 ? '\t' : '\n', fp); + } + } +} + + +lp_t * read_bg(FILE * fp, int * m, int * n) { + // read m, n + int err = fscanf(fp, "%d %d", m, n); + if (err == 0 || err == EOF) + error(2, "Cannot read m or n\n"); + // malloc + lp_t * lp = new_lp(*m, *n); + // read lp + for (int i = 0; i < *m; i++) + for(int j = 0; j < *n; j++) { + err = fscanf(fp, _lp_scan, &lp[i * *n + j]); + if (err == 0 || err == EOF) + error(2, "Cannot read p[%d, %d]\n", i, j); + } + return lp; +} + + +lp_t * read_bg_filename(const char * filename, int * m, int * n) { + FILE * fp = stdin; + if (filename != 0 && !(fp = fopen(filename, "r"))) + error(2, "Cannot open file '%s'\n", filename); + lp_t * lp = read_bg(fp, m, n); + if (filename != 0) fclose(fp); + return lp; +} + + +void write_lpsolve(FILE * fp, const int m, const int n, const lp_t * lp) { + // objective function + for (int j = 1; j < n; j++) + if (lp[j] != 0) fprintf(fp, _lp_lpsolve_out_var, precision, lp[j], j); + fprintf(fp, ";\n"); + // constraints + for (int i = 1; i < m; i++) { + for (int j = 1; j < n; j++) { + lp_t a = lp[i * n + j]; + if (a != 0) fprintf(fp, _lp_lpsolve_out_var, precision, a, j); + } + fprintf(fp, "<= "_lp_lpsolve_out" ;\n", precision, lp[i * n]); + } +} + + +void print_row(const char * msg, const int n, const lp_t * lp, const int row) { + printf("%s", msg); + for (int j = 0; j < n; j++) printf("%"lp_t_fmt1" ", lp[row * n + j]); + putchar('\n'); +} + + +void print_obj(const int n, const lp_t * lp) { + print_row("obj: ", n, lp, 0); +} + + +void print_col(const char * msg, const int m, const int n, const lp_t * lp, const int col) { + printf("%s", msg); + for (int i = 0; i < m; i++) printf("%"lp_t_fmt1" ", lp[i * n + col]); + putchar('\n'); +} + + +void print_bounds(const int m, const int n, const lp_t * lp) { + print_col("bnd: ", m, n, lp, 0); +} diff --git a/pool/shard008/C/0130612_telldir.c b/pool/shard008/C/0130612_telldir.c new file mode 100644 index 0000000000000000000000000000000000000000..10c5eeaf3f5fcb9f1da2c9014dca0b20a7f0ccf6 --- /dev/null +++ b/pool/shard008/C/0130612_telldir.c @@ -0,0 +1,130 @@ +/* + * Copyright (c) 1983, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 4. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)telldir.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: soc2013/dpl/head/lib/libc/gen/telldir.c 235983 2012-05-19 12:44:27Z gleb $"); + +#include "namespace.h" +#include +#include +#include +#include +#include +#include +#include "un-namespace.h" + +#include "libc_private.h" +#include "gen-private.h" +#include "telldir.h" + +/* + * The option SINGLEUSE may be defined to say that a telldir + * cookie may be used only once before it is freed. This option + * is used to avoid having memory usage grow without bound. + */ +#define SINGLEUSE + +/* + * return a pointer into a directory + */ +long +telldir(dirp) + DIR *dirp; +{ + struct ddloc *lp; + + if ((lp = (struct ddloc *)malloc(sizeof(struct ddloc))) == NULL) + return (-1); + if (__isthreaded) + _pthread_mutex_lock(&dirp->dd_lock); + lp->loc_index = dirp->dd_td->td_loccnt++; + lp->loc_seek = dirp->dd_seek; + lp->loc_loc = dirp->dd_loc; + LIST_INSERT_HEAD(&dirp->dd_td->td_locq, lp, loc_lqe); + if (__isthreaded) + _pthread_mutex_unlock(&dirp->dd_lock); + return (lp->loc_index); +} + +/* + * seek to an entry in a directory. + * Only values returned by "telldir" should be passed to seekdir. + */ +void +_seekdir(dirp, loc) + DIR *dirp; + long loc; +{ + struct ddloc *lp; + struct dirent *dp; + + LIST_FOREACH(lp, &dirp->dd_td->td_locq, loc_lqe) { + if (lp->loc_index == loc) + break; + } + if (lp == NULL) + return; + if (lp->loc_loc == dirp->dd_loc && lp->loc_seek == dirp->dd_seek) + goto found; + (void) lseek(dirp->dd_fd, (off_t)lp->loc_seek, SEEK_SET); + dirp->dd_seek = lp->loc_seek; + dirp->dd_loc = 0; + while (dirp->dd_loc < lp->loc_loc) { + dp = _readdir_unlocked(dirp, 0); + if (dp == NULL) + break; + } +found: +#ifdef SINGLEUSE + LIST_REMOVE(lp, loc_lqe); + free((caddr_t)lp); +#endif +} + +/* + * Reclaim memory for telldir cookies which weren't used. + */ +void +_reclaim_telldir(dirp) + DIR *dirp; +{ + struct ddloc *lp; + struct ddloc *templp; + + lp = LIST_FIRST(&dirp->dd_td->td_locq); + while (lp != NULL) { + templp = lp; + lp = LIST_NEXT(lp, loc_lqe); + free(templp); + } + LIST_INIT(&dirp->dd_td->td_locq); +} diff --git a/pool/shard008/C/0130613_prvt026.c b/pool/shard008/C/0130613_prvt026.c new file mode 100644 index 0000000000000000000000000000000000000000..bbabf6ee4fbbddeb98a3e9684f7b48ceeee65da7 --- /dev/null +++ b/pool/shard008/C/0130613_prvt026.c @@ -0,0 +1,82 @@ +static char rcsid[] = "$Id$"; +/* + * $TSUKUBA_Release: Omni OpenMP Compiler 3 $ + * $TSUKUBA_Copyright: + * PLEASE DESCRIBE LICENSE AGREEMENT HERE + * $ + */ +/* private 026 : + * private Àë¸À¤·¤¿ÊÑ¿ô¤òfor directive¤Îchunk¥µ¥¤¥º¤Ë»ØÄꤷ¤¿¾ì¹ç¤Îưºî¤ò³Îǧ + */ + +#include +#include "omni.h" + + +#define LOOPNUM (100 * thds) + +int errors = 0; +int thds, *buff; + +int prvt; + + +void +check(int s) +{ + int i,j, id; + + for (i=0; i +#include "esp_ping.h" + +#include "lwip/ip_addr.h" + +typedef struct _ping_option { + ip4_addr_t ping_target; + uint32_t ping_count; + uint32_t ping_rcv_timeout; + uint32_t ping_delay; + uint16_t ping_id; + esp_ping_found_fn ping_res_fn; + esp_ping_found ping_res; + void *ping_reserve; +} ping_option; + +static ping_option ping_option_info[1]; + +esp_err_t esp_ping_set_target(ping_target_id_t opt_id, void *opt_val, uint32_t opt_len) +{ + esp_err_t ret = ESP_OK; + + if (opt_val == NULL) { + return ESP_ERR_PING_INVALID_PARAMS; + } + + switch (opt_id) { + case PING_TARGET_IP_ADDRESS: + ESP_PING_CHECK_OPTLEN(opt_len, uint32_t); + ping_option_info->ping_target.addr = *(uint32_t *)opt_val; + break; + case PING_TARGET_IP_ADDRESS_COUNT: + ESP_PING_CHECK_OPTLEN(opt_len, uint32_t); + ping_option_info->ping_count = *(uint32_t *)opt_val; + break; + case PING_TARGET_RCV_TIMEO: + ESP_PING_CHECK_OPTLEN(opt_len, uint32_t); + ping_option_info->ping_rcv_timeout = (*(uint32_t *)opt_val) * 1000; + break; + case PING_TARGET_DELAY_TIME: + ESP_PING_CHECK_OPTLEN(opt_len, uint32_t); + ping_option_info->ping_delay = (*(uint32_t *)opt_val) * 1000; + break; + case PING_TARGET_ID: + ESP_PING_CHECK_OPTLEN(opt_len, uint16_t); + ping_option_info->ping_id = *(uint16_t *)opt_val; + break; + case PING_TARGET_RES_FN: + ping_option_info->ping_res_fn = opt_val; + break; + default: + ret = ESP_ERR_PING_INVALID_PARAMS; + break; + } + + return ret; +} + +esp_err_t esp_ping_get_target(ping_target_id_t opt_id, void *opt_val, uint32_t opt_len) +{ + esp_err_t ret = ESP_OK; + + if (opt_val == NULL) { + return ESP_ERR_PING_INVALID_PARAMS; + } + + switch (opt_id) { + case PING_TARGET_IP_ADDRESS: + ESP_PING_CHECK_OPTLEN(opt_len, uint32_t); + *(uint32_t *)opt_val = ping_option_info->ping_target.addr; + break; + case PING_TARGET_IP_ADDRESS_COUNT: + ESP_PING_CHECK_OPTLEN(opt_len, uint32_t); + *(uint32_t *)opt_val = ping_option_info->ping_count; + break; + case PING_TARGET_RCV_TIMEO: + ESP_PING_CHECK_OPTLEN(opt_len, uint32_t); + *(uint32_t *)opt_val = ping_option_info->ping_rcv_timeout; + break; + case PING_TARGET_DELAY_TIME: + ESP_PING_CHECK_OPTLEN(opt_len, uint32_t); + *(uint32_t *)opt_val = ping_option_info->ping_delay; + break; + case PING_TARGET_ID: + ESP_PING_CHECK_OPTLEN(opt_len, uint16_t); + *(uint16_t *)opt_val = ping_option_info->ping_id; + break; + default: + ret = ESP_ERR_PING_INVALID_PARAMS; + break; + } + + return ret; +} + +esp_err_t esp_ping_result(uint8_t res_val, uint16_t ping_len, uint32_t ping_time) +{ + esp_err_t ret = ESP_OK; + + ping_option_info->ping_res.bytes = ping_len; + ping_option_info->ping_res.ping_err = res_val; + ping_option_info->ping_res.resp_time = ping_time; + ping_option_info->ping_res.total_time += ping_time; + ping_option_info->ping_res.total_bytes += ping_len; + + if (res_val == 0) { + ping_option_info->ping_res.timeout_count ++; + } + + if (--ping_option_info->ping_count != 0 && ping_option_info->ping_res_fn) { + ping_option_info->ping_res_fn(PING_TARGET_RES_FN, &ping_option_info->ping_res); + } else { + memset(&ping_option_info->ping_res, 0, sizeof(esp_ping_found)); + } + + return ret; +} diff --git a/pool/shard008/C/0130619_pm.c b/pool/shard008/C/0130619_pm.c new file mode 100644 index 0000000000000000000000000000000000000000..159149321b3c2adb4dcf20372ada8edb2a098c7a --- /dev/null +++ b/pool/shard008/C/0130619_pm.c @@ -0,0 +1,264 @@ +/* + * pm.c - Power management interface + * + * Copyright (C) 2000 Andrew Henroid + * + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#include +#include +#include +#include +#include +#include +#include + +int pm_active; + +/* + * Locking notes: + * pm_devs_lock can be a semaphore providing pm ops are not called + * from an interrupt handler (already a bad idea so no change here). Each + * change must be protected so that an unlink of an entry doesn't clash + * with a pm send - which is permitted to sleep in the current architecture + * + * Module unloads clashing with pm events now work out safely, the module + * unload path will block until the event has been sent. It may well block + * until a resume but that will be fine. + */ + +static DECLARE_MUTEX(pm_devs_lock); +static LIST_HEAD(pm_devs); + +/** + * pm_register - register a device with power management + * @type: device type + * @id: device ID + * @callback: callback function + * + * Add a device to the list of devices that wish to be notified about + * power management events. A &pm_dev structure is returned on success, + * on failure the return is %NULL. + * + * The callback function will be called in process context and + * it may sleep. + */ + +struct pm_dev *pm_register(pm_dev_t type, + unsigned long id, + pm_callback callback) +{ + struct pm_dev *dev = kzalloc(sizeof(struct pm_dev), GFP_KERNEL); + if (dev) { + dev->type = type; + dev->id = id; + dev->callback = callback; + + down(&pm_devs_lock); + list_add(&dev->entry, &pm_devs); + up(&pm_devs_lock); + } + return dev; +} + +/** + * pm_unregister - unregister a device with power management + * @dev: device to unregister + * + * Remove a device from the power management notification lists. The + * dev passed must be a handle previously returned by pm_register. + */ + +void pm_unregister(struct pm_dev *dev) +{ + if (dev) { + down(&pm_devs_lock); + list_del(&dev->entry); + up(&pm_devs_lock); + + kfree(dev); + } +} + +static void __pm_unregister(struct pm_dev *dev) +{ + if (dev) { + list_del(&dev->entry); + kfree(dev); + } +} + +/** + * pm_unregister_all - unregister all devices with matching callback + * @callback: callback function pointer + * + * Unregister every device that would call the callback passed. This + * is primarily meant as a helper function for loadable modules. It + * enables a module to give up all its managed devices without keeping + * its own private list. + */ + +void pm_unregister_all(pm_callback callback) +{ + struct list_head *entry; + + if (!callback) + return; + + down(&pm_devs_lock); + entry = pm_devs.next; + while (entry != &pm_devs) { + struct pm_dev *dev = list_entry(entry, struct pm_dev, entry); + entry = entry->next; + if (dev->callback == callback) + __pm_unregister(dev); + } + up(&pm_devs_lock); +} + +/** + * pm_send - send request to a single device + * @dev: device to send to + * @rqst: power management request + * @data: data for the callback + * + * Issue a power management request to a given device. The + * %PM_SUSPEND and %PM_RESUME events are handled specially. The + * data field must hold the intended next state. No call is made + * if the state matches. + * + * BUGS: what stops two power management requests occurring in parallel + * and conflicting. + * + * WARNING: Calling pm_send directly is not generally recommended, in + * particular there is no locking against the pm_dev going away. The + * caller must maintain all needed locking or have 'inside knowledge' + * on the safety. Also remember that this function is not locked against + * pm_unregister. This means that you must handle SMP races on callback + * execution and unload yourself. + */ + +static int pm_send(struct pm_dev *dev, pm_request_t rqst, void *data) +{ + int status = 0; + unsigned long prev_state, next_state; + + if (in_interrupt()) + BUG(); + + switch (rqst) { + case PM_SUSPEND: + case PM_RESUME: + prev_state = dev->state; + next_state = (unsigned long) data; + if (prev_state != next_state) { + if (dev->callback) + status = (*dev->callback)(dev, rqst, data); + if (!status) { + dev->state = next_state; + dev->prev_state = prev_state; + } + } + else { + dev->prev_state = prev_state; + } + break; + default: + if (dev->callback) + status = (*dev->callback)(dev, rqst, data); + break; + } + return status; +} + +/* + * Undo incomplete request + */ +static void pm_undo_all(struct pm_dev *last) +{ + struct list_head *entry = last->entry.prev; + while (entry != &pm_devs) { + struct pm_dev *dev = list_entry(entry, struct pm_dev, entry); + if (dev->state != dev->prev_state) { + /* previous state was zero (running) resume or + * previous state was non-zero (suspended) suspend + */ + pm_request_t undo = (dev->prev_state + ? PM_SUSPEND:PM_RESUME); + pm_send(dev, undo, (void*) dev->prev_state); + } + entry = entry->prev; + } +} + +/** + * pm_send_all - send request to all managed devices + * @rqst: power management request + * @data: data for the callback + * + * Issue a power management request to a all devices. The + * %PM_SUSPEND events are handled specially. Any device is + * permitted to fail a suspend by returning a non zero (error) + * value from its callback function. If any device vetoes a + * suspend request then all other devices that have suspended + * during the processing of this request are restored to their + * previous state. + * + * WARNING: This function takes the pm_devs_lock. The lock is not dropped until + * the callbacks have completed. This prevents races against pm locking + * functions, races against module unload pm_unregister code. It does + * mean however that you must not issue pm_ functions within the callback + * or you will deadlock and users will hate you. + * + * Zero is returned on success. If a suspend fails then the status + * from the device that vetoes the suspend is returned. + * + * BUGS: what stops two power management requests occurring in parallel + * and conflicting. + */ + +int pm_send_all(pm_request_t rqst, void *data) +{ + struct list_head *entry; + + down(&pm_devs_lock); + entry = pm_devs.next; + while (entry != &pm_devs) { + struct pm_dev *dev = list_entry(entry, struct pm_dev, entry); + if (dev->callback) { + int status = pm_send(dev, rqst, data); + if (status) { + /* return devices to previous state on + * failed suspend request + */ + if (rqst == PM_SUSPEND) + pm_undo_all(dev); + up(&pm_devs_lock); + return status; + } + } + entry = entry->next; + } + up(&pm_devs_lock); + return 0; +} + +EXPORT_SYMBOL(pm_register); +EXPORT_SYMBOL(pm_unregister); +EXPORT_SYMBOL(pm_unregister_all); +EXPORT_SYMBOL(pm_send_all); +EXPORT_SYMBOL(pm_active); + + diff --git a/pool/shard008/C/0130621_launch.c b/pool/shard008/C/0130621_launch.c new file mode 100644 index 0000000000000000000000000000000000000000..9f8cd43923b1188eae61a380e668397479c60955 --- /dev/null +++ b/pool/shard008/C/0130621_launch.c @@ -0,0 +1,48 @@ +#include +#include +#include +#include +#include +#include +#include +#include "io.h" +#include "cmd.h" + +int main(int argc, char** argv) { + char* input_line = NULL; + const char* prompt = "308sh>"; + + // parse the command arguments. + int opt; + while((opt = getopt(argc, argv, "p:")) != -1) { + switch(opt) { + case 'p': + prompt = optarg; + break; + default: + return 1; + } + } + + while(true) { + int status; + input_line = get_line(prompt); + command_t cmd = make_command(input_line); + + pid_t pid; + + // get all the processes that ended since the last check. + while ((pid = waitpid(-1, &status, WNOHANG)) != 0 && pid != -1) { + if (WIFEXITED(status)) { + printf("Child Process [%d] Exited: %d\n", pid, WEXITSTATUS(status)); + } else if (WIFSIGNALED(status)) { + printf("Child Process [%d] Killed: %d\n", pid, WEXITSTATUS(status)); + } + } + + run_command(&cmd); + free(input_line); + free_command(&cmd); + } + +} diff --git a/pool/shard008/C/0130632_lib502.c b/pool/shard008/C/0130632_lib502.c new file mode 100644 index 0000000000000000000000000000000000000000..554583ae2aa45ea74d5d0acfa8ebeaa69cec0245 --- /dev/null +++ b/pool/shard008/C/0130632_lib502.c @@ -0,0 +1,92 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2011, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at http://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ +#include "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +/* + * Get a single URL without select(). + */ + +int test(char *URL) +{ + CURL *c = NULL; + CURLM *m = NULL; + int res = 0; + int running; + + start_test_timing(); + + global_init(CURL_GLOBAL_ALL); + + easy_init(c); + + easy_setopt(c, CURLOPT_URL, URL); + + multi_init(m); + + multi_add_handle(m, c); + + for(;;) { + struct timeval timeout; + fd_set fdread, fdwrite, fdexcep; + int maxfd = -99; + + timeout.tv_sec = 0; + timeout.tv_usec = 100000L; /* 100 ms */ + + multi_perform(m, &running); + + abort_on_test_timeout(); + + if(!running) + break; /* done */ + + FD_ZERO(&fdread); + FD_ZERO(&fdwrite); + FD_ZERO(&fdexcep); + + multi_fdset(m, &fdread, &fdwrite, &fdexcep, &maxfd); + + /* At this point, maxfd is guaranteed to be greater or equal than -1. */ + + select_test(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout); + + abort_on_test_timeout(); + } + +test_cleanup: + + /* proper cleanup sequence - type PA */ + + curl_multi_remove_handle(m, c); + curl_multi_cleanup(m); + curl_easy_cleanup(c); + curl_global_cleanup(); + + return res; +} + diff --git a/pool/shard008/C/0130637_bta_gattc_ci.c b/pool/shard008/C/0130637_bta_gattc_ci.c new file mode 100644 index 0000000000000000000000000000000000000000..8c94a991c169dc6adb9263fe5f95a8fb76d48d40 --- /dev/null +++ b/pool/shard008/C/0130637_bta_gattc_ci.c @@ -0,0 +1,136 @@ +/****************************************************************************** + * + * Copyright (C) 2010-2012 Broadcom Corporation + * + * 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. + * + ******************************************************************************/ + +/****************************************************************************** + * + * This is the implementation file for the GATT call-in functions. + * + ******************************************************************************/ + +#include "bt_target.h" + +#if defined(GATTC_INCLUDED) && (GATTC_INCLUDED == TRUE) + +#include + +#include "bta_api.h" +#include "bta_sys.h" +#include "bta_gattc_ci.h" +#include "gki.h" +#include "utl.h" + +/******************************************************************************* +** +** Function bta_gattc_ci_cache_open +** +** Description This function sends an event to indicate server cache open +** completed. +** +** Parameters server_bda - server BDA of this cache. +** status - BTA_GATT_OK if full buffer of data, +** BTA_GATT_FAIL if an error has occurred. +** +** Returns void +** +*******************************************************************************/ +void bta_gattc_ci_cache_open(BD_ADDR server_bda, UINT16 evt, tBTA_GATT_STATUS status, + UINT16 conn_id) +{ + tBTA_GATTC_CI_EVT *p_evt; + UNUSED(server_bda); + + if ((p_evt = (tBTA_GATTC_CI_EVT *) GKI_getbuf(sizeof(tBTA_GATTC_CI_EVT))) != NULL) { + p_evt->hdr.event = evt; + p_evt->hdr.layer_specific = conn_id; + + p_evt->status = status; + bta_sys_sendmsg(p_evt); + } +} + +/******************************************************************************* +** +** Function bta_gattc_ci_cache_load +** +** Description This function sends an event to BTA indicating the phone has +** load the servere cache and ready to send it to the stack. +** +** Parameters server_bda - server BDA of this cache. +** num_bytes_read - number of bytes read into the buffer +** specified in the read callout-function. +** status - BTA_GATT_OK if full buffer of data, +** BTA_GATT_FAIL if an error has occurred. +** +** Returns void +** +*******************************************************************************/ +void bta_gattc_ci_cache_load(BD_ADDR server_bda, UINT16 evt, UINT16 num_attr, + tBTA_GATTC_NV_ATTR *p_attr, tBTA_GATT_STATUS status, + UINT16 conn_id) +{ + tBTA_GATTC_CI_LOAD *p_evt; + UNUSED(server_bda); + + if ((p_evt = (tBTA_GATTC_CI_LOAD *) GKI_getbuf(sizeof(tBTA_GATTC_CI_LOAD))) != NULL) { + memset(p_evt, 0, sizeof(tBTA_GATTC_CI_LOAD)); + + p_evt->hdr.event = evt; + p_evt->hdr.layer_specific = conn_id; + + p_evt->status = status; + p_evt->num_attr = (num_attr > BTA_GATTC_NV_LOAD_MAX) ? BTA_GATTC_NV_LOAD_MAX : num_attr; + + if (p_evt->num_attr > 0 && p_attr != NULL) { + memcpy(p_evt->attr, p_attr, p_evt->num_attr * sizeof(tBTA_GATTC_NV_ATTR)); + } + + bta_sys_sendmsg(p_evt); + } +} + +/******************************************************************************* +** +** Function bta_gattc_ci_cache_save +** +** Description This function sends an event to BTA indicating the phone has +** save the servere cache. +** +** Parameters server_bda - server BDA of this cache. +** evt - callin event code. +** status - BTA_GATT_OK if full buffer of data, +** BTA_GATT_ERROR if an error has occurred. +*8 conn_id - for this NV operation for. +** +** Returns void +** +*******************************************************************************/ +void bta_gattc_ci_cache_save(BD_ADDR server_bda, UINT16 evt, tBTA_GATT_STATUS status, + UINT16 conn_id) +{ + tBTA_GATTC_CI_EVT *p_evt; + UNUSED(server_bda); + + if ((p_evt = (tBTA_GATTC_CI_EVT *) GKI_getbuf(sizeof(tBTA_GATTC_CI_EVT))) != NULL) { + p_evt->hdr.event = evt; + p_evt->hdr.layer_specific = conn_id; + + p_evt->status = status; + bta_sys_sendmsg(p_evt); + } +} +#endif /* GATTC_INCLUDED */ diff --git a/pool/shard008/C/0130643_fsg.c b/pool/shard008/C/0130643_fsg.c new file mode 100644 index 0000000000000000000000000000000000000000..185a65b9ad529619c6489cafadac3c8f9c15d927 --- /dev/null +++ b/pool/shard008/C/0130643_fsg.c @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2004 aCaB + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * 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. + */ + +/* +** defsg.c +** +** 02/08/2k4 - Dumped and reversed +** 02/08/2k4 - Done coding +** 03/08/2k4 - Cleaning and securing +** 04/08/2k4 - Done porting +** 07/08/2k4 - Started adding support for 1.33 +*/ + +/* +** Unpacks an FSG compressed section. +** +** Czesc bart, good asm, nice piece of code ;) +*/ + +#if HAVE_CONFIG_H +#include "clamav-config.h" +#endif + +#include + +#include "cltypes.h" +#include "rebuildpe.h" +#include "others.h" +#include "packlibs.h" +#include "fsg.h" + +int unfsg_200(char *source, char *dest, int ssize, int dsize, uint32_t rva, uint32_t base, uint32_t ep, int file) { + char *tsrc; + struct cli_exe_section section; /* Yup, just one ;) */ + + if ( cli_unfsg(source, dest, ssize, dsize, NULL, NULL) ) return -1; + + section.raw=0; + section.rsz = dsize; + section.vsz = dsize; + section.rva = rva; + + if (!cli_rebuildpe(dest, §ion, 1, base, ep, 0, 0, file)) { + cli_dbgmsg("FSG: Rebuilding failed\n"); + return 0; + } + return 1; +} + + +int unfsg_133(char *source, char *dest, int ssize, int dsize, struct cli_exe_section *sections, int sectcount, uint32_t base, uint32_t ep, int file) { + char *tsrc=source, *tdst=dest; + int i, upd=1, offs=0, lastsz=dsize; + + for (i = 0 ; i <= sectcount ; i++) { + char *startd=tdst; + if ( cli_unfsg(tsrc, tdst, ssize - (tsrc - source), dsize - (tdst - dest), &tsrc, &tdst) == -1 ) + return -1; + + /* RVA has been filled already in pe.c */ + sections[i].raw=offs; + sections[i].rsz=tdst-startd; + /* cli_dbgmsg("Unpacked section %d @%x size %x Vsize =%x \n", i, offs, tdst-startd, dsize - (startd - dest)); */ + offs+=tdst-startd; + } + + /* Sort out the sections */ + while ( upd ) { + upd = 0; + for (i = 0; i < sectcount ; i++) { + uint32_t trva,trsz,traw; + + if ( sections[i].rva <= sections[i+1].rva ) + continue; + trva = sections[i].rva; + traw = sections[i].raw; + trsz = sections[i].rsz; + sections[i].rva = sections[i+1].rva; + sections[i].rsz = sections[i+1].rsz; + sections[i].raw = sections[i+1].raw; + sections[i+1].rva = trva; + sections[i+1].raw = traw; + sections[i+1].rsz = trsz; + upd = 1; + } + } + + /* Cure Vsizes and debugspam */ + for (i = 0; i <= sectcount ; i++) { + if ( i != sectcount ) { + sections[i].vsz = sections[i+1].rva - sections[i].rva; + lastsz-= sections[i+1].rva - sections[i].rva; + } + else + sections[i].vsz = lastsz; + + cli_dbgmsg("FSG: .SECT%d RVA:%x VSize:%x ROffset: %x, RSize:%x\n", i, sections[i].rva, sections[i].vsz, sections[i].raw, sections[i].rsz); + } + + if (!cli_rebuildpe(dest, sections, sectcount+1, base, ep, 0, 0, file)) { + cli_dbgmsg("FSG: Rebuilding failed\n"); + return 0; + } + return 1; +} diff --git a/pool/shard008/C/0130644_range.c b/pool/shard008/C/0130644_range.c new file mode 100644 index 0000000000000000000000000000000000000000..5b2b71c348772dca3aa7b210cc284905b380e9d5 --- /dev/null +++ b/pool/shard008/C/0130644_range.c @@ -0,0 +1,67 @@ +// +// range.c +// hfsinspect +// +// Created by Adam Knight on 6/7/13. +// Copyright (c) 2013 Adam Knight. All rights reserved. +// + +#include //MIN/MAX + +#include "range.h" + + +#pragma mark Range Helpers + +range make_range(size_t start, size_t count) +{ + range r = { .start = start, .count = count }; + return r; +} + +bool range_equal(range a, range b) +{ + if (a.start == b.start) { + if (a.count == b.count) { + return true; + } + } + return false; +} + +bool range_contains(size_t pos, range r) +{ + /* + 0 in 0,0 is false (start 0; end -1) + 0 in 0,1 is true (start 0; end 0) + 1 in 0,1 is false (start 0; end 0) + 1 in 0,2 is true (start 0; end 1) + 1 in 1,0 is false (start 1; end 0) + */ + size_t start = r.start; + size_t end = r.start + r.count - 1; + + return (pos >= start && pos <= end); +} + +size_t range_max(range r) +{ + return (r.start + r.count); +} + +range range_intersection(range a, range b) +{ + // A range is considered to intersect if the start or end is within our bounds. + range r = {0}; + + if ( + ( range_contains(a.start, b) || range_contains(range_max(a), b) ) || + ( range_contains(b.start, a) || range_contains(range_max(b), a) ) + ) { + r.start = MAX(a.start, b.start); + r.count = MIN(a.count, b.count); + } + + return r; +} + diff --git a/pool/shard008/C/0130646_umc-bus.c b/pool/shard008/C/0130646_umc-bus.c new file mode 100644 index 0000000000000000000000000000000000000000..0fdc38078eee256b157e463e881be39061936e85 --- /dev/null +++ b/pool/shard008/C/0130646_umc-bus.c @@ -0,0 +1,211 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Bus for UWB Multi-interface Controller capabilities. + * + * Copyright (C) 2007 Cambridge Silicon Radio Ltd. + */ +#include +#include +#include +#include +#include +#include + +static int umc_bus_pre_reset_helper(struct device *dev, void *data) +{ + int ret = 0; + + if (dev->driver) { + struct umc_dev *umc = to_umc_dev(dev); + struct umc_driver *umc_drv = to_umc_driver(dev->driver); + + if (umc_drv->pre_reset) + ret = umc_drv->pre_reset(umc); + else + device_release_driver(dev); + } + return ret; +} + +static int umc_bus_post_reset_helper(struct device *dev, void *data) +{ + int ret = 0; + + if (dev->driver) { + struct umc_dev *umc = to_umc_dev(dev); + struct umc_driver *umc_drv = to_umc_driver(dev->driver); + + if (umc_drv->post_reset) + ret = umc_drv->post_reset(umc); + } else + ret = device_attach(dev); + + return ret; +} + +/** + * umc_controller_reset - reset the whole UMC controller + * @umc: the UMC device for the radio controller. + * + * Drivers or all capabilities of the controller will have their + * pre_reset methods called or be unbound from their device. Then all + * post_reset methods will be called or the drivers will be rebound. + * + * Radio controllers must provide pre_reset and post_reset methods and + * reset the hardware in their start method. + * + * If this is called while a probe() or remove() is in progress it + * will return -EAGAIN and not perform the reset. + */ +int umc_controller_reset(struct umc_dev *umc) +{ + struct device *parent = umc->dev.parent; + int ret = 0; + + if (!device_trylock(parent)) + return -EAGAIN; + ret = device_for_each_child(parent, parent, umc_bus_pre_reset_helper); + if (ret >= 0) + ret = device_for_each_child(parent, parent, umc_bus_post_reset_helper); + device_unlock(parent); + + return ret; +} +EXPORT_SYMBOL_GPL(umc_controller_reset); + +/** + * umc_match_pci_id - match a UMC driver to a UMC device's parent PCI device. + * @umc_drv: umc driver with match_data pointing to a zero-terminated + * table of pci_device_id's. + * @umc: umc device whose parent is to be matched. + */ +int umc_match_pci_id(struct umc_driver *umc_drv, struct umc_dev *umc) +{ + const struct pci_device_id *id_table = umc_drv->match_data; + struct pci_dev *pci; + + if (!dev_is_pci(umc->dev.parent)) + return 0; + + pci = to_pci_dev(umc->dev.parent); + return pci_match_id(id_table, pci) != NULL; +} +EXPORT_SYMBOL_GPL(umc_match_pci_id); + +static int umc_bus_rescan_helper(struct device *dev, void *data) +{ + int ret = 0; + + if (!dev->driver) + ret = device_attach(dev); + + return ret; +} + +static void umc_bus_rescan(struct device *parent) +{ + int err; + + /* + * We can't use bus_rescan_devices() here as it deadlocks when + * it tries to retake the dev->parent semaphore. + */ + err = device_for_each_child(parent, NULL, umc_bus_rescan_helper); + if (err < 0) + printk(KERN_WARNING "%s: rescan of bus failed: %d\n", + KBUILD_MODNAME, err); +} + +static int umc_bus_match(struct device *dev, struct device_driver *drv) +{ + struct umc_dev *umc = to_umc_dev(dev); + struct umc_driver *umc_driver = to_umc_driver(drv); + + if (umc->cap_id == umc_driver->cap_id) { + if (umc_driver->match) + return umc_driver->match(umc_driver, umc); + else + return 1; + } + return 0; +} + +static int umc_device_probe(struct device *dev) +{ + struct umc_dev *umc; + struct umc_driver *umc_driver; + int err; + + umc_driver = to_umc_driver(dev->driver); + umc = to_umc_dev(dev); + + get_device(dev); + err = umc_driver->probe(umc); + if (err) + put_device(dev); + else + umc_bus_rescan(dev->parent); + + return err; +} + +static int umc_device_remove(struct device *dev) +{ + struct umc_dev *umc; + struct umc_driver *umc_driver; + + umc_driver = to_umc_driver(dev->driver); + umc = to_umc_dev(dev); + + umc_driver->remove(umc); + put_device(dev); + return 0; +} + +static ssize_t capability_id_show(struct device *dev, struct device_attribute *attr, char *buf) +{ + struct umc_dev *umc = to_umc_dev(dev); + + return sprintf(buf, "0x%02x\n", umc->cap_id); +} +static DEVICE_ATTR_RO(capability_id); + +static ssize_t version_show(struct device *dev, struct device_attribute *attr, char *buf) +{ + struct umc_dev *umc = to_umc_dev(dev); + + return sprintf(buf, "0x%04x\n", umc->version); +} +static DEVICE_ATTR_RO(version); + +static struct attribute *umc_dev_attrs[] = { + &dev_attr_capability_id.attr, + &dev_attr_version.attr, + NULL, +}; +ATTRIBUTE_GROUPS(umc_dev); + +struct bus_type umc_bus_type = { + .name = "umc", + .match = umc_bus_match, + .probe = umc_device_probe, + .remove = umc_device_remove, + .dev_groups = umc_dev_groups, +}; +EXPORT_SYMBOL_GPL(umc_bus_type); + +static int __init umc_bus_init(void) +{ + return bus_register(&umc_bus_type); +} +module_init(umc_bus_init); + +static void __exit umc_bus_exit(void) +{ + bus_unregister(&umc_bus_type); +} +module_exit(umc_bus_exit); + +MODULE_DESCRIPTION("UWB Multi-interface Controller capability bus"); +MODULE_AUTHOR("Cambridge Silicon Radio Ltd."); +MODULE_LICENSE("GPL"); diff --git a/pool/shard008/C/0130647_wrtarga.c b/pool/shard008/C/0130647_wrtarga.c new file mode 100644 index 0000000000000000000000000000000000000000..8328081113941b0580cb8c558566205fb98c1780 --- /dev/null +++ b/pool/shard008/C/0130647_wrtarga.c @@ -0,0 +1,209 @@ +/* + * wrtarga.c + * + * Copyright (C) 1991-1996, Thomas G. Lane. + * Modified 2015-2017 by Guido Vollbeding. + * This file is part of the Independent JPEG Group's software. + * For conditions of distribution and use, see the accompanying README file. + * + * This file contains routines to write output images in Targa format. + * + * These routines may need modification for non-Unix environments or + * specialized applications. As they stand, they assume output to + * an ordinary stdio stream. + * + * Based on code contributed by Lee Daniel Crocker. + */ +// @v9c(done) +#define JPEG_INTERNALS +#include "cdjpeg.h" +#pragma hdrstop + +#ifdef TARGA_SUPPORTED +/* + * To support 12-bit JPEG data, we'd have to scale output down to 8 bits. + * This is not yet implemented. + */ +#if BITS_IN_JSAMPLE != 8 + Sorry, this code only copes with 8-bit JSAMPLEs. /* deliberate syntax err */ +#endif +/* + * The output buffer needs to be writable by fwrite(). On PCs, we must + * allocate the buffer in near data space, because we are assuming small-data + * memory model, wherein fwrite() can't reach far memory. If you need to + * process very wide images on a PC, you might have to compile in large-memory + * model, or else replace fwrite() with a putc() loop --- which will be much + * slower. + */ + +/* Private version of data destination object */ + +typedef struct { + struct djpeg_dest_struct pub; /* public fields */ + char * iobuffer; /* physical I/O buffer */ + JDIMENSION buffer_width; /* width of one row */ +} tga_dest_struct; + +typedef tga_dest_struct * tga_dest_ptr; + +static void write_header(j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, int num_colors) +/* Create and write a Targa header */ +{ + char targaheader[18]; + /* Set unused fields of header to 0 */ + memzero(targaheader, SIZEOF(targaheader)); + if(num_colors > 0) { + targaheader[1] = 1; /* color map type 1 */ + targaheader[5] = (char)(num_colors & 0xFF); + targaheader[6] = (char)(num_colors >> 8); + targaheader[7] = 24; /* 24 bits per cmap entry */ + } + targaheader[12] = (char)(cinfo->output_width & 0xFF); + targaheader[13] = (char)(cinfo->output_width >> 8); + targaheader[14] = (char)(cinfo->output_height & 0xFF); + targaheader[15] = (char)(cinfo->output_height >> 8); + targaheader[17] = 0x20; /* Top-down, non-interlaced */ + if(cinfo->out_color_space == JCS_GRAYSCALE) { + targaheader[2] = 3; /* image type = uncompressed grayscale */ + targaheader[16] = 8; /* bits per pixel */ + } + else { /* must be RGB */ + if(num_colors > 0) { + targaheader[2] = 1; /* image type = colormapped RGB */ + targaheader[16] = 8; + } + else { + targaheader[2] = 2; /* image type = uncompressed RGB */ + targaheader[16] = 24; + } + } + if(JFWRITE(dinfo->output_file, targaheader, 18) != (size_t)18) + ERREXIT(cinfo, JERR_FILE_WRITE); +} +/* + * Write some pixel data. + * In this module rows_supplied will always be 1. + */ +METHODDEF(void) put_pixel_rows(j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, JDIMENSION rows_supplied) +/* used for unquantized full-color output */ +{ + tga_dest_ptr dest = (tga_dest_ptr)dinfo; + JDIMENSION col; + JSAMPROW inptr = dest->pub.buffer[0]; + char * outptr = dest->iobuffer; + for(col = cinfo->output_width; col > 0; col--) { + outptr[0] = (char)GETJSAMPLE(inptr[2]); /* RGB to BGR order */ + outptr[1] = (char)GETJSAMPLE(inptr[1]); + outptr[2] = (char)GETJSAMPLE(inptr[0]); + inptr += 3, outptr += 3; + } + (void)JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width); +} + +METHODDEF(void) put_gray_rows(j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, JDIMENSION rows_supplied) +/* used for grayscale OR quantized color output */ +{ + tga_dest_ptr dest = (tga_dest_ptr)dinfo; + JSAMPROW inptr; + char * outptr; + JDIMENSION col; + inptr = dest->pub.buffer[0]; + outptr = dest->iobuffer; + for(col = cinfo->output_width; col > 0; col--) { + *outptr++ = (char)GETJSAMPLE(*inptr++); + } + (void)JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width); +} +/* + * Write some demapped pixel data when color quantization is in effect. + * For Targa, this is only applied to grayscale data. + */ +METHODDEF(void) put_demapped_gray(j_decompress_ptr cinfo, djpeg_dest_ptr dinfo, JDIMENSION rows_supplied) +{ + tga_dest_ptr dest = (tga_dest_ptr)dinfo; + JSAMPROW inptr; + char * outptr; + JSAMPROW color_map0 = cinfo->colormap[0]; + JDIMENSION col; + inptr = dest->pub.buffer[0]; + outptr = dest->iobuffer; + for(col = cinfo->output_width; col > 0; col--) { + *outptr++ = (char)GETJSAMPLE(color_map0[GETJSAMPLE(*inptr++)]); + } + (void)JFWRITE(dest->pub.output_file, dest->iobuffer, dest->buffer_width); +} +/* + * Startup: write the file header. + */ +METHODDEF(void) start_output_tga(j_decompress_ptr cinfo, djpeg_dest_ptr dinfo) +{ + tga_dest_ptr dest = (tga_dest_ptr)dinfo; + int num_colors, i; + FILE * outfile; + if(cinfo->out_color_space == JCS_GRAYSCALE) { + /* Targa doesn't have a mapped grayscale format, so we will */ + /* demap quantized gray output. Never emit a colormap. */ + write_header(cinfo, dinfo, 0); + if(cinfo->quantize_colors) + dest->pub.put_pixel_rows = put_demapped_gray; + else + dest->pub.put_pixel_rows = put_gray_rows; + } + else if(cinfo->out_color_space == JCS_RGB) { + if(cinfo->quantize_colors) { + /* We only support 8-bit colormap indexes, so only 256 colors */ + num_colors = cinfo->actual_number_of_colors; + if(num_colors > 256) + ERREXIT1(cinfo, JERR_TOO_MANY_COLORS, num_colors); + write_header(cinfo, dinfo, num_colors); + /* Write the colormap. Note Targa uses BGR byte order */ + outfile = dest->pub.output_file; + for(i = 0; i < num_colors; i++) { + putc(GETJSAMPLE(cinfo->colormap[2][i]), outfile); + putc(GETJSAMPLE(cinfo->colormap[1][i]), outfile); + putc(GETJSAMPLE(cinfo->colormap[0][i]), outfile); + } + dest->pub.put_pixel_rows = put_gray_rows; + } + else { + write_header(cinfo, dinfo, 0); + dest->pub.put_pixel_rows = put_pixel_rows; + } + } + else { + ERREXIT(cinfo, JERR_TGA_COLORSPACE); + } +} +// +// Finish up at the end of the file. +// +METHODDEF(void) finish_output_tga(j_decompress_ptr cinfo, djpeg_dest_ptr dinfo) +{ + // Make sure we wrote the output file OK + // @v9c fflush(dinfo->output_file); + // @v9c if(ferror(dinfo->output_file)) + JFFLUSH(dinfo->output_file); // @v9c + if(JFERROR(dinfo->output_file)) // @v9c + ERREXIT(cinfo, JERR_FILE_WRITE); +} +// +// The module selection routine for Targa format output. +// +GLOBAL(djpeg_dest_ptr) jinit_write_targa(j_decompress_ptr cinfo) +{ + /* Create module interface object, fill in method pointers */ + tga_dest_ptr dest = (tga_dest_ptr)(*cinfo->mem->alloc_small)(reinterpret_cast(cinfo), JPOOL_IMAGE, SIZEOF(tga_dest_struct)); + dest->pub.start_output = start_output_tga; + dest->pub.finish_output = finish_output_tga; + /* Calculate output image dimensions so we can allocate space */ + jpeg_calc_output_dimensions(cinfo); + /* Create I/O buffer. Note we make this near on a PC. */ + dest->buffer_width = cinfo->output_width * cinfo->output_components; + dest->iobuffer = (char *)(*cinfo->mem->alloc_small)(reinterpret_cast(cinfo), JPOOL_IMAGE, (size_t)(dest->buffer_width * SIZEOF(char))); + /* Create decompressor output buffer. */ + dest->pub.buffer = (*cinfo->mem->alloc_sarray)(reinterpret_cast(cinfo), JPOOL_IMAGE, dest->buffer_width, (JDIMENSION)1); + dest->pub.buffer_height = 1; + return &dest->pub; +} + +#endif /* TARGA_SUPPORTED */ diff --git a/pool/shard008/C/0130648_chkcset.c b/pool/shard008/C/0130648_chkcset.c new file mode 100644 index 0000000000000000000000000000000000000000..0d197d45ce4f357c13bb8e66868dd4960f27d7b5 --- /dev/null +++ b/pool/shard008/C/0130648_chkcset.c @@ -0,0 +1,231 @@ +/* + * $Id: chkcset.c,v 1.2 2001/06/14 18:16:10 ura Exp $ + */ + +/* + * FreeWnn is a network-extensible Kana-to-Kanji conversion system. + * This file is part of FreeWnn. + * + * Copyright OMRON Corporation. 1987, 1988, 1989, 1990, 1991, 1992, 1999 + * + * Author: OMRON SOFTWARE Co., Ltd. + * + * 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, 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 GNU Emacs; see the file COPYING. If not, write to the + * Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * Commentary: + * + * Change log: + * + * Last modified date: 8,Feb.1999 + * + * Code: + * + */ + +/* + * X11R5 Input Method Test Program + * chkcset.c v 1.0 Tue Mar 12 20:35:00 JST 1991 + */ + +/* + * Author: Takashi Inoue OMRON Corporation + * takashi@ari.ncl.omron.co.jp + */ + +#include "exvalue.h" +#include "func.h" + +/* *INDENT-OFF* */ +FLAG +xsuicf (ic, mode) /* XSet/Unset IC Focus */ + XIC ic; + FLAG mode; +/* *INDENT-ON* */ +{ + cls (prdisp); + prstatus ("Test of XSet/UnsetICFocus()..."); + switch (focuson) + { + case OK: + XUnsetICFocus (ic); + focuson = NG; + prprint ("The IC Focus is unset by calling XUnsetICFocus.\n\n"); + prprint ("Check your own eyes.\n\n"); + prprint ("If you want to set IC,\n"); + prprint ("you have to click your mouse "); + prprint ("\"Focus1\" on menu window again.\n\n"); + cwcolor (ufname, pixel[cmflag][1]); + fprintf (icfp, "...XUnsetICFocus() returned.\n\n"); + break; + default: + XSetICFocus (ic); + focuson = OK; + prprint ("The IC Focus is set by calling XSetICFocus.\n\n"); + prprint ("Check your own eyes.\n\n"); + prprint ("If you want to unset IC,\n"); + prprint ("you have to click your mouse "); + prprint ("\"Focus1\" on menu window again.\n\n"); + cwcolor (ufname, pixel[cmflag][0]); + fprintf (icfp, "...XSetICFocus() returned.\n\n"); + break; + } + prstatus ("done."); + prprint ("Move next test.\n\n"); + prpok (); + return (COMP); +} + +/* *INDENT-OFF* */ +FLAG +sfocus (ic, mode) /* Set FOCUS window */ + XIC ic; + FLAG mode; +/* *INDENT-ON* */ + +{ + Window gfocus; + VALUABLE *focus; + int res; + + if ((mode != DUMMY) && (focuson == OK)) + { + cls (prdisp); + prstatus ("Test of XSetICValues() for change \"Focus Window\"..."); + if (ufocus == window1.win) + { + cwcolor (ufname, pixel[cmflag][1]); + ufocus = window2.win; + ufname = window2.name; + cwcolor (ufname, pixel[cmflag][0]); + } + else if (ufocus == window2.win) + { + cwcolor (ufname, pixel[cmflag][1]); + ufocus = window3.win; + ufname = window3.name; + cwcolor (ufname, pixel[cmflag][0]); + } + else if (ufocus == window3.win) + { + cwcolor (ufname, pixel[cmflag][1]); + ufocus = window1.win; + ufname = window1.name; + cwcolor (ufname, pixel[cmflag][0]); + } + XSetICValues (ic, XNFocusWindow, ufocus, NULL); + prstatus ("done."); + prstatus ("Test of XGetICValues() \"FocusWindow\"..."); + XGetICValues (ic, XNFocusWindow, &gfocus, NULL); + prstatus ("done."); + res = 0; + focus = mkstruct (FW, HEX, ufocus, gfocus); + res = verval (focus); + cls (prdisp); + prveres (res); + if (res != NOERR) + { + prprint ("Test of XSetICValues() \"FocusWindow\" is failed.\n"); + prprint ("FocusWindow has not changed.\n\n"); + prprint ("I will destroy IC and continue test.\n"); + prprint ("Check log file after this test.\n\n"); + fprintf (icfp, "...Test of XSetICValues() \"FocusWindow\" is failed.\n\n"); + prpng (); + return (DIC); + } + prprint ("Test of XSetICValues() \"FocusWindow\" is succeeded.\n"); + prprint ("FocusWindow has changed.\n\n"); + prprint ("Check your own eyes and move next test.\n\n"); + fprintf (icfp, "...Test of XSetICValues() \"FocusWindow\" is succeeded.\n\n"); + prpok (); + return (COMP); + } + else + { + cls (prdisp); + prprint ("You can't check this test.\n\n"); + prprint ("Retry after \"Focus1\" test.\n\n"); + fprintf (icfp, "...Retry after \"Focus1\" test.\n\n"); + } + return (COMP); +} + + +/* *INDENT-OFF* */ +FLAG +sresource (ic, mode) /* Set RESOURCE name/class */ + XIC ic; + FLAG mode; +/* *INDENT-ON* */ + +{ + int sum; + int cnt, res; + RESOURCE gres; + VALUABLE *resource[ARRAY_MAX]; + + if (mode == ONSP) + { + prerrfunc (); + return (COMP); + } + else + { + cls (prdisp); + prstatus ("Test of XSetICValues() for change \"Resource Name\",\"Resource Class\"..."); + if (!strcmp (ures.name, "xim")) + ures.name = "xima"; + else if (!strcmp (ures.name, "xima")) + ures.name = "ximb"; + else if (!strcmp (ures.name, "ximb")) + ures.name = "xim"; + if (!strcmp (ures.class, "Xim")) + ures.class = "Xima"; + else if (!strcmp (ures.class, "Xima")) + ures.class = "Ximb"; + else if (!strcmp (ures.class, "Ximb")) + ures.class = "Xim"; + XSetICValues (ic, XNResourceName, ures.name, XNResourceClass, ures.class, NULL); + prstatus ("done."); + prstatus ("Test of XGetICValues() \"resource name/class\"..."); + XGetICValues (ic, XNResourceName, &gres.name, XNResourceClass, &gres.class, NULL); + prstatus ("done."); + sum = 0; + resource[0] = mkstruct (RN, STR, ures.name, gres.name); + resource[1] = mkstruct (RC, STR, ures.class, gres.class); + for (cnt = 0; cnt < CHKRES; cnt++) + { + res = verval (resource[cnt]); + sum += res; + } + cls (prdisp); + prveres (sum); + if (sum != NOERR) + { + prprint ("Test of XSetICValues() \"ResourceName/Class\" is failed.\n"); + prprint ("ResourceName/ResourceClass has not changed.\n\n"); + prprint ("I will destroy IC and continue test.\n"); + prprint ("Check log file after this test.\n\n"); + fprintf (icfp, "...Test of XSetICValues() \"ResourceName/Class\" is failed.\n\n"); + prpng (); + return (DIC); + } + prprint ("Test of XSetICValues() \"ResourceName/Class\" is succeeded.\n"); + prprint ("ResourceName/ResourceClass has changed.\n\n"); + prprint ("Check your own eyes and move next test\n\n"); + fprintf (icfp, "...Test of XSetICValues() \"ResourceName/Class\" is succeeded.\n\n"); + prpok (); + return (COMP); + } +} diff --git a/pool/shard008/C/0130651_skybox.c b/pool/shard008/C/0130651_skybox.c new file mode 100644 index 0000000000000000000000000000000000000000..e7460234182fedf20a0fff88ad466bae085531d5 --- /dev/null +++ b/pool/shard008/C/0130651_skybox.c @@ -0,0 +1,144 @@ +#include +#include "skybox.h" +#include "gObjectManager.h" +#include "textureManager.h" +#include "shaderManager.h" +#include "scene.h" +#include "trfm3D.h" + +static char buffer[4096]; + +static char* cmap_faces[6] = { "xpos", "xneg", "ypos", "yneg", "zpos", "zneg" }; + +static char *advance_p(char *o, size_t n, + char *overflow) { + char *p; + p = o; + while(n--) { + if (++p > overflow) { + fprintf(stderr, "[E] generate names: directory name too long\n"); + exit(1); + } + } + return p; +} + +static char **generate_names(char *dirname) { + + static char *ext=".jpg"; + size_t i; + size_t ldn; // len of dirname + size_t ln; // len of name + size_t le; // len of extension + char *p = NULL; // start of next name + static char *names[6] = { NULL, NULL, NULL, NULL, NULL, NULL }; + + char *overflow = buffer + 4096; + + ldn = strlen(dirname); + if(!ldn) goto end; + if(dirname[ldn - 1] == '/') ldn--; + le = strlen(ext); + p = &buffer[0]; + for(i = 0; i < 6; i++) { + names[i] = p; + strncpy(p, dirname, ldn); + p = advance_p(p, ldn, overflow); + *p = '/'; + p++; + ln = strlen(cmap_faces[i]); + strncpy(p, cmap_faces[i], ln); + p = advance_p(p, ln, overflow); + strncpy(p, ext, le + 1); + p = advance_p(p, le + 1, overflow); + } + + end: + return &(names[0]); + +} + +// create a (huge) triangle Mesh with a cube map +GObject *CreateSkybox(char *sbname, + char *dirname) { + + static const int A = 1000.0; + float A2 = 0.5f * A; + TriangleMesh *mesh; + Texture *ctex; + GObject *gobj; + int len; + char **names; + + mesh = CreateVoidTriangleMesh(); + + AddPointTMesh(mesh, -A, -A2, A); // P0 + AddPointTMesh(mesh, A, -A2, A); // P1 + AddPointTMesh(mesh, A, A2, A); // P2 + AddPointTMesh(mesh, -A, A2, A); // P3 + AddPointTMesh(mesh, -A, -A2, -A); // P4 + AddPointTMesh(mesh, A, -A2, -A); // P5 + AddPointTMesh(mesh, A, A2, -A); // P6 + AddPointTMesh(mesh, -A, A2, -A); // P7 + + // front + AddTriangleTMesh(mesh, 0, 1, 2); // P0 - P1 - P2 + AddTriangleTMesh(mesh, 2, 3, 0); // P2 - P3 - P0 + // back + AddTriangleTMesh(mesh, 5, 4, 7); + AddTriangleTMesh(mesh, 7, 6, 5); + // left + AddTriangleTMesh(mesh, 4, 0, 3); + AddTriangleTMesh(mesh, 3, 7, 4); + // right + AddTriangleTMesh(mesh, 1, 5, 6); + AddTriangleTMesh(mesh, 6, 2, 1); + // top + AddTriangleTMesh(mesh, 3, 2, 6); + AddTriangleTMesh(mesh, 6, 7, 3); + // bottom + AddTriangleTMesh(mesh, 4, 5, 1); + AddTriangleTMesh(mesh, 1, 0, 4); + + // Create cube map texture and assign. + + names = generate_names(dirname); + ctex = SceneRegisterCubeMapTexture(sbname, + names[0], names[1], + names[2], names[3], + names[4], names[5]); + SetTextureMaterial(mesh->materialFront, ctex); + gobj = SceneRegisterVoidGObject("SKYBOX/", sbname); + AddPatchGObject(gobj, mesh); + return gobj; +} + +void DisplaySky(GObject *sky, camera *cam) { + + ShaderProgram *prev_shader; + RenderState *rs; + GLboolean prev_cull; + float x,y,z; // camera position + static trfm3D localT; + + rs = RenderStateScene(); + + glGetBooleanv(GL_CULL_FACE, &prev_cull); + + prev_shader = GetShaderProgramRS(rs); + SetShaderProgramRS(rs, FindShaderScene("sky")); + glDisable(GL_CULL_FACE); + + // move skybox to camera origin + GetCameraPosition(cam, &x, &y, &z); + SetTransTrfm3D(&localT, x, y, z); + PushRS(rs, AGA_MODELVIEW); + MultTrfmRS(rs, AGA_MODELVIEW, &localT); + DrawGObject(sky); + PopRS(rs, AGA_MODELVIEW); + // restore shader + SetShaderProgramRS(rs, prev_shader); + if (prev_cull == GL_TRUE) + glEnable(GL_CULL_FACE); + +} diff --git a/pool/shard008/C/0130652_packet-redback.c b/pool/shard008/C/0130652_packet-redback.c new file mode 100644 index 0000000000000000000000000000000000000000..acb87ec9bc7a792898521bd24fb3f651c7a163a2 --- /dev/null +++ b/pool/shard008/C/0130652_packet-redback.c @@ -0,0 +1,226 @@ +/* packet-redback.c + * + * $Id$ + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * + * Start of RedBack SmartEdge 400/800 tcpdump trace disassembly + * Copyright 2005-2008 Florian Lohoff + * + * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include +#include "packet-ip.h" + +static int proto_redback = -1; +static gint ett_redback = -1; + +static dissector_table_t osinl_subdissector_table; +static dissector_table_t osinl_excl_subdissector_table; + +static dissector_handle_t ipv4_handle; +static dissector_handle_t ethnofcs_handle; +static dissector_handle_t clnp_handle; +static dissector_handle_t arp_handle; +static dissector_handle_t ppp_handle; +static dissector_handle_t ppphdlc_handle; +static dissector_handle_t data_handle; + +static int hf_redback_context = -1; +static int hf_redback_flags = -1; +static int hf_redback_circuit = -1; +static int hf_redback_length = -1; +static int hf_redback_protocol = -1; +static int hf_redback_l3offset = -1; +static int hf_redback_dataoffset = -1; +static int hf_redback_padding = -1; +static int hf_redback_unknown = -1; + +static void +dissect_redback(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) +{ + guint16 l3off, dataoff, proto; + proto_item *ti; + proto_tree *rbtree = NULL; + tvbuff_t *next_tvb; + + col_set_str(pinfo->cinfo,COL_PROTOCOL,"RBN"); + + dataoff = tvb_get_ntohs(tvb, 20); + l3off = tvb_get_ntohs(tvb, 22); + + if (tree) { + ti = proto_tree_add_item(tree, proto_redback, tvb, 0, -1, ENC_NA); + rbtree = proto_item_add_subtree(ti, ett_redback); + + proto_tree_add_item(rbtree, hf_redback_context, tvb, 0, 4, ENC_BIG_ENDIAN); + proto_tree_add_item(rbtree, hf_redback_flags, tvb, 4, 4, ENC_BIG_ENDIAN); + proto_tree_add_item(rbtree, hf_redback_circuit, tvb, 8, 8, ENC_BIG_ENDIAN); + proto_tree_add_item(rbtree, hf_redback_length, tvb, 16, 2, ENC_BIG_ENDIAN); + proto_tree_add_item(rbtree, hf_redback_protocol, tvb, 18, 2, ENC_BIG_ENDIAN); + proto_tree_add_item(rbtree, hf_redback_dataoffset, tvb, 20, 2, ENC_BIG_ENDIAN); + proto_tree_add_item(rbtree, hf_redback_l3offset, tvb, 22, 2, ENC_BIG_ENDIAN); + + if (dataoff > 24) { + proto_tree_add_item(rbtree, hf_redback_padding, tvb, 24, dataoff-24, ENC_NA); + } + } + + proto = tvb_get_ntohs(tvb, 18); + switch(proto) { + case 0x01: + /* + * IP on Ethernet - Incoming data points to an ethernet header + * outgoing we have a pure IPv4 Packet + */ + next_tvb = tvb_new_subset_remaining(tvb, dataoff); + if (dataoff == l3off) + call_dissector(ipv4_handle, next_tvb, pinfo, tree); + else if (dataoff+2 == l3off) + call_dissector(ppp_handle, next_tvb, pinfo, tree); + else if (dataoff+4 == l3off) + call_dissector(ppphdlc_handle, next_tvb, pinfo, tree); + else + call_dissector(ethnofcs_handle, next_tvb, pinfo, tree); + break; + case 0x02: + /* + * This is ISIS - Either incoming with ethernet FCS + * and CLNP - passed to the eth dissector or in case + * of outgoing its pure ISIS and the linecard attaches + * the ethernet and CLNP headers ... + * + */ + next_tvb = tvb_new_subset_remaining(tvb, dataoff); + if (l3off > dataoff) { + call_dissector(ethnofcs_handle, next_tvb, pinfo, tree); + } else { + guint8 nlpid = tvb_get_guint8(tvb, dataoff); + if(dissector_try_uint(osinl_subdissector_table, nlpid, next_tvb, pinfo, tree)) + break; + next_tvb = tvb_new_subset_remaining(tvb, dataoff+1); + if(dissector_try_uint(osinl_excl_subdissector_table, nlpid, next_tvb, pinfo, tree)) + break; + next_tvb = tvb_new_subset_remaining(tvb, dataoff); + call_dissector(data_handle, next_tvb, pinfo, tree); + } + break; + case 0x06: { + /* + * PPP Messages e.g. LCP, IPCP etc - possibly on ethernet in case of PPPoE. + * PPPoE messages are Protocol 8 ... + */ + guint32 flags; + flags = tvb_get_ntohl(tvb, 4); + + if (flags & 0x00400000) { + next_tvb = tvb_new_subset_remaining(tvb, dataoff); + } else { + if (tree) + proto_tree_add_item(rbtree, hf_redback_unknown, tvb, dataoff, 4, ENC_NA); + next_tvb = tvb_new_subset_remaining(tvb, dataoff+4); + } + + if (l3off == dataoff) { + call_dissector(ppp_handle, next_tvb, pinfo, tree); + } else { + call_dissector(ethnofcs_handle, next_tvb, pinfo, tree); + } + break; + } + case 0x03: /* Unicast Ethernet tx - Seen with PPPoE PADO */ + case 0x04: /* Unicast Ethernet rx - Seen with ARP */ + case 0x08: /* Broadcast Ethernet rx - Seen with PPPoE PADI */ + next_tvb = tvb_new_subset_remaining(tvb, dataoff); + call_dissector(ethnofcs_handle, next_tvb, pinfo, tree); + break; + default: + if (tree) + proto_tree_add_text (rbtree, tvb, 24, -1, "Unknown Protocol Data %u", proto); + break; + } + return; +} + +void +proto_register_redback(void) +{ + static hf_register_info hf[] = { + { &hf_redback_context, + { "Context", "redback.context", FT_UINT32, BASE_HEX, NULL, 0x0, + NULL, HFILL }}, + { &hf_redback_flags, + { "Flags", "redback.flags", FT_UINT32, BASE_HEX, NULL, 0x0, + NULL, HFILL }}, + { &hf_redback_circuit, + { "Circuit", "redback.circuit", FT_UINT64, BASE_HEX, NULL, 0x0, + NULL, HFILL }}, + { &hf_redback_length, + { "Length", "redback.length", FT_UINT16, BASE_DEC, NULL, 0x0, + NULL, HFILL }}, + { &hf_redback_protocol, + { "Protocol", "redback.protocol", FT_UINT16, BASE_DEC, NULL, 0x0, + NULL, HFILL }}, + { &hf_redback_l3offset, + { "Layer 3 Offset", "redback.l3offset", FT_UINT16, BASE_DEC, NULL, 0x0, + NULL, HFILL }}, + { &hf_redback_dataoffset, + { "Data Offset", "redback.dataoffset", FT_UINT16, BASE_DEC, NULL, 0x0, + NULL, HFILL }}, + { &hf_redback_padding, + { "Padding", "redback.padding", FT_BYTES, BASE_NONE, NULL, 0x0, + NULL, HFILL }}, + { &hf_redback_unknown, + { "Unknown", "redback.unknown", FT_BYTES, BASE_NONE, NULL, 0x0, + NULL, HFILL }} + }; + + static gint *ett[] = { + &ett_redback + }; + + proto_redback = proto_register_protocol("Redback", "Redback", "redback"); + proto_register_field_array(proto_redback, hf, array_length(hf)); + proto_register_subtree_array(ett, array_length(ett)); +} + +void +proto_reg_handoff_redback(void) +{ + dissector_handle_t redback_handle; + + osinl_subdissector_table = find_dissector_table("osinl"); + osinl_excl_subdissector_table = find_dissector_table("osinl.excl"); + + ipv4_handle = find_dissector("ip"); + data_handle = find_dissector("data"); + ethnofcs_handle = find_dissector("eth_withoutfcs"); + clnp_handle = find_dissector("clnp"); + arp_handle = find_dissector("arp"); + ppp_handle = find_dissector("ppp"); + ppphdlc_handle = find_dissector("ppp_hdlc"); + + redback_handle = create_dissector_handle(dissect_redback, proto_redback); + dissector_add_uint("wtap_encap", WTAP_ENCAP_REDBACK, redback_handle); +} + + diff --git a/pool/shard008/C/0130657_resource-to-string.c b/pool/shard008/C/0130657_resource-to-string.c new file mode 100644 index 0000000000000000000000000000000000000000..e54d0907331e392dd691101528a6ca590e98779a --- /dev/null +++ b/pool/shard008/C/0130657_resource-to-string.c @@ -0,0 +1,57 @@ + +// Copyright (c) 2008-2010, Regents of the University of Colorado. +// This work was supported by NASA contracts NNJ05HE10G, NNC06CB40C, and +// NNC07CB47C. + + +#include +#include + +#include + +#include "internal.h" +#include "bionet-util.h" + + +char *bionet_resource_value_to_string(const bionet_resource_t *resource, int datapoint_index) { + const bionet_datapoint_t *datapoint; + const bionet_value_t *value; + + if (resource == NULL) { + g_log(BIONET_LOG_DOMAIN, G_LOG_LEVEL_WARNING, "bionet_resource_value_as_string: NULL Resource passed in!"); + return NULL; + } + + datapoint = bionet_resource_get_datapoint_by_index(resource, datapoint_index); + if (datapoint == NULL) { + g_log(BIONET_LOG_DOMAIN, G_LOG_LEVEL_WARNING, "bionet_resource_value_as_string: passed-in Resource has no Datapoint!"); + return NULL; + } + + value = bionet_datapoint_get_value(datapoint); + if (value == NULL) { + g_log(BIONET_LOG_DOMAIN, G_LOG_LEVEL_WARNING, "bionet_resource_value_as_string: Datapoint of passed-in Resource has no Value!"); + return NULL; + } + + return bionet_value_to_str(value); +} + + +char *bionet_resource_timestamp_to_string(const bionet_resource_t *resource, int datapoint_index) { + const bionet_datapoint_t *datapoint; + + if (resource == NULL) { + g_log(BIONET_LOG_DOMAIN, G_LOG_LEVEL_WARNING, "bionet_resource_timestamp_as_string: NULL Resource passed in!"); + return NULL; + } + + datapoint = bionet_resource_get_datapoint_by_index(resource, datapoint_index); + if (datapoint == NULL) { + g_log(BIONET_LOG_DOMAIN, G_LOG_LEVEL_WARNING, "bionet_resource_timestamp_as_string: passed-in Resource has no Datapoint!"); + return NULL; + } + + return strdup(bionet_datapoint_timestamp_to_string(datapoint)); +} + diff --git a/pool/shard008/C/0130660_rb-dialog.c b/pool/shard008/C/0130660_rb-dialog.c new file mode 100644 index 0000000000000000000000000000000000000000..8504ebca17eb6d98f527874a772158b2105f0541 --- /dev/null +++ b/pool/shard008/C/0130660_rb-dialog.c @@ -0,0 +1,163 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ +/* + * Copyright (C) 2002 Jorn Baayen + * Copyright (C) 2004 Colin Walters + * + * 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, or (at your option) + * any later version. + * + * The Rhythmbox authors hereby grant permission for non-GPL compatible + * GStreamer plugins to be used and distributed together with GStreamer + * and Rhythmbox. This permission is above and beyond the permissions granted + * by the GPL license by which Rhythmbox is covered. If you modify this code + * you may extend this exception to your version of the code, but you are not + * obligated to do so. If you do not wish to do so, delete this exception + * statement from your 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 St, Fifth Floor, Boston, MA 02110-1301 USA. + * + */ + +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include "rb-dialog.h" +#include "rb-file-helpers.h" + +/** + * SECTION:rb-dialog + * @short_description: helper functions for creating gtk+ dialog windows + * + * This provides a couple of shortcuts for creating dialogs. If you want + * to annoy the user by displaying an error message, this is the way to do it. + */ + +/** + * rb_error_dialog: + * @parent: parent #GtkWindow for the dialog + * @primary: main error message + * @secondary: secondary error message (printf-style format string) + * @...: any substitution values for the secondary message + * + * Creates and displays a simple error dialog box containing a primary + * message in bold, larger type and a secondary message in the regular + * font. Both the primary and secondary message strings should be + * translated. + * + * Care should be taken to avoid opening multiple error dialog boxes + * when a single error message (such as 'out of disk space') affects + * multiple items. + */ +void +rb_error_dialog (GtkWindow *parent, + const char *primary, + const char *secondary, + ...) +{ + char *text = ""; + va_list args; + GtkWidget *dialog; + + va_start (args, secondary); + g_vasprintf (&text, secondary, args); + va_end (args); + + dialog = gtk_message_dialog_new (parent, + GTK_DIALOG_DESTROY_WITH_PARENT, + GTK_MESSAGE_ERROR, + GTK_BUTTONS_CLOSE, + "%s", primary); + + gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dialog), + "%s", text); + + gtk_window_set_title (GTK_WINDOW (dialog), ""); + + g_signal_connect (dialog, "response", G_CALLBACK (gtk_widget_destroy), NULL); + + gtk_widget_show (dialog); + + g_free (text); +} + +/** + * rb_file_chooser_new: + * @title: title for the file chooser + * @parent: parent #GtkWindow for the file chooser + * @action: the #GtkFileChooserAction + * @local_only: if TRUE, don't show network locations + * + * Creates and shows a regular gtk+ file chooser dialog with + * a given title. The user's music directory (typically ~/Music) is + * added as a shortcut. + * + * For consistency, this should be used anywhere a file chooser is required. + * + * After creating the dialog, the caller should connect a handler to its + * 'response' signal to process the user's selected files or folders. + * + * Return value: (transfer full): the file chooser #GtkWidget + */ +GtkWidget * +rb_file_chooser_new (const char *title, + GtkWindow *parent, + GtkFileChooserAction action, + gboolean local_only) +{ + GtkWidget *dialog; + + if (action == GTK_FILE_CHOOSER_ACTION_OPEN || + action == GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER || + action == GTK_FILE_CHOOSER_ACTION_CREATE_FOLDER) { + dialog = gtk_file_chooser_dialog_new (title, parent, + action, + _("_Cancel"), GTK_RESPONSE_CANCEL, + _("_Open"), GTK_RESPONSE_ACCEPT, + NULL); + gtk_dialog_set_default_response (GTK_DIALOG (dialog), + GTK_RESPONSE_ACCEPT); + } else if (action == GTK_FILE_CHOOSER_ACTION_SAVE) { + dialog = gtk_file_chooser_dialog_new (title, parent, + action, + _("_Cancel"), GTK_RESPONSE_CANCEL, + _("_Save"), GTK_RESPONSE_ACCEPT, + NULL); + gtk_dialog_set_default_response (GTK_DIALOG (dialog), + GTK_RESPONSE_ACCEPT); + gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog), TRUE); + } else { + g_assert_not_reached (); + return NULL; + } + + gtk_file_chooser_set_local_only (GTK_FILE_CHOOSER (dialog), local_only); + gtk_file_chooser_add_shortcut_folder (GTK_FILE_CHOOSER (dialog), + rb_music_dir (), + NULL); + + if (parent != NULL) { + gtk_window_set_transient_for (GTK_WINDOW (dialog), GTK_WINDOW (parent)); + gtk_window_set_destroy_with_parent (GTK_WINDOW (dialog), TRUE); + } + + gtk_widget_show_all (dialog); + + return dialog; +} diff --git a/pool/shard008/C/0130662_functions.c b/pool/shard008/C/0130662_functions.c new file mode 100644 index 0000000000000000000000000000000000000000..53c7a94cd43ecf3e46740ea6d648d141ef65bc51 --- /dev/null +++ b/pool/shard008/C/0130662_functions.c @@ -0,0 +1,97 @@ +/*************************************************************************** + * functions.c + * + * Wed Feb 22 15:40:44 2006 + * Copyright 2006 User + * Email + ****************************************************************************/ + +/* + * 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 Library 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +#include +#include "functions.h" + + + +void bsort (double *x, int n) +{ + int i, j; + double tmp; + + for (i=n-1; i>0; i--) { + for (j=0; j x[j+1]) { + tmp = x[j]; + x[j] = x[j+1]; + x[j+1] = tmp; + } + } + } + return; +} + +/* reject low/high values from array + * note: high values are rejected by lowering the array size only */ +void clip (double *x, int n, int low, int high) +{ + int i; + + if ((low > 0) || (high > 0)) bsort(x, n); + if (low > 0) { + for (i=0; i +#include +#include + +FILE *fp; + +int runs; +int gn; // number of data points + +double **V; + + +void get_input(char *filename); +void mean_plus_variance(double *data, double *mean, double *variance, int num); + +int main(int argc, char *argv[]) +{ + runs=atoi(argv[1]); + gn=atoi(argv[2]); + + V = (double **)malloc(gn*sizeof(double *)); + for(int i=0;i 3) + { + get_input(argv[3]); + } + else + { + fprintf(stderr,"Need <#runs> <#datapoints> \n"); + exit(0); + } + + double mean,var; + + for(i=0;i + * Copyright (C) 2010-2020 ARM Limited or its affiliates. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include +#include +#include +#include "../../common/test_common.h" + +#include "fir_q15.pat" + +#define SNR_ERROR_THRESH ((float32_t)59) +#define ABS_ERROR_THRESH_Q15 ((q15_t)2) + +static void test_arm_fir_q15(void) +{ + size_t sample_index, block_index; + size_t block_size, tap_count; + size_t sample_count = ARRAY_SIZE(in_config) / 2; + size_t length = ARRAY_SIZE(ref_val); + const uint16_t *config = in_config; + const q15_t *input = (const q15_t *)in_val; + const q15_t *coeff = (const q15_t *)in_coeff; + const q15_t *ref = (const q15_t *)ref_val; + q15_t *state, *output_buf, *output; + arm_fir_instance_q15 inst; + + /* Allocate buffers */ + state = malloc(3 * 41 * sizeof(q15_t)); + zassert_not_null(state, ASSERT_MSG_BUFFER_ALLOC_FAILED); + + output_buf = malloc(length * sizeof(q15_t)); + zassert_not_null(output_buf, ASSERT_MSG_BUFFER_ALLOC_FAILED); + + output = output_buf; + + /* Enumerate samples */ + for (sample_index = 0; sample_index < sample_count; sample_index++) { + /* Resolve sample configurations */ + block_size = config[0]; + tap_count = config[1]; + + /* Initialise instance */ + arm_fir_init_q15(&inst, tap_count, coeff, state, block_size); + + /* TODO: Add MEVI support */ + + /* Reset input pointer */ + input = (const q15_t *)in_val; + + /* Enumerate blocks */ + for (block_index = 0; block_index < 2; block_index++) { + /* Run test function */ + arm_fir_q15(&inst, input, output, block_size); + + /* Increment pointers */ + input += block_size; + output += block_size; + } + + /* Increment pointers */ + coeff += tap_count; + config += 2; + } + + /* Validate output */ + zassert_true( + test_snr_error_q15(length, output_buf, ref, SNR_ERROR_THRESH), + ASSERT_MSG_SNR_LIMIT_EXCEED); + + zassert_true( + test_near_equal_q15(length, output_buf, ref, + ABS_ERROR_THRESH_Q15), + ASSERT_MSG_ABS_ERROR_LIMIT_EXCEED); + + /* Free buffers */ + free(state); + free(output_buf); +} + +void test_filtering_fir_q15(void) +{ + ztest_test_suite(filtering_fir_q15, + ztest_unit_test(test_arm_fir_q15) + ); + + ztest_run_test_suite(filtering_fir_q15); +} diff --git a/pool/shard008/C/0130671_zwppm.c b/pool/shard008/C/0130671_zwppm.c new file mode 100644 index 0000000000000000000000000000000000000000..9b889211915d7221030279b9a9ede39803841474 --- /dev/null +++ b/pool/shard008/C/0130671_zwppm.c @@ -0,0 +1,170 @@ +/* Copyright (C) 1995 Aladdin Enterprises. All rights reserved. + + This file is part of Aladdin Ghostscript. + + Aladdin Ghostscript is distributed with NO WARRANTY OF ANY KIND. No author + or distributor accepts any responsibility for the consequences of using it, + or for whether it serves any particular purpose or works at all, unless he + or she says so in writing. Refer to the Aladdin Ghostscript Free Public + License (the "License") for full details. + + Every copy of Aladdin Ghostscript must include a copy of the License, + normally in a plain ASCII text file named PUBLIC. The License grants you + the right to copy, modify and redistribute Aladdin Ghostscript, but only + under certain conditions described in the License. Among other things, the + License requires that the copyright notice and this notice be preserved on + all copies. +*/ + +/* zwppm.c */ +/* Obsolete PPM-file-writing operator */ +#include "memory_.h" +#include "ghost.h" +#include "errors.h" +#include "oper.h" +#include "stream.h" +#include "files.h" +#include "gscdefs.h" +#include "gsmatrix.h" /* for gxdevice.h */ +#include "gxdevice.h" +#include "gxdevmem.h" + +/* Forward references */ +private int gs_writeppmfile(P2(gx_device_memory *, FILE *)); + +/* writeppmfile - */ +private int +zwriteppmfile(register os_ptr op) +{ stream *s; + int code; + check_read_type(*op, t_device); + check_write_file(s, op - 1); + if ( !gs_device_is_memory(op->value.pdevice) ) + return_error(e_rangecheck); + sflush(s); + code = gs_writeppmfile((gx_device_memory *)(op->value.pdevice), s->file); + if ( code >= 0 ) + pop(2); + return code; +} + +/* ------ Initialization procedure ------ */ + +BEGIN_OP_DEFS(zwppm_op_defs) { + {"2writeppmfile", zwriteppmfile}, +END_OP_DEFS(0) } + +/* ------ Non-operator routines ------ */ + +/* Dump the contents of a memory device in PPM format. */ +private int +gs_writeppmfile(gx_device_memory *md, FILE *file) +{ int raster = gx_device_raster((gx_device *)md, 0); + int height = md->height; + int depth = md->color_info.depth; + uint rsize = raster * 3; /* * 3 just for mapped color */ + byte *row = (byte *)gs_malloc(rsize, 1, "ppm file buffer"); + const char *header; + int y; + int code = 0; /* return code */ + if ( row == 0 ) /* can't allocate row buffer */ + return_error(e_VMerror); + + /* A PPM file consists of: magic number, comment, */ + /* width, height, maxvalue, (r,g,b).... */ + + /* Dispatch on the type of the device -- 1-bit mono, */ + /* 8-bit (gray scale or color), 24- or 32-bit true color. */ + + switch ( depth ) + { + case 1: + header = "P4\n# %s 1 bit mono image dump\n%d %d\n"; + break; + + case 8: + header = (gx_device_has_color(md) ? + "P6\n# %s 8 bit mapped color image dump\n%d %d\n255\n" : + "P5\n# %s 8 bit gray scale image dump\n%d %d\n255\n"); + break; + + case 24: + header = "P6\n# %s 24 bit color image dump\n%d %d\n255\n"; + break; + + case 32: + header = "P6\n# %s 32 bit color image dump\n%d %d\n255\n"; + break; + + default: /* shouldn't happen! */ + code = e_undefinedresult; + goto done; + } + + /* Write the header. */ + fprintf(file, header, gs_product, md->width, height); + + /* Dump the contents of the image. */ + for ( y = 0; y < height; y++ ) + { int count; + register byte *from, *to, *end; + (*dev_proc(md, get_bits))((gx_device *)md, y, row, NULL); + switch ( depth ) + { + case 8: + { /* Mapped color, consult the map. */ + if ( gx_device_has_color(md) ) + { /* Map color */ + const byte *palette = md->palette.data; + from = row + raster + raster; + memcpy(from, row, raster); + to = row; + end = from + raster; + while ( from < end ) + { register const byte *cp = + palette + (int)*from++ * 3; + to[0] = cp[0]; /* red */ + to[1] = cp[1]; /* green */ + to[2] = cp[2]; /* blue */ + to += 3; + } + count = raster * 3; + } + else + { /* Map gray scale */ + register const byte *palette = + md->palette.data; + from = to = row, end = row + raster; + while ( from < end ) + *to++ = palette[(int)*from++ * 3]; + count = raster; + } + } + break; + case 32: + { /* This case is different, because we must skip */ + /* every fourth byte. */ + from = to = row, end = row + raster; + while ( from < end ) + { /* from[0] is unused */ + to[0] = from[1]; /* red */ + to[1] = from[2]; /* green */ + to[2] = from[3]; /* blue */ + from += 4; + to += 3; + } + count = to - row; + } + break; + default: + count = raster; + } + if ( fwrite(row, 1, count, file) < count ) + { code = e_ioerror; + goto done; + } + } + +done: gs_free((char *)row, rsize, 1, "ppm file buffer"); + return code; +} diff --git a/pool/shard008/C/0130672_dt-uart.c b/pool/shard008/C/0130672_dt-uart.c new file mode 100644 index 0000000000000000000000000000000000000000..93bb0f5845f4dc1cbd64639818c12eb0a8fe7910 --- /dev/null +++ b/pool/shard008/C/0130672_dt-uart.c @@ -0,0 +1,69 @@ +/* + * xen/drivers/char/dt-uart.c + * + * Generic uart retrieved via the device tree + * + * Julien Grall + * Copyright (c) 2013 Linaro Limited. + * + * 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. + */ + +#include +#include +#include +#include +#include +#include + +/* + * Configure UART port with a string: + * alias,options + * + * @alias: alias used in the device tree for the UART + * @options: UART speficic options (see in each UART driver) + */ +static char __initdata opt_dtuart[30] = ""; +string_param("dtuart", opt_dtuart); + +void __init dt_uart_init(void) +{ + struct dt_device_node *dev; + int ret; + const char *devalias = opt_dtuart; + char *options; + + if ( !console_has("dtuart") || !strcmp(opt_dtuart, "") ) + { + early_printk("No console\n"); + return; + } + + options = strchr(opt_dtuart, ','); + if ( options != NULL ) + *(options++) = '\0'; + else + options = ""; + + early_printk("Looking for UART console %s\n", devalias); + dev = dt_find_node_by_alias(devalias); + + if ( !dev ) + { + early_printk("Unable to find device \"%s\"\n", devalias); + return; + } + + ret = device_init(dev, DEVICE_SERIAL, options); + + if ( ret ) + early_printk("Unable to initialize serial: %d\n", ret); +} diff --git a/pool/shard008/C/0130681_diomdel.c b/pool/shard008/C/0130681_diomdel.c new file mode 100644 index 0000000000000000000000000000000000000000..d81cd0cf386746bf0051bff0edf048665daf0fbe --- /dev/null +++ b/pool/shard008/C/0130681_diomdel.c @@ -0,0 +1,45 @@ +/********** +Copyright 1990 Regents of the University of California. All rights reserved. +Author: 1985 Thomas L. Quarles +**********/ +/* + */ + +#include "spice.h" +#include +#include "util.h" +#include "diodefs.h" +#include "sperror.h" +#include "suffix.h" + + +int +DIOmDelete(inModel,modname,kill) + GENmodel **inModel; + IFuid modname; + GENmodel *kill; +{ + DIOmodel **model = (DIOmodel**)inModel; + DIOmodel *modfast = (DIOmodel*)kill; + DIOinstance *here; + DIOinstance *prev = NULL; + DIOmodel **oldmod; + oldmod = model; + for( ; *model ; model = &((*model)->DIOnextModel)) { + if( (*model)->DIOmodName == modname || + (modfast && *model == modfast) ) goto delgot; + oldmod = model; + } + return(E_NOMOD); + +delgot: + *oldmod = (*model)->DIOnextModel; /* cut deleted device out of list */ + for(here = (*model)->DIOinstances ; here ; here = here->DIOnextInstance) { + if(prev) FREE(prev); + prev = here; + } + if(prev) FREE(prev); + FREE(*model); + return(OK); + +} diff --git a/pool/shard008/C/0130685_xfun.c b/pool/shard008/C/0130685_xfun.c new file mode 100644 index 0000000000000000000000000000000000000000..49ad9ddcd5b30424a470bb46bc85eb3b6317cb84 --- /dev/null +++ b/pool/shard008/C/0130685_xfun.c @@ -0,0 +1,126 @@ +#include "crypt.h" +#include + +CRYPT_XFUN xfun; + +void XMEMCPY(void *dest, const void *src, SIZE_T n) +{ + UCHAR * p1 = (UCHAR *) dest; + UCHAR * p2 = (UCHAR *) src; + + + if(NULL != xfun.xmemcpy) { + xfun.xmemcpy(dest, src, n); + return; + } + + while(n --) { + *p1 = *p2; + p1 ++; + p2 ++; + } +} + +INT XMEMCMP(const void *s1, const void *s2, SIZE_T n) +{ + INT ret = 0; + UCHAR * p1 = (UCHAR *) s1; + UCHAR * p2 = (UCHAR *) s2; + + if(NULL != xfun.xmemcmp) + return xfun.xmemcmp(s1, s2, n); + + while(n --) { + if(*p1 > *p2) { + ret = 1; + break; + } + else if(*p1 < *p2) { + ret = -1; + break; + } + p1 ++; + p2 ++; + } + + return ret; +} + +void XMEMSET(void *s, INT c, SIZE_T n) +{ + UCHAR * p1 = (UCHAR *) s; + + if(NULL != xfun.xmemset) + xfun.xmemset(s, c, n); + + while(n --) { + *p1 = (UCHAR)c; + p1 ++; + } +} + +INT XSTRCMP(const CHAR *s1, const CHAR *s2) +{ + INT ret = 0; + CHAR * p1 = (CHAR *) s1; + CHAR * p2 = (CHAR *) s2; + + if(NULL != xfun.xstrcmp) + return xfun.xstrcmp(s1, s2); + + while(*p1 && *p2) { + if(*p1 > *p2) { + ret = 1; + break; + } + else if(*p1 < *p2) { + ret = -1; + break; + } + p1 ++; + p2 ++; + } + if(*p1 && ! *p2) { + ret = 1; + } else if(! *p1 && *p2) { + ret = -1; + } + return ret; +} + +void XZEROMEM(void *s, SIZE_T n) +{ + if(NULL != xfun.xzeromem) { + xfun.xzeromem(s, n); + } else { + XMEMSET(s, 0, n); + } +} + +SIZE_T XSTRLEN(const CHAR * s) +{ + + const CHAR * p = s; + SIZE_T ret = 0; + + if(NULL != xfun.xstrlen) + return xfun.xstrlen(s); + + while(*p) { + p ++; + ret ++; + } + return ret; +} + +static ULONG rand_seed; + +ULONG XRAND() +{ + if(NULL != xfun.xrand) + return xfun.xrand(); + + rand_seed = (rand_seed * 123 + 59 )% ULONG_MAX; + + return(rand_seed); +} \ No newline at end of file diff --git a/pool/shard008/C/0130688_ohci-ep93xx.c b/pool/shard008/C/0130688_ohci-ep93xx.c new file mode 100644 index 0000000000000000000000000000000000000000..9654fa2996f8ac5f4e140da3120b43ae990b50b1 --- /dev/null +++ b/pool/shard008/C/0130688_ohci-ep93xx.c @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * (C) Copyright 2013 + * Sergey Kostanbaev < sergey.kostanbaev fairwaves.ru > + */ + +#include +#include + +#if defined(CONFIG_USB_OHCI_NEW) && defined(CONFIG_SYS_USB_OHCI_CPU_INIT) +#include +#include + +int usb_cpu_init(void) +{ + struct syscon_regs *syscon = (struct syscon_regs *)SYSCON_BASE; + unsigned long pwr = readl(&syscon->pwrcnt); + writel(pwr | SYSCON_PWRCNT_USH_EN, &syscon->pwrcnt); + + return 0; +} + +int usb_cpu_stop(void) +{ + struct syscon_regs *syscon = (struct syscon_regs *)SYSCON_BASE; + unsigned long pwr = readl(&syscon->pwrcnt); + writel(pwr & ~SYSCON_PWRCNT_USH_EN, &syscon->pwrcnt); + + return 0; +} + +int usb_cpu_init_fail(void) +{ + return usb_cpu_stop(); +} + +#endif /* defined(CONFIG_USB_OHCI) && defined(CONFIG_SYS_USB_OHCI_CPU_INIT) */ diff --git a/pool/shard008/C/0130690_test.c b/pool/shard008/C/0130690_test.c new file mode 100644 index 0000000000000000000000000000000000000000..1af5af4c4630c8096d0913a1a27699b315025601 --- /dev/null +++ b/pool/shard008/C/0130690_test.c @@ -0,0 +1,57 @@ +#include + +#include "linked_list.h" +#include "thread_pool.h" + +#define THREAD_POOL_SIZE 100 +#define WORKERS_NUM 4 +#define TASKS_NUM 50 + +int +search_task(void *data) +{ + node_t *list_head = (node_t *)data; + int key = 3; + search_res_t buf = linked_list_search(list_head, key); + (void) linked_list_delete(list_head, 0); + if (buf.error) + fprintf(stderr, "Element with key %d is not found\n", key); + else + fprintf(stderr, "Key: %d Element: %ld\n", key, buf.elem); + + return 0; +} + +int +delete_task(void *data) +{ + node_t *list_head = (node_t *)data; + (void) linked_list_insert(list_head, 3, 10); + return 0; +} + +int +main(int argc, char *argv[]) +{ + int i; + node_t *list_head; + thread_pool_t* th_pool; + + list_head = linked_list_create(); + th_pool = thread_pool_create(THREAD_POOL_SIZE, WORKERS_NUM); + + for (i = 0; i < TASKS_NUM; i++) + switch (i) { + case 6: + thread_pool_add(th_pool, delete_task, + (void *)list_head); + break; + default: + thread_pool_add(th_pool, search_task, + (void *)list_head); + break; + } + thread_pool_wait_all(th_pool); + thread_pool_destroy(th_pool); + return 0; +} diff --git a/pool/shard008/C/0130691_enc.c b/pool/shard008/C/0130691_enc.c new file mode 100644 index 0000000000000000000000000000000000000000..b4648ca81181e3a1c1c3fed98007512cda6e09db --- /dev/null +++ b/pool/shard008/C/0130691_enc.c @@ -0,0 +1,163 @@ +/* + * enc.c + */ + +/* + * SPDX-License-Identifier: Apache-2.0 + */ + +/* + * This is a model of the enigma hardware as remembered from + * a description read around ten years prior. The model has + * not been tested or validated as cryptographically secure. + * Furthermore the author intentionally did not validate the + * model against published descriptions of the enigma. The + * only test completed was to set the wheels to a known + * position and insert a pt string of text into the function. + * The output was recorded as ct. The wheels were reset to the + * original start position, and the recorded ct was inserted + * into the function. The output was compared to the original + * pt text and matched. The result of the test matched the + * expected outcome, but it does not validate the algorithm + * meets any security requirments. + * + * ********************************************************** + * + * DO NOT USE IN PRODUCTION CODE AS A SECURITY FEATURE + * + * ********************************************************** + */ + +#include "enc.h" + + +/* + * for a pt character encrypt a ct character and update wheels + * Each wheel must be indexed into and out of the wheel arrays + * this process is based on a absolute index of input characters + * and the reflector. + * Note: the output of wheel arrays are added to WHEEL_SIZE + * to prevent a negative index when subtracting the iw value. + * The printk lines have been left in to inspect operations + * of the enigma simulation. simply add the definition DBUG + * to enable the detailed messages. + */ + +char enig_enc(char pt) +{ + short tmpIndex; + char ct; +#ifdef DBUG + printk("\nEE PT: %c, %02x\n", pt, pt); + printk("Index: %d, %d, %d\n", IW1, IW2, IW3); +#endif + tmpIndex = char_to_index(pt); +#ifdef DBUG + printk("EE : %02x\n", tmpIndex); +#endif + /* if error return */ + if (tmpIndex == -1) { + return (char)0xFF; + } + + tmpIndex = (W1[IMOD(IW1, tmpIndex)] + WHEEL_SIZE - IW1) % WHEEL_SIZE; +#ifdef DBUG + printk("EE i1: %02x\n", tmpIndex); +#endif + tmpIndex = (W2[IMOD(IW2, tmpIndex)] + WHEEL_SIZE - IW2) % WHEEL_SIZE; +#ifdef DBUG + printk("EE i2: %02x\n", tmpIndex); +#endif + tmpIndex = (W3[IMOD(IW3, tmpIndex)] + WHEEL_SIZE - IW3) % WHEEL_SIZE; +#ifdef DBUG + printk("EE i3: %02x\n", tmpIndex); +#endif + tmpIndex = R[tmpIndex]; +#ifdef DBUG + printk("EE r: %02x\n", tmpIndex); +#endif + tmpIndex = (W3R[IMOD(IW3, tmpIndex)] + WHEEL_SIZE - IW3) % WHEEL_SIZE; +#ifdef DBUG + printk("EE i3: %02x\n", tmpIndex); +#endif + tmpIndex = (W2R[IMOD(IW2, tmpIndex)] + WHEEL_SIZE - IW2) % WHEEL_SIZE; +#ifdef DBUG + printk("EE i2: %02x\n", tmpIndex); +#endif + tmpIndex = (W1R[IMOD(IW1, tmpIndex)] + WHEEL_SIZE - IW1) % WHEEL_SIZE; +#ifdef DBUG + printk("EE i1: %02x\n", tmpIndex); +#endif + + ct = index_to_char(tmpIndex); +#ifdef DBUG + printk("EE CT: %02x\n", ct); +#endif + /* test ct value or just return error ? */ + update_wheel_index(); + return ct; +} + +/* + * calc reverse path for wheel + * this simplifies the reverse path calculation + * Return: 1:ok -1 error + */ +int calc_rev_wheel(BYTE *wheel, BYTE *backpath) +{ + + int i; + + for (i = 0; i < WHEEL_SIZE; i++) { + if (wheel[i] >= WHEEL_SIZE) { + return -1; + } + backpath[wheel[i]] = i; + } + return 1; +} + + +/* + * convert a-z to 0-25 + */ +short char_to_index(char c) +{ + if (c < 'a' || c > 'z') { + return -1; + } + return (short)(c - 'a'); +} + +/* + * convert from a index 0-25 to a-z + */ +char index_to_char(short i) +{ + if (i < 0 || i > 25) { + return 0xFF; + } + return (char)((short)'a' + i); +} + +/* + * basic update to wheels based on full rotation + * of prior wheel. This could be modified to change + * the direction of rotation or order of updates + */ +void update_wheel_index(void) +{ + IW1++; + if (IW1 >= WHEEL_SIZE) { + IW1 %= WHEEL_SIZE; + IW2++; + } + if (IW2 >= WHEEL_SIZE) { + IW2 %= WHEEL_SIZE; + IW3++; + } + if (IW3 >= WHEEL_SIZE) { + IW3 %= WHEEL_SIZE; + } + +} diff --git a/pool/shard008/C/0130692_pgusage.c b/pool/shard008/C/0130692_pgusage.c new file mode 100644 index 0000000000000000000000000000000000000000..7eae2b0f5b0467835be5f9ec6d388f798840cae6 --- /dev/null +++ b/pool/shard008/C/0130692_pgusage.c @@ -0,0 +1,132 @@ + +/** + * \file pgusage.c + * + * Time-stamp: "2012-02-28 19:49:32 bkorb" + * + * Automated Options Paged Usage module. + * + * This routine will run run-on options through a pager so the + * user may examine, print or edit them at their leisure. + * + * This file is part of AutoOpts, a companion to AutoGen. + * AutoOpts is free software. + * AutoOpts is Copyright (c) 1992-2012 by Bruce Korb - all rights reserved + * + * AutoOpts is available under any one of two licenses. The license + * in use must be one of these two and the choice is under the control + * of the user of the license. + * + * The GNU Lesser General Public License, version 3 or later + * See the files "COPYING.lgplv3" and "COPYING.gplv3" + * + * The Modified Berkeley Software Distribution License + * See the file "COPYING.mbsd" + * + * These files have the following md5sums: + * + * 43b91e8ca915626ed3818ffb1b71248b pkg/libopts/COPYING.gplv3 + * 06a1a2e4760c90ea5e1dad8dfaac4d39 pkg/libopts/COPYING.lgplv3 + * 66a5cedaf62c4b2637025f049f9b826f pkg/libopts/COPYING.mbsd + */ + +/*=export_func optionPagedUsage + * private: + * + * what: Decipher a boolean value + * arg: + tOptions* + pOpts + program options descriptor + + * arg: + tOptDesc* + pOptDesc + the descriptor for this arg + + * + * doc: + * Run the usage output through a pager. + * This is very handy if it is very long. + * This is disabled on platforms without a working fork() function. +=*/ +void +optionPagedUsage(tOptions * pOptions, tOptDesc * pOD) +{ +#if ! defined(HAVE_WORKING_FORK) + if ((pOD->fOptState & OPTST_RESET) != 0) + return; + + (*pOptions->pUsageProc)(pOptions, EXIT_SUCCESS); +#else + static pid_t my_pid; + char zPageUsage[ 1024 ]; + + /* + * IF we are being called after the usage proc is done + * (and thus has called "exit(2)") + * THEN invoke the pager to page through the usage file we created. + */ + switch (pagerState) { + case PAGER_STATE_INITIAL: + { + if ((pOD->fOptState & OPTST_RESET) != 0) + return; + + my_pid = getpid(); + snprintf(zPageUsage, sizeof(zPageUsage), TMP_USAGE_FMT, (tAoUL)my_pid); + unlink(zPageUsage); + + /* + * Set usage output to this temporary file + */ + option_usage_fp = fopen(zPageUsage, "w" FOPEN_BINARY_FLAG); + if (option_usage_fp == NULL) + _exit(EXIT_FAILURE); + + pagerState = PAGER_STATE_READY; + + /* + * Set up so this routine gets called during the exit logic + */ + atexit((void(*)(void))optionPagedUsage); + + /* + * The usage procedure will now put the usage information into + * the temporary file we created above. + */ + (*pOptions->pUsageProc)(pOptions, EXIT_SUCCESS); + + /* NOTREACHED */ + _exit(EXIT_FAILURE); + } + + case PAGER_STATE_READY: + { + tCC* pzPager = (tCC*)getenv(PAGER_NAME); + + /* + * Use the "more(1)" program if "PAGER" has not been defined + */ + if (pzPager == NULL) + pzPager = MORE_STR; + + /* + * Page the file and remove it when done. + */ + snprintf(zPageUsage, sizeof(zPageUsage), PAGE_USAGE_FMT, pzPager, + (tAoUL)my_pid); + fclose(stderr); + dup2(STDOUT_FILENO, STDERR_FILENO); + + (void)system(zPageUsage); + } + + case PAGER_STATE_CHILD: + /* + * This is a child process used in creating shell script usage. + */ + break; + } +#endif +} + +/* + * Local Variables: + * mode: C + * c-file-style: "stroustrup" + * indent-tabs-mode: nil + * End: + * end of autoopts/pgusage.c */ diff --git a/pool/shard008/C/0130695_ctdb_ltdb.c b/pool/shard008/C/0130695_ctdb_ltdb.c new file mode 100644 index 0000000000000000000000000000000000000000..cb07a72375b51f1ff2d1da83d903057bbe51af78 --- /dev/null +++ b/pool/shard008/C/0130695_ctdb_ltdb.c @@ -0,0 +1,345 @@ +/* + ctdb ltdb code + + Copyright (C) Andrew Tridgell 2006 + + 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 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. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include "includes.h" +#include "lib/events/events.h" +#include "lib/tdb/include/tdb.h" +#include "system/network.h" +#include "system/filesys.h" +#include "../include/ctdb_private.h" +#include "db_wrap.h" +#include "lib/util/dlinklist.h" + +/* + find an attached ctdb_db handle given a name + */ +struct ctdb_db_context *ctdb_db_handle(struct ctdb_context *ctdb, const char *name) +{ + struct ctdb_db_context *tmp_db; + for (tmp_db=ctdb->db_list;tmp_db;tmp_db=tmp_db->next) { + if (strcmp(name, tmp_db->db_name) == 0) { + return tmp_db; + } + } + return NULL; +} + + +/* + this is the dummy null procedure that all databases support +*/ +static int ctdb_null_func(struct ctdb_call_info *call) +{ + return 0; +} + + +/* + attach to a specific database +*/ +struct ctdb_db_context *ctdb_attach(struct ctdb_context *ctdb, const char *name, int tdb_flags, + int open_flags, mode_t mode) +{ + struct ctdb_db_context *ctdb_db, *tmp_db; + TDB_DATA data; + int ret; + + ctdb_db = talloc_zero(ctdb, struct ctdb_db_context); + CTDB_NO_MEMORY_NULL(ctdb, ctdb_db); + + ctdb_db->ctdb = ctdb; + ctdb_db->db_name = talloc_strdup(ctdb_db, name); + CTDB_NO_MEMORY_NULL(ctdb, ctdb_db->db_name); + + data.dptr = discard_const(name); + data.dsize = strlen(name); + ctdb_db->db_id = ctdb_hash(&data); + + for (tmp_db=ctdb->db_list;tmp_db;tmp_db=tmp_db->next) { + if (tmp_db->db_id == ctdb_db->db_id) { + ctdb_set_error(ctdb, "CTDB database hash collission '%s' : '%s'", + name, tmp_db->db_name); + talloc_free(ctdb_db); + return NULL; + } + } + + if (mkdir(ctdb->db_directory, 0700) == -1 && errno != EEXIST) { + DEBUG(0,(__location__ " Unable to create ctdb directory '%s'\n", + ctdb->db_directory)); + talloc_free(ctdb_db); + return NULL; + } + + /* add the node id to the database name, so when we run on loopback + we don't conflict in the local filesystem */ + name = talloc_asprintf(ctdb_db, "%s/%s", ctdb->db_directory, name); + + /* when we have a separate daemon this will need to be a real + file, not a TDB_INTERNAL, so the parent can access it to + for ltdb bypass */ + ctdb_db->ltdb = tdb_wrap_open(ctdb, name, 0, TDB_CLEAR_IF_FIRST, open_flags, mode); + if (ctdb_db->ltdb == NULL) { + ctdb_set_error(ctdb, "Failed to open tdb %s\n", name); + talloc_free(ctdb_db); + return NULL; + } + + + /* + all databases support the "null" function. we need this in + order to do forced migration of records + */ + ret = ctdb_set_call(ctdb_db, ctdb_null_func, CTDB_NULL_FUNC); + if (ret != 0) { + talloc_free(ctdb_db); + return NULL; + } + + DLIST_ADD(ctdb->db_list, ctdb_db); + + return ctdb_db; +} + +/* + return the lmaster given a key +*/ +uint32_t ctdb_lmaster(struct ctdb_context *ctdb, const TDB_DATA *key) +{ + return ctdb_hash(key) % ctdb->num_nodes; +} + + +/* + construct an initial header for a record with no ltdb header yet +*/ +static void ltdb_initial_header(struct ctdb_db_context *ctdb_db, + TDB_DATA key, + struct ctdb_ltdb_header *header) +{ + header->rsn = 0; + /* initial dmaster is the lmaster */ + header->dmaster = ctdb_lmaster(ctdb_db->ctdb, &key); + header->laccessor = header->dmaster; + header->lacount = 0; +} + + +/* + fetch a record from the ltdb, separating out the header information + and returning the body of the record. A valid (initial) header is + returned if the record is not present +*/ +int ctdb_ltdb_fetch(struct ctdb_db_context *ctdb_db, + TDB_DATA key, struct ctdb_ltdb_header *header, + TALLOC_CTX *mem_ctx, TDB_DATA *data) +{ + TDB_DATA rec; + struct ctdb_context *ctdb = ctdb_db->ctdb; + + rec = tdb_fetch(ctdb_db->ltdb->tdb, key); + if (rec.dsize < sizeof(*header)) { + TDB_DATA d2; + /* return an initial header */ + if (rec.dptr) free(rec.dptr); + ltdb_initial_header(ctdb_db, key, header); + ZERO_STRUCT(d2); + if (data) { + *data = d2; + } + ctdb_ltdb_store(ctdb_db, key, header, d2); + return 0; + } + + *header = *(struct ctdb_ltdb_header *)rec.dptr; + + if (data) { + data->dsize = rec.dsize - sizeof(struct ctdb_ltdb_header); + data->dptr = talloc_memdup(mem_ctx, + sizeof(struct ctdb_ltdb_header)+rec.dptr, + data->dsize); + } + + free(rec.dptr); + if (data) { + CTDB_NO_MEMORY(ctdb, data->dptr); + } + + return 0; +} + + +/* + fetch a record from the ltdb, separating out the header information + and returning the body of the record. A valid (initial) header is + returned if the record is not present +*/ +int ctdb_ltdb_store(struct ctdb_db_context *ctdb_db, TDB_DATA key, + struct ctdb_ltdb_header *header, TDB_DATA data) +{ + struct ctdb_context *ctdb = ctdb_db->ctdb; + TDB_DATA rec; + int ret; + + rec.dsize = sizeof(*header) + data.dsize; + rec.dptr = talloc_size(ctdb, rec.dsize); + CTDB_NO_MEMORY(ctdb, rec.dptr); + + memcpy(rec.dptr, header, sizeof(*header)); + memcpy(rec.dptr + sizeof(*header), data.dptr, data.dsize); + + ret = tdb_store(ctdb_db->ltdb->tdb, key, rec, TDB_REPLACE); + talloc_free(rec.dptr); + + return ret; +} + + +/* + lock a record in the ltdb, given a key + */ +int ctdb_ltdb_lock(struct ctdb_db_context *ctdb_db, TDB_DATA key) +{ + return tdb_chainlock(ctdb_db->ltdb->tdb, key); +} + +/* + unlock a record in the ltdb, given a key + */ +int ctdb_ltdb_unlock(struct ctdb_db_context *ctdb_db, TDB_DATA key) +{ + return tdb_chainunlock(ctdb_db->ltdb->tdb, key); +} + +struct lock_fetch_state { + struct ctdb_context *ctdb; + void (*recv_pkt)(void *, uint8_t *, uint32_t); + void *recv_context; + struct ctdb_req_header *hdr; +}; + +/* + called when we should retry the operation + */ +static void lock_fetch_callback(void *p) +{ + struct lock_fetch_state *state = talloc_get_type(p, struct lock_fetch_state); + state->recv_pkt(state->recv_context, (uint8_t *)state->hdr, state->hdr->length); + talloc_free(state); + DEBUG(2,(__location__ " PACKET REQUEUED\n")); +} + + +/* + do a non-blocking ltdb_lock, deferring this ctdb request until we + have the chainlock + + It does the following: + + 1) tries to get the chainlock. If it succeeds, then it returns 0 + + 2) if it fails to get a chainlock immediately then it sets up a + non-blocking chainlock via ctdb_lockwait, and when it gets the + chainlock it re-submits this ctdb request to the main packet + receive function + + This effectively queues all ctdb requests that cannot be + immediately satisfied until it can get the lock. This means that + the main ctdb daemon will not block waiting for a chainlock held by + a client + + There are 3 possible return values: + + 0: means that it got the lock immediately. + -1: means that it failed to get the lock, and won't retry + -2: means that it failed to get the lock immediately, but will retry + */ +int ctdb_ltdb_lock_requeue(struct ctdb_db_context *ctdb_db, + TDB_DATA key, struct ctdb_req_header *hdr, + void (*recv_pkt)(void *, uint8_t *, uint32_t ), + void *recv_context) +{ + int ret; + struct tdb_context *tdb = ctdb_db->ltdb->tdb; + struct lockwait_handle *h; + struct lock_fetch_state *state; + + ret = tdb_chainlock_nonblock(tdb, key); + + if (ret != 0 && + !(errno == EACCES || errno == EAGAIN || errno == EDEADLK)) { + /* a hard failure - don't try again */ + return -1; + } + + /* when torturing, ensure we test the contended path */ + if ((ctdb_db->ctdb->flags & CTDB_FLAG_TORTURE) && + random() % 5 == 0) { + ret = -1; + tdb_chainunlock(tdb, key); + } + + /* first the non-contended path */ + if (ret == 0) { + return 0; + } + + state = talloc(ctdb_db, struct lock_fetch_state); + state->ctdb = ctdb_db->ctdb; + state->hdr = hdr; + state->recv_pkt = recv_pkt; + state->recv_context = recv_context; + + /* now the contended path */ + h = ctdb_lockwait(ctdb_db, key, lock_fetch_callback, state); + if (h == NULL) { + tdb_chainunlock(tdb, key); + return -1; + } + + /* we need to move the packet off the temporary context in ctdb_recv_pkt(), + so it won't be freed yet */ + talloc_steal(state, hdr); + talloc_steal(state, h); + + /* now tell the caller than we will retry asynchronously */ + return -2; +} + +/* + a varient of ctdb_ltdb_lock_requeue that also fetches the record + */ +int ctdb_ltdb_lock_fetch_requeue(struct ctdb_db_context *ctdb_db, + TDB_DATA key, struct ctdb_ltdb_header *header, + struct ctdb_req_header *hdr, TDB_DATA *data, + void (*recv_pkt)(void *, uint8_t *, uint32_t ), + void *recv_context) +{ + int ret; + + ret = ctdb_ltdb_lock_requeue(ctdb_db, key, hdr, recv_pkt, recv_context); + if (ret == 0) { + ret = ctdb_ltdb_fetch(ctdb_db, key, header, hdr, data); + if (ret != 0) { + ctdb_ltdb_unlock(ctdb_db, key); + } + } + return ret; +} diff --git a/pool/shard008/C/0130696_jpeg.c b/pool/shard008/C/0130696_jpeg.c new file mode 100644 index 0000000000000000000000000000000000000000..5850b6dd722c330bb63af5c5cfbad4d05f6089d7 --- /dev/null +++ b/pool/shard008/C/0130696_jpeg.c @@ -0,0 +1,177 @@ +#include "omxcam.h" +#include "internal.h" + +void omxcam__jpeg_init (omxcam_jpeg_settings_t* settings){ + settings->quality = 75; + settings->exif.enabled = OMXCAM_TRUE; + settings->exif.tags = 0; + settings->exif.valid_tags = 0; + settings->ijg = OMXCAM_FALSE; + settings->thumbnail.enabled = OMXCAM_TRUE; + settings->thumbnail.width = OMXCAM_JPEG_THUMBNAIL_WIDTH_AUTO; + settings->thumbnail.height = OMXCAM_JPEG_THUMBNAIL_HEIGHT_AUTO; + settings->thumbnail.preview = OMXCAM_FALSE; + settings->raw_bayer = OMXCAM_FALSE; +} + +int omxcam__jpeg_validate (omxcam_jpeg_settings_t* settings){ + if (!omxcam__jpeg_is_valid_quality (settings->quality)){ + omxcam__error ("invalid 'jpeg.quality' value"); + return -1; + } + if (settings->thumbnail.enabled && !settings->thumbnail.preview){ + if (!omxcam__jpeg_is_valid_thumbnail (settings->thumbnail.width)){ + omxcam__error ("invalid 'jpeg.thumbnail.width' value"); + return -1; + } + if (!omxcam__jpeg_is_valid_thumbnail (settings->thumbnail.height)){ + omxcam__error ("invalid 'jpeg.thumbnail.height' value"); + return -1; + } + } + return 0; +} + +int omxcam__jpeg_is_valid_quality (uint32_t quality){ + return quality >= 1 && quality <= 100; +} + +int omxcam__jpeg_is_valid_thumbnail (uint32_t dimension){ + return dimension <= 1024; +} + +int omxcam__jpeg_add_tag (char* key, char* value){ + int key_length = strlen (key); + int value_length = strlen (value); + + struct { + //These two fields need to be together + OMX_CONFIG_METADATAITEMTYPE metadata_st; + char metadata_padding[value_length]; + } item; + + omxcam__omx_struct_init (item.metadata_st); + item.metadata_st.nSize = sizeof (item); + item.metadata_st.eScopeMode = OMX_MetadataScopePortLevel; + item.metadata_st.nScopeSpecifier = 341; + item.metadata_st.eKeyCharset = OMX_MetadataCharsetASCII; + item.metadata_st.nKeySizeUsed = key_length; + memcpy (item.metadata_st.nKey, key, key_length); + item.metadata_st.eValueCharset = OMX_MetadataCharsetASCII; + item.metadata_st.nValueMaxSize = sizeof (item.metadata_padding); + item.metadata_st.nValueSizeUsed = value_length; + memcpy (item.metadata_st.nValue, value, value_length); + + OMX_ERRORTYPE error; + + if ((error = OMX_SetConfig (omxcam__ctx.image_encode.handle, + OMX_IndexConfigMetadataItem, &item))){ + omxcam__error ("OMX_SetConfig - OMX_IndexConfigMetadataItem: %s", + omxcam__dump_OMX_ERRORTYPE (error)); + return -1; + } + + return 0; +} + +int omxcam__jpeg_configure_omx (omxcam_jpeg_settings_t* settings){ + omxcam__trace ("configuring '%s' settings", omxcam__ctx.image_encode.name); + + OMX_ERRORTYPE error; + + //Quality + OMX_IMAGE_PARAM_QFACTORTYPE quality_st; + omxcam__omx_struct_init (quality_st); + quality_st.nPortIndex = 341; + quality_st.nQFactor = settings->quality; + if ((error = OMX_SetParameter (omxcam__ctx.image_encode.handle, + OMX_IndexParamQFactor, &quality_st))){ + omxcam__error ("OMX_SetParameter - OMX_IndexParamQFactor: %s", + omxcam__dump_OMX_ERRORTYPE (error)); + return -1; + } + + //Disable EXIF tags + OMX_CONFIG_BOOLEANTYPE exif_st; + omxcam__omx_struct_init (exif_st); + exif_st.bEnabled = !settings->exif.enabled; + if ((error = OMX_SetParameter (omxcam__ctx.image_encode.handle, + OMX_IndexParamBrcmDisableEXIF, &exif_st))){ + omxcam__error ("OMX_SetParameter - OMX_IndexParamBrcmDisableEXIF: %s", + omxcam__dump_OMX_ERRORTYPE (error)); + return -1; + } + + //Bayer data + if (settings->raw_bayer){ + //The filename is not relevant + char dummy[] = "dummy"; + struct { + //These two fields need to be together + OMX_PARAM_CONTENTURITYPE uri_st; + char padding[5]; + } raw; + omxcam__omx_struct_init (raw.uri_st); + raw.uri_st.nSize = sizeof (raw); + memcpy (raw.uri_st.contentURI, dummy, 5); + if ((error = OMX_SetConfig (omxcam__ctx.camera.handle, + OMX_IndexConfigCaptureRawImageURI, &raw))){ + omxcam__error ("OMX_SetConfig - OMX_IndexConfigCaptureRawImageURI: %s", + omxcam__dump_OMX_ERRORTYPE (error)); + return -1; + } + } + + //Enable IJG table + OMX_PARAM_IJGSCALINGTYPE ijg_st; + omxcam__omx_struct_init (ijg_st); + ijg_st.nPortIndex = 341; + ijg_st.bEnabled = settings->ijg; + if ((error = OMX_SetParameter (omxcam__ctx.image_encode.handle, + OMX_IndexParamBrcmEnableIJGTableScaling, &ijg_st))){ + omxcam__error ("OMX_SetParameter - OMX_IndexParamBrcmEnableIJGTableScaling: " + "%s", omxcam__dump_OMX_ERRORTYPE (error)); + return -1; + } + + if (!settings->exif.enabled) return 0; + + //EXIF tags + //See firmware/documentation/ilcomponents/image_decode.html for valid keys + //See http://www.media.mit.edu/pia/Research/deepview/exif.html#IFD0Tags + //for valid keys and their description + char timestamp[20]; + time_t now; + struct tm ts; + time (&now); + ts = *localtime (&now); + strftime (timestamp, sizeof (timestamp), "%Y:%m:%d %H:%M:%S", &ts); + + if (omxcam__jpeg_add_tag ("EXIF.DateTimeOriginal", timestamp)) return -1; + if (omxcam__jpeg_add_tag ("EXIF.DateTimeDigitized", timestamp)) return -1; + if (omxcam__jpeg_add_tag ("IFD0.DateTime", timestamp)) return -1; + + uint32_t i; + for (i=0; iexif.valid_tags; i++){ + if (omxcam__jpeg_add_tag (settings->exif.tags[i].key, + settings->exif.tags[i].value)){ + return -1; + } + } + + //Thumbnail + OMX_PARAM_BRCMTHUMBNAILTYPE thumbnail_st; + omxcam__omx_struct_init (thumbnail_st); + thumbnail_st.bEnable = settings->thumbnail.enabled; + thumbnail_st.bUsePreview = settings->thumbnail.preview; + thumbnail_st.nWidth = settings->thumbnail.width; + thumbnail_st.nHeight = settings->thumbnail.height; + if ((error = OMX_SetParameter (omxcam__ctx.image_encode.handle, + OMX_IndexParamBrcmThumbnail, &thumbnail_st))){ + omxcam__error ("OMX_SetParameter - OMX_IndexParamBrcmThumbnail: %s", + omxcam__dump_OMX_ERRORTYPE (error)); + return -1; + } + + return 0; +} \ No newline at end of file diff --git a/pool/shard008/C/0130697_blinding.c b/pool/shard008/C/0130697_blinding.c new file mode 100644 index 0000000000000000000000000000000000000000..0a485ee9365ba375f644cc922bcc813e3920123d --- /dev/null +++ b/pool/shard008/C/0130697_blinding.c @@ -0,0 +1,264 @@ +/* ==================================================================== + * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * openssl-core@openssl.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.openssl.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR + * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + * Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * "This product includes cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] */ + +#include + +#include + +#include +#include +#include + +#include "internal.h" + + +#define BN_BLINDING_COUNTER 32 + +struct bn_blinding_st { + BIGNUM *A; /* The base blinding factor, Montgomery-encoded. */ + BIGNUM *Ai; /* The inverse of the blinding factor, Montgomery-encoded. */ + unsigned counter; +}; + +static int bn_blinding_create_param(BN_BLINDING *b, const BIGNUM *e, + const BN_MONT_CTX *mont, BN_CTX *ctx); + +BN_BLINDING *BN_BLINDING_new(void) { + BN_BLINDING *ret = OPENSSL_malloc(sizeof(BN_BLINDING)); + if (ret == NULL) { + OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE); + return NULL; + } + memset(ret, 0, sizeof(BN_BLINDING)); + + ret->A = BN_new(); + if (ret->A == NULL) { + goto err; + } + + ret->Ai = BN_new(); + if (ret->Ai == NULL) { + goto err; + } + + /* The blinding values need to be created before this blinding can be used. */ + ret->counter = BN_BLINDING_COUNTER - 1; + + return ret; + +err: + BN_BLINDING_free(ret); + return NULL; +} + +void BN_BLINDING_free(BN_BLINDING *r) { + if (r == NULL) { + return; + } + + BN_free(r->A); + BN_free(r->Ai); + OPENSSL_free(r); +} + +static int bn_blinding_update(BN_BLINDING *b, const BIGNUM *e, + const BN_MONT_CTX *mont, BN_CTX *ctx) { + if (++b->counter == BN_BLINDING_COUNTER) { + /* re-create blinding parameters */ + if (!bn_blinding_create_param(b, e, mont, ctx)) { + goto err; + } + b->counter = 0; + } else { + if (!BN_mod_mul_montgomery(b->A, b->A, b->A, mont, ctx) || + !BN_mod_mul_montgomery(b->Ai, b->Ai, b->Ai, mont, ctx)) { + goto err; + } + } + + return 1; + +err: + /* |A| and |Ai| may be in an inconsistent state so they both need to be + * replaced the next time this blinding is used. Note that this is only + * sufficient because support for |BN_BLINDING_NO_UPDATE| and + * |BN_BLINDING_NO_RECREATE| was previously dropped. */ + b->counter = BN_BLINDING_COUNTER - 1; + + return 0; +} + +int BN_BLINDING_convert(BIGNUM *n, BN_BLINDING *b, const BIGNUM *e, + const BN_MONT_CTX *mont, BN_CTX *ctx) { + /* |n| is not Montgomery-encoded and |b->A| is. |BN_mod_mul_montgomery| + * cancels one Montgomery factor, so the resulting value of |n| is unencoded. + */ + if (!bn_blinding_update(b, e, mont, ctx) || + !BN_mod_mul_montgomery(n, n, b->A, mont, ctx)) { + return 0; + } + + return 1; +} + +int BN_BLINDING_invert(BIGNUM *n, const BN_BLINDING *b, BN_MONT_CTX *mont, + BN_CTX *ctx) { + /* |n| is not Montgomery-encoded and |b->A| is. |BN_mod_mul_montgomery| + * cancels one Montgomery factor, so the resulting value of |n| is unencoded. + */ + return BN_mod_mul_montgomery(n, n, b->Ai, mont, ctx); +} + +static int bn_blinding_create_param(BN_BLINDING *b, const BIGNUM *e, + const BN_MONT_CTX *mont, BN_CTX *ctx) { + int retry_counter = 32; + + do { + if (!BN_rand_range_ex(b->A, 1, &mont->N)) { + OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); + return 0; + } + + /* |BN_from_montgomery| + |BN_mod_inverse_blinded| is equivalent to, but + * more efficient than, |BN_mod_inverse_blinded| + |BN_to_montgomery|. */ + if (!BN_from_montgomery(b->Ai, b->A, mont, ctx)) { + OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); + return 0; + } + + int no_inverse; + if (BN_mod_inverse_blinded(b->Ai, &no_inverse, b->Ai, mont, ctx)) { + break; + } + + if (!no_inverse) { + OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); + return 0; + } + + /* For reasonably-sized RSA keys, it should almost never be the case that a + * random value doesn't have an inverse. */ + if (retry_counter-- == 0) { + OPENSSL_PUT_ERROR(RSA, RSA_R_TOO_MANY_ITERATIONS); + return 0; + } + ERR_clear_error(); + } while (1); + + if (!BN_mod_exp_mont(b->A, b->A, e, &mont->N, ctx, mont)) { + OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); + return 0; + } + + if (!BN_to_montgomery(b->A, b->A, mont, ctx)) { + OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); + return 0; + } + + return 1; +} diff --git a/pool/shard008/C/0130698_random.c b/pool/shard008/C/0130698_random.c new file mode 100644 index 0000000000000000000000000000000000000000..491bf703309955e6a5aee86d6a7961812577a497 --- /dev/null +++ b/pool/shard008/C/0130698_random.c @@ -0,0 +1,123 @@ +/* Copyright libuv contributors. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +#include "uv.h" +#include "uv-common.h" + +#ifdef _WIN32 +# include "win/internal.h" +#else +# include "unix/internal.h" +#endif + +static int uv__random(void* buf, size_t buflen) { + int rc; + +#if defined(__PASE__) + rc = uv__random_readpath("/dev/urandom", buf, buflen); +#elif defined(_AIX) + rc = uv__random_readpath("/dev/random", buf, buflen); +#elif defined(__APPLE__) || defined(__OpenBSD__) || \ + (defined(__ANDROID_API__) && __ANDROID_API__ >= 28) + rc = uv__random_getentropy(buf, buflen); + if (rc == UV_ENOSYS) + rc = uv__random_devurandom(buf, buflen); +#elif defined(__NetBSD__) + rc = uv__random_sysctl(buf, buflen); +#elif defined(__FreeBSD__) || defined(__linux__) + rc = uv__random_getrandom(buf, buflen); + if (rc == UV_ENOSYS) + rc = uv__random_devurandom(buf, buflen); +# if defined(__linux__) + switch (rc) { + case UV_EACCES: + case UV_EIO: + case UV_ELOOP: + case UV_EMFILE: + case UV_ENFILE: + case UV_ENOENT: + case UV_EPERM: + rc = uv__random_sysctl(buf, buflen); + break; + } +# endif +#elif defined(_WIN32) + uv__once_init(); + rc = uv__random_rtlgenrandom(buf, buflen); +#else + rc = uv__random_devurandom(buf, buflen); +#endif + + return rc; +} + + +static void uv__random_work(struct uv__work* w) { + uv_random_t* req; + + req = container_of(w, uv_random_t, work_req); + req->status = uv__random(req->buf, req->buflen); +} + + +static void uv__random_done(struct uv__work* w, int status) { + uv_random_t* req; + + req = container_of(w, uv_random_t, work_req); + uv__req_unregister(req->loop, req); + + if (status == 0) + status = req->status; + + req->cb(req, status, req->buf, req->buflen); +} + + +int uv_random(uv_loop_t* loop, + uv_random_t* req, + void *buf, + size_t buflen, + unsigned flags, + uv_random_cb cb) { + if (buflen > 0x7FFFFFFFu) + return UV_E2BIG; + + if (flags != 0) + return UV_EINVAL; + + if (cb == NULL) + return uv__random(buf, buflen); + + uv__req_init(loop, req, UV_RANDOM); + req->loop = loop; + req->status = 0; + req->cb = cb; + req->buf = buf; + req->buflen = buflen; + + uv__work_submit(loop, + &req->work_req, + UV__WORK_CPU, + uv__random_work, + uv__random_done); + + return 0; +} diff --git a/pool/shard008/C/0130699_t4k37ab.c b/pool/shard008/C/0130699_t4k37ab.c new file mode 100644 index 0000000000000000000000000000000000000000..40fbc95ec129befd918008c5287421520a366755 --- /dev/null +++ b/pool/shard008/C/0130699_t4k37ab.c @@ -0,0 +1,210 @@ +/* Copyright (c) 2012-2015, The Linux Foundation. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 and + * only version 2 as published by the Free Software Foundation. + * + * 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. + * + */ +#include "msm_sensor.h" +#define t4k37ab_SENSOR_NAME "t4k37ab" +DEFINE_MSM_MUTEX(t4k37ab_mut); + +static struct msm_sensor_ctrl_t t4k37ab_s_ctrl; + +static struct msm_sensor_power_setting t4k37ab_power_setting[] = { + + { + .seq_type = SENSOR_GPIO, + .seq_val = SENSOR_GPIO_VIO, + .config_val = 0, + .delay = 10, + }, + { + .seq_type = SENSOR_GPIO, + .seq_val = SENSOR_GPIO_VIO, + .config_val = GPIO_OUT_HIGH, + .delay = 10, + }, + { + .seq_type = SENSOR_GPIO, + .seq_val = SENSOR_GPIO_VDIG, + .config_val = GPIO_OUT_LOW, + .delay = 10, + }, + { + .seq_type = SENSOR_GPIO, + .seq_val = SENSOR_GPIO_VDIG, + .config_val = GPIO_OUT_HIGH, + .delay = 10, + }, + { + .seq_type = SENSOR_GPIO, + .seq_val = SENSOR_GPIO_VANA, + .config_val = GPIO_OUT_LOW, + .delay = 10, + }, + { + .seq_type = SENSOR_GPIO, + .seq_val = SENSOR_GPIO_VANA, + .config_val = GPIO_OUT_HIGH, + .delay = 10, + }, + { + .seq_type = SENSOR_GPIO, + .seq_val = SENSOR_GPIO_STANDBY, + .config_val = GPIO_OUT_LOW, + .delay = 15, + }, + { + .seq_type = SENSOR_GPIO, + .seq_val = SENSOR_GPIO_STANDBY, + .config_val = GPIO_OUT_HIGH, + .delay = 40, + }, + { + .seq_type = SENSOR_CLK, + .seq_val = SENSOR_CAM_MCLK, + .config_val = 24000000, + .delay = 50, + }, + { + .seq_type = SENSOR_I2C_MUX, + .seq_val = 0, + .config_val = 0, + .delay = 0, + }, + +}; + +static struct v4l2_subdev_info t4k37ab_subdev_info[] = { + { + .code = V4L2_MBUS_FMT_SBGGR10_1X10, + .colorspace = V4L2_COLORSPACE_JPEG, + .fmt = 1, + .order = 0, + }, +}; + +static const struct i2c_device_id t4k37ab_i2c_id[] = { + {t4k37ab_SENSOR_NAME, (kernel_ulong_t)&t4k37ab_s_ctrl}, + { } +}; + +static int32_t msm_t4k37ab_i2c_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + return msm_sensor_i2c_probe(client, id, &t4k37ab_s_ctrl); +} + +static struct i2c_driver t4k37ab_i2c_driver = { + .id_table = t4k37ab_i2c_id, + .probe = msm_t4k37ab_i2c_probe, + .driver = { + .name = t4k37ab_SENSOR_NAME, + }, +}; + +static struct msm_camera_i2c_client t4k37ab_sensor_i2c_client = { + .addr_type = MSM_CAMERA_I2C_WORD_ADDR, +}; + +static const struct of_device_id t4k37ab_dt_match[] = { + {.compatible = "qcom,t4k37ab", .data = &t4k37ab_s_ctrl}, + {} +}; + +MODULE_DEVICE_TABLE(of, t4k37ab_dt_match); + +static struct platform_driver t4k37ab_platform_driver = { + .driver = { + .name = "qcom,t4k37ab", + .owner = THIS_MODULE, + .of_match_table = t4k37ab_dt_match, + }, +}; + +static const char *t4k37abVendor = "Toshiba"; +static const char *t4k37abNAME = "t4k37ab"; +static const char *t4k37abSize = "13.0M"; + +static ssize_t sensor_vendor_show(struct device *dev, + struct device_attribute *attr, char *buf) +{ + sprintf(buf, "%s %s %s\n", t4k37abVendor, t4k37abNAME, t4k37abSize); + return strlen(buf) + 1; +} + +static DEVICE_ATTR(sensor, 0444, sensor_vendor_show, NULL); + +static struct kobject *android_t4k37ab; + +static int t4k37ab_sysfs_init(void) +{ + int ret; + pr_info("%s: kobject create and add\n", __func__); + android_t4k37ab = kobject_create_and_add("rear_camera", NULL); + if (android_t4k37ab == NULL) { + pr_err("%s: subsystem_register failed\n", __func__); + ret = -ENOMEM; + return ret ; + } + pr_info("%s: sysfs_create_file\n", __func__); + ret = sysfs_create_file(android_t4k37ab, &dev_attr_sensor.attr); + if (ret) { + pr_err("%s: sysfs_create_file failed\n", __func__); + kobject_del(android_t4k37ab); + } + return 0; +} + +static int32_t t4k37ab_platform_probe(struct platform_device *pdev) +{ + int32_t rc = 0; + const struct of_device_id *match; + match = of_match_device(t4k37ab_dt_match, &pdev->dev); + rc = msm_sensor_platform_probe(pdev, match->data); + return rc; +} + +static int __init t4k37ab_init_module(void) +{ + int32_t rc = 0; + pr_info("%s:%d\n", __func__, __LINE__); + rc = platform_driver_probe(&t4k37ab_platform_driver, t4k37ab_platform_probe); + if (!rc) { + t4k37ab_sysfs_init(); + return rc; + } + pr_err("%s:%d rc %d\n", __func__, __LINE__, rc); + return i2c_add_driver(&t4k37ab_i2c_driver); +} + +static void __exit t4k37ab_exit_module(void) +{ + pr_info("%s:%d\n", __func__, __LINE__); + if (t4k37ab_s_ctrl.pdev) { + msm_sensor_free_sensor_data(&t4k37ab_s_ctrl); + platform_driver_unregister(&t4k37ab_platform_driver); + } else + i2c_del_driver(&t4k37ab_i2c_driver); + return; +} + +static struct msm_sensor_ctrl_t t4k37ab_s_ctrl = { + .sensor_i2c_client = &t4k37ab_sensor_i2c_client, + .power_setting_array.power_setting = t4k37ab_power_setting, + .power_setting_array.size = ARRAY_SIZE(t4k37ab_power_setting), + .msm_sensor_mutex = &t4k37ab_mut, + .sensor_v4l2_subdev_info = t4k37ab_subdev_info, + .sensor_v4l2_subdev_info_size = ARRAY_SIZE(t4k37ab_subdev_info), +}; + +module_init(t4k37ab_init_module); +module_exit(t4k37ab_exit_module); +MODULE_DESCRIPTION("t4k37ab"); +MODULE_LICENSE("GPL v2"); \ No newline at end of file diff --git a/pool/shard008/C/0130701_resources.c b/pool/shard008/C/0130701_resources.c new file mode 100644 index 0000000000000000000000000000000000000000..9148f2f9b2cbf7122c7f6fb1220e4a3b37dab66e --- /dev/null +++ b/pool/shard008/C/0130701_resources.c @@ -0,0 +1,202 @@ +#include + +#include +WINE_DEFAULT_DEBUG_CHANNEL(resource); + +#ifndef _CFGMGR32_H_ +#define CR_SUCCESS 0x00000000 +#define CR_OUT_OF_MEMORY 0x00000002 +#define CR_INVALID_POINTER 0x00000003 +#define CR_INVALID_DATA 0x0000001F +#endif + +typedef DWORD (WINAPI *CMP_REGNOTIFY) (HANDLE, LPVOID, DWORD, PULONG); +typedef DWORD (WINAPI *CMP_UNREGNOTIFY) (ULONG ); + +static HINSTANCE hSetupApi = NULL; + +/********************************************************************** + * LoadStringW (USER32.@) + * Synced with Wine Staging 1.7.55 + */ +INT WINAPI LoadStringW( HINSTANCE instance, UINT resource_id, + LPWSTR buffer, INT buflen ) +{ + HGLOBAL hmem; + HRSRC hrsrc; + WCHAR *p; + int string_num; + int i; + + TRACE("instance = %p, id = %04x, buffer = %p, length = %d\n", + instance, resource_id, buffer, buflen); + + if(buffer == NULL) + return 0; + + /* Use loword (incremented by 1) as resourceid */ + hrsrc = FindResourceW( instance, MAKEINTRESOURCEW((LOWORD(resource_id) >> 4) + 1), + (LPWSTR)RT_STRING ); + if (!hrsrc) return 0; + hmem = LoadResource( instance, hrsrc ); + if (!hmem) return 0; + + p = LockResource(hmem); + string_num = resource_id & 0x000f; + for (i = 0; i < string_num; i++) + p += *p + 1; + + TRACE("strlen = %d\n", (int)*p ); + + /*if buflen == 0, then return a read-only pointer to the resource itself in buffer + it is assumed that buffer is actually a (LPWSTR *) */ + if(buflen == 0) + { + *((LPWSTR *)buffer) = p + 1; + return *p; + } + + i = min(buflen - 1, *p); + if (i > 0) { + memcpy(buffer, p + 1, i * sizeof (WCHAR)); + buffer[i] = 0; + } else { + if (buflen > 1) { + buffer[0] = 0; + return 0; + } + } + + TRACE("%s loaded !\n", debugstr_w(buffer)); + return i; +} + +/********************************************************************** + * LoadStringA (USER32.@) + * Synced with Wine Staging 1.7.55 + */ +INT WINAPI LoadStringA( HINSTANCE instance, UINT resource_id, LPSTR buffer, INT buflen ) +{ + HGLOBAL hmem; + HRSRC hrsrc; + DWORD retval = 0; + + TRACE("instance = %p, id = %04x, buffer = %p, length = %d\n", + instance, resource_id, buffer, buflen); + + if (!buflen) return -1; + + /* Use loword (incremented by 1) as resourceid */ + if ((hrsrc = FindResourceW( instance, MAKEINTRESOURCEW((LOWORD(resource_id) >> 4) + 1), + (LPWSTR)RT_STRING )) && + (hmem = LoadResource( instance, hrsrc ))) + { + const WCHAR *p = LockResource(hmem); + unsigned int id = resource_id & 0x000f; + + while (id--) p += *p + 1; + + if (buflen != 1) + RtlUnicodeToMultiByteN( buffer, buflen - 1, &retval, (PWSTR)(p + 1), *p * sizeof(WCHAR) ); + } + buffer[retval] = 0; + TRACE("returning %s\n", debugstr_a(buffer)); + return retval; +} + +/* + * @implemented + */ +HDEVNOTIFY +WINAPI +RegisterDeviceNotificationW(HANDLE hRecipient, + LPVOID NotificationFilter, + DWORD Flags) +{ + DWORD ConfigRet = 0; + CMP_REGNOTIFY RegNotify = NULL; + HDEVNOTIFY hDevNotify = NULL; + + if (hSetupApi == NULL) hSetupApi = LoadLibraryA("SETUPAPI.DLL"); + if (hSetupApi == NULL) return NULL; + + RegNotify = (CMP_REGNOTIFY) GetProcAddress(hSetupApi, "CMP_RegisterNotification"); + if (RegNotify == NULL) + { + FreeLibrary(hSetupApi); + hSetupApi = NULL; + return NULL; + } + + ConfigRet = RegNotify(hRecipient, NotificationFilter, Flags, (PULONG) &hDevNotify); + if (ConfigRet != CR_SUCCESS) + { + switch (ConfigRet) + { + case CR_OUT_OF_MEMORY: + SetLastError (ERROR_NOT_ENOUGH_MEMORY); + break; + + case CR_INVALID_POINTER: + SetLastError (ERROR_INVALID_PARAMETER); + break; + + case CR_INVALID_DATA: + SetLastError (ERROR_INVALID_DATA); + break; + + default: + SetLastError (ERROR_SERVICE_SPECIFIC_ERROR); + break; + } + } + + return hDevNotify; +} + + +/* + * @implemented + */ +BOOL +WINAPI +UnregisterDeviceNotification(HDEVNOTIFY Handle) +{ + DWORD ConfigRet = 0; + CMP_UNREGNOTIFY UnRegNotify = NULL; + + if (hSetupApi == NULL) hSetupApi = LoadLibraryA("SETUPAPI.DLL"); + if (hSetupApi == NULL) return FALSE; + + UnRegNotify = (CMP_UNREGNOTIFY) GetProcAddress(hSetupApi, "CMP_UnregisterNotification"); + if (UnRegNotify == NULL) + { + FreeLibrary(hSetupApi); + hSetupApi = NULL; + return FALSE; + } + + ConfigRet = UnRegNotify((ULONG_PTR)Handle ); + if (ConfigRet != CR_SUCCESS) + { + switch (ConfigRet) + { + case CR_INVALID_POINTER: + SetLastError (ERROR_INVALID_PARAMETER); + break; + + case CR_INVALID_DATA: + SetLastError (ERROR_INVALID_DATA); + break; + + default: + SetLastError (ERROR_SERVICE_SPECIFIC_ERROR); + break; + } + return FALSE; + } + + return TRUE; +} + +/* EOF */ diff --git a/pool/shard008/C/0130703_svc_auth.c b/pool/shard008/C/0130703_svc_auth.c new file mode 100644 index 0000000000000000000000000000000000000000..5fedef7d759ed693143795f2cdeb3af13d7f34b5 --- /dev/null +++ b/pool/shard008/C/0130703_svc_auth.c @@ -0,0 +1,109 @@ +/* lib/rpc/svc_auth.c */ +/* + * Copyright (c) 2010, Oracle America, Inc. + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * + * * Neither the name of the "Oracle America, Inc." nor the names of + * its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED + * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * svc_auth_nodes.c, Server-side rpc authenticator interface, + * *WITHOUT* DES authentication. + */ + +#include + +/* + * Server side authenticators are called from authenticate by + * using the client auth struct flavor field to index into svcauthsw. + * The server auth flavors must implement a routine that looks + * like: + * + * enum auth_stat + * flavorx_auth(rqst, msg) + * register struct svc_req *rqst; + * register struct rpc_msg *msg; + * + */ + +static struct svcauthsw_type { + enum_t flavor; + enum auth_stat (*authenticator)(struct svc_req *, struct rpc_msg *, + bool_t *); +} svcauthsw[] = { + {AUTH_GSSAPI, gssrpc__svcauth_gssapi}, /* AUTH_GSSAPI */ + {AUTH_NONE, gssrpc__svcauth_none}, /* AUTH_NONE */ +#if 0 + {AUTH_GSSAPI_COMPAT, gssrpc__svcauth_gssapi}, /* AUTH_GSSAPI_COMPAT */ +#endif + {AUTH_UNIX, gssrpc__svcauth_unix}, /* AUTH_UNIX */ + {AUTH_SHORT, gssrpc__svcauth_short}, /* AUTH_SHORT */ + {RPCSEC_GSS, gssrpc__svcauth_gss} /* RPCSEC_GSS */ +}; +static int svcauthnum = sizeof(svcauthsw) / sizeof(struct svcauthsw_type); + +/* + * The call rpc message, msg has been obtained from the wire. The msg contains + * the raw form of credentials and verifiers. authenticate returns AUTH_OK + * if the msg is successfully authenticated. If AUTH_OK then the routine also + * does the following things: + * set rqst->rq_xprt->verf to the appropriate response verifier; + * sets rqst->rq_client_cred to the "cooked" form of the credentials. + * + * NB: rqst->rq_cxprt->verf must be pre-alloctaed; + * its length is set appropriately. + * + * The caller still owns and is responsible for msg->u.cmb.cred and + * msg->u.cmb.verf. The authentication system retains ownership of + * rqst->rq_client_cred, the cooked credentials. + */ +enum auth_stat +gssrpc__authenticate( + register struct svc_req *rqst, + struct rpc_msg *msg, + bool_t *no_dispatch) +{ + register int cred_flavor, i; + + rqst->rq_cred = msg->rm_call.cb_cred; + rqst->rq_xprt->xp_verf.oa_flavor = gssrpc__null_auth.oa_flavor; + rqst->rq_xprt->xp_verf.oa_length = 0; + cred_flavor = rqst->rq_cred.oa_flavor; + *no_dispatch = FALSE; + for (i = 0; i < svcauthnum; i++) { + if (cred_flavor == svcauthsw[i].flavor && + svcauthsw[i].authenticator != NULL) { + return ((*(svcauthsw[i].authenticator))(rqst, + msg, + no_dispatch)); + } + } + + return (AUTH_REJECTEDCRED); +} diff --git a/pool/shard008/C/0130704_first_network_device.c b/pool/shard008/C/0130704_first_network_device.c new file mode 100644 index 0000000000000000000000000000000000000000..3d06217fdde789eb40c3309e732e3c3b735fdfc1 --- /dev/null +++ b/pool/shard008/C/0130704_first_network_device.c @@ -0,0 +1,196 @@ +// vim:ts=4:sw=4:expandtab +#include +#include +#include +#include +#include +#if defined(__OpenBSD__) || defined(__DragonFly__) +#include +#include +#include +#include +#endif +#if defined(__OpenBSD__) +#include +#include +#elif defined(__DragonFly__) +#include +#endif + +#include "i3status.h" + +#ifdef __OpenBSD__ +#define LOOPBACK_DEV "lo0" +#else +#define LOOPBACK_DEV "lo" +#endif + +static bool sysfs_devtype(char *dest, size_t n, const char *ifnam) { + FILE *fp; + char buf[1024]; + + snprintf(buf, sizeof(buf), "/sys/class/net/%s/uevent", ifnam); + if ((fp = fopen(buf, "r")) == NULL) + return false; + + dest[0] = '\0'; + + while (fgets(buf, sizeof(buf), fp)) { + size_t slen; + char *s; + + slen = strlen(buf); + /* Line is too long to fit in the buffer */ + if (buf[slen - 1] != '\n' && !feof(fp)) + break; + if ((s = strchr(buf, '='))) { + if (strncmp(buf, "DEVTYPE", s - buf)) + continue; + buf[slen - 1] = '\0'; + strncpy(dest, ++s, n); + break; + } + } + fclose(fp); + return true; +} + +static bool is_virtual(const char *ifname) { + char path[1024]; + char *target = NULL; + bool is_virtual = false; + + snprintf(path, sizeof(path), "/sys/class/net/%s", ifname); + if ((target = realpath(path, NULL))) { + if (BEGINS_WITH(target, "/sys/devices/virtual/")) { + is_virtual = true; + } + } + + free(target); + return is_virtual; +} + +static net_type_t iface_type(const char *ifname) { +#if defined(__OpenBSD__) + /* + *First determine if the device is a wireless device by trying two ioctl(2) + * commands against it. If either succeeds we can be sure it's a wireless + * device. + * Otherwise we try another ioctl(2) to determine the interface media. If that + * fails it's not an ethernet device eiter. + */ + struct ifreq ifr; + struct ieee80211_bssid bssid; + struct ieee80211_nwid nwid; +#elif defined(__DragonFly__) + struct ieee80211req ifr; +#endif +#if defined(__OpenBSD__) || defined(__DragonFly__) + struct ifmediareq ifmr; + int s; +#endif +#if defined(__OpenBSD__) + int ibssid, inwid; +#endif +#if defined(__OpenBSD__) || defined(__DragonFly__) + if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1) + return NET_TYPE_OTHER; + + memset(&ifr, 0, sizeof(ifr)); +#endif +#if defined(__OpenBSD__) + ifr.ifr_data = (caddr_t)&nwid; + (void)strlcpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name)); + inwid = ioctl(s, SIOCG80211NWID, (caddr_t)&ifr); + + memset(&bssid, 0, sizeof(bssid)); + strlcpy(bssid.i_name, ifname, sizeof(bssid.i_name)); + ibssid = ioctl(s, SIOCG80211BSSID, &bssid); + + if (ibssid == 0 || inwid == 0) { + close(s); + return NET_TYPE_WIRELESS; + } +#elif defined(__DragonFly__) + (void)strlcpy(ifr.i_name, ifname, sizeof(ifr.i_name)); + ifr.i_type = IEEE80211_IOC_NUMSSIDS; + if (ioctl(s, SIOCG80211, &ifr) == 0) { + close(s); + return NET_TYPE_WIRELESS; + } +#endif +#if defined(__OpenBSD__) || defined(__DragonFly__) + (void)memset(&ifmr, 0, sizeof(ifmr)); + (void)strlcpy(ifmr.ifm_name, ifname, sizeof(ifmr.ifm_name)); + + if (ioctl(s, SIOCGIFMEDIA, (caddr_t)&ifmr) < 0) { + close(s); + return NET_TYPE_OTHER; + } else { + close(s); + return NET_TYPE_ETHERNET; + } +#else + char devtype[32]; + + if (!sysfs_devtype(devtype, sizeof(devtype), ifname)) + return NET_TYPE_OTHER; + + /* Default to Ethernet when no devtype is available */ + if (!devtype[0]) + return NET_TYPE_ETHERNET; + + if (strcmp(devtype, "wlan") == 0) + return NET_TYPE_WIRELESS; + + if (strcmp(devtype, "wwan") == 0) + return NET_TYPE_OTHER; + + return NET_TYPE_OTHER; +#endif + return NET_TYPE_OTHER; +} + +const char *first_eth_interface(const net_type_t type) { + static char *interface = NULL; + struct ifaddrs *ifaddr, *addrp; + net_type_t iftype; + + getifaddrs(&ifaddr); + + if (ifaddr == NULL) + return NULL; + + free(interface); + interface = NULL; + for (addrp = ifaddr; + addrp != NULL; + addrp = addrp->ifa_next) { + if (strncasecmp(LOOPBACK_DEV, addrp->ifa_name, strlen(LOOPBACK_DEV)) == 0) + continue; + if (addrp->ifa_addr == NULL) + continue; +#ifdef __OpenBSD__ + if (addrp->ifa_addr->sa_family != AF_LINK) + continue; +#else + // Skip PF_PACKET addresses (MAC addresses), as they are present on any + // ethernet interface. + if (addrp->ifa_addr->sa_family != AF_INET && + addrp->ifa_addr->sa_family != AF_INET6) + continue; +#endif /* !__OpenBSD__ */ + // Skip this interface if it is a wireless interface. + iftype = iface_type(addrp->ifa_name); + if (iftype != type) + continue; + if (is_virtual(addrp->ifa_name)) + continue; + interface = strdup(addrp->ifa_name); + break; + } + + freeifaddrs(ifaddr); + return interface; +} diff --git a/pool/shard008/C/0130705_fs_vfat.c b/pool/shard008/C/0130705_fs_vfat.c new file mode 100644 index 0000000000000000000000000000000000000000..47e35a93fc71015a483ca29e3e4c7c5739172d33 --- /dev/null +++ b/pool/shard008/C/0130705_fs_vfat.c @@ -0,0 +1,205 @@ +/* + * fsarchiver: Filesystem Archiver + * + * Copyright (C) 2008-2018 Francois Dupoux. All rights reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public + * License v2 as published by the Free Software Foundation. + * + * 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. + * + * Homepage: http://www.fsarchiver.org + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include +#include +#include +#include +#include + +#include "fsarchiver.h" +#include "dico.h" +#include "common.h" +#include "filesys.h" +#include "strlist.h" +#include "fs_vfat.h" +#include "error.h" + +int vfat_mkfs(cdico *d, char *partition, char *fsoptions, char *mkfslabel, char *mkfsuuid) +{ + char stdoutbuf[2048]; + char command[2048]; + char buffer[2048]; + char mkfsopts[2048]; + int exitst; + u32 temp32; + u16 temp16; + + memset(mkfsopts, 0, sizeof(mkfsopts)); + + // ---- check that mkfs.vfat is installed + if (exec_command(command, sizeof(command), NULL, stdoutbuf, sizeof(stdoutbuf), NULL, 0, "mkfs.vfat --help")!=0) + { errprintf("mkfs.vfat not found. please install dosfstools on your system or check the PATH.\n"); + return -1; + } + + // ---- set the correct type of FAT filesystem + if ((dico_get_u16(d, 0, FSYSHEADKEY_FSVFATTYPE, &temp16)==0) && (temp16==FAT_TYPE_FAT16)) + strlcatf(mkfsopts, sizeof(mkfsopts), " -F 16 "); + else + strlcatf(mkfsopts, sizeof(mkfsopts), " -F 32 "); + + // ---- filesystem label + if (strlen(mkfslabel) > 0) + strlcatf(mkfsopts, sizeof(mkfsopts), " -n '%.11s' ", mkfslabel); + else if (dico_get_string(d, 0, FSYSHEADKEY_FSLABEL, buffer, sizeof(buffer))==0 && strlen(buffer)>0) + strlcatf(mkfsopts, sizeof(mkfsopts), " -n '%.11s' ", buffer); + + // ---- filesystem serial + if (strlen(mkfsuuid) > 0) + strlcatf(mkfsopts, sizeof(mkfsopts), " -i '%.8s' ", mkfsuuid); + else if (dico_get_u32(d, 0, FSYSHEADKEY_FSVFATSERIAL, &temp32)==0) + strlcatf(mkfsopts, sizeof(mkfsopts), " -i '%08X' ", temp32); + + // ---- mkfsopt from command line + strlcatf(mkfsopts, sizeof(mkfsopts), " %s ", fsoptions); + + // ---- create the new filesystem using mkfs.vfat + if (exec_command(command, sizeof(command), &exitst, NULL, 0, NULL, 0, "mkfs.vfat %s %s", mkfsopts, partition)!=0 || exitst!=0) + { errprintf("command [%s] failed\n", command); + return -1; + } + + return 0; +} + +int vfat_getinfo(cdico *d, char *devname) +{ + struct vfat_superblock sb; + char label[512]; + u32 serial; + u32 temp32; + u16 type; + int ret=0; + int fd; + int res; + + memset(label, 0, sizeof(label)); + memset(&sb, 0, sizeof(sb)); + + if ((fd=open64(devname, O_RDONLY|O_LARGEFILE))<0) + { ret=-1; + goto vfat_read_sb_return; + } + + res=read(fd, &sb, sizeof(sb)); + if (res!=sizeof(sb)) + { ret=-1; + goto vfat_read_sb_close; + } + + // make sure we can find the magic number + if (be16_to_cpu(sb.magic)!=VFAT_SB_MAGIC) + { msgprintf(MSG_DEBUG1, "(be16_to_cpu(sb.magic)=%.2x) != (VFAT_SB_MAGIC=%.2x)\n", be16_to_cpu(sb.magic), VFAT_SB_MAGIC); + ret=-1; + goto vfat_read_sb_close; + } + + // number of FATs must be 1 or 2 + if (sb.num_fats != 1 && sb.num_fats != 2) + { msgprintf(MSG_DEBUG1, "Invalid number of FAT tables: %d\n", (int)sb.num_fats); + ret=-1; + goto vfat_read_sb_close; + } + + // num_root_dir_ents set to zero indicates a FAT32 + if (sb.num_root_dir_ents == 0) + { type=FAT_TYPE_FAT32; + msgprintf(MSG_DEBUG1, "FAT_TYPE_FAT32\n"); + memcpy(label, ((char*)&sb)+0x047, 11); + memcpy(&temp32, ((char*)&sb)+0x043, 4); + serial=le32_to_cpu(temp32); + } + else + { type=FAT_TYPE_FAT16; + msgprintf(MSG_DEBUG1, "FAT_TYPE_FAT16\n"); + memcpy(label, ((char*)&sb)+0x02B, 11); + memcpy(&temp32, ((char*)&sb)+0x027, 4); + serial=le32_to_cpu(temp32); + } + + // ---- type + dico_add_u16(d, 0, FSYSHEADKEY_FSVFATTYPE, type); + + // ---- label + msgprintf(MSG_DEBUG1, "vfat_label=[%s]\n", label); + dico_add_string(d, 0, FSYSHEADKEY_FSLABEL, label); + + // ---- serial + dico_add_u32(d, 0, FSYSHEADKEY_FSVFATSERIAL, serial); + msgprintf(MSG_DEBUG1, "vfat_serial=[%08X]\n", serial); + + // ---- minimum fsarchiver version required to restore + dico_add_u64(d, 0, FSYSHEADKEY_MINFSAVERSION, FSA_VERSION_BUILD(0, 8, 0, 0)); + +vfat_read_sb_close: + close(fd); +vfat_read_sb_return: + return ret; +} + +int vfat_mount(char *partition, char *mntbuf, char *fsbuf, int flags, char *mntinfo) +{ + return generic_mount(partition, mntbuf, fsbuf, "", flags); +} + +int vfat_umount(char *partition, char *mntbuf) +{ + return generic_umount(mntbuf); +} + +int vfat_test(char *devname) +{ + struct vfat_superblock sb; + int fd; + + if ((fd=open64(devname, O_RDONLY|O_LARGEFILE))<0) + { + msgprintf(MSG_DEBUG1, "open64(%s) failed\n", devname); + return false; + } + + memset(&sb, 0, sizeof(sb)); + if (read(fd, &sb, sizeof(sb))!=sizeof(sb)) + { close(fd); + msgprintf(MSG_DEBUG1, "read failed\n"); + return false; + } + + // ---- check it is a VFAT file system + if (be16_to_cpu(sb.magic)!=VFAT_SB_MAGIC) + { close(fd); + msgprintf(MSG_DEBUG1, "(be16_to_cpu(sb.magic)=%.2x) != (VFAT_SB_MAGIC=%.2x)\n", be16_to_cpu(sb.magic), VFAT_SB_MAGIC); + return false; + } + + close(fd); + return true; +} + +int vfat_get_reqmntopt(char *partition, cstrlist *reqopt, cstrlist *badopt) +{ + if (!reqopt || !badopt) + return -1; + + return 0; +} diff --git a/pool/shard008/C/0130710_ofp_cli_arp.c b/pool/shard008/C/0130710_ofp_cli_arp.c new file mode 100644 index 0000000000000000000000000000000000000000..5f8963a490f0128ab17d64cebf3cd1497d4670dd --- /dev/null +++ b/pool/shard008/C/0130710_ofp_cli_arp.c @@ -0,0 +1,123 @@ +/*- + * Copyright (c) 2014 ENEA Software AB + * Copyright (c) 2014 Nokia + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include +#include +#include + +#include "ofpi_log.h" +#include "ofpi_cli.h" +#include "ofpi_route.h" +#include "ofpi_arp.h" +#include "ofpi_util.h" + + +void f_arp(struct cli_conn *conn, const char *s) +{ + (void)s; + + ofp_show_routes(conn->fd, OFP_SHOW_ARP); + ofp_arp_show_saved_packets(conn->fd); + sendcrlf(conn); +} + +void f_arp_flush(struct cli_conn *conn, const char *s) +{ + (void)s; + + ofp_arp_init_tables(); + sendcrlf(conn); +} + +void f_arp_cleanup(struct cli_conn *conn, const char *s) +{ + int cli = 1; + + (void)s; +#ifdef OFP_USE_LIBCK + (void)cli; + /* Aging not defined in arp ck impl */ +#else + ofp_arp_age_cb(&cli); +#endif + sendcrlf(conn); +} + +void f_arp_add(struct cli_conn *conn, const char *s) +{ + int a, b, c, d, e, f, g, h, i, j; + char dev[16]; + int port, vlan; + struct ofp_ifnet *itf; + uint32_t ipv4_addr; + uint8_t mac[OFP_ETHER_ADDR_LEN]; + + if (sscanf(s, " %d.%d.%d.%d %x:%x:%x:%x:%x:%x %s", + &a, &b, &c, &d, &e, &f, &g, &h, &i, &j, dev) != 11) + return; + + ipv4_addr = odp_cpu_to_be_32((a << 24) | (b << 16) | (c << 8) | d); + mac[0] = e; + mac[1] = f; + mac[2] = g; + mac[3] = h; + mac[4] = i; + mac[5] = j; + + port = ofp_name_to_port_vlan(dev, &vlan); + if (port == -1 || !PHYS_PORT(port)) { + ofp_sendf(conn->fd, "Invalid device name.\r\n"); + sendcrlf(conn); + return; + } + + itf = ofp_get_ifnet(port, vlan); + if (itf == NULL) { + ofp_sendf(conn->fd, "Device not found.\r\n"); + sendcrlf(conn); + return; + } + + if (ofp_arp_ipv4_insert(ipv4_addr, mac, itf, TRUE)) { + ofp_sendf(conn->fd, "Failed to insert arp entry.\r\n"); + sendcrlf(conn); + return; + } + + sendcrlf(conn); +} + +void f_help_arp(struct cli_conn *conn, const char *s) +{ + (void)s; + ofp_sendf(conn->fd, + "Show arp table:\r\n" + " arp\r\n\r\n"); + + ofp_sendf(conn->fd, + "Add arp entry:\r\n" + " arp set IP4ADDR HWADDR dev DEV\r\n" + " IP4ADDR: ip address in a.b.c.d format\r\n" + " HWADDR: mac address in a:b:c:d:e:f format\r\n" + " DEV: ethernet interface name\r\n" + " Example:\r\n" + " arp set 192.168.0.20 90:1b:0e:9a:cf:fc dev fp0\r\n\r\n"); + + ofp_sendf(conn->fd, + "Flush arp table:\r\n" + " arp flush\r\n\r\n"); + + ofp_sendf(conn->fd, + "Clean old entries from arp table:\r\n" + " arp cleanup\r\n\r\n"); + + ofp_sendf(conn->fd, + "Show (this) help:\r\n" + " arp help\r\n\r\n"); + + sendcrlf(conn); +} diff --git a/pool/shard008/C/0130711_network.c b/pool/shard008/C/0130711_network.c new file mode 100644 index 0000000000000000000000000000000000000000..b87f6999d604838fee2e2b29a1a0174d0712eaac --- /dev/null +++ b/pool/shard008/C/0130711_network.c @@ -0,0 +1,227 @@ +/* Jakopter + * Copyright © 2015 ALF@INRIA + * + * 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 3 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. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see . + */ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "network.h" + +/*Input: data received in Jakopter in JSON*/ +jakopter_com_channel_t* network_in_channel; +/*Output: data emitted outside by POST method*/ +jakopter_com_channel_t* network_out_channel; + +pthread_t send_thread; +pthread_t receive_thread; +/*Guard that stops any function if connection isn't initialized.*/ +bool stopped_network = true; +/*guard to know if the thread started*/ +bool recv_ready = false; +struct CurlData { + /* a buffer to handle received data */ + char *memory; + /* size in bytes */ + size_t size; +}; + +static char send_addr[ADDR_SIZE]; +static char recv_addr[ADDR_SIZE]; + + +void* send_routine(void* args) +{ + //char* url = "http://127.0.0.1/index.php"; + CURL* send_handle = curl_easy_init(); + //struct curl_slist *header = NULL; + CURLcode ret; + struct timespec itv = {0, TIMEOUT_NETWORK}; + + char buf[CHANNEL_OUTPUT_SIZE]; + + if (!send_handle) { + perror("[~][network] Can't create curl handle for send"); + return NULL; + } + while (!stopped_network) { + char order[ORDER_SIZE]; + size_t order_len = (uint)jakopter_com_read_int(network_out_channel,4); + memset(order, 0, ORDER_SIZE); + memset(buf, 0, CHANNEL_OUTPUT_SIZE); + + if (order_len > ORDER_SIZE) { + fprintf(stderr, "[~][network] size of order > 256\n"); + continue; + } + + size_t offset = 8 + ORDER_SIZE; + snprintf(buf, CHANNEL_OUTPUT_SIZE, + "id=%d&order=%s&t_x=%f&t_y=%f&t_z=%f&r_x=%f&r_y=%f&r_z=%f&q_w=%f&q_x=%f&q_y=%f&q_z=%f&fly_state=%d", + jakopter_com_read_int(network_out_channel, 0), + (char*)jakopter_com_read_buf(network_out_channel, 8, order_len, &order), + jakopter_com_read_float(network_out_channel, offset), + jakopter_com_read_float(network_out_channel, offset+4), + jakopter_com_read_float(network_out_channel, offset+8), + jakopter_com_read_float(network_out_channel, offset+12), + jakopter_com_read_float(network_out_channel, offset+16), + jakopter_com_read_float(network_out_channel, offset+20), + jakopter_com_read_float(network_out_channel, offset+24), + jakopter_com_read_float(network_out_channel, offset+28), + jakopter_com_read_float(network_out_channel, offset+32), + jakopter_com_read_float(network_out_channel, offset+36), + jakopter_com_read_int(network_out_channel, offset+40) + ); + curl_easy_setopt(send_handle, CURLOPT_POSTFIELDS, buf); + curl_easy_setopt(send_handle, CURLOPT_VERBOSE, 0L); + curl_easy_setopt(send_handle, CURLOPT_URL, send_addr); + curl_easy_setopt(send_handle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); + + ret = curl_easy_perform(send_handle); + + if (ret != CURLE_OK) { + fprintf(stderr, "[~][network] curl_easy_perform(send) failed: %s\n", curl_easy_strerror(ret)); + break; + } + + nanosleep(&itv, NULL); + itv.tv_nsec = TIMEOUT_NETWORK; + } + curl_easy_cleanup(send_handle); + + return NULL; +} + +static size_t write_curl_to_com_channel(void* data, size_t size, size_t nmemb, void* userptr) +{ + size_t realsize = size * nmemb; + jakopter_com_write_int(network_in_channel, 0, (int)realsize); + jakopter_com_write_buf(network_in_channel, 4, data, realsize); + memset(data, 0, realsize); + return realsize; +} +void* receive_routine(void* args) +{ + CURL* recv_handle = curl_easy_init(); + CURLcode ret; + struct timespec itv = {1, TIMEOUT_NETWORK/10}; + if (!recv_handle) { + perror("[~][network] Can't create curl handle for receive"); + return NULL; + } + struct CurlData serv_data; + while (!stopped_network) { + curl_easy_setopt(recv_handle, CURLOPT_WRITEFUNCTION, write_curl_to_com_channel); + curl_easy_setopt(recv_handle, CURLOPT_WRITEDATA, (void *)&serv_data); + curl_easy_setopt(recv_handle, CURLOPT_VERBOSE, 0L); + curl_easy_setopt(recv_handle, CURLOPT_URL, recv_addr); + curl_easy_setopt(recv_handle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); + ret = curl_easy_perform(recv_handle); + + if (ret != CURLE_OK) { + fprintf(stderr, "[~][network] curl_easy_perform(receive) failed: %s\n", curl_easy_strerror(ret)); + break; + } + + nanosleep(&itv, NULL); + itv.tv_nsec = TIMEOUT_NETWORK; + + recv_ready = true; + } + curl_easy_cleanup(recv_handle); + + return NULL; +} + +int jakopter_init_network(const char* server_in, const char* server_out) +{ + if (!stopped_network) + return -1; + stopped_network = false; + memset(recv_addr, 0, 256); + memset(send_addr, 0, 256); + + if (server_out && server_out[0] != '\0') + strncpy(send_addr, server_out, ADDR_SIZE); + else + strncpy(send_addr, DEFAULT_CLIENT_OUT, strlen(DEFAULT_CLIENT_OUT)); + + if (server_in && server_in[0] != '\0') + strncpy(recv_addr, server_in, ADDR_SIZE); + else + strncpy(recv_addr, DEFAULT_CLIENT_IN, strlen(DEFAULT_CLIENT_IN)); + + printf("[*][network] Receiving from: %s\n", recv_addr); + printf("[*][network] Sending to: %s\n", send_addr); + + curl_global_init(CURL_GLOBAL_ALL); + + network_in_channel = jakopter_com_add_channel(CHANNEL_NETWORK_INPUT, CHANNEL_INPUT_SIZE); + network_out_channel = jakopter_com_add_channel(CHANNEL_NETWORK_OUTPUT, CHANNEL_OUTPUT_SIZE); + + printf("[network] channel created\n"); + + if (pthread_create(&send_thread, NULL, send_routine, NULL) < 0) { + perror("[~][network] Can't create thread send"); + return -1; + } + if (pthread_create(&receive_thread, NULL, receive_routine, NULL) < 0) { + perror("[~][network] Can't create thread send"); + return -1; + } + + int i = 0; + while (!recv_ready && i < 200) { + usleep(500); + i++; + } + + printf("[network] threads created\n"); + + return -(i >= 200); +} + +int jakopter_stop_network() +{ + if (!stopped_network) { + stopped_network = true; + + int ret_out = pthread_join(send_thread, NULL); + int ret_in = pthread_join(receive_thread, NULL); + recv_ready = false; + jakopter_com_remove_channel(CHANNEL_NETWORK_INPUT); + jakopter_com_remove_channel(CHANNEL_NETWORK_OUTPUT); + + curl_global_cleanup(); + + int ret = 0; + if (ret_in) + ret |= 2; + if (ret_out) + ret |= 1; + return -ret; + } + else { + fprintf(stderr, "[*][network] Network already stopped\n"); + return -1; + } + //thread join + return 0; +} \ No newline at end of file diff --git a/pool/shard008/C/0130712_negative_deadline.c b/pool/shard008/C/0130712_negative_deadline.c new file mode 100644 index 0000000000000000000000000000000000000000..12c6a0f2bd8eee851c60b3c7fa6d2d45265af539 --- /dev/null +++ b/pool/shard008/C/0130712_negative_deadline.c @@ -0,0 +1,182 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "test/core/end2end/end2end_tests.h" + +#include +#include + +#include +#include +#include +#include +#include +#include +#include "src/core/lib/support/string.h" +#include "test/core/end2end/cq_verifier.h" + +static void *tag(intptr_t t) { return (void *)t; } + +static grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config, + const char *test_name, + grpc_channel_args *client_args, + grpc_channel_args *server_args) { + grpc_end2end_test_fixture f; + gpr_log(GPR_INFO, "%s/%s", test_name, config.name); + f = config.create_fixture(client_args, server_args); + config.init_server(&f, server_args); + config.init_client(&f, client_args, NULL); + return f; +} + +static gpr_timespec n_seconds_time(int n) { + return GRPC_TIMEOUT_SECONDS_TO_DEADLINE(n); +} + +static gpr_timespec five_seconds_time(void) { return n_seconds_time(5); } + +static void drain_cq(grpc_completion_queue *cq) { + grpc_event ev; + do { + ev = grpc_completion_queue_next(cq, five_seconds_time(), NULL); + } while (ev.type != GRPC_QUEUE_SHUTDOWN); +} + +static void shutdown_server(grpc_end2end_test_fixture *f) { + if (!f->server) return; + grpc_server_shutdown_and_notify(f->server, f->cq, tag(1000)); + GPR_ASSERT(grpc_completion_queue_pluck( + f->cq, tag(1000), GRPC_TIMEOUT_SECONDS_TO_DEADLINE(5), NULL) + .type == GRPC_OP_COMPLETE); + grpc_server_destroy(f->server); + f->server = NULL; +} + +static void shutdown_client(grpc_end2end_test_fixture *f) { + if (!f->client) return; + grpc_channel_destroy(f->client); + f->client = NULL; +} + +static void end_test(grpc_end2end_test_fixture *f) { + shutdown_server(f); + shutdown_client(f); + + grpc_completion_queue_shutdown(f->cq); + drain_cq(f->cq); + grpc_completion_queue_destroy(f->cq); +} + +static void simple_request_body(grpc_end2end_test_fixture f, size_t num_ops) { + grpc_call *c; + gpr_timespec deadline = gpr_inf_past(GPR_CLOCK_REALTIME); + cq_verifier *cqv = cq_verifier_create(f.cq); + grpc_op ops[6]; + grpc_op *op; + grpc_metadata_array initial_metadata_recv; + grpc_metadata_array trailing_metadata_recv; + grpc_status_code status; + grpc_call_error error; + char *details = NULL; + size_t details_capacity = 0; + + gpr_log(GPR_DEBUG, "test with %" PRIuPTR " ops", num_ops); + + c = grpc_channel_create_call(f.client, NULL, GRPC_PROPAGATE_DEFAULTS, f.cq, + "/foo", "foo.test.google.fr:1234", deadline, + NULL); + GPR_ASSERT(c); + + grpc_metadata_array_init(&initial_metadata_recv); + grpc_metadata_array_init(&trailing_metadata_recv); + + memset(ops, 0, sizeof(ops)); + op = ops; + op->op = GRPC_OP_RECV_STATUS_ON_CLIENT; + op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv; + op->data.recv_status_on_client.status = &status; + op->data.recv_status_on_client.status_details = &details; + op->data.recv_status_on_client.status_details_capacity = &details_capacity; + op->flags = 0; + op->reserved = NULL; + op++; + op->op = GRPC_OP_RECV_INITIAL_METADATA; + op->data.recv_initial_metadata = &initial_metadata_recv; + op->flags = 0; + op->reserved = NULL; + op++; + op->op = GRPC_OP_SEND_INITIAL_METADATA; + op->data.send_initial_metadata.count = 0; + op->flags = 0; + op->reserved = NULL; + op++; + op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; + op->flags = 0; + op->reserved = NULL; + op++; + GPR_ASSERT(num_ops <= (size_t)(op - ops)); + error = grpc_call_start_batch(c, ops, num_ops, tag(1), NULL); + GPR_ASSERT(GRPC_CALL_OK == error); + + CQ_EXPECT_COMPLETION(cqv, tag(1), 1); + cq_verify(cqv); + + GPR_ASSERT(status == GRPC_STATUS_DEADLINE_EXCEEDED); + + gpr_free(details); + grpc_metadata_array_destroy(&initial_metadata_recv); + grpc_metadata_array_destroy(&trailing_metadata_recv); + + grpc_call_destroy(c); + + cq_verifier_destroy(cqv); +} + +static void test_invoke_simple_request(grpc_end2end_test_config config, + size_t num_ops) { + grpc_end2end_test_fixture f; + + f = begin_test(config, "test_invoke_simple_request", NULL, NULL); + simple_request_body(f, num_ops); + end_test(&f); + config.tear_down_data(&f); +} + +void negative_deadline(grpc_end2end_test_config config) { + size_t i; + for (i = 1; i <= 4; i++) { + test_invoke_simple_request(config, i); + } +} + +void negative_deadline_pre_init(void) {} diff --git a/pool/shard008/C/0130714_tmu.c b/pool/shard008/C/0130714_tmu.c new file mode 100644 index 0000000000000000000000000000000000000000..54629e903a3669f33646c4c0765c1cf788eb006e --- /dev/null +++ b/pool/shard008/C/0130714_tmu.c @@ -0,0 +1,215 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2012 Samsung Electronics + * Copyright 2013 Google Inc. + * + * 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; version 2 of the License. + * + * 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. + */ + +/* EXYNOS - Thermal Management Unit */ + +#include +#include +#include +#include + +#define TRIMINFO_RELOAD 1 +#define CORE_EN 1 +#define THERM_TRIP_EN (1 << 12) + +#define INTEN_RISE0 1 +#define INTEN_RISE1 (1 << 4) +#define INTEN_RISE2 (1 << 8) +#define INTEN_FALL0 (1 << 16) +#define INTEN_FALL1 (1 << 20) +#define INTEN_FALL2 (1 << 24) + +#define TRIM_INFO_MASK 0xff + +#define INTCLEAR_RISE0 1 +#define INTCLEAR_RISE1 (1 << 4) +#define INTCLEAR_RISE2 (1 << 8) +#define INTCLEAR_FALL0 (1 << 16) +#define INTCLEAR_FALL1 (1 << 20) +#define INTCLEAR_FALL2 (1 << 24) +#define INTCLEARALL (INTCLEAR_RISE0 | INTCLEAR_RISE1 | \ + INTCLEAR_RISE2 | INTCLEAR_FALL0 | \ + INTCLEAR_FALL1 | INTCLEAR_FALL2) + +struct tmu_info exynos5420_tmu_info = { + .tmu_base = 0x10060000, + .tmu_mux = 6, + .data = { + .ts = { + .min_val = 25, + .max_val = 125, + .start_warning = 95, + .start_tripping = 105, + .hardware_tripping = 110, + }, + .efuse_min_value = 40, + .efuse_value = 55, + .efuse_max_value = 100, + .slope = 0x10008802, + }, + .dc_value = 25, +}; + +/* + * After reading temperature code from register, compensating + * its value and calculating celsius temperature, + * get current temperature. + * + * @return current temperature of the chip as sensed by TMU + */ +static int get_cur_temp(struct tmu_info *info) +{ + int cur_temp; + struct tmu_reg *reg = (struct tmu_reg *)info->tmu_base; + + /* Temperature code range between min 25 and max 125 */ + cur_temp = read32(®->current_temp) & 0xff; + + /* Calibrate current temperature */ + if (cur_temp) + cur_temp = cur_temp - info->te1 + info->dc_value; + + return cur_temp; +} + +/* + * Monitors status of the TMU device and exynos temperature + * + * @info TMU info + * @temp pointer to the current temperature value + * @return enum tmu_status_t value, code indicating event to execute + */ +enum tmu_status_t tmu_monitor(struct tmu_info *info, int *temp) +{ + if (info->tmu_state == TMU_STATUS_INIT) + return -1; + + int cur_temp; + struct tmu_data *data = &info->data; + + /* Read current temperature of the SOC */ + cur_temp = get_cur_temp(info); + *temp = cur_temp; + + /* Temperature code lies between min 25 and max 125 */ + if (cur_temp >= data->ts.start_tripping && + cur_temp <= data->ts.max_val) + return TMU_STATUS_TRIPPED; + else if (cur_temp >= data->ts.start_warning) + return TMU_STATUS_WARNING; + else if (cur_temp < data->ts.start_warning && + cur_temp >= data->ts.min_val) + return TMU_STATUS_NORMAL; + /* Temperature code does not lie between min 25 and max 125 */ + else { + info->tmu_state = TMU_STATUS_INIT; + printk(BIOS_DEBUG, "EXYNOS_TMU: Thermal reading failed\n"); + return -1; + } + return 0; +} + +/* + * Calibrate and calculate threshold values and + * enable interrupt levels + * + * @param info pointer to the tmu_info struct + */ +static void tmu_setup_parameters(struct tmu_info *info) +{ + unsigned int te_temp, con; + unsigned int warning_code, trip_code, hwtrip_code; + unsigned int cooling_temp; + unsigned int rising_value; + struct tmu_data *data = &info->data; + struct tmu_reg *reg = (struct tmu_reg *)info->tmu_base; + + /* Must reload for using efuse value at EXYNOS */ + write32(®->triminfo_control, TRIMINFO_RELOAD); + + /* Get the compensation parameter */ + te_temp = read32(®->triminfo); + info->te1 = te_temp & TRIM_INFO_MASK; + info->te2 = ((te_temp >> 8) & TRIM_INFO_MASK); + + if ((data->efuse_min_value > info->te1) || + (info->te1 > data->efuse_max_value) + || (info->te2 != 0)) + info->te1 = data->efuse_value; + + /* Get RISING & FALLING Threshold value */ + warning_code = data->ts.start_warning + + info->te1 - info->dc_value; + trip_code = data->ts.start_tripping + + info->te1 - info->dc_value; + hwtrip_code = data->ts.hardware_tripping + + info->te1 - info->dc_value; + + cooling_temp = 0; + + rising_value = ((warning_code << 8) | + (trip_code << 16) | + (hwtrip_code << 24)); + + /* Set interrupt level */ + write32(®->threshold_temp_rise, rising_value); + write32(®->threshold_temp_fall, cooling_temp); + + /* + * Need to init all register settings after getting parameter info + * [28:23] vref [11:8] slope - Tuning parameter + * + * WARNING: this slope value writes into many bits in the tmu_control + * register, with the default FDT value of 268470274 (0x10008802) + * we are using this essentially sets the default register setting + * from the TRM for tmu_control. + * TODO(bhthompson): rewrite this code such that we are not performing + * a hard wipe of tmu_control and re verify functionality. + */ + write32(®->tmu_control, data->slope); + + write32(®->intclear, INTCLEARALL); + /* TMU core enable */ + con = read32(®->tmu_control); + con |= (info->tmu_mux << 20) | THERM_TRIP_EN | CORE_EN; + + write32(®->tmu_control, con); + + /* Enable HW thermal trip */ + power_enable_hw_thermal_trip(); + + /* LEV1 LEV2 interrupt enable */ + write32(®->inten, INTEN_RISE1 | INTEN_RISE2); +} + +/* + * Initialize TMU device + * + * @return int value, 0 for success + */ +int tmu_init(struct tmu_info *info) +{ + info->tmu_state = TMU_STATUS_INIT; + + tmu_setup_parameters(info); + info->tmu_state = TMU_STATUS_NORMAL; + + return 0; +} diff --git a/pool/shard008/C/0130715_hello-5.c b/pool/shard008/C/0130715_hello-5.c new file mode 100644 index 0000000000000000000000000000000000000000..858210a72d3ebcf8059773f7b0b62bb327e2507d --- /dev/null +++ b/pool/shard008/C/0130715_hello-5.c @@ -0,0 +1,75 @@ +/* + * hello-1.c - The simplest kernel module. + */ +#include +#include +#include +#include +#include + +#define DRIVER_AUTHOR "David Rubinstein " +#define DRIVER_DESC "A sample driver" + +static short int myshort = 1; +static int myint = 420; +static long int mylong = 9999; +static char *mystring = "blah"; +static int myintArray[2] = {-1, 1}; +static int arr_argc = 0; + +/* + * module_param(foo,int,0000); + * The first param is the params name + * The second param is it's data type + * The final argument is the permissions bits, + * for exposing parameters in sysfs (if non-zero) at a later stage. +*/ + +module_param(myshort, short, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); +MODULE_PARM_DESC(myshort, "A short integer"); +module_param(myint, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); +MODULE_PARM_DESC(myint, "An integer"); +module_param(mylong, long, S_IRUSR); +MODULE_PARM_DESC(mylong, "A long integer"); +module_param(mystring, charp, 0000); +MODULE_PARM_DESC(mystring, "A character string"); + +/* + * module_param_array(name, type, num, perm); + * The first param is the parameter's (in this case the array's) name + * The second param is the data type of the elements of the array + * The third argument is a pointer to the variable that will store the number + * of elements of the array initialized by the user at module loading time + * The fourth argument is the permissions bit +*/ + +module_param_array(myintArray, int, &arr_argc, 0000); +MODULE_PARM_DESC(myintArray, "An array of integers"); + + +static int __init hello_5_init(void) +{ + int i; + printk(KERN_INFO "Hello, world 5\n=============\n"); + printk(KERN_INFO "myshort is a short integer: %hd\n", myshort); + printk(KERN_INFO "myint is an integer: %d\n", myint); + printk(KERN_INFO "mylong is a long integer: %ld\n", mylong); + printk(KERN_INFO "mystring is a string: %s\n", mystring); + for (i=0; i < (sizeof myintArray/sizeof (int)); i++) + printk(KERN_INFO "MyintArray[%d] = %d\n",i,myintArray[i]); + printk(KERN_INFO "got %d arguments for myintArray.\n", arr_argc); + + return 0; +} + +static void __exit hello_5_exit(void) +{ + printk(KERN_INFO "Goodbye world 5\n"); +} + +module_init(hello_5_init); +module_exit(hello_5_exit); +MODULE_LICENSE("GPL"); +MODULE_AUTHOR(DRIVER_AUTHOR); +MODULE_DESCRIPTION(DRIVER_DESC); +MODULE_SUPPORTED_DEVICE("The lols"); diff --git a/pool/shard008/C/0130720_nlmsgtab.c b/pool/shard008/C/0130720_nlmsgtab.c new file mode 100644 index 0000000000000000000000000000000000000000..b8f4d25cf33533d15ac51665674fa5dfaaf94bc2 --- /dev/null +++ b/pool/shard008/C/0130720_nlmsgtab.c @@ -0,0 +1,176 @@ +/* + * Netlink message type permission tables, for user generated messages. + * + * Author: James Morris + * + * Copyright (C) 2004 Red Hat, Inc., James Morris + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "flask.h" +#include "av_permissions.h" + +struct nlmsg_perm +{ + u16 nlmsg_type; + u32 perm; +}; + +static struct nlmsg_perm nlmsg_route_perms[] = +{ + { RTM_NEWLINK, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_DELLINK, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_GETLINK, NETLINK_ROUTE_SOCKET__NLMSG_READ }, + { RTM_SETLINK, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_NEWADDR, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_DELADDR, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_GETADDR, NETLINK_ROUTE_SOCKET__NLMSG_READ }, + { RTM_NEWROUTE, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_DELROUTE, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_GETROUTE, NETLINK_ROUTE_SOCKET__NLMSG_READ }, + { RTM_NEWNEIGH, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_DELNEIGH, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_GETNEIGH, NETLINK_ROUTE_SOCKET__NLMSG_READ }, + { RTM_NEWRULE, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_DELRULE, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_GETRULE, NETLINK_ROUTE_SOCKET__NLMSG_READ }, + { RTM_NEWQDISC, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_DELQDISC, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_GETQDISC, NETLINK_ROUTE_SOCKET__NLMSG_READ }, + { RTM_NEWTCLASS, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_DELTCLASS, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_GETTCLASS, NETLINK_ROUTE_SOCKET__NLMSG_READ }, + { RTM_NEWTFILTER, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_DELTFILTER, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_GETTFILTER, NETLINK_ROUTE_SOCKET__NLMSG_READ }, + { RTM_NEWACTION, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_DELACTION, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_GETACTION, NETLINK_ROUTE_SOCKET__NLMSG_READ }, + { RTM_NEWPREFIX, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, + { RTM_GETPREFIX, NETLINK_ROUTE_SOCKET__NLMSG_READ }, + { RTM_GETMULTICAST, NETLINK_ROUTE_SOCKET__NLMSG_READ }, + { RTM_GETANYCAST, NETLINK_ROUTE_SOCKET__NLMSG_READ }, + { RTM_GETNEIGHTBL, NETLINK_ROUTE_SOCKET__NLMSG_READ }, + { RTM_SETNEIGHTBL, NETLINK_ROUTE_SOCKET__NLMSG_WRITE }, +}; + +static struct nlmsg_perm nlmsg_firewall_perms[] = +{ + { IPQM_MODE, NETLINK_FIREWALL_SOCKET__NLMSG_WRITE }, + { IPQM_VERDICT, NETLINK_FIREWALL_SOCKET__NLMSG_WRITE }, +}; + +static struct nlmsg_perm nlmsg_tcpdiag_perms[] = +{ + { TCPDIAG_GETSOCK, NETLINK_TCPDIAG_SOCKET__NLMSG_READ }, + { DCCPDIAG_GETSOCK, NETLINK_TCPDIAG_SOCKET__NLMSG_READ }, +}; + +static struct nlmsg_perm nlmsg_xfrm_perms[] = +{ + { XFRM_MSG_NEWSA, NETLINK_XFRM_SOCKET__NLMSG_WRITE }, + { XFRM_MSG_DELSA, NETLINK_XFRM_SOCKET__NLMSG_WRITE }, + { XFRM_MSG_GETSA, NETLINK_XFRM_SOCKET__NLMSG_READ }, + { XFRM_MSG_NEWPOLICY, NETLINK_XFRM_SOCKET__NLMSG_WRITE }, + { XFRM_MSG_DELPOLICY, NETLINK_XFRM_SOCKET__NLMSG_WRITE }, + { XFRM_MSG_GETPOLICY, NETLINK_XFRM_SOCKET__NLMSG_READ }, + { XFRM_MSG_ALLOCSPI, NETLINK_XFRM_SOCKET__NLMSG_WRITE }, + { XFRM_MSG_ACQUIRE, NETLINK_XFRM_SOCKET__NLMSG_WRITE }, + { XFRM_MSG_EXPIRE, NETLINK_XFRM_SOCKET__NLMSG_WRITE }, + { XFRM_MSG_UPDPOLICY, NETLINK_XFRM_SOCKET__NLMSG_WRITE }, + { XFRM_MSG_UPDSA, NETLINK_XFRM_SOCKET__NLMSG_WRITE }, + { XFRM_MSG_POLEXPIRE, NETLINK_XFRM_SOCKET__NLMSG_WRITE }, + { XFRM_MSG_FLUSHSA, NETLINK_XFRM_SOCKET__NLMSG_WRITE }, + { XFRM_MSG_FLUSHPOLICY, NETLINK_XFRM_SOCKET__NLMSG_WRITE }, + { XFRM_MSG_NEWAE, NETLINK_XFRM_SOCKET__NLMSG_WRITE }, + { XFRM_MSG_GETAE, NETLINK_XFRM_SOCKET__NLMSG_READ }, +}; + +static struct nlmsg_perm nlmsg_audit_perms[] = +{ + { AUDIT_GET, NETLINK_AUDIT_SOCKET__NLMSG_READ }, + { AUDIT_SET, NETLINK_AUDIT_SOCKET__NLMSG_WRITE }, + { AUDIT_LIST, NETLINK_AUDIT_SOCKET__NLMSG_READPRIV }, + { AUDIT_ADD, NETLINK_AUDIT_SOCKET__NLMSG_WRITE }, + { AUDIT_DEL, NETLINK_AUDIT_SOCKET__NLMSG_WRITE }, + { AUDIT_LIST_RULES, NETLINK_AUDIT_SOCKET__NLMSG_READPRIV }, + { AUDIT_ADD_RULE, NETLINK_AUDIT_SOCKET__NLMSG_WRITE }, + { AUDIT_DEL_RULE, NETLINK_AUDIT_SOCKET__NLMSG_WRITE }, + { AUDIT_USER, NETLINK_AUDIT_SOCKET__NLMSG_RELAY }, + { AUDIT_SIGNAL_INFO, NETLINK_AUDIT_SOCKET__NLMSG_READ }, +}; + + +static int nlmsg_perm(u16 nlmsg_type, u32 *perm, struct nlmsg_perm *tab, size_t tabsize) +{ + int i, err = -EINVAL; + + for (i = 0; i < tabsize/sizeof(struct nlmsg_perm); i++) + if (nlmsg_type == tab[i].nlmsg_type) { + *perm = tab[i].perm; + err = 0; + break; + } + + return err; +} + +int selinux_nlmsg_lookup(u16 sclass, u16 nlmsg_type, u32 *perm) +{ + int err = 0; + + switch (sclass) { + case SECCLASS_NETLINK_ROUTE_SOCKET: + err = nlmsg_perm(nlmsg_type, perm, nlmsg_route_perms, + sizeof(nlmsg_route_perms)); + break; + + case SECCLASS_NETLINK_FIREWALL_SOCKET: + case SECCLASS_NETLINK_IP6FW_SOCKET: + err = nlmsg_perm(nlmsg_type, perm, nlmsg_firewall_perms, + sizeof(nlmsg_firewall_perms)); + break; + + case SECCLASS_NETLINK_TCPDIAG_SOCKET: + err = nlmsg_perm(nlmsg_type, perm, nlmsg_tcpdiag_perms, + sizeof(nlmsg_tcpdiag_perms)); + break; + + case SECCLASS_NETLINK_XFRM_SOCKET: + err = nlmsg_perm(nlmsg_type, perm, nlmsg_xfrm_perms, + sizeof(nlmsg_xfrm_perms)); + break; + + case SECCLASS_NETLINK_AUDIT_SOCKET: + if ((nlmsg_type >= AUDIT_FIRST_USER_MSG && + nlmsg_type <= AUDIT_LAST_USER_MSG) || + (nlmsg_type >= AUDIT_FIRST_USER_MSG2 && + nlmsg_type <= AUDIT_LAST_USER_MSG2)) { + *perm = NETLINK_AUDIT_SOCKET__NLMSG_RELAY; + } else { + err = nlmsg_perm(nlmsg_type, perm, nlmsg_audit_perms, + sizeof(nlmsg_audit_perms)); + } + break; + + /* No messaging from userspace, or class unknown/unhandled */ + default: + err = -ENOENT; + break; + } + + return err; +} diff --git a/pool/shard008/C/0130723_lightdash-dialogs.c b/pool/shard008/C/0130723_lightdash-dialogs.c new file mode 100644 index 0000000000000000000000000000000000000000..de79eb42dfffa8b50198bf445223460ff0dd8a53 --- /dev/null +++ b/pool/shard008/C/0130723_lightdash-dialogs.c @@ -0,0 +1,157 @@ +/* + * Copyright (C) 2015 adlo + * + * 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 library; if not, see + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include "lightdash.h" +#include "lightdash-dialogs.h" + +static void lightdash_configure_response (GtkWidget *dialog, + gint response, + LightdashPlugin *lightdash) +{ + /* remove the dialog data from the plugin */ + g_object_set_data (G_OBJECT (lightdash->plugin), "dialog", NULL); + + /* unlock the panel menu */ + xfce_panel_plugin_unblock_menu (lightdash->plugin); + + /* destroy the properties dialog */ + gtk_widget_destroy (dialog); +} + +static void lightdash_opacity_slider_changed (GtkRange *range, LightdashPlugin *lightdash) +{ + lightdash->opacity = gtk_range_get_value (range); +} + +static void lightdash_preferences_entry_changed (GtkEditable *editable, LightdashPlugin *lightdash) +{ + const gchar *text = gtk_entry_get_text (GTK_ENTRY (editable)); + gtk_label_set_text (GTK_LABEL (lightdash->button_label), text); + lightdash->button_title = g_strdup (text); +} + +static void lightdash_show_desktop_button_toggled (GtkToggleButton *button, LightdashPlugin *lightdash) +{ + lightdash->show_desktop = gtk_toggle_button_get_active (button); +} + +void lightdash_configure (XfcePanelPlugin *plugin, + LightdashPlugin *lightdash) +{ + GtkWidget *dialog; + GtkWidget *hbox; + GtkWidget *label; + GtkWidget *entry; + GtkWidget *opacity_slider; + GtkWidget *show_desktop_button; + GtkWidget *toplevel; + GtkWindow *window; + + window = NULL; + + toplevel = gtk_widget_get_toplevel (GTK_WIDGET (plugin)); + + if (gtk_widget_is_toplevel (toplevel)) + { + window = GTK_WINDOW (toplevel); + } + + xfce_panel_plugin_block_menu (plugin); + + dialog = xfce_titled_dialog_new_with_buttons (_("lightdash"), + window, + GTK_DIALOG_DESTROY_WITH_PARENT + #if GTK_CHECK_VERSION (3, 0, 0) + #else + | GTK_DIALOG_NO_SEPARATOR + #endif + , + GTK_STOCK_HELP, GTK_RESPONSE_HELP, + GTK_STOCK_CLOSE, GTK_RESPONSE_OK, + NULL); + + #if GTK_CHECK_VERSION (3, 0, 0) + hbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0); + #else + hbox = gtk_hbox_new (FALSE, 0); + #endif + + label = gtk_label_new_with_mnemonic (_("_Title:")); + + entry = gtk_entry_new (); + gtk_entry_set_text (GTK_ENTRY (entry), gtk_label_get_text (GTK_LABEL (lightdash->button_label))); + + g_signal_connect (G_OBJECT (entry), "changed", + G_CALLBACK (lightdash_preferences_entry_changed), lightdash); + + gtk_box_pack_start (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (dialog))), + hbox, TRUE, TRUE, 6); + + gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 6); + + gtk_box_pack_start (GTK_BOX (hbox), entry, TRUE, TRUE, 6); + gtk_widget_show_all (hbox); + + + + #if GTK_CHECK_VERSION (3, 0, 0) + hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0); + #else + hbox = gtk_hbox_new (FALSE, 0); + #endif + + opacity_slider = gtk_hscale_new_with_range (0.0, 100.0, 1.0); + gtk_scale_set_value_pos (GTK_SCALE (opacity_slider), GTK_POS_RIGHT); + gtk_widget_set_size_request (GTK_WIDGET (opacity_slider), 200, -1); + gtk_range_set_value (GTK_RANGE (opacity_slider), lightdash->opacity); + + gtk_box_pack_start (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (dialog))), + hbox, TRUE, TRUE, 6); + + label = gtk_label_new_with_mnemonic (_("Background opacit_y:")); + + gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, FALSE, 6); + + gtk_box_pack_start (GTK_BOX (hbox), opacity_slider, TRUE, TRUE, 6); + + g_signal_connect (G_OBJECT (opacity_slider), "value-changed", + G_CALLBACK (lightdash_opacity_slider_changed), lightdash); + + gtk_widget_show_all (hbox); + + show_desktop_button = gtk_check_button_new_with_label (_("Show desktop behind dashboard")); + gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (show_desktop_button), lightdash->show_desktop); + gtk_box_pack_start (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (dialog))), + show_desktop_button, TRUE, TRUE, 6); + g_signal_connect (G_OBJECT (show_desktop_button), "toggled", + G_CALLBACK (lightdash_show_desktop_button_toggled), lightdash); + + + g_object_set_data (G_OBJECT (plugin), "dialog", dialog); + + g_signal_connect (G_OBJECT (dialog), "response", + G_CALLBACK (lightdash_configure_response), lightdash); + + gtk_widget_show_all (dialog); +} diff --git a/pool/shard008/C/0130724_page_180.c b/pool/shard008/C/0130724_page_180.c new file mode 100644 index 0000000000000000000000000000000000000000..a7ed7ef87335ef995a2eaab268576dadf549fb74 --- /dev/null +++ b/pool/shard008/C/0130724_page_180.c @@ -0,0 +1,75 @@ +/* Setup if we need connman? */ +#include "e_wizard.h" + +static int do_tasks = 1; +/* +E_API int +wizard_page_init(E_Wizard_Page *pg EINA_UNUSED, Eina_Bool *need_xdg_desktops EINA_UNUSED, Eina_Bool *need_xdg_icons EINA_UNUSED) +{ + return 1; +} + +E_API int +wizard_page_shutdown(E_Wizard_Page *pg EINA_UNUSED) +{ + return 1; +} +*/ +E_API int +wizard_page_show(E_Wizard_Page *pg) +{ + Evas_Object *o, *of, *ob; + + o = e_widget_list_add(pg->evas, 1, 0); + e_wizard_title_set(_("Taskbar")); + + of = e_widget_framelist_add(pg->evas, _("Information"), 0); + + ob = e_widget_textblock_add(pg->evas); + e_widget_size_min_set(ob, 260 * e_scale, 200 * e_scale); + e_widget_textblock_markup_set + (ob, + _("A taskbar can be added to
" + "show open windows and applications." + ) + ); + e_widget_framelist_object_append(of, ob); + + ob = e_widget_check_add(pg->evas, _("Enable Taskbar"), &(do_tasks)); + e_widget_framelist_object_append(of, ob); + + e_widget_list_object_append(o, of, 0, 0, 0.5); + + evas_object_show(of); + + e_wizard_page_show(o); + return 1; /* 1 == show ui, and wait for user, 0 == just continue */ +} +/* +E_API int +wizard_page_hide(E_Wizard_Page *pg EINA_UNUSED) +{ + return 1; +} +*/ +E_API int +wizard_page_apply(E_Wizard_Page *pg EINA_UNUSED) +{ + E_Config_Module *em; + Eina_List *l; + + if (do_tasks) return 1; + + EINA_LIST_FOREACH(e_config->modules, l, em) + { + if (!em->name) continue; + if (strcmp(em->name, "tasks")) continue; + e_config->modules = eina_list_remove_list(e_config->modules, l); + eina_stringshare_del(em->name); + free(em); + break; + } + + return 1; +} + diff --git a/pool/shard008/C/0130725_f16.c b/pool/shard008/C/0130725_f16.c new file mode 100644 index 0000000000000000000000000000000000000000..f081a43dbb754828975b4d56e80fe54117ef293b --- /dev/null +++ b/pool/shard008/C/0130725_f16.c @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2021 Stephanos Ioannidis + * Copyright (C) 2010-2021 ARM Limited or its affiliates. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include +#include +#include +#include "../../common/test_common.h" + +#include "f16.pat" + +#define REL_ERROR_THRESH (3.0e-3) + +void test_gaussian_naive_bayes_predict_f16(void) +{ + arm_gaussian_naive_bayes_instance_f16 inst; + + size_t index; + const uint16_t pattern_count = in_dims[0]; + const uint16_t class_count = in_dims[1]; + const uint16_t vec_dims = in_dims[2]; + + const float16_t *params = (const float16_t *)in_param; + const float16_t *input = (const float16_t *)in_val; + float16_t *output_probs_buf, *output_probs; + uint16_t *output_preds_buf, *output_preds; + float16_t *temp; + + /* Initialise instance */ + inst.vectorDimension = vec_dims; + inst.numberOfClasses = class_count; + inst.theta = params; + inst.sigma = params + (class_count * vec_dims); + inst.classPriors = params + (2 * class_count * vec_dims); + inst.epsilon = params[class_count + (2 * class_count * vec_dims)]; + + /* Allocate output buffers */ + output_probs_buf = + malloc(pattern_count * class_count * sizeof(float16_t)); + zassert_not_null(output_probs_buf, ASSERT_MSG_BUFFER_ALLOC_FAILED); + + output_preds_buf = + malloc(pattern_count * sizeof(uint16_t)); + zassert_not_null(output_preds_buf, ASSERT_MSG_BUFFER_ALLOC_FAILED); + + output_probs = output_probs_buf; + output_preds = output_preds_buf; + + temp = malloc(pattern_count * class_count * sizeof(float16_t)); + zassert_not_null(temp, ASSERT_MSG_BUFFER_ALLOC_FAILED); + + /* Enumerate patterns */ + for (index = 0; index < pattern_count; index++) { + /* Run test function */ + *output_preds = + arm_gaussian_naive_bayes_predict_f16( + &inst, input, output_probs, temp); + + /* Increment pointers */ + input += vec_dims; + output_probs += class_count; + output_preds++; + } + + /* Validate output */ + zassert_true( + test_rel_error_f16(pattern_count, output_probs_buf, + (float16_t *)ref_prob, REL_ERROR_THRESH), + ASSERT_MSG_REL_ERROR_LIMIT_EXCEED); + + zassert_true( + test_equal_q15(pattern_count, output_preds_buf, ref_pred), + ASSERT_MSG_INCORRECT_COMP_RESULT); + + /* Free output buffers */ + free(output_probs_buf); + free(output_preds_buf); +} + +void test_bayes_f16(void) +{ + ztest_test_suite(bayes_f16, + ztest_unit_test(test_gaussian_naive_bayes_predict_f16) + ); + + ztest_run_test_suite(bayes_f16); +} diff --git a/pool/shard008/C/0130726_tsinh_cosh.c b/pool/shard008/C/0130726_tsinh_cosh.c new file mode 100644 index 0000000000000000000000000000000000000000..ea400039f9b016b03d270bef940a6818d5c3735f --- /dev/null +++ b/pool/shard008/C/0130726_tsinh_cosh.c @@ -0,0 +1,143 @@ +/* Test file for mpfr_sinh_cosh. + +Copyright 2007, 2008, 2009 Free Software Foundation, Inc. +Contributed by the Arenaire and Cacao projects, INRIA. + +This file is part of the GNU MPFR Library. + +The GNU MPFR 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. + +The GNU MPFR 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. + +You should have received a copy of the GNU Lesser General Public License +along with the GNU MPFR Library; see the file COPYING.LIB. If not, write to +the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, +MA 02110-1301, USA. */ + +#include +#include + +#include "mpfr-test.h" + +#if MPFR_VERSION >= MPFR_VERSION_NUM(2,4,0) + +static void +failed (mpfr_t x, mpfr_t esh, mpfr_t gsh, mpfr_t ech, mpfr_t gch) +{ + printf ("error : mpfr_sinh_cosh (x) x = "); + mpfr_out_str (stdout, 10, 0, x, GMP_RNDD); + printf ("\nsinh(x) expected "); + mpfr_out_str (stdout, 10, 0, esh, GMP_RNDD); + printf ("\n got "); + mpfr_out_str (stdout, 10, 0, gsh, GMP_RNDD); + printf ("\ncosh(x) expected "); + mpfr_out_str (stdout, 10, 0, ech, GMP_RNDD); + printf ("\n got "); + mpfr_out_str (stdout, 10, 0, gch, GMP_RNDD); + putchar ('\n'); + + mpfr_clears (x, esh, gsh, ech, gch, (mpfr_ptr) 0); + exit (1); +} + +/* check against sinh, cosh */ +static void +check (mpfr_t x, mp_rnd_t rnd) +{ + mpfr_t s, c, sx, cx; + int isc, is, ic; + + mpfr_inits2 (MPFR_PREC(x), s, c, sx, cx, (mpfr_ptr) 0); + + isc = mpfr_sinh_cosh (sx, cx, x, rnd); + is = mpfr_sinh (s, x, rnd); + ic = mpfr_cosh (c, x, rnd); + + if (!mpfr_equal_p (s, sx) || !mpfr_equal_p (c, cx)) + failed (x, s, sx, c, cx); + MPFR_ASSERTN (isc = is || ic); + + mpfr_clears (s, c, sx, cx, (mpfr_ptr) 0); +} + +static void +check_nans (void) +{ + mpfr_t x, sh, ch; + + mpfr_init2 (x, 123); + mpfr_init2 (sh, 123); + mpfr_init2 (ch, 123); + + /* nan */ + mpfr_set_nan (x); + mpfr_sinh_cosh (sh, ch, x, GMP_RNDN); + MPFR_ASSERTN (mpfr_nan_p (sh)); + MPFR_ASSERTN (mpfr_nan_p (ch)); + + /* +inf */ + mpfr_set_inf (x, 1); + mpfr_sinh_cosh (sh, ch, x, GMP_RNDN); + MPFR_ASSERTN (mpfr_inf_p (sh)); + MPFR_ASSERTN (mpfr_sgn (sh) > 0); + MPFR_ASSERTN (mpfr_inf_p (ch)); + MPFR_ASSERTN (mpfr_sgn (ch) > 0); + + /* -inf */ + mpfr_set_inf (x, -1); + mpfr_sinh_cosh (sh, ch, x, GMP_RNDN); + MPFR_ASSERTN (mpfr_inf_p (sh)); + MPFR_ASSERTN (mpfr_sgn (sh) < 0); + MPFR_ASSERTN (mpfr_inf_p (ch)); + MPFR_ASSERTN (mpfr_sgn (ch) > 0); + + mpfr_clear (x); + mpfr_clear (sh); + mpfr_clear (ch); +} + +int +main (int argc, char *argv[]) +{ + int i; + mpfr_t x; + + tests_start_mpfr (); + + check_nans (); + + /* check against values given by sinh(x), cosh(x) */ + mpfr_init2 (x, 53); + mpfr_set_str (x, "FEDCBA987654321p-48", 16, GMP_RNDN); + for (i = 0; i < 10; ++i) + { + /* x = i - x / 2 : boggle sign and bits */ + mpfr_ui_sub (x, i, x, GMP_RNDD); + mpfr_div_2ui (x, x, 2, GMP_RNDD); + + check (x, GMP_RNDN); + check (x, GMP_RNDU); + check (x, GMP_RNDD); + } + mpfr_clear (x); + + tests_end_mpfr (); + return 0; +} + +#else + +int +main (void) +{ + printf ("Warning! Test disabled for this MPFR version.\n"); + return 0; +} + +#endif diff --git a/pool/shard008/C/0130728_vmem.c b/pool/shard008/C/0130728_vmem.c new file mode 100644 index 0000000000000000000000000000000000000000..6775d20ddf0b3b4788fb4132d8359334af1d045b --- /dev/null +++ b/pool/shard008/C/0130728_vmem.c @@ -0,0 +1,284 @@ +/** + * collectd - src/vmem.c + * Copyright (C) 2008 Florian octo Forster + * + * 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; only version 2 of the License is applicable. + * + * 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 St, Fifth Floor, Boston, MA 02110-1301 USA + * + * Authors: + * Florian octo Forster + **/ + +#include "collectd.h" +#include "common.h" +#include "plugin.h" + +#if KERNEL_LINUX +static const char *config_keys[] = +{ + "Verbose" +}; +static int config_keys_num = STATIC_ARRAY_SIZE (config_keys); + +static int verbose_output = 0; +/* #endif KERNEL_LINUX */ + +#else +# error "No applicable input method." +#endif /* HAVE_LIBSTATGRAB */ + +static void submit (const char *plugin_instance, const char *type, + const char *type_instance, value_t *values, int values_len) +{ + value_list_t vl = VALUE_LIST_INIT; + + vl.values = values; + vl.values_len = values_len; + + sstrncpy (vl.host, hostname_g, sizeof (vl.host)); + sstrncpy (vl.plugin, "vmem", sizeof (vl.plugin)); + if (plugin_instance != NULL) + sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance)); + sstrncpy (vl.type, type, sizeof (vl.type)); + if (type_instance != NULL) + sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance)); + + plugin_dispatch_values (&vl); +} /* void vmem_submit */ + +static void submit_two (const char *plugin_instance, const char *type, + const char *type_instance, counter_t c0, counter_t c1) +{ + value_t values[2]; + + values[0].counter = c0; + values[1].counter = c1; + + submit (plugin_instance, type, type_instance, values, 2); +} /* void submit_one */ + +static void submit_one (const char *plugin_instance, const char *type, + const char *type_instance, value_t value) +{ + submit (plugin_instance, type, type_instance, &value, 1); +} /* void submit_one */ + +static int vmem_config (const char *key, const char *value) +{ + if (strcasecmp ("Verbose", key) == 0) + { + if ((strcasecmp ("true", value) == 0) + || (strcasecmp ("yes", value) == 0) + || (strcasecmp ("on", value) == 0)) + verbose_output = 1; + else + verbose_output = 0; + } + else + { + return (-1); + } + + return (0); +} /* int vmem_config */ + +static int vmem_read (void) +{ +#if KERNEL_LINUX + counter_t pgpgin = 0; + counter_t pgpgout = 0; + int pgpgvalid = 0; + + counter_t pswpin = 0; + counter_t pswpout = 0; + int pswpvalid = 0; + + counter_t pgfault = 0; + counter_t pgmajfault = 0; + int pgfaultvalid = 0; + + FILE *fh; + char buffer[1024]; + + fh = fopen ("/proc/vmstat", "r"); + if (fh == NULL) + { + char errbuf[1024]; + ERROR ("vmem plugin: fopen (/proc/vmstat) failed: %s", + sstrerror (errno, errbuf, sizeof (errbuf))); + return (-1); + } + + while (fgets (buffer, sizeof (buffer), fh) != NULL) + { + char *fields[4]; + int fields_num; + char *key; + char *endptr; + counter_t counter; + gauge_t gauge; + + fields_num = strsplit (buffer, fields, STATIC_ARRAY_SIZE (fields)); + if (fields_num != 2) + continue; + + key = fields[0]; + + endptr = NULL; + counter = strtoll (fields[1], &endptr, 10); + if (fields[1] == endptr) + continue; + + endptr = NULL; + gauge = strtod (fields[1], &endptr); + if (fields[1] == endptr) + continue; + + /* + * Number of pages + * + * The total number of {inst} pages, e. g dirty pages. + */ + if (strncmp ("nr_", key, strlen ("nr_")) == 0) + { + char *inst = key + strlen ("nr_"); + value_t value = { .gauge = gauge }; + submit_one (NULL, "vmpage_number", inst, value); + } + + /* + * Page in and page outs. For memory and swap. + */ + else if (strcmp ("pgpgin", key) == 0) + { + pgpgin = counter; + pgpgvalid |= 0x01; + } + else if (strcmp ("pgpgout", key) == 0) + { + pgpgout = counter; + pgpgvalid |= 0x02; + } + else if (strcmp ("pswpin", key) == 0) + { + pswpin = counter; + pswpvalid |= 0x01; + } + else if (strcmp ("pswpout", key) == 0) + { + pswpout = counter; + pswpvalid |= 0x02; + } + + /* + * Pagefaults + */ + else if (strcmp ("pgfault", key) == 0) + { + pgfault = counter; + pgfaultvalid |= 0x01; + } + else if (strcmp ("pgmajfault", key) == 0) + { + pgmajfault = counter; + pgfaultvalid |= 0x02; + } + + /* + * Skip the other statistics if verbose output is disabled. + */ + else if (verbose_output == 0) + continue; + + /* + * Number of page allocations, refills, steals and scans. This is collected + * ``per zone'', i. e. for DMA, DMA32, normal and possibly highmem. + */ + else if (strncmp ("pgalloc_", key, strlen ("pgalloc_")) == 0) + { + char *inst = key + strlen ("pgalloc_"); + value_t value = { .counter = counter }; + submit_one (inst, "vmpage_action", "alloc", value); + } + else if (strncmp ("pgrefill_", key, strlen ("pgrefill_")) == 0) + { + char *inst = key + strlen ("pgrefill_"); + value_t value = { .counter = counter }; + submit_one (inst, "vmpage_action", "refill", value); + } + else if (strncmp ("pgsteal_", key, strlen ("pgsteal_")) == 0) + { + char *inst = key + strlen ("pgsteal_"); + value_t value = { .counter = counter }; + submit_one (inst, "vmpage_action", "steal", value); + } + else if (strncmp ("pgscan_kswapd_", key, strlen ("pgscan_kswapd_")) == 0) + { + char *inst = key + strlen ("pgscan_kswapd_"); + value_t value = { .counter = counter }; + submit_one (inst, "vmpage_action", "scan_kswapd", value); + } + else if (strncmp ("pgscan_direct_", key, strlen ("pgscan_direct_")) == 0) + { + char *inst = key + strlen ("pgscan_direct_"); + value_t value = { .counter = counter }; + submit_one (inst, "vmpage_action", "scan_direct", value); + } + + /* + * Page action + * + * number of pages moved to the active or inactive lists and freed, i. e. + * removed from either list. + */ + else if (strcmp ("pgfree", key) == 0) + { + value_t value = { .counter = counter }; + submit_one (NULL, "vmpage_action", "free", value); + } + else if (strcmp ("pgactivate", key) == 0) + { + value_t value = { .counter = counter }; + submit_one (NULL, "vmpage_action", "activate", value); + } + else if (strcmp ("pgdeactivate", key) == 0) + { + value_t value = { .counter = counter }; + submit_one (NULL, "vmpage_action", "deactivate", value); + } + } /* while (fgets) */ + + fclose (fh); + fh = NULL; + + if (pgfaultvalid == 0x03) + submit_two (NULL, "vmpage_faults", NULL, pgfault, pgmajfault); + + if (pgpgvalid == 0x03) + submit_two (NULL, "vmpage_io", "memory", pgpgin, pgpgout); + + if (pswpvalid == 0x03) + submit_two (NULL, "vmpage_io", "swap", pswpin, pswpout); +#endif /* KERNEL_LINUX */ + + return (0); +} /* int vmem_read */ + +void module_register (void) +{ + plugin_register_config ("vmem", vmem_config, + config_keys, config_keys_num); + plugin_register_read ("vmem", vmem_read); +} /* void module_register */ + +/* vim: set sw=2 sts=2 ts=8 : */ diff --git a/pool/shard008/C/0130729_init.c b/pool/shard008/C/0130729_init.c new file mode 100644 index 0000000000000000000000000000000000000000..89d08ba9a728a881f6b7e10a4407ca0a9f1e935f --- /dev/null +++ b/pool/shard008/C/0130729_init.c @@ -0,0 +1,220 @@ +/* + * COPYRIGHT (c) 1989-2014. + * On-Line Applications Research Corporation (OAR). + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rtems.com/license/LICENSE. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include "test_support.h" + +#include +#include +#include +#include +#include +#include + +/* forward declarations to avoid warnings */ +rtems_task Init(rtems_task_argument argument); +void create_all_barriers(void); +void create_all_semaphores(void); +void delete_barrier(void); +void delete_semaphore(void); +void create_fifo(void); +void open_fifo(int expected, int flags); + +#define MAXIMUM 10 +#define NUM_OPEN_REQ 26 + +rtems_id Barriers[MAXIMUM]; +int BarrierCount; + +rtems_id Semaphores[MAXIMUM]; +int SemaphoreCount; + +void create_all_barriers(void) +{ + rtems_status_code status; + int i; + + BarrierCount = 0; + + memset( Barriers, 0, sizeof(Barriers) ); + for ( i=0 ; i +/* end of file */ diff --git a/pool/shard008/C/0130734_hdkeys.c b/pool/shard008/C/0130734_hdkeys.c new file mode 100644 index 0000000000000000000000000000000000000000..71d033ac56037c002c74c90c21c4a8063fe1684e --- /dev/null +++ b/pool/shard008/C/0130734_hdkeys.c @@ -0,0 +1,209 @@ +/* Copyright 2016 BitPay, Inc. + * Copyright 2016 Duncan Tebbs + * Distributed under the MIT/X11 software license, see the accompanying + * file COPYING or http://www.opensource.org/licenses/mit-license.php. + */ + +#include +#include +#include +#include +#include +#include + +#define MAIN_PUBLIC 0x0488B21E +#define MAIN_PRIVATE 0x0488ADE4 +#define TEST_PUBLIC 0x043587CF +#define TEST_PRIVATE 0x04358394 + +void hd_extended_key_init(struct hd_extended_key *ek) +{ + memset(ek, 0, sizeof(*ek)); + bp_key_init(&ek->key); +} + +void hd_extended_key_free(struct hd_extended_key *ek) +{ + bp_key_free(&ek->key); +} + +bool hd_extended_key_deser(struct hd_extended_key *ek, const void *_data, + size_t len) +{ + if (78 != len && 82 != len) return false; + + struct const_buffer buf = { _data, len }; + uint32_t version; + + if (!deser_u32(&version, &buf)) return false; + ek->version = version = be32toh(version); + if (!deser_bytes(&ek->depth, &buf, 1)) return false; + if (!deser_bytes(&ek->parent_fingerprint, &buf, 4)) return false; + if (!deser_u32(&ek->index, &buf)) return false; + ek->index = be32toh(ek->index); + if (!deser_bytes(&ek->chaincode.data, &buf, 32)) return false; + + if (MAIN_PUBLIC == version || TEST_PUBLIC == version) { + if (bp_pubkey_set(&ek->key, buf.p, 33)) { + return true; + } + } else if (MAIN_PRIVATE == version || TEST_PRIVATE == version) { + uint8_t zero; + if (deser_bytes(&zero, &buf, 1) && 0 == zero) { + if (bp_key_secret_set(&ek->key, buf.p, 32)) { + return true; + } + } + } + + return false; +} + +static void hd_extended_key_ser_base(const struct hd_extended_key *ek, + cstring *s, uint32_t version) +{ + ser_u32(s, htobe32(version)); + ser_bytes(s, &ek->depth, 1); + ser_bytes(s, &ek->parent_fingerprint, 4); + ser_u32(s, htobe32(ek->index)); + ser_bytes(s, &ek->chaincode, 32); +} + +bool hd_extended_key_ser_pub(const struct hd_extended_key *ek, cstring *s) +{ + hd_extended_key_ser_base(ek, s, MAIN_PUBLIC); + + void *pub = NULL; + size_t pub_len = 0; + if (bp_pubkey_get(&ek->key, &pub, &pub_len)) { + if (33 == pub_len) { + ser_bytes(s, pub, 33); + free(pub); + return true; + } + } + free(pub); + return false; +} + +bool hd_extended_key_ser_priv(const struct hd_extended_key *ek, cstring *s) +{ + hd_extended_key_ser_base(ek, s, MAIN_PRIVATE); + + const uint8_t zero = 0; + ser_bytes(s, &zero, 1); + return bp_key_secret_get(s->str + s->len, 32, &ek->key); +} + +bool hd_extended_key_generate_master(struct hd_extended_key *ek, + const void *seed, size_t seed_len) +{ + static const uint8_t key[12] = "Bitcoin seed"; + uint8_t I[64]; + hmac_sha512(key, (uint32_t )sizeof(key), seed, (uint32_t )seed_len, I); + + if (bp_key_secret_set(&ek->key, I, 32)) { + memcpy(ek->chaincode.data, &I[32], 32); + ek->index = 0; + ek->version = MAIN_PRIVATE; // get's set public / private during + memset(ek->parent_fingerprint, 0, 4); + ek->depth = 0; + + return true; + } + + return false; +} + +bool hd_extended_key_generate_child(const struct hd_extended_key *parent, + uint32_t index, + struct hd_extended_key *out_child) +{ + bool result = false; + void *parent_pub = NULL; + size_t parent_pub_len = 0; + + uint8_t data[33 + sizeof(uint32_t)]; + if (0 != (0x80000000 & index)) { + + if (!bp_key_secret_get(&data[1], 32, &parent->key)) { + return false; + } + data[0] = 0; + + if (!bp_pubkey_get(&parent->key, &parent_pub, &parent_pub_len)) { + return false; + } + + } else { + + if (!bp_pubkey_get(&parent->key, &parent_pub, &parent_pub_len)) { + return false; + } + memcpy(&data[0], parent_pub, parent_pub_len); + + } + + if (33 != parent_pub_len) { + goto free_parent_pub; + } + + const uint32_t indexBE = htobe32(index); + memcpy(&data[33], &indexBE, sizeof(uint32_t)); + + uint8_t I[64]; + hmac_sha512(parent->chaincode.data, (int)sizeof(parent->chaincode.data), + data, (int)sizeof(data), I); + + if (!bp_key_add_secret(&out_child->key, &parent->key, I)) { + goto free_parent_pub; + } + + uint8_t md160[RIPEMD160_DIGEST_LENGTH]; + bu_Hash160(md160, parent_pub, parent_pub_len); + + memcpy(out_child->chaincode.data, &I[32], 32); + out_child->index = index; + out_child->version = parent->version; + memcpy(out_child->parent_fingerprint, md160, 4); + out_child->depth = parent->depth + 1; + result = true; + +free_parent_pub: + free(parent_pub); + + return result; +} + +bool hd_derive(struct hd_extended_key *out_child, + const struct hd_extended_key *parent_, + const struct hd_path_seg *hdpath, + size_t hdpath_len) +{ + struct hd_extended_key parent; + memcpy(&parent, parent_, sizeof(parent)); + + unsigned int i; + for (i = 0; i < hdpath_len; i++) { + bool is_last = (i == (hdpath_len - 1)); + + uint32_t val = hdpath[i].index; + if (hdpath[i].hardened) + val |= 0x80000000; + + struct hd_extended_key tmp; + struct hd_extended_key *target = &tmp; + if (is_last) + target = out_child; + + hd_extended_key_init(&tmp); + if (!hd_extended_key_generate_child(&parent, val, target)) + return false; + + if (!is_last) + memcpy(&parent, &tmp, sizeof(tmp)); + } + + return true; +} + diff --git a/pool/shard008/C/0130735_t-pow_ui.c b/pool/shard008/C/0130735_t-pow_ui.c new file mode 100644 index 0000000000000000000000000000000000000000..97ccb412bb2a4b26a21efe4f33499698523810dd --- /dev/null +++ b/pool/shard008/C/0130735_t-pow_ui.c @@ -0,0 +1,82 @@ +/* + Copyright (C) 2013 Fredrik Johansson + + This file is part of Arb. + + Arb is free software: you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License (LGPL) as published + by the Free Software Foundation; either version 2.1 of the License, or + (at your option) any later version. See . +*/ + +#include "acb_poly.h" + +int main() +{ + slong iter; + flint_rand_t state; + + flint_printf("pow_ui...."); + fflush(stdout); + + flint_randinit(state); + + /* compare with fmpz_poly */ + for (iter = 0; iter < 10000 * arb_test_multiplier(); iter++) + { + slong zbits1, rbits1, rbits2; + ulong e; + fmpz_poly_t A, B; + acb_poly_t a, b; + + zbits1 = 2 + n_randint(state, 100); + rbits1 = 2 + n_randint(state, 200); + rbits2 = 2 + n_randint(state, 200); + e = n_randint(state, 30); + + fmpz_poly_init(A); + fmpz_poly_init(B); + + acb_poly_init(a); + acb_poly_init(b); + + fmpz_poly_randtest(A, state, 1 + n_randint(state, 8), zbits1); + fmpz_poly_pow(B, A, e); + + acb_poly_set_fmpz_poly(a, A, rbits1); + acb_poly_pow_ui(b, a, e, rbits2); + + if (!acb_poly_contains_fmpz_poly(b, B)) + { + flint_printf("FAIL\n\n"); + flint_printf("bits2 = %wd\n", rbits2); + flint_printf("e = %wu\n", e); + + flint_printf("A = "); fmpz_poly_print(A); flint_printf("\n\n"); + flint_printf("B = "); fmpz_poly_print(B); flint_printf("\n\n"); + + flint_printf("a = "); acb_poly_printd(a, 15); flint_printf("\n\n"); + flint_printf("b = "); acb_poly_printd(b, 15); flint_printf("\n\n"); + + flint_abort(); + } + + acb_poly_pow_ui(a, a, e, rbits2); + if (!acb_poly_equal(a, b)) + { + flint_printf("FAIL (aliasing)\n\n"); + flint_abort(); + } + + fmpz_poly_clear(A); + fmpz_poly_clear(B); + + acb_poly_clear(a); + acb_poly_clear(b); + } + + flint_randclear(state); + flint_cleanup(); + flint_printf("PASS\n"); + return EXIT_SUCCESS; +} diff --git a/pool/shard008/C/0130737_virtio-rng.c b/pool/shard008/C/0130737_virtio-rng.c new file mode 100644 index 0000000000000000000000000000000000000000..171380bd2256b20398068b7425279688290a98b7 --- /dev/null +++ b/pool/shard008/C/0130737_virtio-rng.c @@ -0,0 +1,149 @@ +/* + * Randomness driver for virtio + * Copyright (C) 2007, 2008 Rusty Russell IBM Corporation + * + * 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 St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include +#include +#include +#include +#include + +static struct virtqueue *vq; +static unsigned int data_avail; +static DECLARE_COMPLETION(have_data); +static bool busy; + +static void random_recv_done(struct virtqueue *vq) +{ + /* We can get spurious callbacks, e.g. shared IRQs + virtio_pci. */ + if (!virtqueue_get_buf(vq, &data_avail)) + return; + + complete(&have_data); +} + +/* The host will fill any buffer we give it with sweet, sweet randomness. */ +static void register_buffer(u8 *buf, size_t size) +{ + struct scatterlist sg; + + sg_init_one(&sg, buf, size); + + /* There should always be room for one buffer. */ + if (virtqueue_add_buf(vq, &sg, 0, 1, buf, GFP_KERNEL) < 0) + BUG(); + + virtqueue_kick(vq); +} + +static int virtio_read(struct hwrng *rng, void *buf, size_t size, bool wait) +{ + + if (!busy) { + busy = true; + init_completion(&have_data); + register_buffer(buf, size); + } + + if (!wait) + return 0; + + wait_for_completion(&have_data); + + busy = false; + + return data_avail; +} + +static void virtio_cleanup(struct hwrng *rng) +{ + if (busy) + wait_for_completion(&have_data); +} + + +static struct hwrng virtio_hwrng = { + .name = "virtio", + .cleanup = virtio_cleanup, + .read = virtio_read, +}; + +static int virtrng_probe(struct virtio_device *vdev) +{ + int err; + + if (vq) { + /* We only support one device for now */ + return -EBUSY; + } + /* We expect a single virtqueue. */ + vq = virtio_find_single_vq(vdev, random_recv_done, "input"); + if (IS_ERR(vq)) { + err = PTR_ERR(vq); + vq = NULL; + return err; + } + + err = hwrng_register(&virtio_hwrng); + if (err) { + vdev->config->del_vqs(vdev); + vq = NULL; + return err; + } + + return 0; +} + +static void __devexit virtrng_remove(struct virtio_device *vdev) +{ + vdev->config->reset(vdev); + hwrng_unregister(&virtio_hwrng); + vdev->config->del_vqs(vdev); + vq = NULL; +} + +static struct virtio_device_id id_table[] = { + { VIRTIO_ID_RNG, VIRTIO_DEV_ANY_ID }, + { 0 }, +}; + +static struct virtio_driver virtio_rng_driver = { + .driver.name = KBUILD_MODNAME, + .driver.owner = THIS_MODULE, + .id_table = id_table, + .probe = virtrng_probe, + .remove = __devexit_p(virtrng_remove), +}; + +static int __init init(void) +{ + return register_virtio_driver(&virtio_rng_driver); +} + +static void __exit fini(void) +{ + unregister_virtio_driver(&virtio_rng_driver); +} +module_init(init); +module_exit(fini); + +MODULE_DEVICE_TABLE(virtio, id_table); +MODULE_DESCRIPTION("Virtio random number driver"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard008/C/0130739_webp.c b/pool/shard008/C/0130739_webp.c new file mode 100644 index 0000000000000000000000000000000000000000..191d0451de18564726216ceab779ecba661d46b0 --- /dev/null +++ b/pool/shard008/C/0130739_webp.c @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2016 Glyptodon, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include "config.h" +#include "log.h" +#include "webp.h" + +#include +#include +#include + +#include +#include + +cairo_surface_t* guacenc_webp_decoder(unsigned char* data, int length) { + + int width, height; + + /* Validate WebP and pull dimensions */ + if (!WebPGetInfo((uint8_t*) data, length, &width, &height)) { + guacenc_log(GUAC_LOG_WARNING, "Invalid WebP data"); + return NULL; + } + + /* Create blank Cairo surface */ + cairo_surface_t* surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, + width, height); + + /* Fill surface with opaque black */ + cairo_t* cairo = cairo_create(surface); + cairo_set_operator(cairo, CAIRO_OPERATOR_SOURCE); + cairo_set_source_rgba(cairo, 0.0, 0.0, 0.0, 1.0); + cairo_paint(cairo); + cairo_destroy(cairo); + + /* Finish any pending draws */ + cairo_surface_flush(surface); + + /* Pull underlying buffer and its stride */ + int stride = cairo_image_surface_get_stride(surface); + unsigned char* image = cairo_image_surface_get_data(surface); + + /* Read WebP into surface */ + uint8_t* result = WebPDecodeBGRAInto((uint8_t*) data, length, + (uint8_t*) image, stride * height, stride); + + /* Verify WebP was successfully decoded */ + if (result == NULL) { + guacenc_log(GUAC_LOG_WARNING, "Invalid WebP data"); + cairo_surface_destroy(surface); + return NULL; + } + + /* WebP was read successfully */ + return surface; + +} + diff --git a/pool/shard008/C/0130741_time_QR_UT_inc.c b/pool/shard008/C/0130741_time_QR_UT_inc.c new file mode 100644 index 0000000000000000000000000000000000000000..ad49d956bcbe2d927412337b30140b6e4db0b191 --- /dev/null +++ b/pool/shard008/C/0130741_time_QR_UT_inc.c @@ -0,0 +1,107 @@ +/* + + Copyright (C) 2014, The University of Texas at Austin + + This file is part of libflame and is available under the 3-Clause + BSD license, which can be found in the LICENSE file at the top-level + directory, or at http://opensource.org/licenses/BSD-3-Clause + +*/ + + +#include "FLAME.h" + +#define FLA_ALG_FRONT 0 +#define FLA_ALG_FRONT_ALT 1 + + +void time_QR_UT_inc( + int param_combo, int type, int nrepeats, int m, int n, + FLA_Obj A, FLA_Obj TW, FLA_Obj b, FLA_Obj x, + double *dtime, double *diff, double *gflops ); + + +void time_QR_UT_inc( + int param_combo, int type, int nrepeats, int m, int n, + FLA_Obj A, FLA_Obj TW, FLA_Obj b, FLA_Obj x, + double *dtime, double *diff, double *gflops ) +{ + int + irep; + + double + dtime_old = 1.0e9; + + FLA_Obj A_save; + + FLASH_Obj_create_copy_of( FLA_NO_TRANSPOSE, A, &A_save ); + + for ( irep = 0 ; irep < nrepeats; irep++ ) + { + FLASH_Copy( A_save, A ); + + *dtime = FLA_Clock(); + + switch( param_combo ){ + + // Time parameter combination 0 + case 0:{ + switch( type ){ + case FLA_ALG_FRONT: + FLASH_QR_UT_inc_noopt( A, TW ); + break; + case FLA_ALG_FRONT_ALT: + FLASH_QR_UT_inc_opt1( A, TW ); + break; + default: + printf("trouble\n"); + } + + break; + } + + } + + *dtime = FLA_Clock() - *dtime; + dtime_old = min( *dtime, dtime_old ); + } + + { + FLA_Obj A_save_flat, x_flat, b_flat, y_flat; + FLA_Obj norm; + + FLASH_Obj_create_flat_copy_of_hier( A_save, &A_save_flat ); + FLASH_Obj_create_flat_copy_of_hier( b, &b_flat ); + FLASH_Obj_create_flat_conf_to_hier( FLA_NO_TRANSPOSE, x, &x_flat ); + FLASH_Obj_create_flat_conf_to_hier( FLA_NO_TRANSPOSE, x, &y_flat ); + FLA_Obj_create( FLA_Obj_datatype_proj_to_real( A ), 1, 1, 0, 0, &norm ); + + FLASH_QR_UT_inc_solve( A, TW, b, x ); + + FLASH_Obj_flatten( x, x_flat ); + + FLA_Gemv_external( FLA_NO_TRANSPOSE, FLA_ONE, A_save_flat, x_flat, FLA_MINUS_ONE, b_flat ); + FLA_Gemv_external( FLA_CONJ_TRANSPOSE, FLA_ONE, A_save_flat, b_flat, FLA_ZERO, y_flat ); + FLA_Nrm2_external( y_flat, norm ); + FLA_Obj_extract_real_scalar( norm, diff ); + + FLA_Obj_free( &A_save_flat ); + FLA_Obj_free( &b_flat ); + FLA_Obj_free( &x_flat ); + FLA_Obj_free( &y_flat ); + FLA_Obj_free( &norm ); + } + + *gflops = ( 2.0 * m * n * n - + ( 2.0 / 3.0 ) * n * n * n ) / + dtime_old / + 1.0e9; + + if ( FLA_Obj_is_complex( A ) ) + *gflops *= 4.0; + + *dtime = dtime_old; + + FLASH_Obj_free( &A_save ); +} + diff --git a/pool/shard008/C/0130743_rtl871x_io.c b/pool/shard008/C/0130743_rtl871x_io.c new file mode 100644 index 0000000000000000000000000000000000000000..62eeda02908bf93038b6ffbe23dae6cb30fa04a1 --- /dev/null +++ b/pool/shard008/C/0130743_rtl871x_io.c @@ -0,0 +1,191 @@ +/****************************************************************************** + * rtl871x_io.c + * + * Copyright(c) 2007 - 2010 Realtek Corporation. All rights reserved. + * Linux device driver for RTL8192SU + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * 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, USA + * + * Modifications for inclusion into the Linux staging tree are + * Copyright(c) 2010 Larry Finger. All rights reserved. + * + * Contact information: + * WLAN FAE + * Larry Finger + * + ******************************************************************************/ +/* + * + * The purpose of rtl871x_io.c + * + * a. provides the API + * b. provides the protocol engine + * c. provides the software interface between caller and the hardware interface + * + * For r8712u, both sync/async operations are provided. + * + * Only sync read/write_mem operations are provided. + * + */ + +#define _RTL871X_IO_C_ + +#include "osdep_service.h" +#include "drv_types.h" +#include "rtl871x_io.h" +#include "osdep_intf.h" +#include "usb_ops.h" + +static uint _init_intf_hdl(struct _adapter *padapter, + struct intf_hdl *pintf_hdl) +{ + struct intf_priv *pintf_priv; + void (*set_intf_option)(u32 * poption) = NULL; + void (*set_intf_funs)(struct intf_hdl * pintf_hdl); + void (*set_intf_ops)(struct _io_ops * pops); + uint (*init_intf_priv)(struct intf_priv * pintfpriv); + + set_intf_option = &(r8712_usb_set_intf_option); + set_intf_funs = &(r8712_usb_set_intf_funs); + set_intf_ops = &r8712_usb_set_intf_ops; + init_intf_priv = &r8712_usb_init_intf_priv; + pintf_priv = pintf_hdl->pintfpriv = kmalloc(sizeof(struct intf_priv), + GFP_ATOMIC); + + if (pintf_priv == NULL) + { + goto _init_intf_hdl_fail; + } + + pintf_hdl->adapter = (u8 *)padapter; + set_intf_option(&pintf_hdl->intf_option); + set_intf_funs(pintf_hdl); + set_intf_ops(&pintf_hdl->io_ops); + pintf_priv->intf_dev = (u8 *) & (padapter->dvobjpriv); + + if (init_intf_priv(pintf_priv) == _FAIL) + { + goto _init_intf_hdl_fail; + } + + return _SUCCESS; +_init_intf_hdl_fail: + kfree(pintf_priv); + return _FAIL; +} + +static void _unload_intf_hdl(struct intf_priv *pintfpriv) +{ + void (*unload_intf_priv)(struct intf_priv * pintfpriv); + + unload_intf_priv = &r8712_usb_unload_intf_priv; + unload_intf_priv(pintfpriv); + kfree(pintfpriv); +} + +static uint register_intf_hdl(u8 *dev, struct intf_hdl *pintfhdl) +{ + struct _adapter *adapter = (struct _adapter *)dev; + + pintfhdl->intf_option = 0; + pintfhdl->adapter = dev; + pintfhdl->intf_dev = (u8 *) & (adapter->dvobjpriv); + + if (!_init_intf_hdl(adapter, pintfhdl)) + { + goto register_intf_hdl_fail; + } + + return _SUCCESS; +register_intf_hdl_fail: + return false; +} + +static void unregister_intf_hdl(struct intf_hdl *pintfhdl) +{ + _unload_intf_hdl(pintfhdl->pintfpriv); + memset((u8 *)pintfhdl, 0, sizeof(struct intf_hdl)); +} + +uint r8712_alloc_io_queue(struct _adapter *adapter) +{ + u32 i; + struct io_queue *pio_queue; + struct io_req *pio_req; + + pio_queue = kmalloc(sizeof(*pio_queue), GFP_ATOMIC); + + if (!pio_queue) + { + goto alloc_io_queue_fail; + } + + INIT_LIST_HEAD(&pio_queue->free_ioreqs); + INIT_LIST_HEAD(&pio_queue->processing); + INIT_LIST_HEAD(&pio_queue->pending); + spin_lock_init(&pio_queue->lock); + pio_queue->pallocated_free_ioreqs_buf = kmalloc(NUM_IOREQ * + (sizeof(struct io_req)) + 4, + GFP_ATOMIC); + + if ((pio_queue->pallocated_free_ioreqs_buf) == NULL) + { + goto alloc_io_queue_fail; + } + + memset(pio_queue->pallocated_free_ioreqs_buf, 0, + (NUM_IOREQ * (sizeof(struct io_req)) + 4)); + pio_queue->free_ioreqs_buf = pio_queue->pallocated_free_ioreqs_buf + 4 + - ((addr_t)(pio_queue->pallocated_free_ioreqs_buf) + & 3); + pio_req = (struct io_req *)(pio_queue->free_ioreqs_buf); + + for (i = 0; i < NUM_IOREQ; i++) + { + INIT_LIST_HEAD(&pio_req->list); + list_add_tail(&pio_req->list, &pio_queue->free_ioreqs); + pio_req++; + } + + if ((register_intf_hdl((u8 *)adapter, &(pio_queue->intf))) == _FAIL) + { + goto alloc_io_queue_fail; + } + + adapter->pio_queue = pio_queue; + return _SUCCESS; +alloc_io_queue_fail: + + if (pio_queue) + { + kfree(pio_queue->pallocated_free_ioreqs_buf); + kfree(pio_queue); + } + + adapter->pio_queue = NULL; + return _FAIL; +} + +void r8712_free_io_queue(struct _adapter *adapter) +{ + struct io_queue *pio_queue = adapter->pio_queue; + + if (pio_queue) + { + kfree(pio_queue->pallocated_free_ioreqs_buf); + adapter->pio_queue = NULL; + unregister_intf_hdl(&pio_queue->intf); + kfree(pio_queue); + } +} diff --git a/pool/shard008/C/0130747_early_smbus.c b/pool/shard008/C/0130747_early_smbus.c new file mode 100644 index 0000000000000000000000000000000000000000..39e175305983bc7d10bc5f613e895553e36715e0 --- /dev/null +++ b/pool/shard008/C/0130747_early_smbus.c @@ -0,0 +1,250 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2007-2009 coresystems GmbH + * + * 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; version 2 of the License. + * + * 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 St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +// other bioses use this, too: +#define SMBUS_IO_BASE 0x0500 + +#define SMBHSTSTAT SMBUS_IO_BASE + 0x0 +#define SMBSLVSTAT SMBUS_IO_BASE + 0x1 +#define SMBHSTCTL SMBUS_IO_BASE + 0x2 +#define SMBHSTCMD SMBUS_IO_BASE + 0x3 +#define SMBXMITADD SMBUS_IO_BASE + 0x4 +#define SMBHSTDAT0 SMBUS_IO_BASE + 0x5 +#define SMBHSTDAT1 SMBUS_IO_BASE + 0x6 + +#define SMBBLKDAT SMBUS_IO_BASE + 0x7 +#define SMBSLVCTL SMBUS_IO_BASE + 0x8 +#define SMBTRNSADD SMBUS_IO_BASE + 0x9 +#define SMBSLVDATA SMBUS_IO_BASE + 0xa +#define SMLINK_PIN_CTL SMBUS_IO_BASE + 0xe +#define SMBUS_PIN_CTL SMBUS_IO_BASE + 0xf + +/* Define register settings */ +#define HOST_RESET 0xff +#define READ_CMD 0x01 // 1 in the 0 bit of SMBHSTADD states to READ + +#define SMBUS_TIMEOUT (100*1000*10) + +#define I2C_TRANS_CMD 0x40 +#define CLOCK_SLAVE_ADDRESS 0x69 + +#define SMBUS_DELAY() outb(0x80, 0x80) + +/* Internal functions */ +#if CONFIG_DEBUG_SMBUS +static void smbus_print_error(unsigned char host_status_register, int loops) +{ + /* Check if there actually was an error */ + if (host_status_register == 0x00 || host_status_register == 0x40 || + host_status_register == 0x42) + return; + printk(BIOS_ERR, "SMBus Error: %02x\n", host_status_register); + + if (loops >= SMBUS_TIMEOUT) { + printk(BIOS_ERR, "SMBus Timout\n"); + } + if (host_status_register & (1 << 4)) { + printk(BIOS_ERR, "Interrup/SMI# was Failed Bus Transaction\n"); + } + if (host_status_register & (1 << 3)) { + printk(BIOS_ERR, "Bus Error\n"); + } + if (host_status_register & (1 << 2)) { + printk(BIOS_ERR, "Device Error\n"); + } + if (host_status_register & (1 << 1)) { + /* This isn't a real error... */ + printk(BIOS_DEBUG, "Interrupt/SMI# was Successful Completion\n"); + } + if (host_status_register & (1 << 0)) { + printk(BIOS_ERR, "Host Busy\n"); + } +} +#endif + +static void smbus_wait_until_ready(void) +{ + int loops; + + loops = 0; + + /* Yes, this is a mess, but it's the easiest way to do it */ + while (((inb(SMBHSTSTAT) & 1) == 1) && (loops <= SMBUS_TIMEOUT)) { + SMBUS_DELAY(); + ++loops; + } +#if CONFIG_DEBUG_SMBUS + /* Some systems seem to have a flakey SMBus. No need to spew a lot of + * errors on those, once we know that SMBus access is principally + * working. + */ + smbus_print_error(inb(SMBHSTSTAT), loops); +#endif +} + +static void smbus_reset(void) +{ + outb(HOST_RESET, SMBHSTSTAT); +} + +/* Public functions */ +static void set_ics_data(unsigned char dev, int data, char len) +{ + //int i; + smbus_reset(); + /* clear host data port */ + outb(0x00, SMBHSTDAT0); + SMBUS_DELAY(); + smbus_wait_until_ready(); + + /* read to reset block transfer counter */ + inb(SMBHSTCTL); + + /* fill blocktransfer array */ + if (dev == 0xd2) { + //char d2_data[] = {0x0d,0x00,0x3f,0xcd,0x7f,0xbf,0x1a,0x2a,0x01,0x0f,0x0b,0x00,0x8d,0x9b}; + outb(0x0d, SMBBLKDAT); + outb(0x00, SMBBLKDAT); + outb(0x3f, SMBBLKDAT); + outb(0xcd, SMBBLKDAT); + outb(0x7f, SMBBLKDAT); + outb(0xbf, SMBBLKDAT); + outb(0x1a, SMBBLKDAT); + outb(0x2a, SMBBLKDAT); + outb(0x01, SMBBLKDAT); + outb(0x0f, SMBBLKDAT); + outb(0x0b, SMBBLKDAT); + outb(0x80, SMBBLKDAT); + outb(0x8d, SMBBLKDAT); + outb(0x9b, SMBBLKDAT); + } else { + //char d4_data[] = {0x08,0xff,0x3f,0x00,0x00,0xff,0xff,0xff,0xff}; + outb(0x08, SMBBLKDAT); + outb(0xff, SMBBLKDAT); + outb(0x3f, SMBBLKDAT); + outb(0x00, SMBBLKDAT); + outb(0x00, SMBBLKDAT); + outb(0xff, SMBBLKDAT); + outb(0xff, SMBBLKDAT); + outb(0xff, SMBBLKDAT); + outb(0xff, SMBBLKDAT); + } + + //for (i=0; i < len; i++) + // outb(data[i],SMBBLKDAT); + + outb(dev, SMBXMITADD); + outb(0, SMBHSTCMD); + outb(len, SMBHSTDAT0); + outb(0x74, SMBHSTCTL); + + SMBUS_DELAY(); + + smbus_wait_until_ready(); + + smbus_reset(); + +} + +static unsigned int get_spd_data(const struct mem_controller *ctrl, unsigned int dimm, + unsigned int offset) +{ + unsigned int val, addr; + + smbus_reset(); + + /* clear host data port */ + outb(0x00, SMBHSTDAT0); + SMBUS_DELAY(); + smbus_wait_until_ready(); + + /* Fetch the SMBus address of the SPD ROM from + * the ctrl struct in romstage.c in case they are at + * non-standard positions. + * SMBus Address shifted by 1 + */ + addr = (ctrl->channel0[dimm]) << 1; + + outb(addr | 0x1, SMBXMITADD); + outb(offset, SMBHSTCMD); + outb(0x48, SMBHSTCTL); + + SMBUS_DELAY(); + + smbus_wait_until_ready(); + + val = inb(SMBHSTDAT0); + smbus_reset(); + return val; +} + +static void enable_smbus(void) +{ + device_t dev; + + /* The CX700 ISA Bridge (0x1106, 0x8324) is hardcoded to this location, + * no need to probe. + */ + dev = PCI_DEV(0, 17, 0); + + /* SMBus Clock Select: Divider fof 14.318MHz */ + pci_write_config8(dev, 0x94, 0x20); + + /* SMBus I/O Base, enable SMBus */ + pci_write_config16(dev, 0xd0, SMBUS_IO_BASE | 1); + + /* SMBus Clock from 128K Source, Enable SMBus Host Controller */ + pci_write_config8(dev, 0xd2, 0x05); + + /* Enable I/O decoding */ + pci_write_config16(dev, 0x04, 0x0003); + + /* Setup clock chips */ + set_ics_data(0xd2, 0, 14); + set_ics_data(0xd4, 0, 9); +} + +/* Debugging Function */ +#if CONFIG_DEBUG_SMBUS +static void dump_spd_data(const struct mem_controller *ctrl) +{ + int dimm, offset, regs; + unsigned int val; + + for (dimm = 0; dimm < DIMM_SOCKETS; dimm++) { + printk(BIOS_DEBUG, "SPD Data for DIMM %02x\n", dimm); + + val = get_spd_data(ctrl, dimm, 0); + if (val == 0xff) { + regs = 256; + } else if (val == 0x80) { + regs = 128; + } else { + printk(BIOS_DEBUG, "No DIMM present\n"); + regs = 0; + } + for (offset = 0; offset < regs; offset++) { + printk(BIOS_DEBUG, " Offset %02x = 0x%02x\n", + offset, get_spd_data(ctrl, dimm, offset)); + } + } +} +#else +#define dump_spd_data(ctrl) +#endif diff --git a/pool/shard008/C/0130751_ioperm01.c b/pool/shard008/C/0130751_ioperm01.c new file mode 100644 index 0000000000000000000000000000000000000000..fc5754be9c3915fcf0964174ccd545d37d1069b6 --- /dev/null +++ b/pool/shard008/C/0130751_ioperm01.c @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * Copyright (c) Linux Test Project, 2020 + * Copyright (c) Wipro Technologies Ltd, 2002 + */ + +/* + * This is a basic test for ioperm(2) system call. + * It is intended to provide a limited exposure of the system call. + * + * Author: Subhab Biswas + */ + +#include +#include + +#include "tst_test.h" + +#if defined __i386__ || defined(__x86_64__) +#include + +unsigned long io_addr; +#define NUM_BYTES 3 +#ifndef IO_BITMAP_BITS +#define IO_BITMAP_BITS 1024 +#endif + +static void verify_ioperm(void) +{ + TEST(ioperm(io_addr, NUM_BYTES, 1)); + + if (TST_RET == -1) { + tst_res(TFAIL | TTERRNO, "ioperm() failed for port address " + "%lu, errno=%d : %s", io_addr, + TST_ERR, tst_strerrno(TST_ERR)); + } else { + tst_res(TPASS, "ioperm() passed for port " + "address %lu, returned %lu", + io_addr, TST_RET); + } +} + +static void setup(void) +{ + /* ioperm() is restricted under kernel lockdown. */ + if (tst_lockdown_enabled()) + tst_brk(TCONF, "Kernel is locked down, skip this test"); + + /* + * The value of IO_BITMAP_BITS (include/asm-i386/processor.h) changed + * from kernel 2.6.8 to permit 16-bits ioperm + * + * Ricky Ng-Adam, rngadam@yahoo.com + * */ + if (tst_kvercmp(2, 6, 8) < 0) + io_addr = IO_BITMAP_BITS - NUM_BYTES; + else + io_addr = IO_BITMAP_BITS - NUM_BYTES; +} + +static void cleanup(void) +{ + /* + * Reset I/O privileges for the specified port. + */ + if ((ioperm(io_addr, NUM_BYTES, 0)) == -1) + tst_brk(TBROK | TTERRNO, "ioperm() cleanup failed"); +} + +static struct tst_test test = { + .test_all = verify_ioperm, + .needs_root = 1, + .setup = setup, + .cleanup = cleanup, +}; + +#else +TST_TEST_TCONF("LSB v1.3 does not specify ioperm() for this architecture. (only for i386 or x86_64)"); +#endif /* __i386_, __x86_64__*/ diff --git a/pool/shard008/C/0130758_main.c b/pool/shard008/C/0130758_main.c new file mode 100644 index 0000000000000000000000000000000000000000..1db44d780954ce2ef97c60c4c749c4f6a096a7de --- /dev/null +++ b/pool/shard008/C/0130758_main.c @@ -0,0 +1,83 @@ +#include + +#include "asf.h" +#include "cdc.h" +#include "routing.h" +#include "radio.h" + +void stuff_fifo(uint8_t my_address); +void stuff_fifo(uint8_t my_address) +{ + PacketHeader h; + + h.source = my_address; + h.dest = my_address == 1 ? 2 : 1; + h.type = 0; + uint8_t message[] = "'Sup guys?"; + + if (queuePacket(h, message, sizeof(message))) { + cdc_write_line("Put packet in fifo."); + } +} + +int main(void) +{ + cpu_irq_enable(); + + irq_initialize_vectors(); + + sysclk_init(); + + cdc_start(); + + while (!cdc_opened()); + + cdc_write_line("Routing demo."); + + rtc_init(); + + uint8_t my_address = 1; + uint8_t bullshitbuf[4]; + + while (1) { + cdc_write_string("My address (1-3): "); + cdc_read_string(bullshitbuf, 3); + my_address = (uint8_t)atoi((const char *)bullshitbuf); + cdc_newline(); + + if (my_address >= 1 && my_address <= 3) { + cdc_log_int("You said: ", my_address); + break; + } + + cdc_write_line("Invalid address."); + } + + setupRouting(my_address); // configure router to be node one + + uint32_t then = rtc_get_time(); + + while (1) { + handleReceived(); + + processSendQueue(); + + if (packetsToRead()) { + PacketHeader header; + uint8_t *payload; + uint8_t length = packetReceivedPeek(&header, &payload); + cdc_log_int("Packet type: ", header.type); + cdc_log_string("Received: ", payload); + packetReceivedSkip(); + cdc_newline(); + } + + if (my_address == 1) { + + if (rtc_get_time() - then > 1000) { + stuff_fifo(1); + then = rtc_get_time(); + } + } + } +} diff --git a/pool/shard008/C/0130759_RenderEmpty.c b/pool/shard008/C/0130759_RenderEmpty.c new file mode 100644 index 0000000000000000000000000000000000000000..87688f90461ee594ee40d683d0b16494530e9612 --- /dev/null +++ b/pool/shard008/C/0130759_RenderEmpty.c @@ -0,0 +1,244 @@ +/* -*- c -*- ***************************************************************** +** Copyright (C) 2013 Sandia Corporation +** Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, +** the U.S. Government retains certain rights in this software. +** +** This source code is released under the New BSD License. +** +** This tests the ICET_RENDER_EMPTY_IMAGES option. It makes sure that the +** render callback is invoked even if the option is on and not if the option +** is off. +*****************************************************************************/ + +#include +#include "test_codes.h" +#include "test_util.h" + +#include + +#include +#include +#include + +static const IceTFloat g_background_color[4] = { 0.5, 0.5, 0.5, 1.0 }; +static const IceTFloat g_foreground_color[4] = { 0.0, 0.25, 0.5, 1.0 }; + +IceTBoolean g_render_callback_invoked; +IceTBoolean g_render_callback_parameters_correct; + +static IceTBoolean ColorsEqual(const IceTFloat *color1, const IceTFloat *color2) +{ + IceTBoolean result; + + result = (color1[0] == color2[0]); + result &= (color1[1] == color2[1]); + result &= (color1[2] == color2[2]); + result &= (color1[3] == color2[3]); + + return result; +} + +static void RenderEmptyDraw(const IceTDouble *projection_matrix, + const IceTDouble *modelview_matrix, + const IceTFloat *background_color, + const IceTInt *readback_viewport, + IceTImage result) +{ + IceTSizeType width; + IceTSizeType height; + IceTFloat *colors; + + /* Report that the callback was invoked. */ + g_render_callback_invoked = ICET_TRUE; + + width = icetImageGetWidth(result); + height = icetImageGetHeight(result); + colors = icetImageGetColorf(result); + + /* Set all pixels to something invalid. IceT should be ignoring them. */ + { + IceTSizeType pixel; + for (pixel = 0; pixel < width*height; pixel++) { + colors[4*pixel + 0] = g_foreground_color[0]; + colors[4*pixel + 1] = g_foreground_color[1]; + colors[4*pixel + 2] = g_foreground_color[2]; + colors[4*pixel + 3] = g_foreground_color[3]; + } + } + + g_render_callback_parameters_correct = ICET_TRUE; + + /* Check to make sure that readback_viewport is actually empty. If it is + * not, we can expect an error later when we check the image, but put a + * warning here to help diagnose where the problem is. */ + + if ((readback_viewport[2] != 0) || (readback_viewport[3] != 0)) { + printrank("Got a readback_viewport with a positive dimension: %dx%d\n", + readback_viewport[2], readback_viewport[3]); + g_render_callback_parameters_correct = ICET_FALSE; + } + + /* Even though IceT should ignore anything in the render, it should still + * pass valid rendering parameters. Check them now. */ + if ( (background_color[0] != 0.0f) + || (background_color[1] != 0.0f) + || (background_color[2] != 0.0f) + || (background_color[3] != 0.0f)) { + printrank("Got a bad background color %f %f %f %f.\n", + background_color[0], + background_color[1], + background_color[2], + background_color[3]); + g_render_callback_parameters_correct = ICET_FALSE; + } + { + int column_index; + for (column_index = 0; column_index < 4; column_index++) { + int row_index; + for (row_index = 0; row_index < 4; row_index++) { + IceTDouble projection_value = + ICET_MATRIX(projection_matrix, row_index, column_index); + IceTDouble modelview_value = + ICET_MATRIX(modelview_matrix, row_index, column_index); + IceTDouble expected_value = + (row_index == column_index) ? 1.0 : 0.0; + if (projection_value != expected_value) { + printrank("Got bad projection matrix, " + "row=%d, column=%d, value=%lf\n", + row_index, column_index, projection_value); + } + if (modelview_value != expected_value) { + printrank("Got bad modelview matrix, " + "row=%d, column=%d, value=%lf\n", + row_index, column_index, modelview_value); + } + } + } + } +} + +static void RenderEmptySetupRender() +{ + icetCompositeMode(ICET_COMPOSITE_MODE_BLEND); + icetSetColorFormat(ICET_IMAGE_COLOR_RGBA_FLOAT); + icetSetDepthFormat(ICET_IMAGE_DEPTH_NONE); + icetDisable(ICET_ORDERED_COMPOSITE); + icetEnable(ICET_CORRECT_COLORED_BACKGROUND); + + /* Sequential rendering means that the compositor will not try to skip + * empty tiles. */ + icetStrategy(ICET_STRATEGY_SEQUENTIAL); + + icetDrawCallback(RenderEmptyDraw); + + icetResetTiles(); + icetAddTile(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0); +} + +static void RenderEmptyGetMatrices(IceTDouble *projection_matrix, + IceTDouble *modelview_matrix) +{ + /* Don't really care about the matricies. Just use identities. */ + icetMatrixIdentity(projection_matrix); + icetMatrixIdentity(modelview_matrix); + + /* Declare the geometry well outside the view. */ + icetBoundingBoxd(1000.0, 2000.0, 1000.0, 2000.0, 1000.0, 2000.0); +} + +static int RenderEmptyCheckImage(const IceTImage image) +{ + IceTInt rank; + + icetGetIntegerv(ICET_RANK, &rank); + if (rank == 0) { + const IceTFloat *buffer; + IceTSizeType x, y; + + buffer = icetImageGetColorcf(image); + + for (y = 0; y < SCREEN_HEIGHT; y++) { + for (x = 0; x < SCREEN_WIDTH; x++) { + const IceTFloat *pixel = buffer + 4*(y*SCREEN_WIDTH + x); + if (!ColorsEqual(pixel, g_background_color)) { + printrank("**** Found bad pixel!!!! ****\n"); + printrank("Region location x = %d, y = %d\n", x, y); + printrank("Got color %f %f %f %f\n", + pixel[0], pixel[1], pixel[2], pixel[3]); + printrank("Expected %f %f %f %f\n", + g_background_color[0], + g_background_color[1], + g_background_color[2], + g_background_color[3]); + return TEST_FAILED; + } + } + } + } + + return TEST_PASSED; +} + +static int RenderEmptyTryRender() +{ + IceTDouble projection_matrix[16]; + IceTDouble modelview_matrix[16]; + IceTImage image; + + RenderEmptySetupRender(); + RenderEmptyGetMatrices(projection_matrix, modelview_matrix); + + image = icetDrawFrame(projection_matrix, + modelview_matrix, + g_background_color); + + return RenderEmptyCheckImage(image); +} + +static int RenderEmptyTryOptions() +{ + int result = TEST_PASSED; + + printstat("ICET_RENDER_EMPTY_IMAGES disabled. " + "Should NOT be in draw callback.\n"); + icetDisable(ICET_RENDER_EMPTY_IMAGES); + g_render_callback_invoked = ICET_FALSE; + g_render_callback_parameters_correct = ICET_FALSE; + result += RenderEmptyTryRender(); + if (g_render_callback_invoked) { + printrank("**** The draw callback was called ****\n"); + result = TEST_FAILED; + } + + /* Second call, empty renders should be called. */ + printstat("ICET_RENDER_EMPTY_IMAGES enabled. " + "Draw callback should be invoked everywhere.\n"); + icetEnable(ICET_RENDER_EMPTY_IMAGES); + g_render_callback_invoked = ICET_FALSE; + g_render_callback_parameters_correct = ICET_FALSE; + result += RenderEmptyTryRender(); + if (!g_render_callback_invoked) { + printrank("**** The draw callback was not called ****\n"); + result = TEST_FAILED; + } + if (!g_render_callback_parameters_correct) { + printrank("**** Matricies were wrong in callback ****\n"); + result = TEST_FAILED; + } + + return result; +} + +static int RenderEmptyRun(void) +{ + return RenderEmptyTryOptions(); +} + +int RenderEmpty(int argc, char *argv[]) +{ + /* To remove warning. */ + (void)argc; + (void)argv; + + return run_test(RenderEmptyRun); +} diff --git a/pool/shard008/C/0130760_fbdev_mode.c b/pool/shard008/C/0130760_fbdev_mode.c new file mode 100644 index 0000000000000000000000000000000000000000..85c35ffe0e01782ed6131c173016f25ca6513b04 --- /dev/null +++ b/pool/shard008/C/0130760_fbdev_mode.c @@ -0,0 +1,130 @@ +/****************************************************************************** + + display-fbdev-mesa + + Copyright (C) 1999 Jon Taylor [taylorj@ggi-project.org] + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +****************************************************************************** +*/ + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#ifndef MAP_FAILED +#define MAP_FAILED ((void*)-1) +#endif + +#define FB_KLUDGE_FONTX 8 +#define FB_KLUDGE_FONTY 16 +#define FB_KLUDGE_TEXTMODE 13 +#define TIMINGFILE "/etc/fb.modes" + +int GGIMesa_fbdev_getapi(ggi_visual *vis, int num, char *apiname, char *arguments) +{ + struct fbdev_priv_mesa *priv = GGIMESA_PRIV(vis); + + arguments = '\0'; + + switch(num) { + case 0: + if (priv->oldpriv->have_accel) { + strcpy(apiname, priv->oldpriv->accel); + return 0; + } + break; + } + + return -1; +} + +static int do_setmode(ggi_visual *vis) +{ + struct fbdev_priv_mesa *priv = GGIMESA_PRIV(vis); + int err, id; + char libname[GGI_API_MAXLEN], libargs[GGI_API_MAXLEN]; + ggi_graphtype gt; + + _ggiZapMode(vis, ~GGI_DL_OPDISPLAY); + priv->have_accel = 0; + + for (id = 1; GGIMesa_fbdev_getapi(vis, id, libname, libargs) == 0; id++) { + if (_ggiOpenDL(vis, libname, libargs, NULL) == 0) { + GGIMESADPRINT_LIBS(stderr, "display-fbdev-mesa: Error opening the " + "%s (%s) library.\n", libname, libargs); + return GGI_EFATAL; + } + + GGIMESADPRINT_CORE("Success in loading %s (%s)\n", + libname, libargs); + } + + if (priv->oldpriv->accel && + _ggiOpenDL(vis, priv->accel, NULL, NULL) != 0) { + priv->have_accel = 1; + } else { + priv->have_accel = 0; + } + vis->accelactive = 0; + + ggiIndicateChange(vis, GGI_CHG_APILIST); + + GGIMESADPRINT_CORE("display-fbdev-mesa: do_setmode SUCCESS\n"); + + return 0; +} + + +int GGIMesa_fbdev_setmode(ggi_visual *vis, ggi_mode *mode) +{ + int err; + + if ((err = ggiCheckMode(vis, mode)) != 0) { + return err; + } + + GGIMESADPRINT_CORE("display-fbdev-mesa: setmode %dx%d#%dx%dF%d[0x%02x]\n", + mode->visible.x, mode->visible.y, + mode->virt.x, mode->virt.y, + mode->frames, mode->graphtype); + + memcpy(LIBGGI_MODE(vis), mode, sizeof(ggi_mode)); + + /* Now actually set the mode */ + err = do_setmode(vis); + if (err != 0) { + return err; + } + + GGIMESADPRINT_CORE("display-fbdev-mesa: setmode success.\n"); + + return 0; +} diff --git a/pool/shard008/C/0130766_net.c b/pool/shard008/C/0130766_net.c new file mode 100644 index 0000000000000000000000000000000000000000..d5d72dd1ca1f9a2d331ec4ad60fdf0853763a8ae --- /dev/null +++ b/pool/shard008/C/0130766_net.c @@ -0,0 +1,190 @@ +/* + * AppArmor security module + * + * This file contains AppArmor network mediation + * + * Copyright (C) 1998-2008 Novell/SUSE + * Copyright 2009-2017 Canonical Ltd. + * + * 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, version 2 of the + * License. + */ + +#include "include/apparmor.h" +#include "include/audit.h" +#include "include/cred.h" +#include "include/label.h" +#include "include/net.h" +#include "include/policy.h" + +#include "net_names.h" + + +struct aa_sfs_entry aa_sfs_entry_network[] = { + AA_SFS_FILE_STRING("af_mask", AA_SFS_AF_MASK), + { } +}; + +static const char * const net_mask_names[] = { + "unknown", + "send", + "receive", + "unknown", + + "create", + "shutdown", + "connect", + "unknown", + + "setattr", + "getattr", + "setcred", + "getcred", + + "chmod", + "chown", + "chgrp", + "lock", + + "mmap", + "mprot", + "unknown", + "unknown", + + "accept", + "bind", + "listen", + "unknown", + + "setopt", + "getopt", + "unknown", + "unknown", + + "unknown", + "unknown", + "unknown", + "unknown", +}; + + +/* audit callback for net specific fields */ +void audit_net_cb(struct audit_buffer *ab, void *va) +{ + struct common_audit_data *sa = va; + + audit_log_format(ab, " family="); + if (address_family_names[sa->u.net->family]) + audit_log_string(ab, address_family_names[sa->u.net->family]); + else + audit_log_format(ab, "\"unknown(%d)\"", sa->u.net->family); + audit_log_format(ab, " sock_type="); + if (sock_type_names[aad(sa)->net.type]) + audit_log_string(ab, sock_type_names[aad(sa)->net.type]); + else + audit_log_format(ab, "\"unknown(%d)\"", aad(sa)->net.type); + audit_log_format(ab, " protocol=%d", aad(sa)->net.protocol); + + if (aad(sa)->request & NET_PERMS_MASK) { + audit_log_format(ab, " requested_mask="); + aa_audit_perm_mask(ab, aad(sa)->request, NULL, 0, + net_mask_names, NET_PERMS_MASK); + + if (aad(sa)->denied & NET_PERMS_MASK) { + audit_log_format(ab, " denied_mask="); + aa_audit_perm_mask(ab, aad(sa)->denied, NULL, 0, + net_mask_names, NET_PERMS_MASK); + } + } + if (aad(sa)->peer) { + audit_log_format(ab, " peer="); + aa_label_xaudit(ab, labels_ns(aad(sa)->label), aad(sa)->peer, + FLAGS_NONE, GFP_ATOMIC); + } +} + +/* Generic af perm */ +int aa_profile_af_perm(struct aa_profile *profile, struct common_audit_data *sa, + u32 request, u16 family, int type) +{ + struct aa_perms perms = { }; + unsigned int state; + __be16 buffer[2]; + + AA_BUG(family >= AF_MAX); + AA_BUG(type < 0 || type >= SOCK_MAX); + + if (profile_unconfined(profile)) + return 0; + state = PROFILE_MEDIATES(profile, AA_CLASS_NET); + if (!state) + return 0; + + buffer[0] = cpu_to_be16(family); + buffer[1] = cpu_to_be16((u16) type); + state = aa_dfa_match_len(profile->policy.dfa, state, (char *) &buffer, + 4); + aa_compute_perms(profile->policy.dfa, state, &perms); + aa_apply_modes_to_perms(profile, &perms); + + return aa_check_perms(profile, &perms, request, sa, audit_net_cb); +} + +int aa_af_perm(struct aa_label *label, const char *op, u32 request, u16 family, + int type, int protocol) +{ + struct aa_profile *profile; + DEFINE_AUDIT_NET(sa, op, NULL, family, type, protocol); + + return fn_for_each_confined(label, profile, + aa_profile_af_perm(profile, &sa, request, family, + type)); +} + +static int aa_label_sk_perm(struct aa_label *label, const char *op, u32 request, + struct sock *sk) +{ + int error = 0; + + AA_BUG(!label); + AA_BUG(!sk); + + if (!unconfined(label)) { + struct aa_profile *profile; + DEFINE_AUDIT_SK(sa, op, sk); + + error = fn_for_each_confined(label, profile, + aa_profile_af_sk_perm(profile, &sa, request, sk)); + } + + return error; +} + +int aa_sk_perm(const char *op, u32 request, struct sock *sk) +{ + struct aa_label *label; + int error; + + AA_BUG(!sk); + AA_BUG(in_interrupt()); + + /* TODO: switch to begin_current_label ???? */ + label = begin_current_label_crit_section(); + error = aa_label_sk_perm(label, op, request, sk); + end_current_label_crit_section(label); + + return error; +} + + +int aa_sock_file_perm(struct aa_label *label, const char *op, u32 request, + struct socket *sock) +{ + AA_BUG(!label); + AA_BUG(!sock); + AA_BUG(!sock->sk); + + return aa_label_sk_perm(label, op, request, sock->sk); +} diff --git a/pool/shard008/C/0130767_capture.c b/pool/shard008/C/0130767_capture.c new file mode 100644 index 0000000000000000000000000000000000000000..236150720801e590e0b3da28212b875b2254aba0 --- /dev/null +++ b/pool/shard008/C/0130767_capture.c @@ -0,0 +1,115 @@ +#include "capture.h" + +#include "util.h" +#include "yuv.h" + +#include +#include +#include +#include + +int start_capture(int fd) { + unsigned int i; + enum v4l2_buf_type type; + + for(i = 0; i < BUFFER_COUNT; ++i) { + struct v4l2_buffer buf; + CLEAR(buf); + buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + buf.memory = V4L2_MEMORY_MMAP; + buf.index = i; + + if(-1 == xioctl(fd, VIDIOC_QBUF, &buf)) { + return errnoexit("VIDIOC_QBUF"); + } + } + + type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + if(-1 == xioctl(fd, VIDIOC_STREAMON, &type)) { + return errnoexit("VIDIOC_STREAMON"); + } + + return SUCCESS_LOCAL; +} + +int read_frame(int fd, buffer* frame_buffers, int width, int height, + int* rgb_buffer, int* y_buffer) { + struct v4l2_buffer buf; + CLEAR(buf); + buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + buf.memory = V4L2_MEMORY_MMAP; + + if(-1 == xioctl(fd, VIDIOC_DQBUF, &buf)) { + switch(errno) { + case EAGAIN: + return 0; + case EIO: + default: + return errnoexit("VIDIOC_DQBUF"); + } + } + + assert(buf.index < BUFFER_COUNT); + yuyv422_to_argb(frame_buffers[buf.index].start, width, height, rgb_buffer, + y_buffer); + + if(-1 == xioctl(fd, VIDIOC_QBUF, &buf)) { + return errnoexit("VIDIOC_QBUF"); + } + + return 1; +} + +int stop_capturing(int fd) { + enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + if(-1 != fd && -1 == xioctl(fd, VIDIOC_STREAMOFF, &type)) { + return errnoexit("VIDIOC_STREAMOFF"); + } + + return SUCCESS_LOCAL; +} + +void process_camera(int fd, buffer* frame_buffers, int width, + int height, int* rgb_buffer, int* ybuf) { + if(fd == -1) { + return; + } + + for(;;) { + fd_set fds; + FD_ZERO(&fds); + FD_SET(fd, &fds); + + struct timeval tv; + tv.tv_sec = 2; + tv.tv_usec = 0; + + int result = select(fd + 1, &fds, NULL, NULL, &tv); + if(-1 == result) { + if(EINTR == errno) { + continue; + } + errnoexit("select"); + } else if(0 == result) { + LOGE("select timeout"); + } + + if(read_frame(fd, frame_buffers, width, height, rgb_buffer, ybuf) == 1) { + break; + } + } +} + +void stop_camera(int* fd, int* rgb_buffer, int* y_buffer) { + stop_capturing(*fd); + uninit_device(); + close_device(fd); + + if(rgb_buffer) { + free(rgb_buffer); + } + + if(y_buffer) { + free(y_buffer); + } +} diff --git a/pool/shard008/C/0130768_odroid.c b/pool/shard008/C/0130768_odroid.c new file mode 100644 index 0000000000000000000000000000000000000000..06a31a9585a05afa8d605bde5afbfd7d5c86a384 --- /dev/null +++ b/pool/shard008/C/0130768_odroid.c @@ -0,0 +1,238 @@ +/* + * Copyright (C) 2017 Samsung Electronics Co., Ltd. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#include +#include +#include +#include +#include +#include +#include "i2s.h" +#include "i2s-regs.h" + +struct odroid_priv { + struct snd_soc_card card; + struct snd_soc_dai_link dai_link; + + struct clk *clk_i2s_bus; + struct clk *sclk_i2s; +}; + +static int odroid_card_startup(struct snd_pcm_substream *substream) +{ + struct snd_pcm_runtime *runtime = substream->runtime; + + snd_pcm_hw_constraint_single(runtime, SNDRV_PCM_HW_PARAM_CHANNELS, 2); + return 0; +} + +static int odroid_card_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params) +{ + struct snd_soc_pcm_runtime *rtd = substream->private_data; + struct odroid_priv *priv = snd_soc_card_get_drvdata(rtd->card); + unsigned int pll_freq, rclk_freq, rfs; + int ret; + + switch (params_rate(params)) { + case 64000: + pll_freq = 196608001U; + rfs = 384; + break; + case 44100: + case 88200: + case 176400: + pll_freq = 180633609U; + rfs = 512; + break; + case 32000: + case 48000: + case 96000: + case 192000: + pll_freq = 196608001U; + rfs = 512; + break; + default: + return -EINVAL; + } + + ret = clk_set_rate(priv->clk_i2s_bus, pll_freq / 2 + 1); + if (ret < 0) + return ret; + + /* + * We add 1 to the rclk_freq value in order to avoid too low clock + * frequency values due to the EPLL output frequency not being exact + * multiple of the audio sampling rate. + */ + rclk_freq = params_rate(params) * rfs + 1; + + ret = clk_set_rate(priv->sclk_i2s, rclk_freq); + if (ret < 0) + return ret; + + if (rtd->num_codecs > 1) { + struct snd_soc_dai *codec_dai = rtd->codec_dais[1]; + + ret = snd_soc_dai_set_sysclk(codec_dai, 0, rclk_freq, + SND_SOC_CLOCK_IN); + if (ret < 0) + return ret; + } + + return 0; +} + +static const struct snd_soc_ops odroid_card_ops = { + .startup = odroid_card_startup, + .hw_params = odroid_card_hw_params, +}; + +static void odroid_put_codec_of_nodes(struct snd_soc_dai_link *link) +{ + struct snd_soc_dai_link_component *component = link->codecs; + int i; + + for (i = 0; i < link->num_codecs; i++, component++) { + if (!component->of_node) + break; + of_node_put(component->of_node); + } +} + +static int odroid_audio_probe(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct device_node *cpu, *codec; + struct odroid_priv *priv; + struct snd_soc_dai_link *link; + struct snd_soc_card *card; + int ret; + + priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL); + if (!priv) + return -ENOMEM; + + card = &priv->card; + card->dev = dev; + + card->owner = THIS_MODULE; + card->fully_routed = true; + + snd_soc_card_set_drvdata(card, priv); + + ret = snd_soc_of_parse_card_name(card, "model"); + if (ret < 0) + return ret; + + if (of_property_read_bool(dev->of_node, "samsung,audio-widgets")) { + ret = snd_soc_of_parse_audio_simple_widgets(card, + "samsung,audio-widgets"); + if (ret < 0) + return ret; + } + + if (of_property_read_bool(dev->of_node, "samsung,audio-routing")) { + ret = snd_soc_of_parse_audio_routing(card, + "samsung,audio-routing"); + if (ret < 0) + return ret; + } + + link = &priv->dai_link; + + link->ops = &odroid_card_ops; + link->dai_fmt = SND_SOC_DAIFMT_I2S | SND_SOC_DAIFMT_NB_NF | + SND_SOC_DAIFMT_CBS_CFS; + + card->dai_link = &priv->dai_link; + card->num_links = 1; + + cpu = of_get_child_by_name(dev->of_node, "cpu"); + codec = of_get_child_by_name(dev->of_node, "codec"); + + link->cpu_of_node = of_parse_phandle(cpu, "sound-dai", 0); + if (!link->cpu_of_node) { + dev_err(dev, "Failed parsing cpu/sound-dai property\n"); + return -EINVAL; + } + + ret = snd_soc_of_get_dai_link_codecs(dev, codec, link); + if (ret < 0) + goto err_put_codec_n; + + link->platform_of_node = link->cpu_of_node; + + link->name = "Primary"; + link->stream_name = link->name; + + + priv->sclk_i2s = of_clk_get_by_name(link->cpu_of_node, "i2s_opclk1"); + if (IS_ERR(priv->sclk_i2s)) { + ret = PTR_ERR(priv->sclk_i2s); + goto err_put_i2s_n; + } + + priv->clk_i2s_bus = of_clk_get_by_name(link->cpu_of_node, "iis"); + if (IS_ERR(priv->clk_i2s_bus)) { + ret = PTR_ERR(priv->clk_i2s_bus); + goto err_put_sclk; + } + + ret = devm_snd_soc_register_card(dev, card); + if (ret < 0) { + dev_err(dev, "snd_soc_register_card() failed: %d\n", ret); + goto err_put_clk_i2s; + } + + return 0; + +err_put_clk_i2s: + clk_put(priv->clk_i2s_bus); +err_put_sclk: + clk_put(priv->sclk_i2s); +err_put_i2s_n: + of_node_put(link->cpu_of_node); +err_put_codec_n: + odroid_put_codec_of_nodes(link); + return ret; +} + +static int odroid_audio_remove(struct platform_device *pdev) +{ + struct odroid_priv *priv = platform_get_drvdata(pdev); + + of_node_put(priv->dai_link.cpu_of_node); + odroid_put_codec_of_nodes(&priv->dai_link); + clk_put(priv->sclk_i2s); + clk_put(priv->clk_i2s_bus); + + return 0; +} + +static const struct of_device_id odroid_audio_of_match[] = { + { .compatible = "samsung,odroid-xu3-audio" }, + { .compatible = "samsung,odroid-xu4-audio"}, + { }, +}; +MODULE_DEVICE_TABLE(of, odroid_audio_of_match); + +static struct platform_driver odroid_audio_driver = { + .driver = { + .name = "odroid-audio", + .of_match_table = odroid_audio_of_match, + .pm = &snd_soc_pm_ops, + }, + .probe = odroid_audio_probe, + .remove = odroid_audio_remove, +}; +module_platform_driver(odroid_audio_driver); + +MODULE_AUTHOR("Sylwester Nawrocki "); +MODULE_DESCRIPTION("Odroid XU3/XU4 audio support"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard008/C/0130770_cdr_sqlite.c b/pool/shard008/C/0130770_cdr_sqlite.c new file mode 100644 index 0000000000000000000000000000000000000000..3b93a9ec823591faed23cc79c8ec07ad8139612b --- /dev/null +++ b/pool/shard008/C/0130770_cdr_sqlite.c @@ -0,0 +1,217 @@ +/* + * Asterisk -- An open source telephony toolkit. + * + * Copyright (C) 2004 - 2005, Holger Schurig + * + * + * Ideas taken from other cdr_*.c files + * + * See http://www.asterisk.org for more information about + * the Asterisk project. Please do not directly contact + * any of the maintainers of this project for assistance; + * the project provides a web site, mailing lists and IRC + * channels for your use. + * + * This program is free software, distributed under the terms of + * the GNU General Public License Version 2. See the LICENSE file + * at the top of the source tree. + */ + +/*! \file + * + * \brief Store CDR records in a SQLite database. + * + * \author Holger Schurig + * + * See also + * \arg \ref Config_cdr + * \arg http://www.sqlite.org/ + * + * Creates the database and table on-the-fly + * \ingroup cdr_drivers + */ + +/*** MODULEINFO + sqlite + ***/ + +#include "asterisk.h" + +ASTERISK_FILE_VERSION(__FILE__, "$Revision: 69392 $") + +#include +#include +#include +#include +#include +#include + +#include "asterisk/channel.h" +#include "asterisk/module.h" +#include "asterisk/logger.h" +#include "asterisk/utils.h" + +#define LOG_UNIQUEID 0 +#define LOG_USERFIELD 0 + +/* When you change the DATE_FORMAT, be sure to change the CHAR(19) below to something else */ +#define DATE_FORMAT "%Y-%m-%d %T" + +static char *name = "sqlite"; +static sqlite* db = NULL; + +AST_MUTEX_DEFINE_STATIC(sqlite_lock); + +/*! \brief SQL table format */ +static char sql_create_table[] = "CREATE TABLE cdr (" +" AcctId INTEGER PRIMARY KEY," +" clid VARCHAR(80)," +" src VARCHAR(80)," +" dst VARCHAR(80)," +" dcontext VARCHAR(80)," +" channel VARCHAR(80)," +" dstchannel VARCHAR(80)," +" lastapp VARCHAR(80)," +" lastdata VARCHAR(80)," +" start CHAR(19)," +" answer CHAR(19)," +" end CHAR(19)," +" duration INTEGER," +" billsec INTEGER," +" disposition INTEGER," +" amaflags INTEGER," +" accountcode VARCHAR(20)" +#if LOG_UNIQUEID +" ,uniqueid VARCHAR(32)" +#endif +#if LOG_USERFIELD +" ,userfield VARCHAR(255)" +#endif +");"; + +static int sqlite_log(struct ast_cdr *cdr) +{ + int res = 0; + char *zErr = 0; + struct tm tm; + time_t t; + char startstr[80], answerstr[80], endstr[80]; + int count; + + ast_mutex_lock(&sqlite_lock); + + t = cdr->start.tv_sec; + ast_localtime(&t, &tm, NULL); + strftime(startstr, sizeof(startstr), DATE_FORMAT, &tm); + + t = cdr->answer.tv_sec; + ast_localtime(&t, &tm, NULL); + strftime(answerstr, sizeof(answerstr), DATE_FORMAT, &tm); + + t = cdr->end.tv_sec; + ast_localtime(&t, &tm, NULL); + strftime(endstr, sizeof(endstr), DATE_FORMAT, &tm); + + for(count=0; count<5; count++) { + res = sqlite_exec_printf(db, + "INSERT INTO cdr (" + "clid,src,dst,dcontext," + "channel,dstchannel,lastapp,lastdata, " + "start,answer,end," + "duration,billsec,disposition,amaflags, " + "accountcode" +# if LOG_UNIQUEID + ",uniqueid" +# endif +# if LOG_USERFIELD + ",userfield" +# endif + ") VALUES (" + "'%q', '%q', '%q', '%q', " + "'%q', '%q', '%q', '%q', " + "'%q', '%q', '%q', " + "%d, %d, %d, %d, " + "'%q'" +# if LOG_UNIQUEID + ",'%q'" +# endif +# if LOG_USERFIELD + ",'%q'" +# endif + ")", NULL, NULL, &zErr, + cdr->clid, cdr->src, cdr->dst, cdr->dcontext, + cdr->channel, cdr->dstchannel, cdr->lastapp, cdr->lastdata, + startstr, answerstr, endstr, + cdr->duration, cdr->billsec, cdr->disposition, cdr->amaflags, + cdr->accountcode +# if LOG_UNIQUEID + ,cdr->uniqueid +# endif +# if LOG_USERFIELD + ,cdr->userfield +# endif + ); + if (res != SQLITE_BUSY && res != SQLITE_LOCKED) + break; + usleep(200); + } + + if (zErr) { + ast_log(LOG_ERROR, "cdr_sqlite: %s\n", zErr); + free(zErr); + } + + ast_mutex_unlock(&sqlite_lock); + return res; +} + +static int unload_module(void) +{ + if (db) + sqlite_close(db); + ast_cdr_unregister(name); + return 0; +} + +static int load_module(void) +{ + char *zErr; + char fn[PATH_MAX]; + int res; + + /* is the database there? */ + snprintf(fn, sizeof(fn), "%s/cdr.db", ast_config_AST_LOG_DIR); + db = sqlite_open(fn, 0660, &zErr); + if (!db) { + ast_log(LOG_ERROR, "cdr_sqlite: %s\n", zErr); + free(zErr); + return -1; + } + + /* is the table there? */ + res = sqlite_exec(db, "SELECT COUNT(AcctId) FROM cdr;", NULL, NULL, NULL); + if (res) { + res = sqlite_exec(db, sql_create_table, NULL, NULL, &zErr); + if (res) { + ast_log(LOG_ERROR, "cdr_sqlite: Unable to create table 'cdr': %s\n", zErr); + free(zErr); + goto err; + } + + /* TODO: here we should probably create an index */ + } + + res = ast_cdr_register(name, ast_module_info->description, sqlite_log); + if (res) { + ast_log(LOG_ERROR, "Unable to register SQLite CDR handling\n"); + return -1; + } + return 0; + +err: + if (db) + sqlite_close(db); + return -1; +} + +AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "SQLite CDR Backend"); diff --git a/pool/shard008/C/0130772_scratch_buffer_grow.c b/pool/shard008/C/0130772_scratch_buffer_grow.c new file mode 100644 index 0000000000000000000000000000000000000000..3f27e0e03c8b62984cbed628ba473c38f8a81307 --- /dev/null +++ b/pool/shard008/C/0130772_scratch_buffer_grow.c @@ -0,0 +1,52 @@ +/* Variable-sized buffer with on-stack default allocation. + Copyright (C) 2015 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C 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. + + The GNU C 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. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, see + . */ + +#include +#include + +bool +__libc_scratch_buffer_grow (struct scratch_buffer *buffer) +{ + void *new_ptr; + size_t new_length = buffer->length * 2; + + /* Discard old buffer. */ + scratch_buffer_free (buffer); + + /* Check for overflow. */ + if (__glibc_likely (new_length >= buffer->length)) + new_ptr = malloc (new_length); + else + { + __set_errno (ENOMEM); + new_ptr = NULL; + } + + if (__glibc_unlikely (new_ptr == NULL)) + { + /* Buffer must remain valid to free. */ + scratch_buffer_init (buffer); + return false; + } + + /* Install new heap-based buffer. */ + buffer->data = new_ptr; + buffer->length = new_length; + return true; +} +libc_hidden_def (__libc_scratch_buffer_grow); diff --git a/pool/shard008/C/0130773_CWE127_Buffer_Underread__char_declare_cpy_17.c b/pool/shard008/C/0130773_CWE127_Buffer_Underread__char_declare_cpy_17.c new file mode 100644 index 0000000000000000000000000000000000000000..2ae01315af0994ec69effbffffa75b29dfe81904 --- /dev/null +++ b/pool/shard008/C/0130773_CWE127_Buffer_Underread__char_declare_cpy_17.c @@ -0,0 +1,104 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE127_Buffer_Underread__char_declare_cpy_17.c +Label Definition File: CWE127_Buffer_Underread.stack.label.xml +Template File: sources-sink-17.tmpl.c +*/ +/* + * @description + * CWE: 127 Buffer Under-read + * BadSource: Set data pointer to before the allocated memory buffer + * GoodSource: Set data pointer to the allocated memory buffer + * Sink: cpy + * BadSink : Copy data to string using strcpy + * Flow Variant: 17 Control flow: for loops + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +void CWE127_Buffer_Underread__char_declare_cpy_17_bad() +{ + int i; + char * data; + char dataBuffer[100]; + memset(dataBuffer, 'A', 100-1); + dataBuffer[100-1] = '\0'; + for(i = 0; i < 1; i++) + { + /* FLAW: Set data pointer to before the allocated memory buffer */ + data = dataBuffer - 8; + } + { + char dest[100*2]; + memset(dest, 'C', 100*2-1); /* fill with 'C's */ + dest[100*2-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */ + strcpy(dest, data); + printLine(dest); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() - use goodsource and badsink by changing the conditions on the for statements */ +static void goodG2B() +{ + int h; + char * data; + char dataBuffer[100]; + memset(dataBuffer, 'A', 100-1); + dataBuffer[100-1] = '\0'; + for(h = 0; h < 1; h++) + { + /* FIX: Set data pointer to the allocated memory buffer */ + data = dataBuffer; + } + { + char dest[100*2]; + memset(dest, 'C', 100*2-1); /* fill with 'C's */ + dest[100*2-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */ + strcpy(dest, data); + printLine(dest); + } +} + +void CWE127_Buffer_Underread__char_declare_cpy_17_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE127_Buffer_Underread__char_declare_cpy_17_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE127_Buffer_Underread__char_declare_cpy_17_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard008/C/0130777_keysym.c b/pool/shard008/C/0130777_keysym.c new file mode 100644 index 0000000000000000000000000000000000000000..f126f2854b4cead74ca49fcac371178210be069a --- /dev/null +++ b/pool/shard008/C/0130777_keysym.c @@ -0,0 +1,148 @@ + +#include "keysym.h" + +static int +sdl_keysym_init(sdl_keysym *self, PyObject *args, PyObject *kwargs) +{ + self->event = NULL; + PyErr_SetString(PyExc_TypeError, + "keysym objects are not constructible"); + return -1; +} + +static int +sdl_keysym_setattro(sdl_keysym *self, PyObject *attr, PyObject *val) +{ + /* val should not be large enough to be a PyLong */ + if (!PyString_Check(attr) || !PyInt_Check(val)) + { + PyErr_SetString(PyExc_ValueError, "Bad parameters"); + return -1; + } + const char *aname = PyString_AsString(attr); + int v = PyInt_AsLong(val); + if (!strcmp(aname, "scancode")) + self->ks->scancode = v; + else if (!strcmp(aname, "sym")) + self->ks->sym = v; + else if (!strcmp(aname, "mod")) + self->ks->mod = v; + else if (!strcmp(aname, "unicode")) + self->ks->unicode = v; + else + { + PyErr_SetString(PyExc_AttributeError, "Invalid attribute"); + return -1; + } + return 0; +} + +static PyObject * +sdl_keysym_getattro(sdl_keysym *self, PyObject *attr) +{ + if (!PyString_Check(attr)) + { + PyErr_SetString(PyExc_AttributeError, "Invalid attribute name"); + return NULL; + } + const char *aname = PyString_AsString(attr); + if (!strcmp(aname, "scancode")) + return PyInt_FromLong(self->ks->scancode); + else if (!strcmp(aname, "sym")) + return PyInt_FromLong(self->ks->sym); + else if (!strcmp(aname, "mod")) + return PyInt_FromLong(self->ks->mod); + else if (!strcmp(aname, "unicode")) + return PyInt_FromLong(self->ks->unicode); + PyErr_SetString(PyExc_AttributeError, "Invalid attribute"); + return NULL; +} + +static void +sdl_keysym_dealloc(sdl_keysym *self) +{ + Py_XDECREF(self->event); + PyObject_Del(self); +} + +PyTypeObject sdl_keysymType = { + PyObject_HEAD_INIT(NULL) + 0, /* ob_size */ + "SDL.keysym", /* tp_name */ + sizeof(sdl_keysym), /* tp_basicsize */ + 0, /* tp_itemsize */ + (destructor)sdl_keysym_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + (getattrofunc)sdl_keysym_getattro,/* tp_getattro */ + (setattrofunc)sdl_keysym_setattro,/* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ + "SDL keysym Structure", /* tp_doc */ + 0, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ + 0, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + 0, /* tp_descr_get */ + 0, /* tp_descr_set */ + 0, /* tp_dictoffset */ + (initproc)sdl_keysym_init, /* tp_init */ + 0, /* tp_alloc */ + PyType_GenericNew, /* tp_new */ +}; + +void sdl_keysym_register_type(PyObject *module) +{ + if (PyType_Ready(&sdl_keysymType) < 0) + { + fprintf(stderr, "Error initializing sdl_keysymType\n"); + return; + } + + Py_INCREF(&sdl_keysymType); + PyModule_AddObject(module, "keysym", (PyObject *) &sdl_keysymType); +} + +PyObject *sdl_keysym_from_SDL_keysym(SDL_keysym *ks) +{ + if (ks == NULL) + Py_RETURN_NONE; + sdl_keysym *k = PyObject_New(sdl_keysym, &sdl_keysymType); + k->ks = ks; + k->event = NULL; + return (PyObject *) k; +} + +PyObject *sdl_keysym_from_SDL_keysym_and_event(SDL_keysym *ks, sdl_Event *evt) +{ + PyObject *k = sdl_keysym_from_SDL_keysym(ks); + ((sdl_keysym *) k)->event = (PyObject *) evt; + Py_INCREF((PyObject *) evt); + return k; +} + +PyObject *sdl_keysym_get_type(void) +{ + return (PyObject *) &sdl_keysymType; +} + +SDL_keysym *sdl_keysym_get_SDL_keysym(PyObject *ko) +{ + return ((sdl_keysym *) ko)->ks; +} diff --git a/pool/shard008/C/0130778_serial.c b/pool/shard008/C/0130778_serial.c new file mode 100644 index 0000000000000000000000000000000000000000..b243c7526e18db50270cf15ebc8761273a3aadbf --- /dev/null +++ b/pool/shard008/C/0130778_serial.c @@ -0,0 +1,206 @@ +/* + * FreeRTOS Kernel V10.1.1 + * Copyright (C) 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * http://www.FreeRTOS.org + * http://aws.amazon.com/freertos + * + * 1 tab == 4 spaces! + */ + +/* BASIC INTERRUPT DRIVEN SERIAL PORT DRIVER. + * + * This file only supports UART 0 + */ + +/* Standard includes. */ +#include + +/* Scheduler includes. */ +#include "FreeRTOS.h" +#include "queue.h" +#include "task.h" + +/* Demo application includes. */ +#include "serial.h" + +/* The queue used to hold received characters. */ +static QueueHandle_t xRxedChars; + +/* The queue used to hold characters waiting transmission. */ +static QueueHandle_t xCharsForTx; + +static volatile short sTHREEmpty; + +static volatile short queueFail = pdFALSE; + +/*-----------------------------------------------------------*/ +xComPortHandle xSerialPortInitMinimal( unsigned long ulWantedBaud, unsigned portBASE_TYPE uxQueueLength ) +{ + /* Initialise the hardware. */ + portENTER_CRITICAL(); + { + /* Create the queues used by the com test task. */ + xRxedChars = xQueueCreate( uxQueueLength, ( unsigned portBASE_TYPE ) sizeof(signed char) ); + xCharsForTx = xQueueCreate( uxQueueLength, ( unsigned portBASE_TYPE ) sizeof(signed char) ); + + if( xRxedChars == 0 ) + { + queueFail = pdTRUE; + } + + if( xCharsForTx == 0 ) + { + queueFail = pdTRUE; + } + + /* Initialize UART asynchronous mode */ + BGR0 = configCLKP1_CLOCK_HZ / ulWantedBaud; + + SCR0 = 0x17; /* 8N1 */ + SMR0 = 0x0d; /* enable SOT3, Reset, normal mode */ + SSR0 = 0x02; /* LSB first, enable receive interrupts */ + + PIER08_IE2 = 1; /* enable input */ + DDR08_D2 = 0; /* switch P08_2 to input */ + DDR08_D3 = 1; /* switch P08_3 to output */ + } + portEXIT_CRITICAL(); + + /* Unlike other ports, this serial code does not allow for more than one + com port. We therefore don't return a pointer to a port structure and can + instead just return NULL. */ + return NULL; +} +/*-----------------------------------------------------------*/ + +signed portBASE_TYPE xSerialGetChar( xComPortHandle pxPort, signed char *pcRxedChar, TickType_t xBlockTime ) +{ + /* Get the next character from the buffer. Return false if no characters + are available, or arrive before xBlockTime expires. */ + if( xQueueReceive(xRxedChars, pcRxedChar, xBlockTime) ) + { + return pdTRUE; + } + else + { + return pdFALSE; + } +} +/*-----------------------------------------------------------*/ + +signed portBASE_TYPE xSerialPutChar( xComPortHandle pxPort, signed char cOutChar, TickType_t xBlockTime ) +{ +signed portBASE_TYPE xReturn; + + /* Transmit a character. */ + portENTER_CRITICAL(); + { + if( sTHREEmpty == pdTRUE ) + { + /* If sTHREEmpty is true then the UART Tx ISR has indicated that + there are no characters queued to be transmitted - so we can + write the character directly to the shift Tx register. */ + sTHREEmpty = pdFALSE; + TDR0 = cOutChar; + xReturn = pdPASS; + } + else + { + /* sTHREEmpty is false, so there are still characters waiting to be + transmitted. We have to queue this character so it gets + transmitted in turn. */ + + /* Return false if after the block time there is no room on the Tx + queue. It is ok to block inside a critical section as each task + maintains it's own critical section status. */ + if( xQueueSend(xCharsForTx, &cOutChar, xBlockTime) == pdTRUE ) + { + xReturn = pdPASS; + } + else + { + xReturn = pdFAIL; + } + } + + if( pdPASS == xReturn ) + { + /* Turn on the Tx interrupt so the ISR will remove the character from the + queue and send it. This does not need to be in a critical section as + if the interrupt has already removed the character the next interrupt + will simply turn off the Tx interrupt again. */ + SSR0_TIE = 1; + } + } + portEXIT_CRITICAL(); + + return pdPASS; +} +/*-----------------------------------------------------------*/ + +/* + * UART RX interrupt service routine. + */ +__interrupt void UART0_RxISR( void ) +{ +volatile signed char cChar; +portBASE_TYPE xHigherPriorityTaskWoken = pdFALSE; + + /* Get the character from the UART and post it on the queue of Rxed + characters. */ + cChar = RDR0; + + xQueueSendFromISR( xRxedChars, ( const void *const ) &cChar, &xHigherPriorityTaskWoken ); + + if( xHigherPriorityTaskWoken ) + { + /*If the post causes a task to wake force a context switch + as the woken task may have a higher priority than the task we have + interrupted. */ + portYIELD_FROM_ISR(); + } +} +/*-----------------------------------------------------------*/ + +/* + * UART Tx interrupt service routine. + */ +__interrupt void UART0_TxISR( void ) +{ +signed char cChar; +signed portBASE_TYPE xTaskWoken = pdFALSE; + + /* The previous character has been transmitted. See if there are any + further characters waiting transmission. */ + if( xQueueReceiveFromISR(xCharsForTx, &cChar, &xTaskWoken) == pdTRUE ) + { + /* There was another character queued - transmit it now. */ + TDR0 = cChar; + } + else + { + /* There were no other characters to transmit. */ + sTHREEmpty = pdTRUE; + + /* Disable transmit interrupts */ + SSR0_TIE = 0; + } +} diff --git a/pool/shard008/C/0130782_savedump.c b/pool/shard008/C/0130782_savedump.c new file mode 100644 index 0000000000000000000000000000000000000000..3bbb3de2a8c8d818b861f9045f8af20dabac675b --- /dev/null +++ b/pool/shard008/C/0130782_savedump.c @@ -0,0 +1,104 @@ +#include "pcap.h" + +/* prototype of the packet handler */ +void packet_handler(u_char *param, const struct pcap_pkthdr *header, const u_char *pkt_data); + +int main(int argc, char **argv) +{ +pcap_if_t *alldevs; +pcap_if_t *d; +int inum; +int i=0; +pcap_t *adhandle; +char errbuf[PCAP_ERRBUF_SIZE]; +pcap_dumper_t *dumpfile; + + + + /* Check command line */ + if(argc != 2) + { + printf("usage: %s filename", argv[0]); + return -1; + } + + /* Retrieve the device list on the local machine */ + if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL, &alldevs, errbuf) == -1) + { + fprintf(stderr,"Error in pcap_findalldevs: %s\n", errbuf); + exit(1); + } + + /* Print the list */ + for(d=alldevs; d; d=d->next) + { + printf("%d. %s", ++i, d->name); + if (d->description) + printf(" (%s)\n", d->description); + else + printf(" (No description available)\n"); + } + + if(i==0) + { + printf("\nNo interfaces found! Make sure WinPcap is installed.\n"); + return -1; + } + + printf("Enter the interface number (1-%d):",i); + scanf_s("%d", &inum); + + if(inum < 1 || inum > i) + { + printf("\nInterface number out of range.\n"); + /* Free the device list */ + pcap_freealldevs(alldevs); + return -1; + } + + /* Jump to the selected adapter */ + for(d=alldevs, i=0; i< inum-1 ;d=d->next, i++); + + + /* Open the device */ + if ( (adhandle= pcap_open(d->name, // name of the device + 65536, // portion of the packet to capture + // 65536 guarantees that the whole packet will be captured on all the link layers + PCAP_OPENFLAG_PROMISCUOUS, // promiscuous mode + 1000, // read timeout + NULL, // authentication on the remote machine + errbuf // error buffer + ) ) == NULL) + { + fprintf(stderr,"\nUnable to open the adapter. %s is not supported by WinPcap\n", d->name); + /* Free the device list */ + pcap_freealldevs(alldevs); + return -1; + } + + /* Open the dump file */ + dumpfile = pcap_dump_open(adhandle, argv[1]); + + if(dumpfile==NULL) + { + fprintf(stderr,"\nError opening output file\n"); + return -1; + } + + printf("\nlistening on %s... Press Ctrl+C to stop...\n", d->description); + + /* At this point, we no longer need the device list. Free it */ + pcap_freealldevs(alldevs); + + /* start the capture */ + pcap_loop(adhandle, 0, packet_handler, (unsigned char *)dumpfile); + + return 0; +} + +/* Callback function invoked by libpcap for every incoming packet */ +void packet_handler(u_char *dumpfile, const struct pcap_pkthdr *header, const u_char *pkt_data) +{ + /* save the packet on the dump file */ + pcap_dump(dumpfile, header, pkt_data); +} diff --git a/pool/shard008/C/0130783_avx512f-rint-sfix-vec-1.c b/pool/shard008/C/0130783_avx512f-rint-sfix-vec-1.c new file mode 100644 index 0000000000000000000000000000000000000000..d22385c95e5219114a327b1067941b8588f30288 --- /dev/null +++ b/pool/shard008/C/0130783_avx512f-rint-sfix-vec-1.c @@ -0,0 +1,51 @@ +/* { dg-do run } */ +/* { dg-options "-O2 -ffast-math -ftree-vectorize -mavx512f" } */ +/* { dg-require-effective-target avx512f } */ + +#define __NO_MATH_INLINES +#include "math_m_pi.h" +#include "avx512f-check.h" + +#define NUM 64 + +static void +__attribute__((__target__("fpmath=sse"))) +init_src (double *src) +{ + int i, sign = 1; + double f = rand (); + + for (i = 0; i < NUM; i++) + { + src[i] = (i + 1) * f * M_PI * sign; + if (i < (NUM / 2)) + { + if ((i % 6) == 0) + f = f * src[i]; + } + else if (i == (NUM / 2)) + f = rand (); + else if ((i % 6) == 0) + f = 1 / (f * (i + 1) * src[i] * M_PI * sign); + sign = -sign; + } +} + +static void +__attribute__((__target__("fpmath=387"))) +avx512f_test (void) +{ + double a[NUM]; + int r[NUM]; + int i; + + init_src (a); + + for (i = 0; i < NUM; i++) + r[i] = (int) rint (a[i]); + + /* check results: */ + for (i = 0; i < NUM; i++) + if (r[i] != (int) rint (a[i])) + abort(); +} diff --git a/pool/shard008/C/0130785_app_ices.c b/pool/shard008/C/0130785_app_ices.c new file mode 100644 index 0000000000000000000000000000000000000000..ce96c9da0f0ae4adea06a3cd2f8dd85ee58b98bf --- /dev/null +++ b/pool/shard008/C/0130785_app_ices.c @@ -0,0 +1,215 @@ +/* + * Asterisk -- An open source telephony toolkit. + * + * Copyright (C) 1999 - 2005, Digium, Inc. + * + * Mark Spencer + * + * See http://www.asterisk.org for more information about + * the Asterisk project. Please do not directly contact + * any of the maintainers of this project for assistance; + * the project provides a web site, mailing lists and IRC + * channels for your use. + * + * This program is free software, distributed under the terms of + * the GNU General Public License Version 2. See the LICENSE file + * at the top of the source tree. + */ + +/*! \file + * + * \brief Stream to an icecast server via ICES (see contrib/asterisk-ices.xml) + * + * \author Mark Spencer + * + * \extref ICES - http://www.icecast.org/ices.php + * + * \ingroup applications + */ + +/*** MODULEINFO + extended + ***/ + +#include "asterisk.h" + +ASTERISK_FILE_VERSION(__FILE__, "$Revision: 361471 $") + +#include +#include +#include + +#include "asterisk/paths.h" /* use ast_config_AST_CONFIG_DIR */ +#include "asterisk/lock.h" +#include "asterisk/file.h" +#include "asterisk/channel.h" +#include "asterisk/frame.h" +#include "asterisk/pbx.h" +#include "asterisk/module.h" +#include "asterisk/translate.h" +#include "asterisk/app.h" + +/*** DOCUMENTATION + + + Encode and stream using 'ices'. + + + + ICES configuration file. + + + + Streams to an icecast server using ices (available separately). + A configuration file must be supplied for ices (see contrib/asterisk-ices.xml). + ICES version 2 client and server required. + + + + ***/ + +#define path_BIN "/usr/bin/" +#define path_LOCAL "/usr/local/bin/" + +static char *app = "ICES"; + +static int icesencode(char *filename, int fd) +{ + int res; + + res = ast_safe_fork(0); + if (res < 0) + ast_log(LOG_WARNING, "Fork failed\n"); + if (res) { + return res; + } + + if (ast_opt_high_priority) + ast_set_priority(0); + dup2(fd, STDIN_FILENO); + ast_close_fds_above_n(STDERR_FILENO); + + /* Most commonly installed in /usr/local/bin + * But many places has it in /usr/bin + * As a last-ditch effort, try to use PATH + */ + execl(path_LOCAL "ices2", "ices", filename, SENTINEL); + execl(path_BIN "ices2", "ices", filename, SENTINEL); + execlp("ices2", "ices", filename, SENTINEL); + + ast_debug(1, "Couldn't find ices version 2, attempting to use ices version 1.\n"); + + execl(path_LOCAL "ices", "ices", filename, SENTINEL); + execl(path_BIN "ices", "ices", filename, SENTINEL); + execlp("ices", "ices", filename, SENTINEL); + + ast_log(LOG_WARNING, "Execute of ices failed, could not find command.\n"); + close(fd); + _exit(0); +} + +static int ices_exec(struct ast_channel *chan, const char *data) +{ + int res = 0; + int fds[2]; + int ms = -1; + int pid = -1; + int flags; + int oreadformat; + struct ast_frame *f; + char filename[256]=""; + char *c; + + if (ast_strlen_zero(data)) { + ast_log(LOG_WARNING, "ICES requires an argument (configfile.xml)\n"); + return -1; + } + + if (pipe(fds)) { + ast_log(LOG_WARNING, "Unable to create pipe\n"); + return -1; + } + flags = fcntl(fds[1], F_GETFL); + fcntl(fds[1], F_SETFL, flags | O_NONBLOCK); + + ast_stopstream(chan); + + if (chan->_state != AST_STATE_UP) + res = ast_answer(chan); + + if (res) { + close(fds[0]); + close(fds[1]); + ast_log(LOG_WARNING, "Answer failed!\n"); + return -1; + } + + oreadformat = chan->readformat; + res = ast_set_read_format(chan, AST_FORMAT_SLINEAR); + if (res < 0) { + close(fds[0]); + close(fds[1]); + ast_log(LOG_WARNING, "Unable to set write format to signed linear\n"); + return -1; + } + if (((char *)data)[0] == '/') + ast_copy_string(filename, (char *) data, sizeof(filename)); + else + snprintf(filename, sizeof(filename), "%s/%s", ast_config_AST_CONFIG_DIR, (char *)data); + /* Placeholder for options */ + c = strchr(filename, '|'); + if (c) + *c = '\0'; + res = icesencode(filename, fds[0]); + if (res >= 0) { + pid = res; + for (;;) { + /* Wait for audio, and stream */ + ms = ast_waitfor(chan, -1); + if (ms < 0) { + ast_debug(1, "Hangup detected\n"); + res = -1; + break; + } + f = ast_read(chan); + if (!f) { + ast_debug(1, "Null frame == hangup() detected\n"); + res = -1; + break; + } + if (f->frametype == AST_FRAME_VOICE) { + res = write(fds[1], f->data.ptr, f->datalen); + if (res < 0) { + if (errno != EAGAIN) { + ast_log(LOG_WARNING, "Write failed to pipe: %s\n", strerror(errno)); + res = -1; + ast_frfree(f); + break; + } + } + } + ast_frfree(f); + } + } + close(fds[0]); + close(fds[1]); + + if (pid > -1) + kill(pid, SIGKILL); + if (!res && oreadformat) + ast_set_read_format(chan, oreadformat); + + return res; +} + +static int unload_module(void) +{ + return ast_unregister_application(app); +} + +static int load_module(void) +{ + return ast_register_application_xml(app, ices_exec); +} + +AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Encode and Stream via icecast and ices"); diff --git a/pool/shard008/C/0130787_open-app-config.c b/pool/shard008/C/0130787_open-app-config.c new file mode 100644 index 0000000000000000000000000000000000000000..e3c72b90d3794658bdaeea98acf608fc2ade5170 --- /dev/null +++ b/pool/shard008/C/0130787_open-app-config.c @@ -0,0 +1,283 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- +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 +Library General Public License for more details. + +You should have received a copy of the GNU Library General Public +License along with this program; if not, write to the +Free Software Foundation, Inc., 59 Temple Place - Suite 330, +Boston, MA 02111-1307, USA. + +Author: David Liang + +*/ +#include +#include +#include +#include "config.h" +#include "open-app-config.h" + +/* TODO maybe we should make it an abstruct */ +struct _OpenAppConfigPrivate +{ + GKeyFile *key_file; +}; + +G_DEFINE_TYPE (OpenAppConfig, open_app_config, G_TYPE_OBJECT) + +static GKeyFile * +create_default_key_file (gchar *file_url) +{ + g_return_val_if_fail (file_url != NULL, NULL); + + GKeyFile *key_file; + const gchar *default_url; + const gchar *default_type; + GError *error; + gchar *content; + gint len; + + key_file = g_key_file_new (); + default_url = "api.opendesktop.org"; + default_type = "ocs"; + g_key_file_set_value (key_file, "Server", "uri", default_url); + g_key_file_set_value (key_file, "Server", "type", default_type); + content = g_key_file_to_data (key_file, &len, NULL); + + error = NULL; + if (!g_file_set_contents (file_url, content, len, &error)) { + g_error ("Error in save user file %s\n", error->message); + g_error_free (error); + } + g_free (content); + + return key_file; +} + +static void +open_app_config_init (OpenAppConfig *config) +{ + OpenAppConfigPrivate *priv; + GError *error; + gchar *filename; + + config->priv = priv = G_TYPE_INSTANCE_GET_PRIVATE (config, + OPEN_APP_TYPE_CONFIG, + OpenAppConfigPrivate); + + filename = g_build_filename (g_get_user_config_dir (), PACKAGE_NAME, "config", NULL); + if (!g_file_test (filename, G_FILE_TEST_EXISTS)) { + g_free (filename); + filename = g_build_filename (CONFIGDIR, "config", NULL); + } + + if (!g_file_test (filename, G_FILE_TEST_EXISTS)) { + gchar *dir, *cmd; + + dir = g_build_filename (g_get_user_config_dir (), PACKAGE_NAME, NULL); + if (!g_file_test (dir, G_FILE_TEST_EXISTS)) { + g_mkdir (dir, 0755); + } + g_free (dir); + + g_free (filename); + filename = g_build_filename (g_get_user_config_dir (), PACKAGE_NAME, "config", NULL); + priv->key_file = create_default_key_file (filename); + } else { + priv->key_file = g_key_file_new (); + error = NULL; + g_key_file_load_from_file (priv->key_file, filename, G_KEY_FILE_NONE, &error); + + if (error) { + g_warning ("Failed to load keyfile %s %s", filename, error->message); + g_error_free (error); + + g_key_file_free (priv->key_file); + priv->key_file = NULL; + } + } + g_free (filename); +} + +static void +open_app_config_dispose (GObject *object) +{ + G_OBJECT_CLASS (open_app_config_parent_class)->dispose (object); +} + +static void +open_app_config_finalize (GObject *object) +{ + OpenAppConfig *config = OPEN_APP_CONFIG (object); + OpenAppConfigPrivate *priv = config->priv; + + if (priv->key_file) + g_key_file_free (priv->key_file); + + G_OBJECT_CLASS (open_app_config_parent_class)->finalize (object); +} + +static void +open_app_config_class_init (OpenAppConfigClass *klass) +{ + GObjectClass *object_class = G_OBJECT_CLASS (klass); + + object_class->dispose = open_app_config_dispose; + object_class->finalize = open_app_config_finalize; + + g_type_class_add_private (object_class, sizeof (OpenAppConfigPrivate)); +} + +OpenAppConfig * +open_app_config_new (void) +{ + return g_object_new (OPEN_APP_TYPE_CONFIG, NULL); +} + +gchar * +open_app_config_get_server_uri (OpenAppConfig *config) +{ + g_return_val_if_fail (config->priv->key_file != NULL, NULL); + + OpenAppConfigPrivate *priv; + GError *error; + gchar *val; + + priv = config->priv; + error = NULL; + val = g_key_file_get_value (priv->key_file, "Server", "uri", &error); + + if (error) { + g_warning ("Failed to load server uri %s", error->message); + g_error_free (error); + return NULL; + } + + if (val && val [0]) + return val; + else + return NULL; +} + +gchar * +open_app_config_get_server_type (OpenAppConfig *config) +{ + OpenAppConfigPrivate *priv; + GError *error; + gchar *val; + + priv = config->priv; + error = NULL; + val = g_key_file_get_value (priv->key_file, "Server", "type", &error); + + if (error) { + g_warning ("Failed to load server type %s", error->message); + g_error_free (error); + return NULL; + } + + if (val && val [0]) + return val; + else + return NULL; +} + +gchar * +open_app_config_get_username (OpenAppConfig *config) +{ + OpenAppConfigPrivate *priv; + GError *error; + gchar *val; + + priv = config->priv; + error = NULL; + val = g_key_file_get_value (priv->key_file, "Server", "username", &error); + if (error) { + g_error_free (error); + return NULL; + } + + if (val && val [0]) + return val; + else + return NULL; +} + +gchar * +open_app_config_get_password (OpenAppConfig *config) +{ + OpenAppConfigPrivate *priv; + GError *error; + gchar *val; + + priv = config->priv; + error = NULL; + val = g_key_file_get_value (priv->key_file, "Server", "password", &error); + if (error) { + g_error_free (error); + return NULL; + } + if (val && val [0]) { + gchar *real; + gint len; + + real = g_base64_decode (val, &len); + g_free (val); + return real; + } else + return NULL; +} + +gboolean +open_app_config_save (OpenAppConfig *config, gchar *username, gchar *password) +{ + OpenAppConfigPrivate *priv; + GError *error; + gchar *filename; + gchar *content; + gint len; + gboolean val; + + if (!username) + return TRUE; + priv = config->priv; + g_key_file_set_value (priv->key_file, "Server", "username", username); + if (password) { + const gchar *warning; + gchar *encode; + + encode = g_base64_encode (password, strlen (password)); + g_key_file_set_value (priv->key_file, "Server", "password", encode); + g_free (encode); + + warning = "The password is base64 encoded, should not save it to local "; + error = NULL; + if (!g_key_file_set_comment (priv->key_file, "Server", "password", warning, &error)) { + g_error ("Error in set comment %s\n", error->message); + g_error_free (error); + error = NULL; + } + } + error = NULL; + content = g_key_file_to_data (priv->key_file, &len, &error); + if (error) { + g_error ("Error in get data %s\n", error->message); + g_error_free (error); + return FALSE; + } + + filename = g_build_filename (g_get_user_config_dir (), PACKAGE_NAME, "config", NULL); + error = NULL; + if (!g_file_set_contents (filename, content, len, &error)) { + val = FALSE; + g_error ("Error in save user file %s\n", error->message); + g_error_free (error); + } else { + val = TRUE; + } + g_free (content); + g_free (filename); + + return val; +} diff --git a/pool/shard008/C/0130790_mips-sde-tdep.c b/pool/shard008/C/0130790_mips-sde-tdep.c new file mode 100644 index 0000000000000000000000000000000000000000..685c3c7263c0c5c8e12c2d02e243219ea3daf432 --- /dev/null +++ b/pool/shard008/C/0130790_mips-sde-tdep.c @@ -0,0 +1,268 @@ +/* Target-dependent code for SDE on MIPS processors. + + Copyright (C) 2014-2020 Free Software Foundation, Inc. + + This file is part of GDB. + + 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 . */ + +#include "defs.h" +#include "osabi.h" +#include "elf-bfd.h" +#include "block.h" +#include "symtab.h" + +#include "frame.h" +#include "frame-unwind.h" +#include "frame-base.h" +#include "trad-frame.h" + +#include "mips-tdep.h" + +/* Fill in the register cache *THIS_CACHE for THIS_FRAME for use + in the SDE frame unwinder. */ + +static struct trad_frame_cache * +mips_sde_frame_cache (struct frame_info *this_frame, void **this_cache) +{ + struct gdbarch *gdbarch = get_frame_arch (this_frame); + const struct mips_regnum *regs = mips_regnum (gdbarch); + const int sizeof_reg_t = mips_abi_regsize (gdbarch); + enum mips_abi abi = mips_abi (gdbarch); + struct trad_frame_cache *cache; + CORE_ADDR xcpt_frame; + CORE_ADDR start_addr; + CORE_ADDR stack_addr; + CORE_ADDR pc; + int i; + + if (*this_cache != NULL) + return (struct trad_frame_cache *) *this_cache; + cache = trad_frame_cache_zalloc (this_frame); + *this_cache = cache; + + /* The previous registers are held in struct xcptcontext + which is at $sp+offs + + struct xcptcontext { + reg_t sr; CP0 Status + reg_t cr; CP0 Cause + reg_t epc; CP0 EPC + reg_t vaddr; CP0 BadVAddr + reg_t regs[32]; General registers + reg_t mdlo; LO + reg_t mdhi; HI + reg_t mdex; ACX + ... + }; + */ + + stack_addr = get_frame_register_signed (this_frame, + gdbarch_sp_regnum (gdbarch)); + switch (abi) + { + case MIPS_ABI_O32: + /* 40: XCPTCONTEXT + 24: xcpt_gen() argspace (16 bytes) + 16: _xcptcall() saved ra, rounded up ( 8 bytes) + 00: _xcptcall() argspace (16 bytes) */ + xcpt_frame = stack_addr + 40; + break; + case MIPS_ABI_N32: + case MIPS_ABI_N64: + default: /* Wild guess. */ + /* 16: XCPTCONTEXT + 16: xcpt_gen() argspace ( 0 bytes) + 00: _xcptcall() saved ra, rounded up (16 bytes) */ + xcpt_frame = stack_addr + 16; + break; + } + + trad_frame_set_reg_addr (cache, + MIPS_PS_REGNUM + gdbarch_num_regs (gdbarch), + xcpt_frame + 0 * sizeof_reg_t); + trad_frame_set_reg_addr (cache, + regs->cause + gdbarch_num_regs (gdbarch), + xcpt_frame + 1 * sizeof_reg_t); + trad_frame_set_reg_addr (cache, + regs->pc + gdbarch_num_regs (gdbarch), + xcpt_frame + 2 * sizeof_reg_t); + trad_frame_set_reg_addr (cache, + regs->badvaddr + gdbarch_num_regs (gdbarch), + xcpt_frame + 3 * sizeof_reg_t); + for (i = 0; i < MIPS_NUMREGS; i++) + trad_frame_set_reg_addr (cache, + i + MIPS_ZERO_REGNUM + gdbarch_num_regs (gdbarch), + xcpt_frame + (4 + i) * sizeof_reg_t); + trad_frame_set_reg_addr (cache, + regs->lo + gdbarch_num_regs (gdbarch), + xcpt_frame + 36 * sizeof_reg_t); + trad_frame_set_reg_addr (cache, + regs->hi + gdbarch_num_regs (gdbarch), + xcpt_frame + 37 * sizeof_reg_t); + + pc = get_frame_pc (this_frame); + find_pc_partial_function (pc, NULL, &start_addr, NULL); + trad_frame_set_id (cache, frame_id_build (start_addr, stack_addr)); + + return cache; +} + +/* Implement the this_id function for the SDE frame unwinder. */ + +static void +mips_sde_frame_this_id (struct frame_info *this_frame, void **this_cache, + struct frame_id *this_id) +{ + struct trad_frame_cache *this_trad_cache + = mips_sde_frame_cache (this_frame, this_cache); + + trad_frame_get_id (this_trad_cache, this_id); +} + +/* Implement the prev_register function for the SDE frame unwinder. */ + +static struct value * +mips_sde_frame_prev_register (struct frame_info *this_frame, + void **this_cache, + int prev_regnum) +{ + struct trad_frame_cache *trad_cache + = mips_sde_frame_cache (this_frame, this_cache); + + return trad_frame_get_register (trad_cache, this_frame, prev_regnum); +} + +/* Implement the sniffer function for the SDE frame unwinder. */ + +static int +mips_sde_frame_sniffer (const struct frame_unwind *self, + struct frame_info *this_frame, + void **this_cache) +{ + CORE_ADDR pc = get_frame_pc (this_frame); + const char *name; + + find_pc_partial_function (pc, &name, NULL, NULL); + return (name + && (strcmp (name, "_xcptcall") == 0 + || strcmp (name, "_sigtramp") == 0)); +} + +/* Data structure for the SDE frame unwinder. */ + +static const struct frame_unwind mips_sde_frame_unwind = +{ + SIGTRAMP_FRAME, + default_frame_unwind_stop_reason, + mips_sde_frame_this_id, + mips_sde_frame_prev_register, + NULL, + mips_sde_frame_sniffer +}; + +/* Implement the this_base, this_locals, and this_args hooks + for the normal unwinder. */ + +static CORE_ADDR +mips_sde_frame_base_address (struct frame_info *this_frame, void **this_cache) +{ + struct trad_frame_cache *this_trad_cache + = mips_sde_frame_cache (this_frame, this_cache); + + return trad_frame_get_this_base (this_trad_cache); +} + +static const struct frame_base mips_sde_frame_base = +{ + &mips_sde_frame_unwind, + mips_sde_frame_base_address, + mips_sde_frame_base_address, + mips_sde_frame_base_address +}; + +static const struct frame_base * +mips_sde_frame_base_sniffer (struct frame_info *this_frame) +{ + if (mips_sde_frame_sniffer (&mips_sde_frame_unwind, this_frame, NULL)) + return &mips_sde_frame_base; + else + return NULL; +} + +static void +mips_sde_elf_osabi_sniff_abi_tag_sections (bfd *abfd, asection *sect, + void *obj) +{ + enum gdb_osabi *os_ident_ptr = (enum gdb_osabi *) obj; + const char *name; + + name = bfd_section_name (sect); + + /* The presence of a section with a ".sde" prefix is indicative + of an SDE binary. */ + if (startswith (name, ".sde")) + *os_ident_ptr = GDB_OSABI_SDE; +} + +/* OSABI sniffer for MIPS SDE. */ + +static enum gdb_osabi +mips_sde_elf_osabi_sniffer (bfd *abfd) +{ + enum gdb_osabi osabi = GDB_OSABI_UNKNOWN; + unsigned int elfosabi; + + /* If the generic sniffer gets a hit, return and let other sniffers + get a crack at it. */ + bfd_map_over_sections (abfd, + generic_elf_osabi_sniff_abi_tag_sections, + &osabi); + if (osabi != GDB_OSABI_UNKNOWN) + return GDB_OSABI_UNKNOWN; + + elfosabi = elf_elfheader (abfd)->e_ident[EI_OSABI]; + + if (elfosabi == ELFOSABI_NONE) + { + /* When elfosabi is ELFOSABI_NONE (0), then the ELF structures in the + file are conforming to the base specification for that machine + (there are no OS-specific extensions). In order to determine the + real OS in use we must look for OS notes that have been added. + + For SDE, we simply look for sections named with .sde as prefixes. */ + bfd_map_over_sections (abfd, + mips_sde_elf_osabi_sniff_abi_tag_sections, + &osabi); + } + return osabi; +} + +static void +mips_sde_init_abi (struct gdbarch_info info, struct gdbarch *gdbarch) +{ + frame_unwind_append_unwinder (gdbarch, &mips_sde_frame_unwind); + frame_base_append_sniffer (gdbarch, mips_sde_frame_base_sniffer); +} + +void _initialize_mips_sde_tdep (); +void +_initialize_mips_sde_tdep () +{ + gdbarch_register_osabi_sniffer (bfd_arch_mips, + bfd_target_elf_flavour, + mips_sde_elf_osabi_sniffer); + + gdbarch_register_osabi (bfd_arch_mips, 0, GDB_OSABI_SDE, mips_sde_init_abi); +} diff --git a/pool/shard008/C/0130795_install.c b/pool/shard008/C/0130795_install.c new file mode 100644 index 0000000000000000000000000000000000000000..ecd10e93caa9259413cee1b5e9473309c7967220 --- /dev/null +++ b/pool/shard008/C/0130795_install.c @@ -0,0 +1,102 @@ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include + +#include "install.h" + +/** + * @addtogroup Gotham_Module_Install + * @{ + */ + +/** + * Define module name + */ +static const char *name = "Install"; + +/** + * @brief Callback for freeing a eina_hash from a job object + * @param data data to free + */ +static void +_job_free_cb(void *data) +{ + EINA_SAFETY_ON_NULL_RETURN(data); + free(data); +} + +/** + * @brief Install Module init function. + * Init needed libraries (eina), and register in eina_log_domain + * @return Module name + */ +const char * +module_init(void) +{ + eina_init(); + _module_install_log_dom = eina_log_domain_register("module_install", + EINA_COLOR_CYAN); + return name; +} + +/** + * @brief Install Module register function. + * Allocate module objects and register functions. + * @param gotham Gotham object + * @return Install module structure + */ +void * +module_register(Gotham *gotham) +{ + Module_Install *install; + + if (gotham->me->type != GOTHAM_CITIZEN_TYPE_BOTMAN) + return NULL; + + install = calloc(1, sizeof(Module_Install)); + EINA_SAFETY_ON_NULL_RETURN_VAL(install, NULL); + + install->gotham = gotham; + install->jobs = eina_hash_pointer_new(_job_free_cb); + install->conf = gotham_serialize_file_to_struct(MODULE_INSTALL_CONF, (Gotham_Deserialization_Function)azy_value_to_Module_Install_Conf); + + module_install_botman_commands_register(); + + return install; +} + +/** + * @brief Install Module unregister function. + * Remove functions from list and free Module_Help structure + * @param data Module_Install structure + */ +void +module_unregister(void *data) +{ + Module_Install *install = data; + + EINA_SAFETY_ON_NULL_RETURN(install); + + module_install_botman_commands_unregister(); + eina_hash_free(install->jobs); + + free(install); +} + +/** + * @brief Install Module shutdown function. + * Unregister from eina_log and shutdown eina + */ +void +module_shutdown(void) +{ + eina_log_domain_unregister(_module_install_log_dom); + eina_shutdown(); +} + +/** + * @} + */ diff --git a/pool/shard008/C/0130801_zte_tps65132.c b/pool/shard008/C/0130801_zte_tps65132.c new file mode 100644 index 0000000000000000000000000000000000000000..ee7fb2754021f69e27c9eddc24f1b55f13d2f34b --- /dev/null +++ b/pool/shard008/C/0130801_zte_tps65132.c @@ -0,0 +1,266 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +/////////////// +#include + +#include + +#include + +#include +#include + +#include +#include + +#include + +#include + +#include +#include +#include +#include +#include + +#include +#include <../../../drivers/staging/android/timed_output.h> +#include +#include +#include +#include +#include +#include + +#include "zte_tps65132.h" + + +#define TPS65132_DRIVER_NAME "tps65132" + +#define NXP_TPS65132_DEBUG + +#define DRIVER_DESC "NFC driver for TPS65132" + +#define MAX_BUFFER_SIZE 512 +#define TPS65132_MSG_MAX_SIZE 0x21 /* at normal HCI mode */ + +/* Timing restrictions (ms) */ +#define TPS65132_RESETVEN_TIME 35 /* 7 */ + +//struct tps65132_nfc_platform_data tps65132_nfc_platform_data; + +enum tps65132_irq { + TPS65132_NONE, + TPS65132_INT, +}; + +struct stps65132_dev { + wait_queue_head_t read_wq; + //struct tps65132_nfc_platform_data *pdata; + struct mutex read_mutex; + struct i2c_client *client; + struct miscdevice miscdev; + bool irq_enabled; + spinlock_t irq_enabled_lock; + enum tps65132_irq read_irq; + + int updata_gpio; + int ven_gpio; + int irq_gpio; + int (*request_resources) (void); + void (*free_resources) (void); + void (*enable) (int fw); + int (*test) (void); + void (*disable) (void); + int (*irq_status) (void); +}; + +static struct stps65132_dev * tps65132_dev; + +static int tps65132_write_reg_val(unsigned char reg, unsigned char val) +{ + int i = 0; + int err = 0; + + while (i < 3) + { +#ifdef NXP_TPS65132_DEBUG + pr_debug("%s: 0x%x:0x%x", __FUNCTION__,reg, val); +#endif + err = i2c_smbus_write_byte_data(tps65132_dev->client, reg, val); + if(err < 0){ + printk(KERN_ERR"%s, err=%d\n", __FUNCTION__, err); + break; + } + i++; + } + + return err; +} + +static unsigned char tps65132_read_reg( unsigned char reg) +{ + return i2c_smbus_read_byte_data(tps65132_dev->client, reg); +} + +void tps65132_set_output_voltage(int positive_voltage, int negative_voltage) +{ + int pos_val=0; + int neg_val=0; + int regff_val=0; + + pos_val= ( positive_voltage - 4000)/100; + neg_val= ( negative_voltage - 4000)/100; + +#ifdef NXP_TPS65132_DEBUG + pr_debug("[tps]%s:positive_voltage=%d,negative_voltage=%d, ",__FUNCTION__,positive_voltage,negative_voltage); + pr_debug("pos_val=0x%x , neg_val= 0x%x ~~~~~~~~~\n",pos_val,neg_val); +#endif + + tps65132_write_reg_val(0x00,pos_val); + tps65132_write_reg_val(0x01,neg_val); + regff_val=tps65132_read_reg(0xff) ; +#ifdef NXP_TPS65132_DEBUG + pr_debug("regff_val=0x%x~~~~~~~~~\n",regff_val); +#endif + regff_val |=(1<<8); +#ifdef NXP_TPS65132_DEBUG + pr_debug("regff_val=0x%x~~~~~~~~~\n",regff_val); +#endif + tps65132_write_reg_val(0xff,regff_val); + +} + +void tps65132_show_reg(void ) +{ + int val0,val1,regff_val; + val0=tps65132_read_reg(0x00); + val1=tps65132_read_reg(0x01); + regff_val=tps65132_read_reg(0xff); +#ifdef NXP_TPS65132_DEBUG + pr_debug("[tps]%s:reg00=0x%x, reg01=0x%x ,regff_val= 0x%x~~~~~~~~~~~~\n",__FUNCTION__,val0,val1,regff_val); +#endif +} + +static __devinit int tps65132_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + int irq_gpio = -1; + int updata_gpio = -1; + int ven_gpio = -1; + int ret; + +#ifdef NXP_TPS65132_DEBUG + pr_debug("[tps] %s:line%d +\n",__FUNCTION__,__LINE__); +#endif + + if (tps65132_dev != NULL) { + dev_warn(&client->dev, "only one tps65132 supported.\n"); + return -EBUSY; + } + + if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) { + dev_err(&client->dev, "%s : need I2C_FUNC_I2C\n", __func__); + return -ENODEV; + } + + tps65132_dev = kzalloc(sizeof(struct stps65132_dev), GFP_KERNEL); + if (tps65132_dev == NULL) { + dev_err(&client->dev, "failed to allocate memory for module data\n"); + ret = -ENOMEM; + goto err_exit; + } + + tps65132_dev->client = client; + tps65132_dev->irq_gpio = irq_gpio; + tps65132_dev->updata_gpio = updata_gpio; + tps65132_dev->ven_gpio = ven_gpio; + + i2c_set_clientdata(client, tps65132_dev); + +#if defined(CONFIG_ZTEMT_MIPI_1080P_R63311_SHARP_IPS) + //tps65132_set_output_voltage(5600,5600); + tps65132_set_output_voltage(5000,5000); +#else + tps65132_set_output_voltage(4900,4900); +#endif + + +#ifdef NXP_TPS65132_DEBUG + pr_debug("[tps] %s:line%d -\n",__FUNCTION__,__LINE__); +#endif + + return 0; + +err_exit: + return ret; + +} + +static __devexit int tps65132_remove(struct i2c_client *client) +{ + struct stps65132_dev *dev = i2c_get_clientdata(client); + + dev_dbg(&client->dev, "%s\n", __func__); + + if (dev->disable) + dev->disable(); + + mutex_destroy(&dev->read_mutex); + kfree(dev); + + tps65132_dev = NULL; + + return 0; +} + +static struct of_device_id tps_match_table[] = { + { .compatible = "tps,tps65132_i2c_adapter",}, + { }, +}; + +static const struct i2c_device_id tps65132_id_table[] = { + { TPS65132_DRIVER_NAME, 0 }, + { } +}; + +MODULE_DEVICE_TABLE(i2c, tps65132_id_table); + +static struct i2c_driver tps65132_driver = { + .id_table = tps65132_id_table, + .probe = tps65132_probe, + .remove = tps65132_remove, + .driver = { + .owner = THIS_MODULE, + .name = TPS65132_DRIVER_NAME, + .of_match_table = tps_match_table, + }, +}; + +module_i2c_driver(tps65132_driver); + +MODULE_DESCRIPTION("I2C_TEST_TPS"); +MODULE_LICENSE("GPL"); + diff --git a/pool/shard008/C/0130802_checker.c b/pool/shard008/C/0130802_checker.c new file mode 100644 index 0000000000000000000000000000000000000000..f599cc837ae0ddc4ddad052fdb846ae305c6672a --- /dev/null +++ b/pool/shard008/C/0130802_checker.c @@ -0,0 +1,172 @@ +/* + * License Applicability. Except to the extent portions of this file are + * made subject to an alternative license as permitted in the SGI Free + * Software License B, Version 1.1 (the "License"), the contents of this + * file are subject only to the provisions of the License. You may not use + * this file except in compliance with the License. You may obtain a copy + * of the License at Silicon Graphics, Inc., attn: Legal Services, 1600 + * Amphitheatre Parkway, Mountain View, CA 94043-1351, or at: + * + * http://oss.sgi.com/projects/FreeB + * + * Note that, as provided in the License, the Software is distributed on an + * "AS IS" basis, with ALL EXPRESS AND IMPLIED WARRANTIES AND CONDITIONS + * DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES AND + * CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A + * PARTICULAR PURPOSE, AND NON-INFRINGEMENT. + * + * Original Code. The Original Code is: OpenGL Sample Implementation, + * Version 1.2.1, released January 26, 2000, developed by Silicon Graphics, + * Inc. The Original Code is Copyright (c) 1991-2000 Silicon Graphics, Inc. + * Copyright in any portions created by third parties is as indicated + * elsewhere herein. All Rights Reserved. + * + * Additional Notice Provisions: The application programming interfaces + * established by SGI in conjunction with the Original Code are The + * OpenGL(R) Graphics System: A Specification (Version 1.2.1), released + * April 1, 1999; The OpenGL(R) Graphics System Utility Library (Version + * 1.3), released November 4, 1998; and OpenGL(R) Graphics with the X + * Window System(R) (Version 1.3), released October 19, 1998. This software + * was created using the OpenGL(R) version 1.2.1 Sample Implementation + * published by SGI, but has not been independently verified as being + * compliant with the OpenGL(R) version 1.2.1 Specification. + * + */ + +/* checker.c + * This program texture maps a checkerboard image onto + * two rectangles. + * + * If running this program on OpenGL 1.0, texture objects are + * not used. + */ +#include +#include +#include "ug.h" + +/* Create checkerboard texture */ +#define checkImageWidth 64 +#define checkImageHeight 64 +static GLubyte checkImage[checkImageHeight][checkImageWidth][4]; + +#ifdef GL_VERSION_1_1 +static GLuint texName; +#endif + +void makeCheckImage(void) +{ + int i, j, c; + + for (i = 0; i < checkImageHeight; i++) { + for (j = 0; j < checkImageWidth; j++) { + c = ((((i&0x8)==0)^((j&0x8))==0))*255; + checkImage[i][j][0] = (GLubyte) c; + checkImage[i][j][1] = (GLubyte) c; + checkImage[i][j][2] = (GLubyte) c; + checkImage[i][j][3] = (GLubyte) 255; + } + } +} + +void init(void) +{ + static const GLfloat v[] = { + -2.0, -1.0, 0.0, + -2.0, 1.0, 0.0, + 0.0, -1.0, 0.0, + 0.0, 1.0, 0.0, + + 1.0, -1.0, 0.0, + 1.0, 1.0, 0.0, + 2.41421, -1.0, -1.41421, + 2.41421, 1.0, -1.41421, + }; + static const GLfloat t[] = { + 0.0, 0.0, + 0.0, 1.0, + 1.0, 0.0, + 1.0, 1.0, + + 0.0, 0.0, + 0.0, 1.0, + 1.0, 0.0, + 1.0, 1.0, + }; + glClearColor (0.0, 0.0, 0.0, 0.0); + glShadeModel(GL_FLAT); + glEnable(GL_DEPTH_TEST); + + makeCheckImage(); + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + +#ifdef GL_VERSION_1_1 + glGenTextures(1, &texName); + glBindTexture(GL_TEXTURE_2D, texName); +#endif + + glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); +#ifdef GL_VERSION_1_1 + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, checkImageWidth, checkImageHeight, + 0, GL_RGBA, GL_UNSIGNED_BYTE, checkImage); +#else + glTexImage2D(GL_TEXTURE_2D, 0, 4, checkImageWidth, checkImageHeight, + 0, GL_RGBA, GL_UNSIGNED_BYTE, checkImage); +#endif + glVertexPointer(3, GL_FLOAT, 0, v); + glTexCoordPointer(2, GL_FLOAT, 0, t); + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_TEXTURE_COORD_ARRAY); +} + +void display(UGWindow uwin) +{ + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glEnable(GL_TEXTURE_2D); + glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); +#ifdef GL_VERSION_1_1 + glBindTexture(GL_TEXTURE_2D, texName); +#endif + + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + glDrawArrays(GL_TRIANGLE_STRIP, 4, 4); + glFlush(); + ugSwapBuffers(uwin); + glDisable(GL_TEXTURE_2D); +} + +void reshape(UGWindow uwin, int w, int h) +{ + glViewport(0, 0, (GLsizei) w, (GLsizei) h); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + ugluPerspectivef(60.0, (GLfloat) w/(GLfloat) h, 1.0, 30.0); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + glTranslatef(0.0, 0.0, -3.6); +} + +void keyboard (UGWindow uwin, int key, int x, int y) +{ + switch (key) { + case 27: + exit(0); + break; + default: + break; + } +} + +int main(int argc, char** argv) +{ + UGCtx ug = ugInit(); + UGWindow uwin = ugCreateWindow (ug, "UG_DEPTH", argv[0], 250, 250, 100, 100); + init (); + ugDisplayFunc(uwin, display); + ugReshapeFunc(uwin, reshape); + ugKeyboardFunc(uwin, keyboard); + ugMainLoop(ug); + return 0; +} diff --git a/pool/shard008/C/0130805_pci.c b/pool/shard008/C/0130805_pci.c new file mode 100644 index 0000000000000000000000000000000000000000..4d50dad29ddffae5f364744946a92bd9fdcf72b5 --- /dev/null +++ b/pool/shard008/C/0130805_pci.c @@ -0,0 +1,177 @@ +// SPDX-License-Identifier: ISC +/* + * Copyright (C) 2016 Felix Fietkau + */ + +#include +#include +#include + +#include "mt76x2.h" + +static const struct pci_device_id mt76x2e_device_table[] = { + { PCI_DEVICE(0x14c3, 0x7662) }, + { PCI_DEVICE(0x14c3, 0x7612) }, + { PCI_DEVICE(0x14c3, 0x7602) }, + { }, +}; + +static int +mt76x2e_probe(struct pci_dev *pdev, const struct pci_device_id *id) +{ + static const struct mt76_driver_ops drv_ops = { + .txwi_size = sizeof(struct mt76x02_txwi), + .drv_flags = MT_DRV_TX_ALIGNED4_SKBS | + MT_DRV_SW_RX_AIRTIME, + .survey_flags = SURVEY_INFO_TIME_TX, + .update_survey = mt76x02_update_channel, + .tx_prepare_skb = mt76x02_tx_prepare_skb, + .tx_complete_skb = mt76x02_tx_complete_skb, + .rx_skb = mt76x02_queue_rx_skb, + .rx_poll_complete = mt76x02_rx_poll_complete, + .sta_ps = mt76x02_sta_ps, + .sta_add = mt76x02_sta_add, + .sta_remove = mt76x02_sta_remove, + }; + struct mt76x02_dev *dev; + struct mt76_dev *mdev; + int ret; + + ret = pcim_enable_device(pdev); + if (ret) + return ret; + + ret = pcim_iomap_regions(pdev, BIT(0), pci_name(pdev)); + if (ret) + return ret; + + pci_set_master(pdev); + + ret = pci_set_dma_mask(pdev, DMA_BIT_MASK(32)); + if (ret) + return ret; + + mdev = mt76_alloc_device(&pdev->dev, sizeof(*dev), &mt76x2_ops, + &drv_ops); + if (!mdev) + return -ENOMEM; + + dev = container_of(mdev, struct mt76x02_dev, mt76); + mt76_mmio_init(mdev, pcim_iomap_table(pdev)[0]); + mt76x2_reset_wlan(dev, false); + + mdev->rev = mt76_rr(dev, MT_ASIC_VERSION); + dev_info(mdev->dev, "ASIC revision: %08x\n", mdev->rev); + + mt76_wr(dev, MT_INT_MASK_CSR, 0); + + ret = devm_request_irq(mdev->dev, pdev->irq, mt76x02_irq_handler, + IRQF_SHARED, KBUILD_MODNAME, dev); + if (ret) + goto error; + + ret = mt76x2_register_device(dev); + if (ret) + goto error; + + /* Fix up ASPM configuration */ + + /* RG_SSUSB_G1_CDR_BIR_LTR = 0x9 */ + mt76_rmw_field(dev, 0x15a10, 0x1f << 16, 0x9); + + /* RG_SSUSB_G1_CDR_BIC_LTR = 0xf */ + mt76_rmw_field(dev, 0x15a0c, 0xf << 28, 0xf); + + /* RG_SSUSB_CDR_BR_PE1D = 0x3 */ + mt76_rmw_field(dev, 0x15c58, 0x3 << 6, 0x3); + + mt76_pci_disable_aspm(pdev); + + return 0; + +error: + ieee80211_free_hw(mt76_hw(dev)); + return ret; +} + +static void +mt76x2e_remove(struct pci_dev *pdev) +{ + struct mt76_dev *mdev = pci_get_drvdata(pdev); + struct mt76x02_dev *dev = container_of(mdev, struct mt76x02_dev, mt76); + + mt76_unregister_device(mdev); + mt76x2_cleanup(dev); + mt76_free_device(mdev); +} + +static int __maybe_unused +mt76x2e_suspend(struct pci_dev *pdev, pm_message_t state) +{ + struct mt76_dev *mdev = pci_get_drvdata(pdev); + int i, err; + + napi_disable(&mdev->tx_napi); + tasklet_kill(&mdev->pre_tbtt_tasklet); + mt76_worker_disable(&mdev->tx_worker); + + mt76_for_each_q_rx(mdev, i) + napi_disable(&mdev->napi[i]); + + pci_enable_wake(pdev, pci_choose_state(pdev, state), true); + pci_save_state(pdev); + err = pci_set_power_state(pdev, pci_choose_state(pdev, state)); + if (err) + goto restore; + + return 0; + +restore: + mt76_for_each_q_rx(mdev, i) + napi_enable(&mdev->napi[i]); + napi_enable(&mdev->tx_napi); + + return err; +} + +static int __maybe_unused +mt76x2e_resume(struct pci_dev *pdev) +{ + struct mt76_dev *mdev = pci_get_drvdata(pdev); + struct mt76x02_dev *dev = container_of(mdev, struct mt76x02_dev, mt76); + int i, err; + + err = pci_set_power_state(pdev, PCI_D0); + if (err) + return err; + + pci_restore_state(pdev); + + mt76_worker_enable(&mdev->tx_worker); + mt76_for_each_q_rx(mdev, i) { + napi_enable(&mdev->napi[i]); + napi_schedule(&mdev->napi[i]); + } + napi_enable(&mdev->tx_napi); + napi_schedule(&mdev->tx_napi); + + return mt76x2_resume_device(dev); +} + +MODULE_DEVICE_TABLE(pci, mt76x2e_device_table); +MODULE_FIRMWARE(MT7662_FIRMWARE); +MODULE_FIRMWARE(MT7662_ROM_PATCH); +MODULE_LICENSE("Dual BSD/GPL"); + +static struct pci_driver mt76pci_driver = { + .name = KBUILD_MODNAME, + .id_table = mt76x2e_device_table, + .probe = mt76x2e_probe, + .remove = mt76x2e_remove, +#ifdef CONFIG_PM + .suspend = mt76x2e_suspend, + .resume = mt76x2e_resume, +#endif /* CONFIG_PM */ +}; + +module_pci_driver(mt76pci_driver); diff --git a/pool/shard008/C/0130809_nested_struct7.c b/pool/shard008/C/0130809_nested_struct7.c new file mode 100644 index 0000000000000000000000000000000000000000..9a66499ab81f58600598a6530f2b7e3251ac3dbb --- /dev/null +++ b/pool/shard008/C/0130809_nested_struct7.c @@ -0,0 +1,111 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure passing with different structure size. + Contains structs as parameter of the struct itself. + Sample taken from Alan Modras patch to src/prep_cif.c. + Limitations: none. + PR: none. + Originator: 20051010 */ + +/* { dg-do run } */ +#include "ffitest.h" + +typedef struct A { + unsigned long long a; + unsigned char b; +} A; + +typedef struct B { + struct A x; + unsigned char y; +} B; + +static B B_fn(struct A b2, struct B b3) +{ + struct B result; + + result.x.a = b2.a + b3.x.a; + result.x.b = b2.b + b3.x.b + b3.y; + result.y = b2.b + b3.x.b; + + printf("%d %d %d %d %d: %d %d %d\n", (int)b2.a, b2.b, + (int)b3.x.a, b3.x.b, b3.y, + (int)result.x.a, result.x.b, result.y); + + return result; +} + +static void +B_gn(ffi_cif* cif __UNUSED__, void* resp, void** args, + void* userdata __UNUSED__) +{ + struct A b0; + struct B b1; + + b0 = *(struct A*)(args[0]); + b1 = *(struct B*)(args[1]); + + *(B*)resp = B_fn(b0, b1); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + void* args_dbl[3]; + ffi_type* cls_struct_fields[3]; + ffi_type* cls_struct_fields1[3]; + ffi_type cls_struct_type, cls_struct_type1; + ffi_type* dbl_arg_types[3]; + + struct A e_dbl = { 1LL, 7}; + struct B f_dbl = {{12.0 , 127}, 99}; + + struct B res_dbl; + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + cls_struct_type1.size = 0; + cls_struct_type1.alignment = 0; + cls_struct_type1.type = FFI_TYPE_STRUCT; + cls_struct_type1.elements = cls_struct_fields1; + + cls_struct_fields[0] = &ffi_type_uint64; + cls_struct_fields[1] = &ffi_type_uchar; + cls_struct_fields[2] = NULL; + + cls_struct_fields1[0] = &cls_struct_type; + cls_struct_fields1[1] = &ffi_type_uchar; + cls_struct_fields1[2] = NULL; + + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type1; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type1, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &e_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(B_fn), &res_dbl, args_dbl); + /* { dg-output "1 7 12 127 99: 13 233 134" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b)); + + CHECK(ffi_prep_closure_loc(pcl, &cif, B_gn, NULL, code) == FFI_OK); + + res_dbl = ((B(*)(A, B))(code))(e_dbl, f_dbl); + /* { dg-output "\n1 7 12 127 99: 13 233 134" } */ + CHECK( res_dbl.x.a == (e_dbl.a + f_dbl.x.a)); + CHECK( res_dbl.x.b == (e_dbl.b + f_dbl.x.b + f_dbl.y)); + CHECK( res_dbl.y == (e_dbl.b + f_dbl.x.b)); + + exit(0); +} diff --git a/pool/shard008/C/0130810_ulimits.c b/pool/shard008/C/0130810_ulimits.c new file mode 100644 index 0000000000000000000000000000000000000000..18b55aaaf3ce7a8cb6724d55090a37f18deaa2d2 --- /dev/null +++ b/pool/shard008/C/0130810_ulimits.c @@ -0,0 +1,322 @@ +/*****************************************************************************\ + * src/slurmd/slurmstepd/ulimits.c - set user limits for job + ***************************************************************************** + * Copyright (C) 2002-2007 The Regents of the University of California. + * Copyright (C) 2008-2010 Lawrence Livermore National Security. + * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER). + * Written by Mark Grondona . + * CODE-OCEC-09-009. All rights reserved. + * + * This file is part of SLURM, a resource management program. + * For details, see . + * Please also read the included file: DISCLAIMER. + * + * SLURM 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. + * + * In addition, as a special exception, the copyright holders give permission + * to link the code of portions of this program with the OpenSSL library under + * certain conditions as described in each individual source file, and + * distribute linked combinations including the two. You must obey the GNU + * General Public License in all respects for all of the code used other than + * OpenSSL. If you modify file(s) with this exception, you may extend this + * exception to your version of the file(s), but you are not obligated to do + * so. If you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files in + * the program, then also delete it here. + * + * SLURM 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 SLURM; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +\*****************************************************************************/ + +#include "config.h" + +#include +#include +#include +#include +#include +#include + +#include "src/common/log.h" +#include "src/common/env.h" /* For unsetenvp() */ +#include "src/common/strlcpy.h" +#include "src/common/xmalloc.h" +#include "src/common/macros.h" +#include "src/common/slurm_rlimits_info.h" + +#include "src/slurmd/slurmstepd/slurmstepd_job.h" + +/* + * Prototypes: + * + */ +static int _get_env_val(char **env, const char *name, unsigned long *valp, + bool *u_req_propagate); +static int _set_limit(char **env, slurm_rlimits_info_t *rli); + +/* + * Set user resource limits using the values of the environment variables + * of the name "SLURM_RLIMIT_*" that are found in job->env. + * + * The sys admin can control the propagation of user limits in the slurm + * conf file by setting values for the PropagateResourceRlimits and + * ResourceLimits keywords. + * + * NOTE: THIS FUNCTION SHOULD ONLY BE CALLED RIGHT BEFORE THE EXEC OF + * A SCRIPT AFTER THE FORK SO AS TO LIMIT THE ABOUT OF EFFECT THE + * LIMITS HAVE WHEN COMBINED WITH THE SLURMSTEPD. RLIMIT_FSIZE IS THE + * MAIN REASON SINCE IF THE USER SETS THIS TO BE LOWER THAN THE SIZE + * OF THE CURRENT SLURMD.LOG THE STEPD WILL CORE THE NEXT TIME + * ANYTHING IS WRITTEN TO IT. SO IF RUNNING +DEBUG2 AND THE USER IS + * GETTING CORES WITH FILE SYSTEM LIMIT ERRORS THIS IS THE REASON. + * + * NOTE: The slurmstepd will not normally write a core file due to setuid(). + * Run as normal user to disable setuid() and permit a core file to be written. + */ + +int set_user_limits(stepd_step_rec_t *job) +{ +#ifdef RLIMIT_AS +#define SLURM_RLIMIT_VSIZE RLIMIT_AS +#define SLURM_RLIMIT_VNAME "RLIMIT_AS" +#elif defined(RLIMIT_DATA) +/* RLIMIT_DATA is useless on many systems which provide anonymous + * mmap()'s in addition to brk(), use it here only as a fallback for + * oddball systems lacking RLIMIT_AS. */ +#define SLURM_RLIMIT_VSIZE RLIMIT_DATA +#define SLURM_RLIMIT_VNAME "RLIMIT_DATA" +#endif + slurm_rlimits_info_t *rli; + struct rlimit r; + rlim_t task_mem_bytes; +#ifdef SLURM_RLIMIT_VSIZE + uint16_t vsize_factor; +#endif + + if (getrlimit(RLIMIT_CPU, &r) == 0) { + if (r.rlim_max != RLIM_INFINITY) { + error("SLURM process CPU time limit is %d seconds", + (int) r.rlim_max); + } + } + + for (rli = get_slurm_rlimits_info(); rli->name; rli++) + _set_limit( job->env, rli ); + + /* Set soft and hard rss and vsize limit for this process, + * handle job limit (for all spawned processes) in slurmd */ + task_mem_bytes = job->step_mem; /* MB */ + task_mem_bytes *= (1024 * 1024); + + /* Many systems, Linux included, ignore RSS limits, but set it + * here anyway for consistency and to provide a way for + * applications to interrogate what the RSS limit is (with the + * caveat that the real RSS limit is over all job tasks on the + * node and not per process, but hopefully this is better than + * nothing). */ +#ifdef RLIMIT_RSS + if ((task_mem_bytes) && (getrlimit(RLIMIT_RSS, &r) == 0) && + (r.rlim_max > task_mem_bytes)) { + r.rlim_max = r.rlim_cur = task_mem_bytes; + if (setrlimit(RLIMIT_RSS, &r)) { + /* Indicates that limit has already been exceeded */ + fatal("setrlimit(RLIMIT_RSS, %u MB): %m", + job->step_mem); + } else + debug2("Set task rss(%u MB)", job->step_mem); +#if 0 + getrlimit(RLIMIT_RSS, &r); + info("task RSS limits: %u %u", r.rlim_cur, r.rlim_max); +#endif + } +#endif + +#ifdef SLURM_RLIMIT_VSIZE + if ((task_mem_bytes) && + ((vsize_factor = slurm_get_vsize_factor()) != 0) && + (getrlimit(SLURM_RLIMIT_VSIZE, &r) == 0) && + (r.rlim_max > task_mem_bytes)) { + r.rlim_max = task_mem_bytes * (vsize_factor / 100.0); + r.rlim_cur = r.rlim_max; + if (setrlimit(SLURM_RLIMIT_VSIZE, &r)) { + /* Indicates that limit has already been exceeded */ + fatal("setrlimit(%s, %u MB): %m", + SLURM_RLIMIT_VNAME, job->step_mem); + } else + debug2("Set task vsize(%u MB)", job->step_mem); +#if 0 + getrlimit(SLURM_RLIMIT_VSIZE, &r); + info("task VSIZE limits: %u %u", r.rlim_cur, r.rlim_max); +#endif + } +#endif + + return SLURM_SUCCESS; +} + +/* + * Return an rlimit as a string suitable for printing. + */ +static char * rlim_to_string (unsigned long rlim, char *buf, size_t n) +{ + if (rlim == (unsigned long) RLIM_INFINITY) + strlcpy (buf, "inf", n); + else + snprintf (buf, n, "%lu", rlim); + return (buf); +} + +/* Set umask using value of env var SLURM_UMASK */ +extern int +set_umask(stepd_step_rec_t *job) +{ + mode_t mask; + char *val; + + if (!(val = getenvp(job->env, "SLURM_UMASK"))) { + if (job->stepid != SLURM_EXTERN_CONT) + debug("Couldn't find SLURM_UMASK in environment"); + return SLURM_ERROR; + } + + mask = strtol(val, (char **)NULL, 8); + umask(mask); + return SLURM_SUCCESS; +} + +/* + * Set rlimit using value of env vars such as SLURM_RLIMIT_FSIZE if + * the slurm config file has PropagateResourceLimits=YES or the user + * requested it with srun --propagate. + * + * NOTE: THIS FUNCTION SHOULD ONLY BE CALLED RIGHT BEFORE THE EXEC OF + * A SCRIPT AFTER THE FORK SO AS TO LIMIT THE ABOUT OF EFFECT THE + * LIMITS HAVE WHEN COMBINED WITH THE SLURMSTEPD. RLIMIT_FSIZE IS THE + * MAIN REASON SINCE IF THE USER SETS THIS TO BE LOWER THAN THE SIZE + * OF THE CURRENT SLURMD.LOG THE STEPD WILL CORE THE NEXT TIME + * ANYTHING IS WRITTEN TO IT. SO IF RUNNING +DEBUG2 AND THE USER IS + * GETTING CORES WITH FILE SYSTEM LIMIT ERRORS THIS IS THE REASON. + */ +static int +_set_limit(char **env, slurm_rlimits_info_t *rli) +{ + unsigned long env_value; + char max[24], cur[24], req[24]; + struct rlimit r; + bool u_req_propagate; /* e.g. true if 'srun --propagate' */ + + char env_name[25] = "SLURM_RLIMIT_"; + char *rlimit_name = &env_name[6]; + + strcpy( &env_name[sizeof("SLURM_RLIMIT_")-1], rli->name ); + + if (_get_env_val( env, env_name, &env_value, &u_req_propagate )){ + debug( "Couldn't find %s in environment", env_name ); + return SLURM_ERROR; + } + + /* + * Users shouldn't get the SLURM_RLIMIT_* env vars in their environ + */ + unsetenvp( env, env_name ); + + /* + * We'll only attempt to set the propagated soft rlimit when indicated + * by the slurm conf file settings, or the user requested it. + */ + if ( ! (rli->propagate_flag == PROPAGATE_RLIMITS || u_req_propagate)) + return SLURM_SUCCESS; + + if (getrlimit( rli->resource, &r ) < 0) { + error("getrlimit(%s): %m", rlimit_name); + return SLURM_ERROR; + } + + /* + * Nothing to do if the rlimit won't change + */ + if (r.rlim_cur == (rlim_t) env_value) { + debug2( "_set_limit: %s setrlimit %s no change in value: %lu", + u_req_propagate?"user":"conf", rlimit_name, + (unsigned long) r.rlim_cur); + return SLURM_SUCCESS; + } + + debug2("_set_limit: %-14s: max:%s cur:%s req:%s", rlimit_name, + rlim_to_string (r.rlim_max, max, sizeof (max)), + rlim_to_string (r.rlim_cur, cur, sizeof (cur)), + rlim_to_string (env_value, req, sizeof (req)) ); + + r.rlim_cur = (rlim_t) env_value; + if (r.rlim_max < r.rlim_cur) + r.rlim_max = r.rlim_cur; + + if (setrlimit( rli->resource, &r ) < 0) { + /* + * Report an error only if the user requested propagate + */ + if (u_req_propagate) { + error( "Can't propagate %s of %s from submit host: %m", + rlimit_name, + r.rlim_cur == RLIM_INFINITY ? "'unlimited'" : + rlim_to_string( r.rlim_cur, cur, sizeof(cur))); + } else { + verbose("Can't propagate %s of %s from submit host: %m", + rlimit_name, + r.rlim_cur == RLIM_INFINITY ? "'unlimited'" : + rlim_to_string( r.rlim_cur, cur, sizeof(cur))); + } + return SLURM_ERROR; + } + debug2( "_set_limit: %s setrlimit %s succeeded", + u_req_propagate?"user":"conf", rlimit_name ); + + return SLURM_SUCCESS; +} + +/* + * Determine the value of the env var 'name' (if it exists) and whether + * or not the user wants to use its value as the jobs soft rlimit. + */ +static int _get_env_val(char **env, const char *name, unsigned long *valp, + bool *u_req_propagate) +{ + char *val = NULL; + char *p = NULL; + + xassert(env != NULL); + xassert(name != NULL); + + if (!(val = getenvp(env, name))) + return (-1); + + /* + * The letter 'U' would have been prepended to the string value if the + * user requested to have this rlimit propagated via 'srun --propagate' + */ + if (*val == 'U') { + *u_req_propagate = true; + debug2( "_get_env_val: %s propagated by user option", &name[6]); + val++; + } + else + *u_req_propagate = false; + + *valp = strtoul(val, &p, 10); + + if (p && (*p != '\0')) { + error("Invalid %s env var, value = `%s'", name, val); + return (-1); + } + + return (0); +} diff --git a/pool/shard008/C/0130811_accgyro_mpu6500.c b/pool/shard008/C/0130811_accgyro_mpu6500.c new file mode 100644 index 0000000000000000000000000000000000000000..ad95196e18ebdad142421b718defe89cbb34305e --- /dev/null +++ b/pool/shard008/C/0130811_accgyro_mpu6500.c @@ -0,0 +1,116 @@ +/* + * This file is part of Cleanflight. + * + * Cleanflight 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. + * + * Cleanflight 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 Cleanflight. If not, see . + */ + +#include +#include +#include + +#include +#include "build/build_config.h" + +#include "common/axis.h" +#include "common/maths.h" + +#include "system.h" +#include "exti.h" +#include "gpio.h" +#include "gyro_sync.h" + +#include "sensor.h" +#include "accgyro.h" +#include "accgyro_mpu.h" +#include "accgyro_mpu6500.h" + +static bool mpu6500ReadTemp(int16_t *tempData) +{ + uint8_t buf[2]; + if (!mpuConfiguration.read(MPU_RA_TEMP_OUT_H, 2, buf)) { + return false; + } + + // MPU-6500-Datasheet2.pdf P12 + const int16_t RoomTemp_Offset = 21; + const int16_t Temp_Sensitivity = 333; + + // RM-MPU-6500A-00.pdf P33 + *tempData = RoomTemp_Offset + ((int16_t)(buf[0] << 8 | buf[1]) - RoomTemp_Offset) / Temp_Sensitivity; + + return true; +} + +bool mpu6500AccDetect(acc_t *acc) +{ + if (mpuDetectionResult.sensor != MPU_65xx_I2C) { + return false; + } + + acc->init = mpu6500AccInit; + acc->read = mpuAccRead; + + return true; +} + +bool mpu6500GyroDetect(gyro_t *gyro) +{ + if (mpuDetectionResult.sensor != MPU_65xx_I2C) { + return false; + } + + gyro->init = mpu6500GyroInit; + gyro->read = mpuGyroRead; + gyro->temperature = mpu6500ReadTemp; + gyro->isDataReady = mpuIsDataReady; + + // 16.4 dps/lsb scalefactor + gyro->scale = 1.0f / 16.4f; + + return true; +} + +void mpu6500AccInit(acc_t *acc) +{ + mpuIntExtiInit(); + + acc->acc_1G = 512 * 8; +} + +void mpu6500GyroInit(uint8_t lpf) +{ + mpuIntExtiInit(); + + mpuConfiguration.write(MPU_RA_PWR_MGMT_1, MPU6500_BIT_RESET); + delay(100); + mpuConfiguration.write(MPU_RA_SIGNAL_PATH_RESET, 0x07); + delay(100); + mpuConfiguration.write(MPU_RA_PWR_MGMT_1, 0); + delay(100); + mpuConfiguration.write(MPU_RA_PWR_MGMT_1, INV_CLK_PLL); + mpuConfiguration.write(MPU_RA_GYRO_CONFIG, INV_FSR_2000DPS << 3); + mpuConfiguration.write(MPU_RA_ACCEL_CONFIG, INV_FSR_8G << 3); + mpuConfiguration.write(MPU_RA_CONFIG, lpf); + mpuConfiguration.write(MPU_RA_SMPLRT_DIV, gyroMPU6xxxCalculateDivider()); // Get Divider + + // Data ready interrupt configuration +#ifdef USE_MPU9250_MAG + mpuConfiguration.write(MPU_RA_INT_PIN_CFG, 0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 1 << 1 | 0 << 0); // INT_ANYRD_2CLEAR, BYPASS_EN +#else + mpuConfiguration.write(MPU_RA_INT_PIN_CFG, 0 << 7 | 0 << 6 | 0 << 5 | 1 << 4 | 0 << 3 | 0 << 2 | 0 << 1 | 0 << 0); // INT_ANYRD_2CLEAR, BYPASS_EN +#endif +#ifdef USE_MPU_DATA_READY_SIGNAL + mpuConfiguration.write(MPU_RA_INT_ENABLE, 0x01); // RAW_RDY_EN interrupt enable +#endif +} diff --git a/pool/shard008/C/0130814_vdecdd_utils.c b/pool/shard008/C/0130814_vdecdd_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..c134ce8881244097f7c1d350670f56b071cf4951 --- /dev/null +++ b/pool/shard008/C/0130814_vdecdd_utils.c @@ -0,0 +1,194 @@ +/*! + ***************************************************************************** + * + * @File vdecdd_utils.c + * @Title VDEC Utilities + * @Description This file contains the VDEC utitlities compiled into user and kernel mode. + * --------------------------------------------------------------------------- + * + * Copyright (c) Imagination Technologies Ltd. + * + * The contents of this file are subject to the MIT license as set out below. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * Alternatively, the contents of this file may be used under the terms of the + * GNU General Public License Version 2 ("GPL")in which case the provisions of + * GPL are applicable instead of those above. + * + * If you wish to allow use of your version of this file only under the terms + * of GPL, and not to allow others to use your version of this file under the + * terms of the MIT license, indicate your decision by deleting the provisions + * above and replace them with the notice and other provisions required by GPL + * as set out in the file called "GPLHEADER" included in this distribution. If + * you do not delete the provisions above, a recipient may use your version of + * this file under the terms of either the MIT license or GPL. + * + * This License is also included in this distribution in the file called + * "MIT_COPYING". + * + *****************************************************************************/ + +#include "vdecdd_utils.h" + + +/*! +****************************************************************************** + + @Function VDECDDUTILS_FreeStrUnit + + ******************************************************************************/ +IMG_RESULT VDECDDUTILS_FreeStrUnit( + VDECDD_sStrUnit * psStrUnit +) +{ + BSPP_sBitStrSeg * psBitStrSeg; + + /* Loop over bit stream segments...*/ + psBitStrSeg = (BSPP_sBitStrSeg *)LST_removeHead(&psStrUnit->sBitStrSegList); + while (psBitStrSeg != IMG_NULL) + { + /* Free segment. */ + IMG_FREE(psBitStrSeg); + + /* Get next segment. */ + psBitStrSeg = (BSPP_sBitStrSeg *)LST_removeHead(&psStrUnit->sBitStrSegList); + } + + /* Free the sequence header...*/ + if (psStrUnit->psSequHdrInfo != IMG_NULL) + { + psStrUnit->psSequHdrInfo->ui32RefCount--; + if (psStrUnit->psSequHdrInfo->ui32RefCount == 0) + { + IMG_FREE(psStrUnit->psSequHdrInfo); + psStrUnit->psSequHdrInfo = IMG_NULL; + } + } + + /* Free the picture header... */ + if (psStrUnit->psPictHdrInfo != IMG_NULL) + { + if (psStrUnit->psPictHdrInfo->sPictSgmData.pvData) + { + IMG_FREE(psStrUnit->psPictHdrInfo->sPictSgmData.pvData); + psStrUnit->psPictHdrInfo->sPictSgmData.pvData = IMG_NULL; + } + + IMG_FREE(psStrUnit->psPictHdrInfo); + psStrUnit->psPictHdrInfo = IMG_NULL; + } + + /* Free stream unit. */ + IMG_FREE(psStrUnit); + psStrUnit = IMG_NULL; + + /* Return success...*/ + return IMG_SUCCESS; +} + + +/*! +****************************************************************************** + + @Function VDECDDUTILS_CreateStrUnit + + @Description this function allocate a structure for a complete data unit + +******************************************************************************/ +IMG_RESULT VDECDDUTILS_CreateStrUnit( + VDECDD_sStrUnit ** ppsStrUnit, + LST_T * sBSList +) +{ + VDECDD_sStrUnit * psStrUnit; + BSPP_sBitStrSeg * psBitStrSeg; + + VDEC_MALLOC(psStrUnit); + IMG_ASSERT(psStrUnit != IMG_NULL); + if (psStrUnit == IMG_NULL) + { + return IMG_ERROR_OUT_OF_MEMORY; + } + VDEC_BZERO(psStrUnit); + if (sBSList != IMG_NULL) + { + // copy BS list to this list + LST_init(&psStrUnit->sBitStrSegList); + for ( psBitStrSeg = LST_first( sBSList); psBitStrSeg != NULL; psBitStrSeg = LST_first(sBSList) ) + { + psBitStrSeg = LST_removeHead(sBSList); + LST_add(&psStrUnit->sBitStrSegList,psBitStrSeg); + } + } + + *ppsStrUnit = psStrUnit; + + return IMG_SUCCESS; +} + + + +/*! +****************************************************************************** + + @Function VDECDDUTILS_CreateStrUnitOld + + @Description this function allocate a structure for a complete data unit + + +******************************************************************************/ +IMG_RESULT VDECDDUTILS_CreateStrUnitOld( + VDECDD_sStrUnit ** ppsStrUnit, + BSPP_sSequHdrInfo * psSeqInfo, + BSPP_sPictHdrInfo * psPicInfo, + LST_T * sBSList +) +{ + VDECDD_sStrUnit * psStrUnit; + BSPP_sBitStrSeg * psBitStrSeg; + + VDEC_MALLOC(psStrUnit); + IMG_ASSERT(psStrUnit != IMG_NULL); + if (psStrUnit == IMG_NULL) + { + return IMG_ERROR_OUT_OF_MEMORY; + } + VDEC_BZERO(psStrUnit); + if (sBSList != IMG_NULL) + { + // copy BS list to this list + LST_init(&psStrUnit->sBitStrSegList); + for ( psBitStrSeg = LST_first( sBSList); psBitStrSeg != NULL; psBitStrSeg = LST_first(sBSList) ) + { + psBitStrSeg = LST_removeHead(sBSList); + LST_add(&psStrUnit->sBitStrSegList,psBitStrSeg); + } + + } + if(psSeqInfo !=IMG_NULL) + { + psStrUnit->psSequHdrInfo = psSeqInfo; + psStrUnit->psSequHdrInfo->ui32RefCount = 1; + } + psStrUnit->psPictHdrInfo = psPicInfo; + *ppsStrUnit = psStrUnit; + + return IMG_SUCCESS; +} diff --git a/pool/shard008/C/0130816_jit_op.c b/pool/shard008/C/0130816_jit_op.c new file mode 100644 index 0000000000000000000000000000000000000000..ec5e2e4170c44a9a9864dfa2c1a458829d488e5d --- /dev/null +++ b/pool/shard008/C/0130816_jit_op.c @@ -0,0 +1,100 @@ +/* + * Cisco router simulation platform. + * Copyright (c) 2007 Christophe Fillot (cf@utc.fr) + * + * JIT operations. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cpu.h" +#include "jit_op.h" + +u_int jit_op_blk_sizes[JIT_OP_POOL_NR] = { + 0, 32, 64, 128, 256, 384, 512, 1024, +}; + +/* Get a JIT op (allocate one if necessary) */ +jit_op_t *jit_op_get(cpu_gen_t *cpu,int size_index,u_int opcode) +{ + jit_op_t *op; + size_t len; + + assert(size_index < JIT_OP_POOL_NR); + op = cpu->jit_op_pool[size_index]; + + if (op != NULL) { + assert(op->ob_size_index == size_index); + cpu->jit_op_pool[size_index] = op->next; + } else { + /* no block found, allocate one */ + len = sizeof(*op) + jit_op_blk_sizes[size_index]; + + op = malloc(len); + assert(op != NULL); + op->ob_size_index = size_index; + } + + op->opcode = opcode; + op->param[0] = op->param[1] = op->param[2] = -1; + op->next = NULL; + op->ob_ptr = op->ob_data; + op->arg_ptr = NULL; + op->insn_name = NULL; + return op; +} + +/* Release a JIT op */ +void jit_op_free(cpu_gen_t *cpu,jit_op_t *op) +{ + assert(op->ob_size_index < JIT_OP_POOL_NR); + op->next = cpu->jit_op_pool[op->ob_size_index]; + cpu->jit_op_pool[op->ob_size_index] = op; +} + +/* Free a list of JIT ops */ +void jit_op_free_list(cpu_gen_t *cpu,jit_op_t *op_list) +{ + jit_op_t *op,*opn; + + for(op=op_list;op;op=opn) { + opn = op->next; + jit_op_free(cpu,op); + } +} + +/* Initialize JIT op pools for the specified CPU */ +int jit_op_init_cpu(cpu_gen_t *cpu) +{ + cpu->jit_op_array = calloc(cpu->jit_op_array_size,sizeof(jit_op_t *)); + + if (!cpu->jit_op_array) + return(-1); + + memset(cpu->jit_op_pool,0,sizeof(cpu->jit_op_pool)); + return(0); +} + +/* Free memory used by pools */ +void jit_op_free_pools(cpu_gen_t *cpu) +{ + jit_op_t *op,*opn; + int i; + + for(i=0;ijit_op_pool[i];op;op=opn) { + opn = op->next; + free(op); + } + + cpu->jit_op_pool[i] = NULL; + } +} diff --git a/pool/shard008/C/0130821_i82801b11.c b/pool/shard008/C/0130821_i82801b11.c new file mode 100644 index 0000000000000000000000000000000000000000..5c40708ba8cb7edd1a944f36c841750ed3bd6907 --- /dev/null +++ b/pool/shard008/C/0130821_i82801b11.c @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2006 Fabrice Bellard + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +/* + * QEMU i82801b11 dmi-to-pci Bridge Emulation + * + * Copyright (c) 2009, 2010, 2011 + * Isaku Yamahata + * VA Linux Systems Japan K.K. + * Copyright (C) 2012 Jason Baron + * + * 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 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. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see + */ + +#include "qemu/osdep.h" +#include "hw/pci/pci.h" +#include "hw/i386/ich9.h" + + +/*****************************************************************************/ +/* ICH9 DMI-to-PCI bridge */ +#define I82801ba_SSVID_OFFSET 0x50 +#define I82801ba_SSVID_SVID 0 +#define I82801ba_SSVID_SSID 0 + +typedef struct I82801b11Bridge { + /*< private >*/ + PCIBridge parent_obj; + /*< public >*/ +} I82801b11Bridge; + +static int i82801b11_bridge_initfn(PCIDevice *d) +{ + int rc; + + pci_bridge_initfn(d, TYPE_PCI_BUS); + + rc = pci_bridge_ssvid_init(d, I82801ba_SSVID_OFFSET, + I82801ba_SSVID_SVID, I82801ba_SSVID_SSID); + if (rc < 0) { + goto err_bridge; + } + pci_config_set_prog_interface(d->config, PCI_CLASS_BRIDGE_PCI_INF_SUB); + return 0; + +err_bridge: + pci_bridge_exitfn(d); + + return rc; +} + +static void i82801b11_bridge_class_init(ObjectClass *klass, void *data) +{ + PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); + DeviceClass *dc = DEVICE_CLASS(klass); + + k->is_bridge = 1; + k->vendor_id = PCI_VENDOR_ID_INTEL; + k->device_id = PCI_DEVICE_ID_INTEL_82801BA_11; + k->revision = ICH9_D2P_A2_REVISION; + k->init = i82801b11_bridge_initfn; + k->config_write = pci_bridge_write_config; + set_bit(DEVICE_CATEGORY_BRIDGE, dc->categories); +} + +static const TypeInfo i82801b11_bridge_info = { + .name = "i82801b11-bridge", + .parent = TYPE_PCI_BRIDGE, + .instance_size = sizeof(I82801b11Bridge), + .class_init = i82801b11_bridge_class_init, +}; + +static void d2pbr_register(void) +{ + type_register_static(&i82801b11_bridge_info); +} + +type_init(d2pbr_register); diff --git a/pool/shard008/C/0130824_main_winmain.c b/pool/shard008/C/0130824_main_winmain.c new file mode 100644 index 0000000000000000000000000000000000000000..e1dded0c349a7750597ae1eef1f00be22daba285 --- /dev/null +++ b/pool/shard008/C/0130824_main_winmain.c @@ -0,0 +1,78 @@ +/* + * WPA Supplicant / WinMain() function for Windows-based applications + * Copyright (c) 2006, Jouni Malinen + * + * This software may be distributed under the terms of the BSD license. + * See README for more details. + */ + +#include "includes.h" + +#include "common.h" +#include "wpa_supplicant_i.h" + +#ifdef _WIN32_WCE +#define CMDLINE LPWSTR +#else /* _WIN32_WCE */ +#define CMDLINE LPSTR +#endif /* _WIN32_WCE */ + + +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, + CMDLINE lpCmdLine, int nShowCmd) +{ + int i; + struct wpa_interface *ifaces, *iface; + int iface_count, exitcode = -1; + struct wpa_params params; + struct wpa_global *global; + + if (os_program_init()) + return -1; + + os_memset(¶ms, 0, sizeof(params)); + params.wpa_debug_level = MSG_MSGDUMP; + params.wpa_debug_file_path = "\\Temp\\wpa_supplicant-log.txt"; + params.wpa_debug_show_keys = 1; + + iface = ifaces = os_zalloc(sizeof(struct wpa_interface)); + if (ifaces == NULL) + return -1; + iface_count = 1; + + iface->confname = "default"; + iface->driver = "ndis"; + iface->ifname = ""; + + exitcode = 0; + global = wpa_supplicant_init(¶ms); + if (global == NULL) { + printf("Failed to initialize wpa_supplicant\n"); + exitcode = -1; + } + + for (i = 0; exitcode == 0 && i < iface_count; i++) { + if ((ifaces[i].confname == NULL && + ifaces[i].ctrl_interface == NULL) || + ifaces[i].ifname == NULL) { + if (iface_count == 1 && (params.ctrl_interface || + params.dbus_ctrl_interface)) + break; + exitcode = -1; + break; + } + if (wpa_supplicant_add_iface(global, &ifaces[i], NULL) == NULL) + exitcode = -1; + } + + if (exitcode == 0) + exitcode = wpa_supplicant_run(global); + + wpa_supplicant_deinit(global); + + os_free(ifaces); + + os_program_deinit(); + + return exitcode; +} diff --git a/pool/shard008/C/0130825_vport-netdev.c b/pool/shard008/C/0130825_vport-netdev.c new file mode 100644 index 0000000000000000000000000000000000000000..52a1ed9633ec9b8da8464de1d7c0282b28cb7a09 --- /dev/null +++ b/pool/shard008/C/0130825_vport-netdev.c @@ -0,0 +1,211 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Copyright (c) 2007-2012 Nicira, Inc. + */ + +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "datapath.h" +#include "vport.h" +#include "vport-internal_dev.h" +#include "vport-netdev.h" + +static struct vport_ops ovs_netdev_vport_ops; + +/* Must be called with rcu_read_lock. */ +static void netdev_port_receive(struct sk_buff *skb) +{ + struct vport *vport; + + vport = ovs_netdev_get_vport(skb->dev); + if (unlikely(!vport)) + goto error; + + if (unlikely(skb_warn_if_lro(skb))) + goto error; + + /* Make our own copy of the packet. Otherwise we will mangle the + * packet for anyone who came before us (e.g. tcpdump via AF_PACKET). + */ + skb = skb_share_check(skb, GFP_ATOMIC); + if (unlikely(!skb)) + return; + + if (skb->dev->type == ARPHRD_ETHER) { + skb_push(skb, ETH_HLEN); + skb_postpush_rcsum(skb, skb->data, ETH_HLEN); + } + ovs_vport_receive(vport, skb, skb_tunnel_info(skb)); + return; +error: + kfree_skb(skb); +} + +/* Called with rcu_read_lock and bottom-halves disabled. */ +static rx_handler_result_t netdev_frame_hook(struct sk_buff **pskb) +{ + struct sk_buff *skb = *pskb; + + if (unlikely(skb->pkt_type == PACKET_LOOPBACK)) + return RX_HANDLER_PASS; + + netdev_port_receive(skb); + return RX_HANDLER_CONSUMED; +} + +static struct net_device *get_dpdev(const struct datapath *dp) +{ + struct vport *local; + + local = ovs_vport_ovsl(dp, OVSP_LOCAL); + return local->dev; +} + +struct vport *ovs_netdev_link(struct vport *vport, const char *name) +{ + int err; + + vport->dev = dev_get_by_name(ovs_dp_get_net(vport->dp), name); + if (!vport->dev) { + err = -ENODEV; + goto error_free_vport; + } + + if (vport->dev->flags & IFF_LOOPBACK || + (vport->dev->type != ARPHRD_ETHER && + vport->dev->type != ARPHRD_NONE) || + ovs_is_internal_dev(vport->dev)) { + err = -EINVAL; + goto error_put; + } + + rtnl_lock(); + err = netdev_master_upper_dev_link(vport->dev, + get_dpdev(vport->dp), + NULL, NULL, NULL); + if (err) + goto error_unlock; + + err = netdev_rx_handler_register(vport->dev, netdev_frame_hook, + vport); + if (err) + goto error_master_upper_dev_unlink; + + dev_disable_lro(vport->dev); + dev_set_promiscuity(vport->dev, 1); + vport->dev->priv_flags |= IFF_OVS_DATAPATH; + rtnl_unlock(); + + return vport; + +error_master_upper_dev_unlink: + netdev_upper_dev_unlink(vport->dev, get_dpdev(vport->dp)); +error_unlock: + rtnl_unlock(); +error_put: + dev_put(vport->dev); +error_free_vport: + ovs_vport_free(vport); + return ERR_PTR(err); +} +EXPORT_SYMBOL_GPL(ovs_netdev_link); + +static struct vport *netdev_create(const struct vport_parms *parms) +{ + struct vport *vport; + + vport = ovs_vport_alloc(0, &ovs_netdev_vport_ops, parms); + if (IS_ERR(vport)) + return vport; + + return ovs_netdev_link(vport, parms->name); +} + +static void vport_netdev_free(struct rcu_head *rcu) +{ + struct vport *vport = container_of(rcu, struct vport, rcu); + + if (vport->dev) + dev_put(vport->dev); + ovs_vport_free(vport); +} + +void ovs_netdev_detach_dev(struct vport *vport) +{ + ASSERT_RTNL(); + vport->dev->priv_flags &= ~IFF_OVS_DATAPATH; + netdev_rx_handler_unregister(vport->dev); + netdev_upper_dev_unlink(vport->dev, + netdev_master_upper_dev_get(vport->dev)); + dev_set_promiscuity(vport->dev, -1); +} + +static void netdev_destroy(struct vport *vport) +{ + rtnl_lock(); + if (vport->dev->priv_flags & IFF_OVS_DATAPATH) + ovs_netdev_detach_dev(vport); + rtnl_unlock(); + + call_rcu(&vport->rcu, vport_netdev_free); +} + +void ovs_netdev_tunnel_destroy(struct vport *vport) +{ + rtnl_lock(); + if (vport->dev->priv_flags & IFF_OVS_DATAPATH) + ovs_netdev_detach_dev(vport); + + /* We can be invoked by both explicit vport deletion and + * underlying netdev deregistration; delete the link only + * if it's not already shutting down. + */ + if (vport->dev->reg_state == NETREG_REGISTERED) + rtnl_delete_link(vport->dev); + dev_put(vport->dev); + vport->dev = NULL; + rtnl_unlock(); + + call_rcu(&vport->rcu, vport_netdev_free); +} +EXPORT_SYMBOL_GPL(ovs_netdev_tunnel_destroy); + +/* Returns null if this device is not attached to a datapath. */ +struct vport *ovs_netdev_get_vport(struct net_device *dev) +{ + if (likely(dev->priv_flags & IFF_OVS_DATAPATH)) + return (struct vport *) + rcu_dereference_rtnl(dev->rx_handler_data); + else + return NULL; +} + +static struct vport_ops ovs_netdev_vport_ops = { + .type = OVS_VPORT_TYPE_NETDEV, + .create = netdev_create, + .destroy = netdev_destroy, + .send = dev_queue_xmit, +}; + +int __init ovs_netdev_init(void) +{ + return ovs_vport_ops_register(&ovs_netdev_vport_ops); +} + +void ovs_netdev_exit(void) +{ + ovs_vport_ops_unregister(&ovs_netdev_vport_ops); +} diff --git a/pool/shard008/C/0130826_board-htcrhodium-keypad.c b/pool/shard008/C/0130826_board-htcrhodium-keypad.c new file mode 100644 index 0000000000000000000000000000000000000000..32142613dbcd95a1d9389a500a702aae2460d0e9 --- /dev/null +++ b/pool/shard008/C/0130826_board-htcrhodium-keypad.c @@ -0,0 +1,99 @@ +/* arch/arm/mach-msm/board-htcrhodium-keypad.c + * Copyright (C) 2007-2009 HTC Corporation. + * Author: Thomas Tsai + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * 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. +*/ + +#include +#include +#include +#include +#include +#include "gpio_chip.h" +#include "board-htcrhodium.h" +static char *keycaps = "--qwerty"; +#undef MODULE_PARAM_PREFIX +#define MODULE_PARAM_PREFIX "board_rhodium." +module_param_named(keycaps, keycaps, charp, 0); + + +static unsigned int rhodium_col_gpios[] = { RHODIUM_KPD_COL0, RHODIUM_KPD_COL1 }; + +static unsigned int rhodium_row_gpios[] = { RHODIUM_KPD_ROW0, RHODIUM_KPD_ROW1, RHODIUM_KPD_ROW2, RHODIUM_KPD_ROW3 }; + +#define KEYMAP_INDEX(col, row) ((col)*ARRAY_SIZE(rhodium_row_gpios) + (row)) + +/* HOME(up) + MENU (down)*/ +static const unsigned short rhodium_keymap[ARRAY_SIZE(rhodium_col_gpios) * + ARRAY_SIZE(rhodium_row_gpios)] = { + + //DEVICE IS RHOD400 !!!!! + + //GPIO 27 == Keyboard IRQ + //39 == Volume UP (GPIO 39) + //40 == Volume DOWN (GPIO 40) + //18 == END key + + [KEYMAP_INDEX(0, 2)] = KEY_SEND, + [KEYMAP_INDEX(1, 1)] = KEY_VOLUMEUP, + [KEYMAP_INDEX(0, 0)] = KEY_VOLUMEDOWN, + + [KEYMAP_INDEX(0, 2)] = KEY_HOME, + [KEYMAP_INDEX(0, 2)] = KEY_MENU, + [KEYMAP_INDEX(1, 3)] = KEY_END, +}; + + +static struct gpio_event_matrix_info rhodium_keypad_matrix_info = { + .info.func = gpio_event_matrix_func, + .keymap = rhodium_keymap, + .output_gpios = rhodium_col_gpios, + .input_gpios = rhodium_row_gpios, + .noutputs = ARRAY_SIZE(rhodium_col_gpios), + .ninputs = ARRAY_SIZE(rhodium_row_gpios), + .settle_time = 40 * NSEC_PER_USEC, + .poll_time = 20 * NSEC_PER_MSEC, + .debounce_delay = 50 * NSEC_PER_MSEC, + .flags = GPIOKPF_LEVEL_TRIGGERED_IRQ | + GPIOKPF_REMOVE_PHANTOM_KEYS | + GPIOKPF_PRINT_UNMAPPED_KEYS /*| GPIOKPF_PRINT_MAPPED_KEYS*/ +}; + +static struct gpio_event_info *rhodium_keypad_info[] = { + &rhodium_keypad_matrix_info.info, +}; + +static struct gpio_event_platform_data rhodium_keypad_data = { + .name = "rhodium-keypad", + .info = rhodium_keypad_info, + .info_count = ARRAY_SIZE(rhodium_keypad_info) +}; + +static struct platform_device rhodium_keypad_device = { + .name = GPIO_EVENT_DEV_NAME, + .id = 0, + .dev = { + .platform_data = &rhodium_keypad_data, + }, +}; + +static int __init rhodium_init_keypad(void) +{ + if (!machine_is_htcrhodium()) + return 0; + + rhodium_keypad_matrix_info.keymap = rhodium_keymap; + + return platform_device_register(&rhodium_keypad_device); +} + +device_initcall(rhodium_init_keypad); + diff --git a/pool/shard008/C/0130832_path.c b/pool/shard008/C/0130832_path.c new file mode 100644 index 0000000000000000000000000000000000000000..c84f14c20a1e0411c3a49531dc67415d70a3af32 --- /dev/null +++ b/pool/shard008/C/0130832_path.c @@ -0,0 +1,44 @@ +#include "path.h" + +Path Path_new() +{ + Path self; + self.current = 0; + self.back = FALSE; + self.is_complete = FALSE; + return self; +} + +Directions Path_intersection(Path* self, Intersections i) +{ + if(self->is_complete) + { + self->current += 1; + Directions d = Node_current(self->nodes + self->current); + return d; + } + if(self->back) { + self->back = FALSE; + Directions c = Node_current(self->nodes + self->current); + Directions d = Node_next(self->nodes + self->current); + if(d == BACK_DIR) + { + self->current -= 1; + self->back = TRUE; + return Directions_changeRef(c, BACK_DIR); + } + else + return Directions_changeRef(c, d); + } + else { + self->current += 1; + Node_new(self->nodes + self->current, i); + return Node_current(self->nodes + self->current); + } +} + +void Path_back(Path* self) +{ + self->back = TRUE; +} + diff --git a/pool/shard008/C/0130837_board.c b/pool/shard008/C/0130837_board.c new file mode 100644 index 0000000000000000000000000000000000000000..9a5b62e7b2dce081682f3d4cb286b7be03c13702 --- /dev/null +++ b/pool/shard008/C/0130837_board.c @@ -0,0 +1,269 @@ +/** + * \file board.c + * \author Alexander Winiger (alexander.winiger@hslu.ch) + * \date 15.09.2015 + * \brief Target board general functions implementation + * + */ + +#include "board.h" +#include "fsl_clock_manager.h" +#include "fsl_cop_hal.h" +#include "fsl_smc_hal.h" + +/*! + * LED GPIO pins objects + */ +Gpio_t Led1; +Gpio_t Led2; +#if !defined(SX1276_BOARD_FREEDOM) && !defined(SX1276_BOARD_EMBED) +Gpio_t Led3; +#endif + +/*! + * Button GPIO pin objects + */ +Gpio_t SwitchA; + +/*! + * IRQ GPIO pins objects + */ +Gpio_t Irq1Fxos8700cq; +Gpio_t Irq2Fxos8700cq; + +/*! + * MCU objects + */ +Adc_t Adc; +I2c_t I2c; +I2C_TypeDef Fxos; +Uart_t Uart0; +Uart_t Uart1; +Uart_t Uart2; +#if defined( USE_USB_CDC ) +Uart_t UartUsb; +#endif + +/*! + * Default clock configurations + */ +/* Configuration for enter VLPR mode. Core clock = 4MHz. */ +const clock_manager_user_config_t g_defaultClockConfigVlpr = +{ + .mcgConfig = + { + .mcg_mode = kMcgModeBLPI, // Work in BLPI mode. + .irclkEnable = true,// MCGIRCLK enable. + .irclkEnableInStop = false,// MCGIRCLK disable in STOP mode. + .ircs = kMcgIrcFast,// Select IRC4M. + .fcrdiv = 0U,// FCRDIV is 0. + + .frdiv = 0U, + .drs = kMcgDcoRangeSelLow,// Low frequency range + .dmx32 = kMcgDmx32Default,// DCO has a default range of 25% + + .pll0EnableInFllMode = false,// PLL0 disable + .pll0EnableInStop = false,// PLL0 disalbe in STOP mode + .prdiv0 = 0U, + .vdiv0 = 0U, + }, + .simConfig = + { + .pllFllSel = kClockPllFllSelFll, // PLLFLLSEL select FLL. + .er32kSrc = kClockEr32kSrcLpo,// ERCLK32K selection, use LPO. + .outdiv1 = 0U, + .outdiv4 = 4U, + }, + .oscerConfig = + { + .enable = true, // OSCERCLK enable. + .enableInStop = false,// OSCERCLK disable in STOP mode. + } +}; + +/* Configuration for enter RUN mode. Core clock = 48MHz. */ +const clock_manager_user_config_t g_defaultClockConfigRun = +{ + .mcgConfig = + { + .mcg_mode = kMcgModePEE, // Work in PEE mode. + .irclkEnable = true,// MCGIRCLK enable. + .irclkEnableInStop = false,// MCGIRCLK disable in STOP mode. + .ircs = kMcgIrcSlow,// Select IRC32k. + .fcrdiv = 0U,// FCRDIV is 0. + + .frdiv = 3U, + .drs = kMcgDcoRangeSelLow,// Low frequency range + .dmx32 = kMcgDmx32Default,// DCO has a default range of 25% + + .pll0EnableInFllMode = false,// PLL0 disable + .pll0EnableInStop = false,// PLL0 disalbe in STOP mode + .prdiv0 = 0x1U, + .vdiv0 = 0x0U, + }, + .simConfig = + { + .pllFllSel = kClockPllFllSelPll, // PLLFLLSEL select PLL. + .er32kSrc = kClockEr32kSrcLpo,// ERCLK32K selection, use LPO. + .outdiv1 = 1U, + .outdiv4 = 3U, + }, + .oscerConfig = + { + .enable = true, // OSCERCLK enable. + .enableInStop = false,// OSCERCLK disable in STOP mode. + } +}; + +/*! + * Initializes the unused GPIO to a known status + */ +static void BoardUnusedIoInit( void ); + +/*! + * Flag to indicate if the MCU is Initialized + */ +static bool McuInitialized = false; + +void BoardInitPeriph( void ) +{ + /* Init the GPIO pins */ + GpioInit(&Led1, LED_1, PIN_OUTPUT, PIN_PUSH_PULL, PIN_NO_PULL, 1); + GpioInit(&Led2, LED_2, PIN_OUTPUT, PIN_PUSH_PULL, PIN_NO_PULL, 1); +#if !defined(SX1276_BOARD_FREEDOM) && !defined(SX1276_BOARD_EMBED) + GpioInit(&Led3, LED_3, PIN_OUTPUT, PIN_PUSH_PULL, PIN_NO_PULL, 1); +#endif + + /* Init the Switch GPIO pins */ + GpioInit(&SwitchA, SWITCH_A, PIN_INPUT, PIN_PUSH_PULL, PIN_PULL_UP, 1); + + /* Init the IRQ GPIO pins*/ + GpioInit(&Irq1Fxos8700cq, IRQ_1_FXOS8700CQ, PIN_INPUT, PIN_PUSH_PULL, PIN_NO_PULL, 1); + GpioInit(&Irq2Fxos8700cq, IRQ_2_FXOS8700CQ, PIN_INPUT, PIN_PUSH_PULL, PIN_NO_PULL, 1); + + /* Init GPS */ +// GpsInit(); + // Switch LED 1, 2 OFF + GpioWrite(&Led1, 1); + GpioWrite(&Led2, 1); +#if !defined(SX1276_BOARD_FREEDOM) && !defined(SX1276_BOARD_EMBED) + GpioWrite(&Led2, 1); +#endif +} + +void BoardInitMcu( void ) +{ + if ( McuInitialized == false ) { + /* Disable watchdog */ + COP_HAL_Disable (SIM_BASE_PTR); + + /* Enable clock for PORTs */ + CLOCK_SYS_EnablePortClock (PORTA_IDX); + CLOCK_SYS_EnablePortClock (PORTC_IDX); + CLOCK_SYS_EnablePortClock (PORTE_IDX); + + /* Set allowed power mode, allow all. */ + SMC_HAL_SetProtection(SMC, kAllowPowerModeAll); + + /* Setup board clock source. */ + // Setup OSC0 if used. + // Configure OSC0 pin mux. + PORT_HAL_SetMuxMode(EXTAL0_PORT, EXTAL0_PIN, EXTAL0_PINMUX); + PORT_HAL_SetMuxMode(XTAL0_PORT, XTAL0_PIN, XTAL0_PINMUX); + + /* Function to initialize OSC0 base on board configuration. */ + osc_user_config_t + osc0Config = + { + .freq = OSC0_XTAL_FREQ, + .hgo = MCG_HGO0, + .range = MCG_RANGE0, + .erefs = MCG_EREFS0, + .enableCapacitor2p = OSC0_SC2P_ENABLE_CONFIG, + .enableCapacitor4p = OSC0_SC4P_ENABLE_CONFIG, + .enableCapacitor8p = OSC0_SC8P_ENABLE_CONFIG, + .enableCapacitor16p = OSC0_SC16P_ENABLE_CONFIG, + }; + + CLOCK_SYS_OscInit(0U, &osc0Config); + + /* Set system clock configuration. */ +#if (CLOCK_INIT_CONFIG == CLOCK_VLPR) + CLOCK_SYS_SetConfiguration (&g_defaultClockConfigVlpr); +#else + CLOCK_SYS_SetConfiguration(&g_defaultClockConfigRun); +#endif + + /*! SPI channel to be used by Semtech SX1276 */ +#if defined(SX1276_BOARD_FREEDOM) || defined(SX1276_BOARD_EMBED) + SX1276.Spi.instance = RADIO_SPI_INSTANCE; + SX1276.Spi.isSlave = false; + SpiInit(&SX1276.Spi, RADIO_MOSI, RADIO_MISO, RADIO_SCLK, RADIO_NSS); + SX1276IoInit(); +#endif + +#if defined( USE_USB_CDC ) + UartInit( &UartUsb, UART_USB_CDC, NC, NC ); + UartConfig( &UartUsb, RX_TX, 115200, UART_8_BIT, UART_1_STOP_BIT, NO_PARITY, NO_FLOW_CTRL ); +#elif defined(DEBUG) + GpioInit(&Uart0.Tx, UART0_TX, PIN_ALTERNATE_FCT, PIN_PUSH_PULL, PIN_PULL_UP, 1); + GpioInit(&Uart0.Rx, UART0_RX, PIN_ALTERNATE_FCT, PIN_PUSH_PULL, PIN_PULL_UP, 1); + CLOCK_SYS_SetLpsciSrc(0, kClockLpsciSrcPllFllSel); + DbgConsole_Init(0, 115200, kDebugConsoleLPSCI); + TimerSetLowPowerEnable(false); +#elif( LOW_POWER_MODE_ENABLE ) + TimerSetLowPowerEnable( true ); +#else + TimerSetLowPowerEnable(false); +#endif /* USE_USB_CDC */ + BoardUnusedIoInit(); + +#if !defined(FSL_RTOS_FREE_RTOS) + if ( TimerGetLowPowerEnable() == true ) { + RtcInit(); + } else { + TimerHwInit(); + } +#endif + + McuInitialized = true; + } +} + +void BoardDeInitMcu( void ) +{ +#if defined(SX1276_BOARD_FREEDOM) || defined(SX1276_BOARD_EMBED) + SpiDeInit(&SX1276.Spi); + SX1276IoDeInit(); +#endif + + McuInitialized = false; +} + +uint8_t BoardGetBatteryLevel( void ) +{ + /* Device is connected to an external power source*/ + return 0; +} + +uint32_t BoardGetRandomSeed( void ) +{ + return (ID1 ^ ID2 ^ ID3); +} + +void BoardGetUniqueId( uint8_t *id ) +{ + id[0] = (ID1 + ID3) >> 24; + id[1] = (ID1 + ID3) >> 16; + id[2] = (ID1 + ID3) >> 8; + id[3] = (ID1 + ID3); + id[4] = ID2 >> 24; + id[5] = ID2 >> 16; + id[6] = ID2 >> 8; + id[7] = ID2; +} + +static void BoardUnusedIoInit( void ) +{ + // \todo Initialize unused gpio to known state +} diff --git a/pool/shard008/C/0130838_hda-decode-verb.c b/pool/shard008/C/0130838_hda-decode-verb.c new file mode 100644 index 0000000000000000000000000000000000000000..8263b7f6b66fd7ec77306151df7b86c22b0b6507 --- /dev/null +++ b/pool/shard008/C/0130838_hda-decode-verb.c @@ -0,0 +1,126 @@ +/* + * hda-emu - simple HD-audio codec emulator for debugging snd-hda-intel driver + * + * Decode HD-audio verb/parameter values + * + * Copyright (c) Takashi Iwai + * + * This driver 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 driver 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include +#include +#include +#include +#include +#include "hda-types.h" +#include "hda-log.h" + +enum { DECODE, ENCODE }; + +static void usage(int mode) +{ + if (mode == DECODE) { + fprintf(stderr, + "usage: \n" + " hda-decode-verb VALUE\n" + " Decode the encoded command value\n" + " hda-decode-verb VERB PARAMETER\n" + " Decode the verb and parameter values\n" + ); + } else { + fprintf(stderr, + "usage: \n" + " hda-encode-verb VERB PARAMETER\n" + " Encode the verb and parameter values\n" + ); + } + exit(1); +} + +unsigned int hda_decode_verb(struct xhda_codec *codec, unsigned int val) +{ + unsigned int cid, /*dir,*/ nid, verb, parm; + + hda_log(HDA_LOG_INFO, "raw value = 0x%08x\n", val); + + cid = (val >> 28) & 0xf; + /* dir = (val >> 27) & 1; */ + nid = (val >> 20) & 0x7f; + verb = (val >> 8) & 0xfff; + parm = val & 0xff; + hda_log(HDA_LOG_INFO, + "cid = %d, nid = 0x%02x, verb = 0x%x, parm = 0x%02x\n", + cid, nid, verb, parm); + + return hda_decode_verb_parm(codec, verb, parm); +} + + +static void encode(const char *vstr, const char *pstr) +{ + unsigned int verb, parm; + + if (hda_encode_verb_parm(vstr, pstr, &verb, &parm) < 0) { + hda_log(HDA_LOG_ERR, "Invalid parameters\n"); + exit(1); + } + hda_log(HDA_LOG_INFO, "verb = 0x%x, parm = 0x%x\n", verb, parm); +} + +int main(int argc, char **argv) +{ + int mode = DECODE; + int c; + + hda_log_init(NULL, 0); + hda_log_level_set(HDA_LOG_INFO); + + if (strstr(argv[0], "hda-encode-verb")) + mode = ENCODE; + + while ((c = getopt(argc, argv, "de")) != -1) { + switch (c) { + case 'd': + mode = DECODE; + break; + case 'e': + mode = ENCODE; + break; + default: + usage(mode); + } + } + + switch (mode) { + case DECODE: + if (optind >= argc) + usage(mode); + if (optind + 1 == argc) { + hda_decode_verb(NULL, strtoul(argv[optind], NULL, 0)); + } else { + hda_decode_verb_parm(NULL, + strtoul(argv[optind], NULL, 0), + strtoul(argv[optind + 1], NULL, 0)); + } + break; + case ENCODE: + if (optind + 2 > argc) + usage(mode); + encode(argv[optind], argv[optind + 1]); + break; + } + return 0; +} diff --git a/pool/shard008/C/0130841_register_set.c b/pool/shard008/C/0130841_register_set.c new file mode 100644 index 0000000000000000000000000000000000000000..659def4d810d2b7d4bc45d776238dd3385d2bd1f --- /dev/null +++ b/pool/shard008/C/0130841_register_set.c @@ -0,0 +1,225 @@ +/* + * Copyright (c) 2012 The Native Client Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include "native_client/tests/common/register_set.h" + +#include +#include + +#include "native_client/src/include/nacl_assert.h" + +#if defined(__native_client__) +# include "native_client/src/untrusted/nacl/nacl_thread.h" +#endif + + +struct RegInfo { + const char *reg_name; + int reg_offset; + int reg_size; +}; + +#define DEFINE_REG(regname) \ + { \ + #regname, \ + offsetof(struct NaClSignalContext, regname), \ + sizeof(((struct NaClSignalContext *) NULL)->regname) \ + } + +const struct RegInfo kRegs[] = { + /* + * We do not look at x86 segment registers because they are not + * saved by REGS_SAVER_FUNC. + */ +#if NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86 && NACL_BUILD_SUBARCH == 32 + DEFINE_REG(eax), + DEFINE_REG(ecx), + DEFINE_REG(edx), + DEFINE_REG(ebx), + DEFINE_REG(stack_ptr), + DEFINE_REG(ebp), + DEFINE_REG(esi), + DEFINE_REG(edi), + DEFINE_REG(prog_ctr), + DEFINE_REG(flags) +#elif NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86 && NACL_BUILD_SUBARCH == 64 + DEFINE_REG(rax), + DEFINE_REG(rbx), + DEFINE_REG(rcx), + DEFINE_REG(rdx), + DEFINE_REG(rsi), + DEFINE_REG(rdi), + DEFINE_REG(rbp), + DEFINE_REG(stack_ptr), + DEFINE_REG(r8), + DEFINE_REG(r9), + DEFINE_REG(r10), + DEFINE_REG(r11), + DEFINE_REG(r12), + DEFINE_REG(r13), + DEFINE_REG(r14), + DEFINE_REG(r15), + DEFINE_REG(prog_ctr), + DEFINE_REG(flags) +#elif NACL_ARCH(NACL_BUILD_ARCH) == NACL_arm + DEFINE_REG(r0), + DEFINE_REG(r1), + DEFINE_REG(r2), + DEFINE_REG(r3), + DEFINE_REG(r4), + DEFINE_REG(r5), + DEFINE_REG(r6), + DEFINE_REG(r7), + DEFINE_REG(r8), + DEFINE_REG(r9), + DEFINE_REG(r10), + DEFINE_REG(r11), + DEFINE_REG(r12), + DEFINE_REG(stack_ptr), + DEFINE_REG(lr), + DEFINE_REG(prog_ctr), + DEFINE_REG(cpsr) +#else +# error Unsupported architecture +#endif +}; + +#undef DEFINE_REG + +/* Flags readable and writable by untrusted code. */ +const uint8_t kX86FlagBits[5] = { 0, 2, 6, 7, 11 }; +/* + * kX86KnownFlagsMask contains kX86FlagBits plus the trap flag (which + * is not readable or writable by untrusted code) so that trusted-code + * tests will check that the trap flag is still set. + */ +static const uint32_t kX86KnownFlagsMask = + (1<<0) | (1<<2) | (1<<6) | (1<<7) | (1<<11) | + (1<<8); /* Trap flag */ + +void RegsFillTestValues(struct NaClSignalContext *regs) { + unsigned int index; + for (index = 0; index < sizeof(*regs); index++) { + ((char *) regs)[index] = index + 1; + } +#if NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86 + /* Set x86 flags to a value that we know will work. */ + regs->flags = RESET_X86_FLAGS_VALUE; +#endif +} + +#if defined(__native_client__) +void RegsApplySandboxConstraints(struct NaClSignalContext *regs) { +#if NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86 && NACL_BUILD_SUBARCH == 64 + uint64_t r15; + __asm__("mov %%r15, %0" : "=r"(r15)); + regs->r15 = r15; + regs->prog_ctr = r15 + (uint32_t) regs->prog_ctr; + regs->stack_ptr = r15 + (uint32_t) regs->stack_ptr; + regs->rbp = r15 + (uint32_t) regs->rbp; +#else + UNREFERENCED_PARAMETER(regs); +#endif +} +#endif + +static uint64_t RegsGetRegValue(const struct NaClSignalContext *regs, + unsigned int regnum) { + uintptr_t ptr = (uintptr_t) regs + kRegs[regnum].reg_offset; + assert(regnum < NACL_ARRAY_SIZE(kRegs)); + if (kRegs[regnum].reg_size == 4) { + return *(uint32_t *) ptr; + } else if (kRegs[regnum].reg_size == 8) { + return *(uint64_t *) ptr; + } else { + fprintf(stderr, "Unknown register size: %i\n", kRegs[regnum].reg_size); + _exit(1); + } +} + +static void RegsDump(const struct NaClSignalContext *regs) { + unsigned int regnum; + for (regnum = 0; regnum < NACL_ARRAY_SIZE(kRegs); regnum++) { + long long value = RegsGetRegValue(regs, regnum); + fprintf(stderr, " %s=0x%llx (%lld)\n", + kRegs[regnum].reg_name, value, value); + } +} + +static void RegsNormalizeFlags(struct NaClSignalContext *regs) { +#if NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86 + regs->flags &= kX86KnownFlagsMask; +#elif NACL_ARCH(NACL_BUILD_ARCH) == NACL_arm + regs->cpsr &= REGS_ARM_USER_CPSR_FLAGS_MASK; +#endif +} + +void RegsAssertEqual(const struct NaClSignalContext *actual, + const struct NaClSignalContext *expected) { + int match = 1; + unsigned int regnum; + + /* Make a copy so that we can ignore some of the x86/ARM flags. */ + struct NaClSignalContext copy_actual = *actual; + struct NaClSignalContext copy_expected = *expected; + RegsNormalizeFlags(©_actual); + RegsNormalizeFlags(©_expected); + +#if NACL_ARCH(NACL_BUILD_ARCH) == NACL_arm + /* + * We skip comparison of r9 because it is not supposed to be + * settable or readable by untrusted code. However, for debugging + * purposes we still include r9 in register dumps printed by + * RegsDump(), so r9 remains listed in kRegs[]. + */ + copy_expected.r9 = copy_actual.r9; +#endif + + for (regnum = 0; regnum < NACL_ARRAY_SIZE(kRegs); regnum++) { + if (RegsGetRegValue(©_actual, regnum) != + RegsGetRegValue(©_expected, regnum)) { + fprintf(stderr, "Mismatch in register %s\n", kRegs[regnum].reg_name); + match = 0; + } + } + if (!match) { + fprintf(stderr, "Expected register state:\n"); + RegsDump(expected); + fprintf(stderr, "Actual register state:\n"); + RegsDump(actual); + _exit(1); + } +} + +void RegsUnsetNonCalleeSavedRegisters(struct NaClSignalContext *regs) { +#if NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86 && NACL_BUILD_SUBARCH == 32 + regs->eax = 0; + regs->ecx = 0; + regs->edx = 0; + regs->flags = 0; +#elif NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86 && NACL_BUILD_SUBARCH == 64 + regs->rax = 0; + regs->rcx = 0; + regs->rdx = 0; + regs->rsi = 0; + regs->rdi = 0; + regs->r8 = 0; + regs->r9 = 0; + regs->r10 = 0; + regs->r11 = 0; + regs->flags = 0; +#elif NACL_ARCH(NACL_BUILD_ARCH) == NACL_arm + regs->r0 = 0; + regs->r1 = 0; + regs->r2 = 0; + regs->r3 = 0; + regs->r12 = 0; + regs->lr = 0; + regs->cpsr = 0; +#else +# error Unsupported architecture +#endif +} diff --git a/pool/shard008/C/0130843_tool_getpass.c b/pool/shard008/C/0130843_tool_getpass.c new file mode 100644 index 0000000000000000000000000000000000000000..a3fffa9b3e09123403bbe55edca1cda981d106d4 --- /dev/null +++ b/pool/shard008/C/0130843_tool_getpass.c @@ -0,0 +1,260 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2012, Daniel Stenberg, , et al. + * + * This software is licensed as described in the file COPYING, which + * you should have received as part of this distribution. The terms + * are also available at http://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ +#include "tool_setup.h" + +#ifndef HAVE_GETPASS_R +/* this file is only for systems without getpass_r() */ + +#ifdef HAVE_UNISTD_H +# include +#endif + +#ifdef HAVE_FCNTL_H +# include +#endif + +#ifdef HAVE_TERMIOS_H +# include +#elif defined(HAVE_TERMIO_H) +# include +#endif + +#ifdef __VMS +# include descrip +# include starlet +# include iodef +#endif + +#ifdef WIN32 +# include +#endif + +#ifdef NETWARE +# ifdef __NOVELL_LIBC__ +# include +# else +# include +# endif +#endif + +#define _MPRINTF_REPLACE +#include + +#include "tool_getpass.h" + +#include "memdebug.h" /* keep this as LAST include */ + +#ifdef __VMS +/* VMS implementation */ +char *getpass_r(const char *prompt, char *buffer, size_t buflen) +{ + long sts; + short chan; + + /* MSK, 23-JAN-2004, iosbdef.h wasn't in VAX V7.2 or CC 6.4 */ + /* distribution so I created this. May revert back later to */ + /* struct _iosb iosb; */ + struct _iosb + { + short int iosb$w_status; /* status */ + short int iosb$w_bcnt; /* byte count */ + int unused; /* unused */ + } iosb; + + $DESCRIPTOR(ttdesc, "TT"); + + buffer[0] = '\0'; + sts = sys$assign(&ttdesc, &chan, 0, 0); + if(sts & 1) { + sts = sys$qiow(0, chan, + IO$_READPROMPT | IO$M_NOECHO, + &iosb, 0, 0, buffer, buflen, 0, 0, + prompt, strlen(prompt)); + + if((sts & 1) && (iosb.iosb$w_status & 1)) + buffer[iosb.iosb$w_bcnt] = '\0'; + + sts = sys$dassgn(chan); + } + return buffer; /* we always return success */ +} +#define DONE +#endif /* __VMS */ + +#ifdef __SYMBIAN32__ +# define getch() getchar() +#endif + +#if defined(WIN32) || defined(__SYMBIAN32__) + +char *getpass_r(const char *prompt, char *buffer, size_t buflen) +{ + size_t i; + fputs(prompt, stderr); + + for(i = 0; i < buflen; i++) { + buffer[i] = (char)getch(); + if(buffer[i] == '\r' || buffer[i] == '\n') { + buffer[i] = '\0'; + break; + } + else + if(buffer[i] == '\b') + /* remove this letter and if this is not the first key, remove the + previous one as well */ + i = i - (i >= 1) ? 2 : 1; + } +#ifndef __SYMBIAN32__ + /* since echo is disabled, print a newline */ + fputs("\n", stderr); +#endif + /* if user didn't hit ENTER, terminate buffer */ + if(i == buflen) + buffer[buflen-1] = '\0'; + + return buffer; /* we always return success */ +} +#define DONE +#endif /* WIN32 || __SYMBIAN32__ */ + +#ifdef NETWARE +/* NetWare implementation */ +#ifdef __NOVELL_LIBC__ +char *getpass_r(const char *prompt, char *buffer, size_t buflen) +{ + return getpassword(prompt, buffer, buflen); +} +#else +char *getpass_r(const char *prompt, char *buffer, size_t buflen) +{ + size_t i = 0; + + printf("%s", prompt); + do { + buffer[i++] = getch(); + if(buffer[i-1] == '\b') { + /* remove this letter and if this is not the first key, + remove the previous one as well */ + if(i > 1) { + printf("\b \b"); + i = i - 2; + } + else { + RingTheBell(); + i = i - 1; + } + } + else if(buffer[i-1] != 13) + putchar('*'); + + } while((buffer[i-1] != 13) && (i < buflen)); + buffer[i-1] = '\0'; + printf("\r\n"); + return buffer; +} +#endif /* __NOVELL_LIBC__ */ +#define DONE +#endif /* NETWARE */ + +#ifndef DONE /* not previously provided */ + +#ifdef HAVE_TERMIOS_H +# define struct_term struct termios +#elif defined(HAVE_TERMIO_H) +# define struct_term struct termio +#else +# undef struct_term +#endif + +static bool ttyecho(bool enable, int fd) +{ +#ifdef struct_term + static struct_term withecho; + static struct_term noecho; +#endif + if(!enable) { + /* disable echo by extracting the current 'withecho' mode and remove the + ECHO bit and set back the struct */ +#ifdef HAVE_TERMIOS_H + tcgetattr(fd, &withecho); + noecho = withecho; + noecho.c_lflag &= ~ECHO; + tcsetattr(fd, TCSANOW, &noecho); +#elif defined(HAVE_TERMIO_H) + ioctl(fd, TCGETA, &withecho); + noecho = withecho; + noecho.c_lflag &= ~ECHO; + ioctl(fd, TCSETA, &noecho); +#else + /* neither HAVE_TERMIO_H nor HAVE_TERMIOS_H, we can't disable echo! */ + (void)fd; + return FALSE; /* not disabled */ +#endif + return TRUE; /* disabled */ + } + else { + /* re-enable echo, assumes we disabled it before (and set the structs we + now use to reset the terminal status) */ +#ifdef HAVE_TERMIOS_H + tcsetattr(fd, TCSAFLUSH, &withecho); +#elif defined(HAVE_TERMIO_H) + ioctl(fd, TCSETA, &withecho); +#else + return FALSE; /* not enabled */ +#endif + return TRUE; /* enabled */ + } +} + +char *getpass_r(const char *prompt, /* prompt to display */ + char *password, /* buffer to store password in */ + size_t buflen) /* size of buffer to store password in */ +{ + ssize_t nread; + bool disabled; + int fd = open("/dev/tty", O_RDONLY); + if(-1 == fd) + fd = 1; /* use stdin if the tty couldn't be used */ + + disabled = ttyecho(FALSE, fd); /* disable terminal echo */ + + fputs(prompt, stderr); + nread = read(fd, password, buflen); + if(nread > 0) + password[--nread] = '\0'; /* zero terminate where enter is stored */ + else + password[0] = '\0'; /* got nothing */ + + if(disabled) { + /* if echo actually was disabled, add a newline */ + fputs("\n", stderr); + (void)ttyecho(TRUE, fd); /* enable echo */ + } + + if(1 != fd) + close(fd); + + return password; /* return pointer to buffer */ +} + +#endif /* DONE */ +#endif /* HAVE_GETPASS_R */ diff --git a/pool/shard008/C/0130849_machine_kexec.c b/pool/shard008/C/0130849_machine_kexec.c new file mode 100644 index 0000000000000000000000000000000000000000..2a81ba159b8f027fa698b3528605dcf2a968c703 --- /dev/null +++ b/pool/shard008/C/0130849_machine_kexec.c @@ -0,0 +1,193 @@ +/* + * machine_kexec.c - handle transition of Linux booting another kernel + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern void relocate_new_kernel(void); +extern const unsigned int relocate_new_kernel_size; + +extern unsigned long kexec_start_address; +extern unsigned long kexec_indirection_page; +extern unsigned long kexec_mach_type; +extern unsigned long kexec_boot_atags; + +static atomic_t waiting_for_crash_ipi; + +static unsigned long dt_mem; +/* + * Provide a dummy crash_notes definition while crash dump arrives to arm. + * This prevents breakage of crash_notes attribute in kernel/ksysfs.c. + */ + +int machine_kexec_prepare(struct kimage *image) +{ + struct kexec_segment *current_segment; + __be32 header; + int i, err; + + /* + * Validate that if the current HW supports SMP, then the SW supports + * and implements CPU hotplug for the current HW. If not, we won't be + * able to kexec reliably, so fail the prepare operation. + */ + if (num_possible_cpus() > 1 && platform_can_secondary_boot() && + !platform_can_cpu_hotplug()) + return -EINVAL; + + /* + * No segment at default ATAGs address. try to locate + * a dtb using magic. + */ + for (i = 0; i < image->nr_segments; i++) { + current_segment = &image->segment[i]; + + if (!memblock_is_region_memory(idmap_to_phys(current_segment->mem), + current_segment->memsz)) + return -EINVAL; + + err = get_user(header, (__be32*)current_segment->buf); + if (err) + return err; + + if (be32_to_cpu(header) == OF_DT_HEADER) + dt_mem = current_segment->mem; + } + return 0; +} + +void machine_kexec_cleanup(struct kimage *image) +{ +} + +void machine_crash_nonpanic_core(void *unused) +{ + struct pt_regs regs; + + crash_setup_regs(®s, NULL); + printk(KERN_DEBUG "CPU %u will stop doing anything useful since another CPU has crashed\n", + smp_processor_id()); + crash_save_cpu(®s, smp_processor_id()); + flush_cache_all(); + + set_cpu_online(smp_processor_id(), false); + atomic_dec(&waiting_for_crash_ipi); + while (1) + cpu_relax(); +} + +static void machine_kexec_mask_interrupts(void) +{ + unsigned int i; + struct irq_desc *desc; + + for_each_irq_desc(i, desc) { + struct irq_chip *chip; + + chip = irq_desc_get_chip(desc); + if (!chip) + continue; + + if (chip->irq_eoi && irqd_irq_inprogress(&desc->irq_data)) + chip->irq_eoi(&desc->irq_data); + + if (chip->irq_mask) + chip->irq_mask(&desc->irq_data); + + if (chip->irq_disable && !irqd_irq_disabled(&desc->irq_data)) + chip->irq_disable(&desc->irq_data); + } +} + +void machine_crash_shutdown(struct pt_regs *regs) +{ + unsigned long msecs; + + local_irq_disable(); + disable_nonboot_cpus(); + + atomic_set(&waiting_for_crash_ipi, num_online_cpus() - 1); + smp_call_function(machine_crash_nonpanic_core, NULL, false); + msecs = 1000; /* Wait at most a second for the other cpus to stop */ + while ((atomic_read(&waiting_for_crash_ipi) > 0) && msecs) { + mdelay(1); + msecs--; + } + if (atomic_read(&waiting_for_crash_ipi) > 0) + pr_warn("Non-crashing CPUs did not react to IPI\n"); + + crash_save_cpu(regs, smp_processor_id()); + machine_kexec_mask_interrupts(); + + pr_info("Loading crashdump kernel...\n"); +} + +/* + * Function pointer to optional machine-specific reinitialization + */ +void (*kexec_reinit)(void); + +void machine_kexec(struct kimage *image) +{ + unsigned long page_list, reboot_entry_phys; + void (*reboot_entry)(void); + void *reboot_code_buffer; + + /* + * This can only happen if machine_shutdown() failed to disable some + * CPU, and that can only happen if the checks in + * machine_kexec_prepare() were not correct. If this fails, we can't + * reliably kexec anyway, so BUG_ON is appropriate. + */ + BUG_ON(num_online_cpus() > 1); + + page_list = image->head & PAGE_MASK; + + reboot_code_buffer = page_address(image->control_code_page); + + /* Prepare parameters for reboot_code_buffer*/ + set_kernel_text_rw(); + kexec_start_address = image->start; + kexec_indirection_page = page_list; + kexec_mach_type = machine_arch_type; + kexec_boot_atags = dt_mem ?: image->start - KEXEC_ARM_ZIMAGE_OFFSET + + KEXEC_ARM_ATAGS_OFFSET; + + /* copy our kernel relocation code to the control code page */ + reboot_entry = fncpy(reboot_code_buffer, + &relocate_new_kernel, + relocate_new_kernel_size); + + /* get the identity mapping physical address for the reboot code */ + reboot_entry_phys = virt_to_idmap(reboot_entry); + + pr_info("Bye!\n"); + + if (kexec_reinit) + kexec_reinit(); + + soft_restart(reboot_entry_phys); +} + +void arch_crash_save_vmcoreinfo(void) +{ +#ifdef CONFIG_ARM_LPAE + VMCOREINFO_CONFIG(ARM_LPAE); +#endif +} diff --git a/pool/shard008/C/0130851_gpio.c b/pool/shard008/C/0130851_gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..1aba41c6351ea68d92884e56ebbd10ae86b237a7 --- /dev/null +++ b/pool/shard008/C/0130851_gpio.c @@ -0,0 +1,328 @@ +/* + * TI DaVinci GPIO Support + * + * Copyright (c) 2006-2007 David Brownell + * Copyright (c) 2007, MontaVista Software, Inc. + * + * 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + + +static DEFINE_SPINLOCK(gpio_lock); + +struct davinci_gpio { + struct gpio_chip chip; + struct gpio_controller *__iomem regs; +}; + +static struct davinci_gpio chips[DIV_ROUND_UP(DAVINCI_N_GPIO, 32)]; + +static unsigned __initdata ngpio; + +/* create a non-inlined version */ +static struct gpio_controller __iomem * __init gpio2controller(unsigned gpio) +{ + return __gpio_to_controller(gpio); +} + + +/*--------------------------------------------------------------------------*/ + +/* + * board setup code *MUST* set PINMUX0 and PINMUX1 as + * needed, and enable the GPIO clock. + */ + +static int davinci_direction_in(struct gpio_chip *chip, unsigned offset) +{ + struct davinci_gpio *d = container_of(chip, struct davinci_gpio, chip); + struct gpio_controller *__iomem g = d->regs; + u32 temp; + + spin_lock(&gpio_lock); + temp = __raw_readl(&g->dir); + temp |= (1 << offset); + __raw_writel(temp, &g->dir); + spin_unlock(&gpio_lock); + + return 0; +} + +/* + * Read the pin's value (works even if it's set up as output); + * returns zero/nonzero. + * + * Note that changes are synched to the GPIO clock, so reading values back + * right after you've set them may give old values. + */ +static int davinci_gpio_get(struct gpio_chip *chip, unsigned offset) +{ + struct davinci_gpio *d = container_of(chip, struct davinci_gpio, chip); + struct gpio_controller *__iomem g = d->regs; + + return (1 << offset) & __raw_readl(&g->in_data); +} + +static int +davinci_direction_out(struct gpio_chip *chip, unsigned offset, int value) +{ + struct davinci_gpio *d = container_of(chip, struct davinci_gpio, chip); + struct gpio_controller *__iomem g = d->regs; + u32 temp; + u32 mask = 1 << offset; + + spin_lock(&gpio_lock); + temp = __raw_readl(&g->dir); + temp &= ~mask; + __raw_writel(mask, value ? &g->set_data : &g->clr_data); + __raw_writel(temp, &g->dir); + spin_unlock(&gpio_lock); + return 0; +} + +/* + * Assuming the pin is muxed as a gpio output, set its output value. + */ +static void +davinci_gpio_set(struct gpio_chip *chip, unsigned offset, int value) +{ + struct davinci_gpio *d = container_of(chip, struct davinci_gpio, chip); + struct gpio_controller *__iomem g = d->regs; + + __raw_writel((1 << offset), value ? &g->set_data : &g->clr_data); +} + +static int __init davinci_gpio_setup(void) +{ + int i, base; + + /* The gpio banks conceptually expose a segmented bitmap, + * and "ngpio" is one more than the largest zero-based + * bit index that's valid. + */ + if (cpu_is_davinci_dm355()) { /* or dm335() */ + ngpio = 104; + } else if (cpu_is_davinci_dm644x()) { /* or dm337() */ + ngpio = 71; + } else if (cpu_is_davinci_dm646x()) { + /* NOTE: each bank has several "reserved" bits, + * unusable as GPIOs. Only 33 of the GPIO numbers + * are usable, and we're not rejecting the others. + */ + ngpio = 43; + } else { + /* if cpu_is_davinci_dm643x() ngpio = 111 */ + pr_err("GPIO setup: how many GPIOs?\n"); + return -EINVAL; + } + + if (WARN_ON(DAVINCI_N_GPIO < ngpio)) + ngpio = DAVINCI_N_GPIO; + + for (i = 0, base = 0; base < ngpio; i++, base += 32) { + chips[i].chip.label = "DaVinci"; + + chips[i].chip.direction_input = davinci_direction_in; + chips[i].chip.get = davinci_gpio_get; + chips[i].chip.direction_output = davinci_direction_out; + chips[i].chip.set = davinci_gpio_set; + + chips[i].chip.base = base; + chips[i].chip.ngpio = ngpio - base; + if (chips[i].chip.ngpio > 32) + chips[i].chip.ngpio = 32; + + chips[i].regs = gpio2controller(base); + + gpiochip_add(&chips[i].chip); + } + + return 0; +} +pure_initcall(davinci_gpio_setup); + +/*--------------------------------------------------------------------------*/ +/* + * We expect irqs will normally be set up as input pins, but they can also be + * used as output pins ... which is convenient for testing. + * + * NOTE: The first few GPIOs also have direct INTC hookups in addition + * to their GPIOBNK0 irq, with a bit less overhead but less flexibility + * on triggering (e.g. no edge options). We don't try to use those. + * + * All those INTC hookups (direct, plus several IRQ banks) can also + * serve as EDMA event triggers. + */ + +static void gpio_irq_disable(unsigned irq) +{ + struct gpio_controller *__iomem g = get_irq_chip_data(irq); + u32 mask = __gpio_mask(irq_to_gpio(irq)); + + __raw_writel(mask, &g->clr_falling); + __raw_writel(mask, &g->clr_rising); +} + +static void gpio_irq_enable(unsigned irq) +{ + struct gpio_controller *__iomem g = get_irq_chip_data(irq); + u32 mask = __gpio_mask(irq_to_gpio(irq)); + + if (irq_desc[irq].status & IRQ_TYPE_EDGE_FALLING) + __raw_writel(mask, &g->set_falling); + if (irq_desc[irq].status & IRQ_TYPE_EDGE_RISING) + __raw_writel(mask, &g->set_rising); +} + +static int gpio_irq_type(unsigned irq, unsigned trigger) +{ + struct gpio_controller *__iomem g = get_irq_chip_data(irq); + u32 mask = __gpio_mask(irq_to_gpio(irq)); + + if (trigger & ~(IRQ_TYPE_EDGE_FALLING | IRQ_TYPE_EDGE_RISING)) + return -EINVAL; + + irq_desc[irq].status &= ~IRQ_TYPE_SENSE_MASK; + irq_desc[irq].status |= trigger; + + __raw_writel(mask, (trigger & IRQ_TYPE_EDGE_FALLING) + ? &g->set_falling : &g->clr_falling); + __raw_writel(mask, (trigger & IRQ_TYPE_EDGE_RISING) + ? &g->set_rising : &g->clr_rising); + return 0; +} + +static struct irq_chip gpio_irqchip = { + .name = "GPIO", + .enable = gpio_irq_enable, + .disable = gpio_irq_disable, + .set_type = gpio_irq_type, +}; + +static void +gpio_irq_handler(unsigned irq, struct irq_desc *desc) +{ + struct gpio_controller *__iomem g = get_irq_chip_data(irq); + u32 mask = 0xffff; + + /* we only care about one bank */ + if (irq & 1) + mask <<= 16; + + /* temporarily mask (level sensitive) parent IRQ */ + desc->chip->ack(irq); + while (1) { + u32 status; + int n; + int res; + + /* ack any irqs */ + status = __raw_readl(&g->intstat) & mask; + if (!status) + break; + __raw_writel(status, &g->intstat); + if (irq & 1) + status >>= 16; + + /* now demux them to the right lowlevel handler */ + n = (int)get_irq_data(irq); + while (status) { + res = ffs(status); + n += res; + generic_handle_irq(n - 1); + status >>= res; + } + } + desc->chip->unmask(irq); + /* now it may re-trigger */ +} + +/* + * NOTE: for suspend/resume, probably best to make a platform_device with + * suspend_late/resume_resume calls hooking into results of the set_wake() + * calls ... so if no gpios are wakeup events the clock can be disabled, + * with outputs left at previously set levels, and so that VDD3P3V.IOPWDN0 + * (dm6446) can be set appropriately for GPIOV33 pins. + */ + +static int __init davinci_gpio_irq_setup(void) +{ + unsigned gpio, irq, bank; + unsigned bank_irq; + struct clk *clk; + u32 binten = 0; + + if (cpu_is_davinci_dm355()) { /* or dm335() */ + bank_irq = IRQ_DM355_GPIOBNK0; + } else if (cpu_is_davinci_dm644x()) { + bank_irq = IRQ_GPIOBNK0; + } else if (cpu_is_davinci_dm646x()) { + bank_irq = IRQ_DM646X_GPIOBNK0; + } else { + printk(KERN_ERR "Don't know first GPIO bank IRQ.\n"); + return -EINVAL; + } + + clk = clk_get(NULL, "gpio"); + if (IS_ERR(clk)) { + printk(KERN_ERR "Error %ld getting gpio clock?\n", + PTR_ERR(clk)); + return PTR_ERR(clk); + } + clk_enable(clk); + + for (gpio = 0, irq = gpio_to_irq(0), bank = 0; + gpio < ngpio; + bank++, bank_irq++) { + struct gpio_controller *__iomem g = gpio2controller(gpio); + unsigned i; + + __raw_writel(~0, &g->clr_falling); + __raw_writel(~0, &g->clr_rising); + + /* set up all irqs in this bank */ + set_irq_chained_handler(bank_irq, gpio_irq_handler); + set_irq_chip_data(bank_irq, g); + set_irq_data(bank_irq, (void *)irq); + + for (i = 0; i < 16 && gpio < ngpio; i++, irq++, gpio++) { + set_irq_chip(irq, &gpio_irqchip); + set_irq_chip_data(irq, g); + set_irq_handler(irq, handle_simple_irq); + set_irq_flags(irq, IRQF_VALID); + } + + binten |= BIT(bank); + } + + /* BINTEN -- per-bank interrupt enable. genirq would also let these + * bits be set/cleared dynamically. + */ + __raw_writel(binten, (void *__iomem) + IO_ADDRESS(DAVINCI_GPIO_BASE + 0x08)); + + printk(KERN_INFO "DaVinci: %d gpio irqs\n", irq - gpio_to_irq(0)); + + return 0; +} +arch_initcall(davinci_gpio_irq_setup); diff --git a/pool/shard008/C/0130855_kms_render.c b/pool/shard008/C/0130855_kms_render.c new file mode 100644 index 0000000000000000000000000000000000000000..e0a2b58f6b82fbdd54a84d11a94ece9e0280da4f --- /dev/null +++ b/pool/shard008/C/0130855_kms_render.c @@ -0,0 +1,251 @@ +/* + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * Authors: + * Imre Deak + */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "igt.h" +#include +#include +#include +#include +#include + +#include "intel_bufmgr.h" + +drmModeRes *resources; +int drm_fd; +static drm_intel_bufmgr *bufmgr; +struct intel_batchbuffer *batch; +uint32_t devid; + +enum test_flags { + TEST_DIRECT_RENDER = 0x01, + TEST_GPU_BLIT = 0x02, +}; + +static int paint_fb(struct igt_fb *fb, const char *test_name, + const char *mode_format_str, const char *cconf_str) +{ + cairo_t *cr; + + cr = igt_get_cairo_ctx(drm_fd, fb); + + igt_paint_color_gradient(cr, 0, 0, fb->width, fb->height, 1, 1, 1); + igt_paint_test_pattern(cr, fb->width, fb->height); + + cairo_move_to(cr, fb->width / 2, fb->height / 2); + cairo_set_font_size(cr, 36); + igt_cairo_printf_line(cr, align_hcenter, 10, "%s", test_name); + igt_cairo_printf_line(cr, align_hcenter, 10, "%s", mode_format_str); + igt_cairo_printf_line(cr, align_hcenter, 10, "%s", cconf_str); + + cairo_destroy(cr); + + return 0; +} + +static void gpu_blit(struct igt_fb *dst_fb, struct igt_fb *src_fb) +{ + drm_intel_bo *dst_bo; + drm_intel_bo *src_bo; + int bpp; + + igt_assert(dst_fb->drm_format == src_fb->drm_format); + igt_assert(src_fb->drm_format == DRM_FORMAT_RGB565 || + igt_drm_format_to_bpp(src_fb->drm_format) != 16); + bpp = igt_drm_format_to_bpp(src_fb->drm_format); + dst_bo = gem_handle_to_libdrm_bo(bufmgr, drm_fd, "destination", + dst_fb->gem_handle); + igt_assert(dst_bo); + src_bo = gem_handle_to_libdrm_bo(bufmgr, drm_fd, "source", + src_fb->gem_handle); + igt_assert(src_bo); + + intel_blt_copy(batch, + src_bo, 0, 0, src_fb->width * bpp / 8, + dst_bo, 0, 0, dst_fb->width * bpp / 8, + src_fb->width, src_fb->height, bpp); + intel_batchbuffer_flush(batch); + gem_quiescent_gpu(drm_fd); + + drm_intel_bo_unreference(src_bo); + drm_intel_bo_unreference(dst_bo); +} + +static int test_format(const char *test_name, + struct kmstest_connector_config *cconf, + drmModeModeInfo *mode, uint32_t format, + enum test_flags flags) +{ + int width; + int height; + struct igt_fb fb[2]; + char *mode_format_str; + char *cconf_str; + int ret; + + ret = asprintf(&mode_format_str, "%s @ %dHz / %s", + mode->name, mode->vrefresh, igt_format_str(format)); + igt_assert_lt(0, ret); + ret = asprintf(&cconf_str, "pipe %s, encoder %s, connector %s", + kmstest_pipe_name(cconf->pipe), + kmstest_encoder_type_str(cconf->encoder->encoder_type), + kmstest_connector_type_str(cconf->connector->connector_type)); + igt_assert_lt(0, ret); + + igt_info("Beginning test %s with %s on %s\n", + test_name, mode_format_str, cconf_str); + + width = mode->hdisplay; + height = mode->vdisplay; + + if (!igt_create_fb(drm_fd, width, height, format, + LOCAL_DRM_FORMAT_MOD_NONE, &fb[0])) + goto err1; + + if (!igt_create_fb(drm_fd, width, height, format, + LOCAL_DRM_FORMAT_MOD_NONE, &fb[1])) + goto err2; + + if (drmModeSetCrtc(drm_fd, cconf->crtc->crtc_id, fb[0].fb_id, + 0, 0, &cconf->connector->connector_id, 1, + mode)) + goto err2; + do_or_die(drmModePageFlip(drm_fd, cconf->crtc->crtc_id, fb[0].fb_id, + 0, NULL)); + sleep(2); + + if (flags & TEST_DIRECT_RENDER) { + paint_fb(&fb[0], test_name, mode_format_str, cconf_str); + } else if (flags & TEST_GPU_BLIT) { + paint_fb(&fb[1], test_name, mode_format_str, cconf_str); + gpu_blit(&fb[0], &fb[1]); + } + sleep(5); + + igt_info("Test %s with %s on %s: PASSED\n", + test_name, mode_format_str, cconf_str); + free(mode_format_str); + free(cconf_str); + + igt_remove_fb(drm_fd, &fb[1]); + igt_remove_fb(drm_fd, &fb[0]); + + return 0; + +err2: + igt_remove_fb(drm_fd, &fb[0]); +err1: + igt_info("Test %s with %s on %s: SKIPPED\n", + test_name, mode_format_str, cconf_str); + free(mode_format_str); + free(cconf_str); + + return -1; +} + +static void test_connector(const char *test_name, + struct kmstest_connector_config *cconf, + enum test_flags flags) +{ + const uint32_t *formats; + int format_count; + int i; + + igt_get_all_cairo_formats(&formats, &format_count); + for (i = 0; i < format_count; i++) { + if (intel_gen(intel_get_drm_devid(drm_fd)) < 4 + && formats[i] == DRM_FORMAT_XRGB2101010) { + igt_info("gen2/3 don't support 10bpc, skipping\n"); + continue; + } + + test_format(test_name, + cconf, &cconf->connector->modes[0], + formats[i], flags); + } +} + +static int run_test(const char *test_name, enum test_flags flags) +{ + int i; + + resources = drmModeGetResources(drm_fd); + igt_assert(resources); + + /* Find any connected displays */ + for (i = 0; i < resources->count_connectors; i++) { + uint32_t connector_id; + int j; + + connector_id = resources->connectors[i]; + for (j = 0; j < resources->count_crtcs; j++) { + struct kmstest_connector_config cconf; + + if (!kmstest_get_connector_config(drm_fd, connector_id, + 1 << j, &cconf)) + continue; + + test_connector(test_name, &cconf, flags); + + kmstest_free_connector_config(&cconf); + } + } + + drmModeFreeResources(resources); + + return 1; +} + +igt_main +{ + struct { + enum test_flags flags; + const char *name; + } tests[] = { + { TEST_DIRECT_RENDER, "direct-render" }, + { TEST_GPU_BLIT, "gpu-blit" }, + }; + int i; + + igt_skip_on_simulation(); + + igt_fixture { + drm_fd = drm_open_driver_master(DRIVER_INTEL); + + bufmgr = drm_intel_bufmgr_gem_init(drm_fd, 4096); + devid = intel_get_drm_devid(drm_fd); + batch = intel_batchbuffer_alloc(bufmgr, devid); + + kmstest_set_vt_graphics_mode(); + } + + for (i = 0; i < ARRAY_SIZE(tests); i++) { + igt_subtest(tests[i].name) + run_test(tests[i].name, tests[i].flags); + } + + igt_fixture + close(drm_fd); +} diff --git a/pool/shard008/C/0130858_mobs.c b/pool/shard008/C/0130858_mobs.c new file mode 100644 index 0000000000000000000000000000000000000000..eabcaae742245127f1148ba3682f38f08831e60f --- /dev/null +++ b/pool/shard008/C/0130858_mobs.c @@ -0,0 +1,128 @@ +/* + 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, see . + */ + +#include "vars.h" +#include "gpu3d.h" + +void SpawnMob(void) { + + Uint8 i = 0; + + while ((mob[i][0] > 0) & (i < 128)) + i++; + if (i < 128) { + mob[i][0] = iwavedata[wave][1]; //hp + mob[i][1] = iwavedata[wave][3]; //color + mob[i][2] = iwavedata[wave][2]; //model + mob[i][3] = iwavedata[wave][4]; //speed + mob[i][4] = spawnx; + mob[i][5] = spawny; + mob[i][6] = iwavedata[wave][6]; //z + mob[i][7] = 1024 * dirmap[spawnx / 65536 / 2][spawny / 65536 / 2]; // turn + + mob[i][10] = 0; //hurt + + } + zl_vibro = 10; + +} + +void MobModel(Uint8 i) { + Uint8 model = mob[i][2]; + Uint8 c = mob[i][1]; + + if (mob[i][10]) { + mob[i][10] = 0; + c = 15; + } + + switch (model) { + case 0: + zlvertex = 0; + zlpoint(32768, 25000, -32768); + zlvertex = 1; + zlpoint(-32768, 25000, -32768); + zlvertex = 2; + zlpoint(0, 15000, 65536); + if (vbufferz[0] > 20000) + if (vvis[0]) { + DrawLine2(vbufferx[0], vbuffery[0], vbufferx[1], vbuffery[1], + c); + DrawLine2(vbufferx[2], vbuffery[2], vbufferx[1], vbuffery[1], + c); + DrawLine2(vbufferx[2], vbuffery[2], vbufferx[0], vbuffery[0], + c); + } + + break; + case 1: + zlvertex = 0; + zlpoint(32768, 000, 0); + zlvertex = 1; + zlpoint(-32768, 000, 0); + zlvertex = 2; + zlpoint(0, 60000, 0); + if (vbufferz[0] > 20000) + if (vvis[0]) { + DrawLine2(vbufferx[0], vbuffery[0], vbufferx[1], vbuffery[1], + c); + DrawLine2(vbufferx[2], vbuffery[2], vbufferx[1], vbuffery[1], + c); + DrawLine2(vbufferx[2], vbuffery[2], vbufferx[0], vbuffery[0], + c); + } + + break; + case 2: + zlvertex = 0; + zlpoint(32768, 0, -32768); + zlvertex = 1; + zlpoint(-32768, 0, -32768); + zlvertex = 2; + zlpoint(-32768, 0, 32768); + zlvertex = 3; + zlpoint(32768, 0, 32768); + if (vbufferz[0] > 20000) + if (vvis[0]) { + DrawLine2(vbufferx[0], vbuffery[0], vbufferx[1], vbuffery[1], + c); + DrawLine2(vbufferx[2], vbuffery[2], vbufferx[1], vbuffery[1], + c); + DrawLine2(vbufferx[2], vbuffery[2], vbufferx[3], vbuffery[3], + c); + DrawLine2(vbufferx[3], vbuffery[3], vbufferx[0], vbuffery[0], + c); + } + + break; + + } + +} + +void RenderMobs(void) { + Uint8 i, c; + for (i = 0; i < 128; i++) + if (mob[i][0] > 0) + if (zabs(mob[i][4] - cursorx) < 7 * 65536) + if (zabs(mob[i][5] - cursory) < 5 * 65536) { + zlpushmatrix(); + zltranslate(mob[i][4], mob[i][6], -mob[i][5]); + zlrotatey(-mob[i][7]); + MobModel(i); + zlpopmatrix(); + } +} + diff --git a/pool/shard008/C/0130862_nft-object-test.c b/pool/shard008/C/0130862_nft-object-test.c new file mode 100644 index 0000000000000000000000000000000000000000..d2ca444153419beaf463c9d7cae0afbafe7de75c --- /dev/null +++ b/pool/shard008/C/0130862_nft-object-test.c @@ -0,0 +1,78 @@ +/* + * (C) 2013 by Ana Rey Botello + * + * 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. + * + */ + +#include +#include +#include +#include + +#include +#include + +static int test_ok = 1; + +static void print_err(const char *msg) +{ + test_ok = 0; + printf("\033[31mERROR:\e[0m %s\n", msg); +} + +static void cmp_nftnl_obj(struct nftnl_obj *a, struct nftnl_obj *b) +{ + if (strcmp(nftnl_obj_get_str(a, NFTNL_OBJ_TABLE), + nftnl_obj_get_str(b, NFTNL_OBJ_TABLE)) != 0) + print_err("table name mismatches"); + if (strcmp(nftnl_obj_get_str(a, NFTNL_OBJ_NAME), + nftnl_obj_get_str(b, NFTNL_OBJ_NAME)) != 0) + print_err("name mismatches"); + if (nftnl_obj_get_u32(a, NFTNL_OBJ_FAMILY) != + nftnl_obj_get_u32(b, NFTNL_OBJ_FAMILY)) + print_err("family mismatches"); + if (nftnl_obj_get_u32(a, NFTNL_OBJ_TYPE) != + nftnl_obj_get_u32(b, NFTNL_OBJ_TYPE)) + print_err("type mismatches"); +} + +int main(int argc, char *argv[]) +{ + char buf[4096]; + struct nlmsghdr *nlh; + struct nftnl_obj *a; + struct nftnl_obj *b; + + a = nftnl_obj_alloc(); + b = nftnl_obj_alloc(); + if (a == NULL || b == NULL) + print_err("OOM"); + + nftnl_obj_set_str(a, NFTNL_OBJ_TABLE, "test"); + nftnl_obj_set_str(a, NFTNL_OBJ_NAME, "test"); + nftnl_obj_set_u32(a, NFTNL_OBJ_FAMILY, AF_INET); + nftnl_obj_set_u32(a, NFTNL_OBJ_USE, 1); + nftnl_obj_set_u64(a, NFTNL_OBJ_CTR_BYTES, 0x12345678abcd); + nftnl_obj_set_u64(a, NFTNL_OBJ_CTR_PKTS, 0xcd12345678ab); + + /* cmd extracted from include/linux/netfilter/nf_tables.h */ + nlh = nftnl_nlmsg_build_hdr(buf, NFT_MSG_NEWOBJ, AF_INET, 0, 1234); + nftnl_obj_nlmsg_build_payload(nlh, a); + + if (nftnl_obj_nlmsg_parse(nlh, b) < 0) + print_err("parsing problems"); + + cmp_nftnl_obj(a, b); + + nftnl_obj_free(a); + nftnl_obj_free(b); + if (!test_ok) + exit(EXIT_FAILURE); + + printf("%s: \033[32mOK\e[0m\n", argv[0]); + return EXIT_SUCCESS; +} diff --git a/pool/shard008/C/0130863_query.c b/pool/shard008/C/0130863_query.c new file mode 100644 index 0000000000000000000000000000000000000000..70c4ceded91a1927d8e8fbb90773c11794c265c9 --- /dev/null +++ b/pool/shard008/C/0130863_query.c @@ -0,0 +1,110 @@ +/* + * query.c - manage DNS queries + * + * Copyright (C) 2014 - 2015, Xiaoxiao + * + * 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 . + */ + +#include +#include "dns.h" +#include "query.h" +#include "utils.h" + + +/* + * @var qlist + * @desc query list + */ +#define QLIST_SIZE 128 +static query_t * qlist[QLIST_SIZE]; + + +/* + * @func query_add() + * @desc add new DNS query + */ +int query_add(query_t *query) +{ + query->ttl = 10; + query->qid = query->id; + for (int i = 0; i < QLIST_SIZE; i++) + { + if (qlist[i] == NULL) + { + qlist[i] = query; + return 0; + } + } + return -1; +} + + +/* + * @func query_search() + * @desc search DNS query from query list + * @param id - query id + */ +query_t *query_search(uint16_t id) +{ + for (int i = 0; i < QLIST_SIZE; i++) + { + if ((qlist[i] != NULL) && (qlist[i]->id == id)) + { + return qlist[i]; + } + } + return NULL; +} + + +/* + * @func query_delete() + * @desc delete DNS query from query list + * @param id - query id + */ +int query_delete(uint16_t id) +{ + for (int i = 0; i < QLIST_SIZE; i++) + { + if ((qlist[i] != NULL) && (qlist[i]->id == id)) + { + free(qlist[i]); + qlist[i] = NULL; + return 0; + } + } + return -1; +} + + +/* + * @func query_tick() + * @desc delete old queries periodically + */ +void query_tick(void) +{ + for (int i = 0; i < QLIST_SIZE; i++) + { + if (qlist[i] != NULL) + { + qlist[i]->ttl--; + if (qlist[i]->ttl == 0) + { + free(qlist[i]); + qlist[i] = NULL; + } + } + } +} diff --git a/pool/shard008/C/0130864_unix2dos.c b/pool/shard008/C/0130864_unix2dos.c new file mode 100644 index 0000000000000000000000000000000000000000..d69f1105409d33459a8027ec654ae0c5eecb6259 --- /dev/null +++ b/pool/shard008/C/0130864_unix2dos.c @@ -0,0 +1,85 @@ +#include + +int main(argc, argv) +int argc; +char *argv[]; + +{ + FILE *fpi, *fpo, *fopen(); + char srcfs[256] ; + char buf[256]; + int i,j; + + if (argc == 1) + return 0; + else { + while (--argc > 0) + if ((fpi = fopen(*++argv, "r")) == NULL) + { + printf("cat: can't open %s\n", *argv); + break; + } + else + { + strcpy(srcfs,*argv); + strcpy(buf, srcfs); + strcat(buf, ".tmp"); + if ((fpo = fopen(buf, "w")) == NULL) + { + printf("cat: can't open %s\n", buf); + break; + } + else + { + u2d(fpi,fpo); + fclose(fpo); + fclose(fpi); + if ((fpi = fopen(buf, "r")) == NULL) + { + printf("cat: can't open %s for copy back\n", buf); + break; + } + else + if ((fpo = fopen(srcfs, "w")) == NULL) + { + printf("cat: can't open %s for copy back\n", srcfs); + break; + } + else + { + filecopy(fpi,fpo); + fclose(fpo); + fclose(fpi); + strcpy(srcfs,"rm "); + strcat(srcfs, buf); + system(srcfs); + } + } + } + return 0; + } +} + +u2d(fpi,fpo) +FILE *fpi,*fpo; +{ + int c; + + while ((c = getc(fpi)) != EOF) + if (c != '\n') + putc(c, fpo); + else { + putc('\r',fpo); + putc('\n',fpo); + } +} + +filecopy(fpi,fpo) +FILE *fpi, *fpo; +{ + int c; + + while ((c = getc(fpi)) != EOF) + putc(c, fpo); +} + diff --git a/pool/shard008/C/0130865_Longest-Valid-Parentheses.c b/pool/shard008/C/0130865_Longest-Valid-Parentheses.c new file mode 100644 index 0000000000000000000000000000000000000000..19f3baaaf4f32a68a8b3adce6ada2a7bcbe1d0c7 --- /dev/null +++ b/pool/shard008/C/0130865_Longest-Valid-Parentheses.c @@ -0,0 +1,43 @@ +#include +#include +#include + +int longestValidParentheses(char* s) { + int len = strlen(s), cnt = 0, tmp = 0; + int buffer[len+1]; + int bTop = 0; + + for(int i=0; i 0){ + s[i] = 2; + s[buffer[--bTop]] = 0; + } + } + + for(int i=0; i 2){ + cnt = cnt < tmp ? tmp : cnt; + tmp = 0; + continue; + } + + tmp += s[i]; + } + + return cnt>tmp ? cnt : tmp; +} + +int main(int argc, char const *argv[]) +{ + char s[] = "))))))(((((((((()())()((((((((((()()()()()()()"; + printf("%s\n", s); + printf("%d\n", longestValidParentheses(s)); + printf("%s\n", s); + return 0; +} \ No newline at end of file diff --git a/pool/shard008/C/0130867_call_seq.c b/pool/shard008/C/0130867_call_seq.c new file mode 100644 index 0000000000000000000000000000000000000000..31193b44767963b2eb581cddb5c44e6c2f6cd1f8 --- /dev/null +++ b/pool/shard008/C/0130867_call_seq.c @@ -0,0 +1,152 @@ +/* + httperf -- a tool for measuring web server performance + Copyright 2000-2007 Hewlett-Packard Company + + This file is part of httperf, a web server performance measurment + tool. + + 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. + + In addition, as a special exception, the copyright holders give + permission to link the code of this work with the OpenSSL project's + "OpenSSL" library (or with modified versions of it that use the same + license as the "OpenSSL" library), and distribute linked combinations + including the two. You must obey the GNU General Public License in + all respects for all of the code used other than "OpenSSL". If you + modify this file, you may extend this exception to your version of the + file, but you are not obligated to do so. If you do not wish to do + so, delete this exception statement from your 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 +*/ + +/* Issue a sequence of calls on a connection. */ + +#include "config.h" + +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#define CONN_PRIVATE_DATA(c) \ + ((Conn_Private_Data *) ((char *)(c) + conn_private_data_offset)) + +#define MIN(a,b) ((a) < (b) ? (a) : (b)) + +typedef struct Conn_Private_Data + { + int num_calls; + int num_completed; + int num_destroyed; + } +Conn_Private_Data; + +static size_t conn_private_data_offset; + +static void +issue_calls (Conn *conn) +{ + Conn_Private_Data *priv; + Call *call; + int i; + + priv = CONN_PRIVATE_DATA (conn); + priv->num_completed = 0; + priv->num_destroyed = 0; + + for (i = 0; i < param.burst_len; ++i) + if (priv->num_calls++ < param.num_calls) + { + call = call_new (); + if (call) + { + core_send (conn, call); + call_dec_ref (call); + } + } +} + +static void +conn_connected (Event_Type et, Conn *conn) +{ + assert (et == EV_CONN_CONNECTED && object_is_conn (conn)); + + issue_calls (conn); +} + +static void +call_done (Event_Type et, Call *call) +{ + Conn *conn = call->conn; + Conn_Private_Data *priv; + + assert (et == EV_CALL_RECV_STOP && conn && object_is_conn (conn)); + + priv = CONN_PRIVATE_DATA (conn); + ++priv->num_completed; +} + +static void +call_destroyed (Event_Type et, Call *call) +{ + Conn_Private_Data *priv; + Conn *conn; + + assert (et == EV_CALL_DESTROYED && object_is_call (call)); + + conn = call->conn; + priv = CONN_PRIVATE_DATA (conn); + + if (++priv->num_destroyed >= MIN (param.burst_len, param.num_calls)) + { + if (priv->num_completed == priv->num_destroyed + && priv->num_calls < param.num_calls) + issue_calls (conn); + else + core_close (conn); + } +} + +static void +init (void) +{ + Any_Type arg; + + conn_private_data_offset = object_expand (OBJ_CONN, + sizeof (Conn_Private_Data)); + + arg.l = 0; + event_register_handler (EV_CONN_CONNECTED, (Event_Handler) conn_connected, + arg); + event_register_handler (EV_CALL_RECV_STOP, (Event_Handler) call_done, arg); + event_register_handler (EV_CALL_DESTROYED, (Event_Handler) call_destroyed, + arg); +} + +Load_Generator call_seq = + { + "performs a sequence of calls on a connection", + init, + no_op, + no_op + }; diff --git a/pool/shard008/C/0130869_record-sizes.c b/pool/shard008/C/0130869_record-sizes.c new file mode 100644 index 0000000000000000000000000000000000000000..4f52e54a02f0871e2d47b27c2355cecf089b1082 --- /dev/null +++ b/pool/shard008/C/0130869_record-sizes.c @@ -0,0 +1,167 @@ +/* + * Copyright (C) 2008-2012 Free Software Foundation, Inc. + * + * Author: Simon Josefsson + * + * This file is part of GnuTLS. + * + * GnuTLS 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. + * + * GnuTLS 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 GnuTLS; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include +#include +#include "eagain-common.h" + +#include "utils.h" + +const char *side = ""; + +static void tls_log_func(int level, const char *str) +{ + fprintf(stderr, "%s|<%d>| %s", side, level, str); +} + +/* This test attempts to transfer various sizes using ARCFOUR-128. + */ + +#ifndef ENABLE_FIPS140 + +#define MAX_BUF 16384 +static char b1[MAX_BUF + 1]; +static char buffer[MAX_BUF + 1]; + +void doit(void) +{ + /* Server stuff. */ + gnutls_anon_server_credentials_t s_anoncred; + const gnutls_datum_t p3 = + { (unsigned char *) pkcs3, strlen(pkcs3) }; + static gnutls_dh_params_t dh_params; + gnutls_session_t server; + int sret = GNUTLS_E_AGAIN; + /* Client stuff. */ + gnutls_anon_client_credentials_t c_anoncred; + gnutls_session_t client; + int cret = GNUTLS_E_AGAIN, i; + /* Need to enable anonymous KX specifically. */ + ssize_t ns; + int ret, transferred = 0; + + /* General init. */ + global_init(); + gnutls_global_set_log_function(tls_log_func); + if (debug) + gnutls_global_set_log_level(4711); + + /* Init server */ + gnutls_anon_allocate_server_credentials(&s_anoncred); + gnutls_dh_params_init(&dh_params); + gnutls_dh_params_import_pkcs3(dh_params, &p3, GNUTLS_X509_FMT_PEM); + gnutls_anon_set_server_dh_params(s_anoncred, dh_params); + gnutls_init(&server, GNUTLS_SERVER); + gnutls_priority_set_direct(server, + "NONE:+VERS-TLS-ALL:+ARCFOUR-128:+MAC-ALL:+SIGN-ALL:+COMP-NULL:+ANON-DH", + NULL); + gnutls_credentials_set(server, GNUTLS_CRD_ANON, s_anoncred); + gnutls_transport_set_push_function(server, server_push); + gnutls_transport_set_pull_function(server, server_pull); + gnutls_transport_set_ptr(server, server); + + /* Init client */ + gnutls_anon_allocate_client_credentials(&c_anoncred); + gnutls_init(&client, GNUTLS_CLIENT); + gnutls_priority_set_direct(client, + "NONE:+VERS-TLS-ALL:+CIPHER-ALL:+MAC-ALL:+SIGN-ALL:+COMP-NULL:+ANON-DH", + NULL); + gnutls_credentials_set(client, GNUTLS_CRD_ANON, c_anoncred); + gnutls_transport_set_push_function(client, client_push); + gnutls_transport_set_pull_function(client, client_pull); + gnutls_transport_set_ptr(client, client); + + memset(b1, 0, sizeof(b1)); + HANDSHAKE(client, server); + + if (debug) + success("Handshake established\n"); + + memset(b1, 1, MAX_BUF); + + /* try the maximum allowed */ + ret = gnutls_record_send(client, b1, MAX_BUF); + if (ret < 0) { + fprintf(stderr, "Error sending %d bytes: %s\n", + (int) MAX_BUF, gnutls_strerror(ret)); + exit(1); + } + + if (ret != MAX_BUF) { + fprintf(stderr, "Couldn't send %d bytes\n", (int) MAX_BUF); + exit(1); + } + + ret = gnutls_record_recv(server, buffer, MAX_BUF); + if (ret < 0) { + fprintf(stderr, "Error receiving %d bytes: %s\n", + (int) MAX_BUF, gnutls_strerror(ret)); + exit(1); + } + + if (ret != MAX_BUF) { + fprintf(stderr, "Couldn't receive %d bytes, received %d\n", + (int) MAX_BUF, ret); + exit(1); + } + + if (memcmp(b1, buffer, MAX_BUF) != 0) { + fprintf(stderr, "Buffers do not match!\n"); + exit(1); + } + + /* Try sending various other sizes */ + for (i = 1; i < 128; i++) { + TRANSFER(client, server, b1, i, buffer, MAX_BUF); + } + if (debug) + fputs("\n", stdout); + + + + gnutls_bye(client, GNUTLS_SHUT_RDWR); + gnutls_bye(server, GNUTLS_SHUT_RDWR); + + gnutls_deinit(client); + gnutls_deinit(server); + + gnutls_anon_free_client_credentials(c_anoncred); + gnutls_anon_free_server_credentials(s_anoncred); + + gnutls_dh_params_deinit(dh_params); + + gnutls_global_deinit(); +} + +#else +void doit(void) +{ + exit(77); +} +#endif diff --git a/pool/shard008/C/0130870_gschem_alignment_combo.c b/pool/shard008/C/0130870_gschem_alignment_combo.c new file mode 100644 index 0000000000000000000000000000000000000000..8de7a339edb191922f8e23494f26ffb4e0eb4e9a --- /dev/null +++ b/pool/shard008/C/0130870_gschem_alignment_combo.c @@ -0,0 +1,180 @@ +/* Lepton EDA Schematic Capture + * Copyright (C) 1998-2010 Ales Hvezda + * Copyright (C) 1998-2015 gEDA Contributors + * Copyright (C) 2017-2020 Lepton EDA Contributors + * + * 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 + */ +/*! \file gschem_alignment_combo.c + * + * \brief A GtkComboBox with the gschem text alignments. + */ +#include + +#include +#ifdef HAVE_STDLIB_H +#include +#endif +#ifdef HAVE_STRING_H +#include +#endif + +#include "gschem.h" + + +/*! \brief The columns in the GtkListStore + */ +enum +{ + COLUMN_NAME, + COLUMN_ALIGN, + COLUMN_COUNT +}; + + + +/*! \brief Stores the list of alignments for use by the GtkComboBox + */ +static GtkListStore* align_list_store = NULL; + + + +/*! \brief Create the alignment combo box list store for the text property dialog + * + * \return A GtkListStore with gschem text alignment entries. + */ +static GtkListStore * +create_align_list_store () +{ + GtkTreeIter iter; + GtkListStore *store; + + store = gtk_list_store_new (COLUMN_COUNT, G_TYPE_STRING, G_TYPE_INT); + + /* Upper row */ + + gtk_list_store_append (store, &iter); + gtk_list_store_set (store, &iter, COLUMN_NAME, _("Upper Left"), COLUMN_ALIGN, UPPER_LEFT, -1); + gtk_list_store_append (store, &iter); + gtk_list_store_set (store, &iter, COLUMN_NAME, _("Upper Middle"), COLUMN_ALIGN, UPPER_MIDDLE, -1); + gtk_list_store_append (store, &iter); + gtk_list_store_set (store, &iter, COLUMN_NAME, _("Upper Right"), COLUMN_ALIGN, UPPER_RIGHT, -1); + + /* Middle row */ + + gtk_list_store_append (store, &iter); + gtk_list_store_set (store, &iter, COLUMN_NAME, _("Middle Left"), COLUMN_ALIGN, MIDDLE_LEFT, -1); + gtk_list_store_append (store, &iter); + gtk_list_store_set (store, &iter, COLUMN_NAME, _("Middle Middle"), COLUMN_ALIGN, MIDDLE_MIDDLE, -1); + gtk_list_store_append (store, &iter); + gtk_list_store_set (store, &iter, COLUMN_NAME, _("Middle Right"), COLUMN_ALIGN, MIDDLE_RIGHT, -1); + + /* Lower row */ + + gtk_list_store_append (store, &iter); + gtk_list_store_set (store, &iter, COLUMN_NAME, _("Lower Left"), COLUMN_ALIGN, LOWER_LEFT, -1); + gtk_list_store_append (store, &iter); + gtk_list_store_set (store, &iter, COLUMN_NAME, _("Lower Middle"), COLUMN_ALIGN, LOWER_MIDDLE, -1); + gtk_list_store_append (store, &iter); + gtk_list_store_set (store, &iter, COLUMN_NAME, _("Lower Right"), COLUMN_ALIGN, LOWER_RIGHT, -1); + + return store; +} + + +/*! \brief Create a ComboBox with the gschem alignments. + * + * \return A GtkWidget for selecting text alignments. + */ +GtkWidget* +gschem_alignment_combo_new () +{ + GtkCellRenderer *cell; + GtkComboBox *combo; + + if (align_list_store == NULL) { + align_list_store = create_align_list_store (); + } + + combo = GTK_COMBO_BOX (gtk_combo_box_new_with_model (GTK_TREE_MODEL (align_list_store))); + + gtk_combo_box_set_wrap_width (GTK_COMBO_BOX (combo), 3); + + cell = gtk_cell_renderer_text_new (); + gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combo), cell, TRUE); + gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combo), cell, "text", COLUMN_NAME, NULL); + + return GTK_WIDGET (combo); +} + + + +/*! \brief Get the currently selected text alignment + * + * \param [in,out] widget The text alignment combo box + * \return The currently selected text alignment + */ +int +gschem_alignment_combo_get_align (GtkWidget *widget) +{ + int align = -1; + GtkTreeIter iter; + GValue value = {0}; + + if (gtk_combo_box_get_active_iter (GTK_COMBO_BOX(widget), &iter)) { + gtk_tree_model_get_value (GTK_TREE_MODEL (align_list_store), &iter, COLUMN_ALIGN, &value); + align = g_value_get_int (&value); + g_value_unset (&value); + } + + return align; +} + + + +/*! \brief Select the given text alignment + * + * \par Function Description + * Selects the given text alignment. With an invalid alignment, this + * function does nothing. + * + * \param [in,out] widget The text alignment combo box + * \param [in] align The text alignment to select + */ +void +gschem_alignment_combo_set_align (GtkWidget *widget, int align) +{ + g_return_if_fail (align_list_store != NULL); + + if (align >= 0) { + GtkTreeIter iter; + gboolean success; + GValue value = {0}; + + success = gtk_tree_model_get_iter_first (GTK_TREE_MODEL (align_list_store), &iter); + while (success) { + gtk_tree_model_get_value (GTK_TREE_MODEL (align_list_store), &iter, COLUMN_ALIGN, &value); + if (g_value_get_int (&value) == align) { + g_value_unset (&value); + gtk_combo_box_set_active_iter (GTK_COMBO_BOX (widget), &iter); + break; + } + g_value_unset (&value); + success = gtk_tree_model_iter_next (GTK_TREE_MODEL (align_list_store), &iter); + } + } else { + gtk_combo_box_set_active_iter (GTK_COMBO_BOX(widget), NULL); + } +} diff --git a/pool/shard008/C/0130873_dss-of.c b/pool/shard008/C/0130873_dss-of.c new file mode 100644 index 0000000000000000000000000000000000000000..bc114ec332c71ea8b1cf90d113593c0b419926a7 --- /dev/null +++ b/pool/shard008/C/0130873_dss-of.c @@ -0,0 +1,243 @@ +/* + * Copyright (C) 2013 Texas Instruments + * Author: Tomi Valkeinen + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 as published by + * the Free Software Foundation. + * + * 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. + */ + +#include +#include +#include +#include +#include + +#include