code
stringlengths
4
1.01M
language
stringclasses
2 values
/* * Beautiful Capi generates beautiful C API wrappers for your C++ classes * Copyright (C) 2015 Petr Petrovich Petrov * * This file is part of Beautiful Capi. * * Beautiful Capi 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. * * Beautiful Capi 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 Beautiful Capi. If not, see <http://www.gnu.org/licenses/>. * */ /* * WARNING: This file was automatically generated by Beautiful Capi! * Do not edit this file! Please edit the source API description. */ #ifndef POINTSET_POINTS_DEFINITION_INCLUDED #define POINTSET_POINTS_DEFINITION_INCLUDED #include "PointSet/PointsDecl.h" #include "PointSet/Position.h" #ifdef __cplusplus inline PointSet::PointsPtr::PointsPtr() { SetObject(PointSet::PointsPtr(PointSet::PointsPtr::force_creating_from_raw_pointer, point_set_points_default(), false).Detach()); } inline size_t PointSet::PointsPtr::Size() const { return point_set_points_size_const(GetRawPointer()); } inline void PointSet::PointsPtr::Reserve(size_t capacity) { point_set_points_reserve(GetRawPointer(), capacity); } inline void PointSet::PointsPtr::Resize(size_t size, const PointSet::Position& default_value) { point_set_points_resize(GetRawPointer(), size, default_value.GetRawPointer()); } inline PointSet::Position PointSet::PointsPtr::GetElement(size_t index) const { return PointSet::Position(PointSet::Position::force_creating_from_raw_pointer, point_set_points_get_element_const(GetRawPointer(), index), false); } inline void PointSet::PointsPtr::SetElement(size_t index, const PointSet::Position& value) { point_set_points_set_element(GetRawPointer(), index, value.GetRawPointer()); } inline void PointSet::PointsPtr::PushBack(const PointSet::Position& value) { point_set_points_push_back(GetRawPointer(), value.GetRawPointer()); } inline void PointSet::PointsPtr::Clear() { point_set_points_clear(GetRawPointer()); } inline PointSet::PointsPtr::PointsPtr(const PointsPtr& other) { SetObject(other.GetRawPointer()); if (other.GetRawPointer()) { point_set_points_add_ref(other.GetRawPointer()); } } #ifdef POINTSET_CPP_COMPILER_HAS_RVALUE_REFERENCES inline PointSet::PointsPtr::PointsPtr(PointsPtr&& other) { mObject = other.mObject; other.mObject = 0; } #endif /* POINTSET_CPP_COMPILER_HAS_RVALUE_REFERENCES */ inline PointSet::PointsPtr::PointsPtr(PointSet::PointsPtr::ECreateFromRawPointer, void *object_pointer, bool add_ref_object) { SetObject(object_pointer); if (add_ref_object && object_pointer) { point_set_points_add_ref(object_pointer); } } inline PointSet::PointsPtr::~PointsPtr() { if (GetRawPointer()) { point_set_points_release(GetRawPointer()); SetObject(0); } } inline PointSet::PointsPtr& PointSet::PointsPtr::operator=(const PointSet::PointsPtr& other) { if (GetRawPointer() != other.GetRawPointer()) { if (GetRawPointer()) { point_set_points_release(GetRawPointer()); SetObject(0); } SetObject(other.GetRawPointer()); if (other.GetRawPointer()) { point_set_points_add_ref(other.GetRawPointer()); } } return *this; } #ifdef POINTSET_CPP_COMPILER_HAS_RVALUE_REFERENCES inline PointSet::PointsPtr& PointSet::PointsPtr::operator=(PointSet::PointsPtr&& other) { if (GetRawPointer() != other.GetRawPointer()) { if (GetRawPointer()) { point_set_points_release(GetRawPointer()); SetObject(0); } mObject = other.mObject; other.mObject = 0; } return *this; } #endif /* POINTSET_CPP_COMPILER_HAS_RVALUE_REFERENCES */ inline PointSet::PointsPtr PointSet::PointsPtr::Null() { return PointSet::PointsPtr(PointSet::PointsPtr::force_creating_from_raw_pointer, static_cast<void*>(0), false); } inline bool PointSet::PointsPtr::IsNull() const { return !GetRawPointer(); } inline bool PointSet::PointsPtr::IsNotNull() const { return GetRawPointer() != 0; } inline bool PointSet::PointsPtr::operator!() const { return !GetRawPointer(); } inline void* PointSet::PointsPtr::Detach() { void* result = GetRawPointer(); SetObject(0); return result; } inline void* PointSet::PointsPtr::GetRawPointer() const { return PointSet::PointsPtr::mObject ? mObject: 0; } inline PointSet::PointsPtr* PointSet::PointsPtr::operator->() { return this; } inline const PointSet::PointsPtr* PointSet::PointsPtr::operator->() const { return this; } inline void PointSet::PointsPtr::SetObject(void* object_pointer) { mObject = object_pointer; } #endif /* __cplusplus */ #endif /* POINTSET_POINTS_DEFINITION_INCLUDED */
Java
package fr.hnit.babyname; /* The babyname app 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. The babyname app 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 the TXM platform. If not, see http://www.gnu.org/licenses */ import android.app.AlertDialog; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { public static final String UPDATE_EXTRA = "update"; ListView namesListView; BabyNameAdapter adapter; public static BabyNameDatabase database = new BabyNameDatabase(); public static ArrayList<BabyNameProject> projects = new ArrayList<>(); Intent editIntent; Intent findIntent; Intent settingsIntent; Intent aboutIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (database.size() == 0) database.initialize(); namesListView = (ListView) findViewById(R.id.listView); registerForContextMenu(namesListView); namesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { BabyNameProject project = projects.get(i); if (project != null) { doFindName(project); } } }); adapter = new BabyNameAdapter(this, projects); namesListView.setAdapter(adapter); if (projects.size() == 0) { initializeProjects(); } editIntent = new Intent(MainActivity.this, EditActivity.class); findIntent = new Intent(MainActivity.this, FindActivity.class); settingsIntent = new Intent(MainActivity.this, SettingsActivity.class); aboutIntent = new Intent(MainActivity.this, AboutActivity.class); } @Override public void onResume() { super.onResume(); // Always call the superclass method first adapter.notifyDataSetChanged(); for (BabyNameProject project : projects) { if (project.needSaving) { //Toast.makeText(this, "Saving changes of "+project+"... "+project, Toast.LENGTH_SHORT).show(); if (!BabyNameProject.storeProject(project, this)) { Toast.makeText(this, "Error: could not save changes to babyname project: "+project, Toast.LENGTH_LONG).show(); } } } } private void initializeProjects() { //AppLogger.info("Initializing projects..."); for (String filename : this.fileList()) { if (filename.endsWith(".baby")) { //AppLogger.info("Restoring... "+filename); try { BabyNameProject project = BabyNameProject.readProject(filename, this); if (project != null) projects.add(project); else Toast.makeText(MainActivity.this, "Error: could not read baby name project from "+filename, Toast.LENGTH_LONG).show(); } catch (Exception e) { e.printStackTrace(); } } } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_list, menu); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); if (adapter.getCount() <= info.position) return false; BabyNameProject project = adapter.getItem(info.position); if (project == null) return false; switch (item.getItemId()) { case R.id.action_reset_baby: doResetBaby(project); return true; case R.id.action_top_baby: doShowTop10(project); return true; case R.id.action_delete_baby: doDeleteBaby(project); return true; default: return super.onContextItemSelected(item); } } public void doResetBaby(final BabyNameProject project) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.reset_question_title); builder.setMessage(R.string.reset_question_content); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { project.reset(); adapter.notifyDataSetChanged(); if (!BabyNameProject.storeProject(project, MainActivity.this)) { Toast.makeText(MainActivity.this, "Error: could not save reset changes to babyname project: "+project, Toast.LENGTH_LONG).show(); } dialog.dismiss(); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // I do not need any action here you might dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } public void doDeleteBaby(final BabyNameProject project) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.delete_question_title); builder.setMessage(R.string.delete_question_content); builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { projects.remove(project); MainActivity.this.deleteFile(project.getID()+".baby"); adapter.notifyDataSetChanged(); dialog.dismiss(); } }); builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } public String projectToString(BabyNameProject p) { String l1 = ""; if (p.genders.contains(NameData.F) && p.genders.contains(NameData.M)) { l1 += getString(R.string.boy_or_girl_name); } else if (p.genders.contains(NameData.M)) { l1 += getString(R.string.boy_name); } else { l1 +=getString( R.string.girl_name); } if (p.origins.size() == 1) { l1 += "\n\t "+String.format(getString(R.string.origin_is), p.origins.toArray()[0]); } else if (p.origins.size() > 1) { l1 += "\n\t "+String.format(getString(R.string.origin_are), p.origins); } else { l1 += "\n\t "+getString(R.string.no_origin); } if (p.pattern != null) { if (".*".equals(p.pattern.toString())) { l1 += "\n\t "+getString(R.string.no_pattern); } else { l1 += "\n\t "+String.format(getString(R.string.matches_with), p.pattern); } } if (p.nexts.size() == 1) { l1 += "\n\t"+getString(R.string.one_remaining_name); } else if (p.nexts.size() == 0) { int n = p.scores.size(); if (n > 11) n = n - 10; l1 += "\n\t"+String.format(getString(R.string.no_remaining_loop), p.loop, n); } else { l1 += "\n\t"+String.format(getString(R.string.remaining_names), p.nexts.size()); } if (p.scores.size() > 0 && p.getBest() != null) { l1 += "\n\n\t"+String.format(getString(R.string.bact_match_is), p.getBest()); } return l1; } public void doShowTop10(final BabyNameProject project) { List<Integer> names = project.getTop10(); final StringBuffer buffer = new StringBuffer(); int n = 0; for (Integer name : names) { buffer.append("\n"+MainActivity.database.get(name)+": "+project.scores.get(name)); } if (names.size() == 0) buffer.append(getString(R.string.no_name_rated)); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.top_title); builder.setMessage(buffer.toString()); builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); if (names.size() > 0) builder.setNegativeButton(R.string.copy, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("baby top10", buffer.toString()); clipboard.setPrimaryClip(clip); Toast.makeText(MainActivity.this, R.string.text_copied, Toast.LENGTH_LONG).show(); } }); AlertDialog alert = builder.create(); alert.show(); //Toast.makeText(this, buffer.toString(), Toast.LENGTH_LONG).show(); } public void doFindName(BabyNameProject project) { //AppLogger.info("Open FindActivity with "+project+" index="+projects.indexOf(project)); findIntent.putExtra(FindActivity.PROJECT_EXTRA, projects.indexOf(project)); this.startActivityForResult(findIntent, 0); } private void openEditActivity(BabyNameProject project) { //AppLogger.info("Open EditActivity with "+project+" index="+projects.indexOf(project)); editIntent.putExtra(EditActivity.PROJECT_EXTRA, projects.indexOf(project)); this.startActivityForResult(editIntent, 0); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: this.startActivityForResult(settingsIntent, 0); return true; case R.id.action_about: this.startActivityForResult(aboutIntent, 0); return true; case R.id.action_new_baby: doNewBaby(); return true; default: return super.onOptionsItemSelected(item); } } public void doNewBaby() { Toast.makeText(this, R.string.new_baby, Toast.LENGTH_LONG).show(); BabyNameProject project = new BabyNameProject(); projects.add(project); openEditActivity(project); } }
Java
import { useState } from "react"; import { PropTypes } from "prop-types"; import { SaveOutlined, WarningOutlined } from "@ant-design/icons"; import { Button, Col, Form, Input, InputNumber, Row, Select, Switch, Typography, Space, } from "@nextgisweb/gui/antd"; import i18n from "@nextgisweb/pyramid/i18n!"; import { AddressGeocoderOptions, DegreeFormatOptions, UnitsAreaOptions, UnitsLengthOptions, } from "./select-options"; const { Title } = Typography; const INPUT_DEFAULT_WIDTH = { width: "100%" }; export const SettingsForm = ({ onFinish, initialValues, srsOptions, status, }) => { const [geocoder, setGeocoder] = useState( initialValues.address_geocoder || "nominatim" ); const onValuesChange = (changedValues, allValues) => { setGeocoder(allValues.address_geocoder); }; return ( <Form name="webmap_settings" className="webmap-settings-form" initialValues={initialValues} onFinish={onFinish} onValuesChange={onValuesChange} layout="vertical" > <Title level={4}>{i18n.gettext("Identify popup")}</Title> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item name="popup_width" label={i18n.gettext("Width, px")} rules={[ { required: true, }, ]} > <InputNumber min="100" style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="popup_height" label={i18n.gettext("Height, px")} rules={[ { required: true, }, ]} > <InputNumber min="100" style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="identify_radius" label={i18n.gettext("Radius, px")} rules={[ { required: true, }, ]} > <InputNumber min="1" style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> </Row> <Row gutter={[16, 16]}> <Col span={24}> <Form.Item> <Space direction="horizontal"> <Form.Item noStyle name="identify_attributes" valuePropName="checked" > <Switch /> </Form.Item> {i18n.gettext("Show feature attributes")} </Space> </Form.Item> </Col> </Row> <Title level={4}>{i18n.gettext("Measurement")}</Title> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item name="units_length" label={i18n.gettext("Length units")} > <Select options={UnitsLengthOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="units_area" label={i18n.gettext("Area units")} > <Select options={UnitsAreaOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={8}> <Form.Item name="degree_format" label={i18n.gettext("Degree format")} > <Select options={DegreeFormatOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> </Row> <Row gutter={[16, 16]}> <Col span={24}> <Form.Item name="measurement_srid" label={i18n.gettext("Measurement SRID")} > <Select options={srsOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> </Row> <Title level={4}>{i18n.gettext("Address search")}</Title> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item> <Space direction="horizontal"> <Form.Item noStyle name="address_search_enabled" valuePropName="checked" > <Switch /> </Form.Item> {i18n.gettext("Enable")} </Space> </Form.Item> </Col> <Col span={16}> <Form.Item> <Space direction="horizontal"> <Form.Item noStyle name="address_search_extent" valuePropName="checked" > <Switch /> </Form.Item> {i18n.gettext("Limit by web map initial extent")} </Space> </Form.Item> </Col> </Row> <Row gutter={[16, 16]}> <Col span={8}> <Form.Item name="address_geocoder" label={i18n.gettext("Provider")} > <Select options={AddressGeocoderOptions} style={INPUT_DEFAULT_WIDTH} /> </Form.Item> </Col> <Col span={16}> {geocoder == "nominatim" ? ( <Form.Item name="nominatim_countrycodes" label={i18n.gettext( "Limit search results to countries" )} rules={[ { pattern: new RegExp( /^(?:(?:[A-Za-z]+)(?:-[A-Za-z]+)?(?:,|$))+(?<!,)$/ ), message: ( <div> {i18n.gettext( "Invalid countries. For example ru or gb,de" )} </div> ), }, ]} > <Input style={INPUT_DEFAULT_WIDTH} /> </Form.Item> ) : ( <Form.Item name="yandex_api_geocoder_key" label={i18n.gettext("Yandex.Maps API Geocoder Key")} > <Input style={INPUT_DEFAULT_WIDTH} /> </Form.Item> )} </Col> </Row> <Row className="row-submit"> <Col> <Button htmlType="submit" type={"primary"} danger={status === "saved-error"} icon={ status === "saved-error" ? ( <WarningOutlined /> ) : ( <SaveOutlined /> ) } loading={status === "saving"} > {i18n.gettext("Save")} </Button> </Col> </Row> </Form> ); }; SettingsForm.propTypes = { initialValues: PropTypes.object, onFinish: PropTypes.func, srsOptions: PropTypes.array, status: PropTypes.string, };
Java
#!/usr/bin/env python # File written by pyctools-editor. Do not edit. import argparse import logging from pyctools.core.compound import Compound import pyctools.components.arithmetic import pyctools.components.qt.qtdisplay import pyctools.components.zone.zoneplategenerator class Network(object): components = \ { 'clipper': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': "{'func': '16+((data > 180)*219)'}", 'pos': (200.0, 200.0)}, 'clipper2': { 'class': 'pyctools.components.arithmetic.Arithmetic', 'config': "{'func': '16+((data > 230)*219)'}", 'pos': (200.0, 330.0)}, 'qd': { 'class': 'pyctools.components.qt.qtdisplay.QtDisplay', 'config': "{'framerate': 60}", 'pos': (460.0, 200.0)}, 'stacker': { 'class': 'pyctools.components.arithmetic.Arithmetic2', 'config': "{'func': 'numpy.vstack((data1,data2))'}", 'pos': (330.0, 200.0)}, 'zpg': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.04, 'kt': -0.34, 'xlen': 600, 'ylen': " "400, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 200.0)}, 'zpg2': { 'class': 'pyctools.components.zone.zoneplategenerator.ZonePlateGenerator', 'config': "{'kx': 0.002, 'kt': -0.017, 'xlen': 600, 'ylen': " "200, 'zlen': 1000, 'looping': 'repeat'}", 'pos': (70.0, 330.0)}} linkages = \ { ('clipper', 'output'): [('stacker', 'input1')], ('clipper2', 'output'): [('stacker', 'input2')], ('stacker', 'output'): [('qd', 'input')], ('zpg', 'output'): [('clipper', 'input')], ('zpg2', 'output'): [('clipper2', 'input')]} def make(self): comps = {} for name, component in self.components.items(): comps[name] = eval(component['class'])(config=eval(component['config'])) return Compound(linkages=self.linkages, **comps) if __name__ == '__main__': from PyQt5 import QtCore, QtWidgets QtWidgets.QApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) app = QtWidgets.QApplication([]) comp = Network().make() cnf = comp.get_config() parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) cnf.parser_add(parser) parser.add_argument('-v', '--verbose', action='count', default=0, help='increase verbosity of log messages') args = parser.parse_args() logging.basicConfig(level=logging.ERROR - (args.verbose * 10)) del args.verbose cnf.parser_set(args) comp.set_config(cnf) comp.start() app.exec_() comp.stop() comp.join()
Java
# -*- coding: utf-8 -*- import itertools """ Languages | ShortCode | Wordnet Albanian | sq | als Arabic | ar | arb Bulgarian | bg | bul Catalan | ca | cat Chinese | zh | cmn Chinese (Taiwan) | qn | qcn Greek | el | ell Basque | eu | eus Persian | fa | fas Finish | fi | fin French | fr | fra Galician | gl | glg Hebrew | he | heb Croatian | hr | hrv Indonesian | id | ind Italian | it | ita Japanese | ja | jpn Norwegian NyNorsk | nn | nno Norwegian Bokmål | nb/no | nob Polish | pl | pol Portuguese | pt | por Slovenian | sl | slv Spanish | es | spa Swedish | sv | swe Thai | tt | tha Malay | ms | zsm """ """ Language short codes => Wordnet Code """ AVAILABLE_LANGUAGES = dict([('sq','als'), ('ar', 'arb'), ('bg', 'bul'), ('ca', 'cat'), ('da', 'dan'), ('zh', 'cmn'), ('el','ell'), ('eu', 'eus'), ('fa', 'fas'), ('fi', 'fin'), ('fr', 'fra'), ('gl','glg'), ('he', 'heb'), ('hr', 'hrv'), ('id', 'ind'), ('it', 'ita'), ('ja','jpn'), ('nn', 'nno'), ('nb', 'nob'), ('no', 'nob'), ('pl', 'pol'), ('pt', 'por'), ('qn','qcn'), ('sl', 'slv'), ('es', 'spa'), ('sv', 'swe'), ('tt', 'tha'), ('ms', 'zsm'), ('en', 'eng')]) """ Language names => Short Code """ AVAILABLE_LANGUAGES_NAMES = dict([ ('albanian', 'sq'), ('arabic', 'ar'),('bulgarian', 'bg'), ('catalan', 'cat'), ('danish', 'da'), ('chinese', 'zh'), ('basque', 'eu'), ('persian', 'fa'), ('finnish', 'fi'), ('france', 'fr'), ('galician', 'gl'), ('hebrew', 'he'), ('croatian', 'hr'), ('indonesian', 'id'), ('italian', 'it'), ('japanese', 'ja'), ('norwegian_nynorsk', 'nn'), ('norwegian', 'no'), ('norwegian_bokmal', 'nb'), ('polish', 'pl'), ('portuguese', 'pt'), ('slovenian', 'sl'), ('spanish', 'es'), ('swedish', 'sv'), ('thai', 'sv'), ('malay', 'ms'), ('english', 'en') ]) class WordnetManager(object): def __init__(self, language="en"): """ Constructor for the wordnet manager. It takes a main language. """ self.__language = language def __isLanguageAvailable(self, code=None, language_name=None): """ Check if a language is available """ if code is None and language_name is None: raise Exception("Error evaluating the correct language") if code is not None and code.lower() in AVAILABLE_LANGUAGES: return True if language_name is not None and language_name.lower() in AVAILABLE_LANGUAGES_NAMES: return True return False def __nameToWordnetCode(self, name): """ It returns the wordnet code for a given language name """ if not self.__isLanguageAvailable(language_name=name): raise Exception("Wordnet code not found for the language name %s " % name) name = name.lower() languageShortCode = AVAILABLE_LANGUAGES_NAMES[name] wordnetCode = self.__shortCodeToWordnetCode(code=languageShortCode) return wordnetCode def __shortCodeToWordnetCode(self, shortCode): """ It returns the wordnet code from a given language short code """ if not self.__isLanguageAvailable(code=shortCode): raise Exception("Wordnet code not found for the language short code %s " % shortCode) code = shortCode.lower() wordnetCode = AVAILABLE_LANGUAGES[code] return wordnetCode def __getSynsets(self, word, wordNetCode): """ It returns the synsets given both word and language code """ from nltk.corpus import wordnet as wn synsets = wn.synsets(word, lang=wordNetCode) return synsets def getLemmas(self, word, languageCode="en"): """ Get the lemmas for a given word :word: The word :languageCode: The language for a given lemma """ wnCode = self.__shortCodeToWordnetCode(shortCode=languageCode) synsets = self.__getSynsets(word, wnCode) #wn.synsets(word, lang=wnCode) lemmas = dict([('en', [])]) for synset in synsets: enLemmas = synset.lemma_names() lemmas['en'].extend(enLemmas) if languageCode != "en" and self.__isLanguageAvailable(code=languageCode): langLemmas = list(sorted(set(synset.lemma_names(lang=wnCode)))) lemmas[languageCode] = langLemmas lemmas['en'] = list(sorted(set(lemmas.get('en', [])))) return lemmas def getSynonyms(self, words=[], language_code="en"): """ Get the synonyms from a list of words. :words: A list of words :language_code: the language for the synonyms. """ if words is None or not isinstance(words, list) or list(words) <= 0: return [] if not self.__isLanguageAvailable(code=language_code): return [] wnCode = self.__shortCodeToWordnetCode(language_code) result = {} for word in words: result[word] = dict([('lemmas', self.getLemmas(word,languageCode=language_code))]) return result def getHyponyms(self, words, language_code="en"): """ Get specific synsets from a given synset """ wnCode = self.__shortCodeToWordnetCode(language_code) result = {} for word in words: synonyms = self.__getSynsets(word, wnCode) hyponyms = [hyp for synset in synonyms for hyp in synset.hyponyms()] engLemmas = [hyp.lemma_names() for hyp in hyponyms] lemmas = dict([('en', list(sorted(set(itertools.chain.from_iterable(engLemmas)), key=lambda s: s.lower())))]) if language_code != "en": languageLemmas = [hyp.lemma_names(lang=wnCode) for hyp in hyponyms] languageLemmas = list(sorted(set(itertools.chain.from_iterable(languageLemmas)), key=lambda s: s.lower())) lemmas[language_code] = languageLemmas result[word] = dict([ ('lemmas', lemmas), ('language', language_code)]) return result def getHypernyms(self, words, language_code="en"): """ Get general synsets from a given synset """ wnCode = self.__shortCodeToWordnetCode(language_code) result = {} for word in words: synonyms = self.__getSynsets(word, wnCode) hypernyms = [hyp for synset in synonyms for hyp in synset.hypernyms()] engLemmas = [hyp.lemma_names() for hyp in hypernyms] lemmas = dict([('en', list(sorted(set(itertools.chain.from_iterable(engLemmas)), key=lambda s: s.lower())))]) if language_code != "en": languageLemmas = [hyp.lemma_names(lang=wnCode) for hyp in hypernyms] languageLemmas = list(sorted(set(itertools.chain.from_iterable(languageLemmas)), key=lambda s: s.lower())) lemmas[language_code] = languageLemmas result[word] = dict([ ('lemmas', lemmas), ('language', language_code)]) return result
Java
package com.weatherapp.model.entities; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class Location implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String name; public Location(String name) { this.name = name; } public Location() {} public String getName() { return name; } public void setName(String name) { this.name = name; } }
Java
# Courses-Pick-Helper What this program will do is to constantly scan your shopping cart on your student centre account and help you enroll very fast !!! Basically help you with enrolling courses in your shopping cart of your student centre account when it's "OPEN". Note that this will succeed iff there is no conflict of this course with other courses you've enrolled in.
Java
package units.interfaces; public abstract interface Value<T> extends MyComparable<T> { // OPERATIONS default boolean invariant() { return true; } default void checkInvariant() { if(!invariant()) { System.exit(-1); } } public abstract T newInstance(double value); public abstract T abs(); public abstract T min(T value); public abstract T max(T value); public abstract T add(T value); public abstract T sub(T value); public abstract T mul(double value); public abstract T div(double value); public abstract double div(T value); }
Java
############################################################################# # $HeadURL$ ############################################################################# """ ..mod: FTSRequest ================= Helper class to perform FTS job submission and monitoring. """ # # imports import sys import re import time # # from DIRAC from DIRAC import gLogger, S_OK, S_ERROR from DIRAC.Core.Utilities.File import checkGuid from DIRAC.Core.Utilities.Adler import compareAdler, intAdlerToHex, hexAdlerToInt from DIRAC.Core.Utilities.SiteSEMapping import getSitesForSE from DIRAC.Core.Utilities.Time import dateTime from DIRAC.Resources.Storage.StorageElement import StorageElement from DIRAC.Resources.Catalog.FileCatalog import FileCatalog from DIRAC.Core.Utilities.ReturnValues import returnSingleResult from DIRAC.AccountingSystem.Client.Types.DataOperation import DataOperation from DIRAC.ConfigurationSystem.Client.Helpers.Resources import Resources from DIRAC.Core.Security.ProxyInfo import getProxyInfo from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations from DIRAC.DataManagementSystem.Client.FTSJob import FTSJob from DIRAC.DataManagementSystem.Client.FTSFile import FTSFile # # RCSID __RCSID__ = "$Id$" class FTSRequest( object ): """ .. class:: FTSRequest Helper class for FTS job submission and monitoring. """ # # default checksum type __defaultCksmType = "ADLER32" # # flag to disablr/enable checksum test, default: disabled __cksmTest = False def __init__( self ): """c'tor :param self: self reference """ self.log = gLogger.getSubLogger( self.__class__.__name__, True ) # # final states tuple self.finalStates = ( 'Canceled', 'Failed', 'Hold', 'Finished', 'FinishedDirty' ) # # failed states tuple self.failedStates = ( 'Canceled', 'Failed', 'Hold', 'FinishedDirty' ) # # successful states tuple self.successfulStates = ( 'Finished', 'Done' ) # # all file states tuple self.fileStates = ( 'Done', 'Active', 'Pending', 'Ready', 'Canceled', 'Failed', 'Finishing', 'Finished', 'Submitted', 'Hold', 'Waiting' ) self.statusSummary = {} # # request status self.requestStatus = 'Unknown' # # dict for FTS job files self.fileDict = {} # # dict for replicas information self.catalogReplicas = {} # # dict for metadata information self.catalogMetadata = {} # # dict for files that failed to register self.failedRegistrations = {} # # placehoder for FileCatalog reference self.oCatalog = None # # submit timestamp self.submitTime = '' # # placeholder FTS job GUID self.ftsGUID = '' # # placeholder for FTS server URL self.ftsServer = '' # # flag marking FTS job completness self.isTerminal = False # # completness percentage self.percentageComplete = 0.0 # # source SE name self.sourceSE = '' # # flag marking source SE validity self.sourceValid = False # # source space token self.sourceToken = '' # # target SE name self.targetSE = '' # # flag marking target SE validity self.targetValid = False # # target space token self.targetToken = '' # # placeholder for target StorageElement self.oTargetSE = None # # placeholder for source StorageElement self.oSourceSE = None # # checksum type, set it to default self.__cksmType = self.__defaultCksmType # # disable checksum test by default self.__cksmTest = False # # statuses that prevent submitting to FTS self.noSubmitStatus = ( 'Failed', 'Done', 'Staging' ) # # were sources resolved? self.sourceResolved = False # # Number of file transfers actually submitted self.submittedFiles = 0 self.transferTime = 0 self.submitCommand = Operations().getValue( 'DataManagement/FTSPlacement/FTS2/SubmitCommand', 'glite-transfer-submit' ) self.monitorCommand = Operations().getValue( 'DataManagement/FTSPlacement/FTS2/MonitorCommand', 'glite-transfer-status' ) self.ftsJob = None self.ftsFiles = [] #################################################################### # # Methods for setting/getting/checking the SEs # def setSourceSE( self, se ): """ set SE for source :param self: self reference :param str se: source SE name """ if se == self.targetSE: return S_ERROR( "SourceSE is TargetSE" ) self.sourceSE = se self.oSourceSE = StorageElement( self.sourceSE ) return self.__checkSourceSE() def __checkSourceSE( self ): """ check source SE availability :param self: self reference """ if not self.sourceSE: return S_ERROR( "SourceSE not set" ) res = self.oSourceSE.isValid( 'Read' ) if not res['OK']: return S_ERROR( "SourceSE not available for reading" ) res = self.__getSESpaceToken( self.oSourceSE ) if not res['OK']: self.log.error( "FTSRequest failed to get SRM Space Token for SourceSE", res['Message'] ) return S_ERROR( "SourceSE does not support FTS transfers" ) if self.__cksmTest: res = self.oSourceSE.getChecksumType() if not res["OK"]: self.log.error( "Unable to get checksum type for SourceSE", "%s: %s" % ( self.sourceSE, res["Message"] ) ) cksmType = res["Value"] if cksmType in ( "NONE", "NULL" ): self.log.warn( "Checksum type set to %s at SourceSE %s, disabling checksum test" % ( cksmType, self.sourceSE ) ) self.__cksmTest = False elif cksmType != self.__cksmType: self.log.warn( "Checksum type mismatch, disabling checksum test" ) self.__cksmTest = False self.sourceToken = res['Value'] self.sourceValid = True return S_OK() def setTargetSE( self, se ): """ set target SE :param self: self reference :param str se: target SE name """ if se == self.sourceSE: return S_ERROR( "TargetSE is SourceSE" ) self.targetSE = se self.oTargetSE = StorageElement( self.targetSE ) return self.__checkTargetSE() def setTargetToken( self, token ): """ target space token setter :param self: self reference :param str token: target space token """ self.targetToken = token return S_OK() def __checkTargetSE( self ): """ check target SE availability :param self: self reference """ if not self.targetSE: return S_ERROR( "TargetSE not set" ) res = self.oTargetSE.isValid( 'Write' ) if not res['OK']: return S_ERROR( "TargetSE not available for writing" ) res = self.__getSESpaceToken( self.oTargetSE ) if not res['OK']: self.log.error( "FTSRequest failed to get SRM Space Token for TargetSE", res['Message'] ) return S_ERROR( "TargetSE does not support FTS transfers" ) # # check checksum types if self.__cksmTest: res = self.oTargetSE.getChecksumType() if not res["OK"]: self.log.error( "Unable to get checksum type for TargetSE", "%s: %s" % ( self.targetSE, res["Message"] ) ) cksmType = res["Value"] if cksmType in ( "NONE", "NULL" ): self.log.warn( "Checksum type set to %s at TargetSE %s, disabling checksum test" % ( cksmType, self.targetSE ) ) self.__cksmTest = False elif cksmType != self.__cksmType: self.log.warn( "Checksum type mismatch, disabling checksum test" ) self.__cksmTest = False self.targetToken = res['Value'] self.targetValid = True return S_OK() @staticmethod def __getSESpaceToken( oSE ): """ get space token from StorageElement instance :param self: self reference :param StorageElement oSE: StorageElement instance """ res = oSE.getStorageParameters( "SRM2" ) if not res['OK']: return res return S_OK( res['Value'].get( 'SpaceToken' ) ) #################################################################### # # Methods for setting/getting FTS request parameters # def setFTSGUID( self, guid ): """ FTS job GUID setter :param self: self reference :param str guid: string containg GUID """ if not checkGuid( guid ): return S_ERROR( "Incorrect GUID format" ) self.ftsGUID = guid return S_OK() def setFTSServer( self, server ): """ FTS server setter :param self: self reference :param str server: FTS server URL """ self.ftsServer = server return S_OK() def isRequestTerminal( self ): """ check if FTS job has terminated :param self: self reference """ if self.requestStatus in self.finalStates: self.isTerminal = True return S_OK( self.isTerminal ) def setCksmTest( self, cksmTest = False ): """ set cksm test :param self: self reference :param bool cksmTest: flag to enable/disable checksum test """ self.__cksmTest = bool( cksmTest ) return S_OK( self.__cksmTest ) #################################################################### # # Methods for setting/getting/checking files and their metadata # def setLFN( self, lfn ): """ add LFN :lfn: to :fileDict: :param self: self reference :param str lfn: LFN to add to """ self.fileDict.setdefault( lfn, {'Status':'Waiting'} ) return S_OK() def setSourceSURL( self, lfn, surl ): """ source SURL setter :param self: self reference :param str lfn: LFN :param str surl: source SURL """ target = self.fileDict[lfn].get( 'Target' ) if target == surl: return S_ERROR( "Source and target the same" ) return self.__setFileParameter( lfn, 'Source', surl ) def getSourceSURL( self, lfn ): """ get source SURL for LFN :lfn: :param self: self reference :param str lfn: LFN """ return self.__getFileParameter( lfn, 'Source' ) def setTargetSURL( self, lfn, surl ): """ set target SURL for LFN :lfn: :param self: self reference :param str lfn: LFN :param str surl: target SURL """ source = self.fileDict[lfn].get( 'Source' ) if source == surl: return S_ERROR( "Source and target the same" ) return self.__setFileParameter( lfn, 'Target', surl ) def getFailReason( self, lfn ): """ get fail reason for file :lfn: :param self: self reference :param str lfn: LFN """ return self.__getFileParameter( lfn, 'Reason' ) def getRetries( self, lfn ): """ get number of attepmts made to transfer file :lfn: :param self: self reference :param str lfn: LFN """ return self.__getFileParameter( lfn, 'Retries' ) def getTransferTime( self, lfn ): """ get duration of transfer for file :lfn: :param self: self reference :param str lfn: LFN """ return self.__getFileParameter( lfn, 'Duration' ) def getFailed( self ): """ get list of wrongly transferred LFNs :param self: self reference """ return S_OK( [ lfn for lfn in self.fileDict if self.fileDict[lfn].get( 'Status', '' ) in self.failedStates ] ) def getStaging( self ): """ get files set for prestaging """ return S_OK( [lfn for lfn in self.fileDict if self.fileDict[lfn].get( 'Status', '' ) == 'Staging'] ) def getDone( self ): """ get list of succesfully transferred LFNs :param self: self reference """ return S_OK( [ lfn for lfn in self.fileDict if self.fileDict[lfn].get( 'Status', '' ) in self.successfulStates ] ) def __setFileParameter( self, lfn, paramName, paramValue ): """ set :paramName: to :paramValue: for :lfn: file :param self: self reference :param str lfn: LFN :param str paramName: parameter name :param mixed paramValue: a new parameter value """ self.setLFN( lfn ) self.fileDict[lfn][paramName] = paramValue return S_OK() def __getFileParameter( self, lfn, paramName ): """ get value of :paramName: for file :lfn: :param self: self reference :param str lfn: LFN :param str paramName: parameter name """ if lfn not in self.fileDict: return S_ERROR( "Supplied file not set" ) if paramName not in self.fileDict[lfn]: return S_ERROR( "%s not set for file" % paramName ) return S_OK( self.fileDict[lfn][paramName] ) #################################################################### # # Methods for submission # def submit( self, monitor = False, printOutput = True ): """ submit FTS job :param self: self reference :param bool monitor: flag to monitor progress of FTS job :param bool printOutput: flag to print output of execution to stdout """ res = self.__prepareForSubmission() if not res['OK']: return res res = self.__submitFTSTransfer() if not res['OK']: return res resDict = { 'ftsGUID' : self.ftsGUID, 'ftsServer' : self.ftsServer, 'submittedFiles' : self.submittedFiles } if monitor or printOutput: gLogger.always( "Submitted %s@%s" % ( self.ftsGUID, self.ftsServer ) ) if monitor: self.monitor( untilTerminal = True, printOutput = printOutput, full = False ) return S_OK( resDict ) def __prepareForSubmission( self ): """ check validity of job before submission :param self: self reference """ if not self.fileDict: return S_ERROR( "No files set" ) if not self.sourceValid: return S_ERROR( "SourceSE not valid" ) if not self.targetValid: return S_ERROR( "TargetSE not valid" ) if not self.ftsServer: res = self.__resolveFTSServer() if not res['OK']: return S_ERROR( "FTSServer not valid" ) self.resolveSource() self.resolveTarget() res = self.__filesToSubmit() if not res['OK']: return S_ERROR( "No files to submit" ) return S_OK() def __getCatalogObject( self ): """ CatalogInterface instance facade :param self: self reference """ try: if not self.oCatalog: self.oCatalog = FileCatalog() return S_OK() except: return S_ERROR() def __updateReplicaCache( self, lfns = None, overwrite = False ): """ update replica cache for list of :lfns: :param self: self reference :param mixed lfns: list of LFNs :param bool overwrite: flag to trigger cache clearing and updating """ if not lfns: lfns = self.fileDict.keys() toUpdate = [ lfn for lfn in lfns if ( lfn not in self.catalogReplicas ) or overwrite ] if not toUpdate: return S_OK() res = self.__getCatalogObject() if not res['OK']: return res res = self.oCatalog.getReplicas( toUpdate ) if not res['OK']: return S_ERROR( "Failed to update replica cache: %s" % res['Message'] ) for lfn, error in res['Value']['Failed'].items(): self.__setFileParameter( lfn, 'Reason', error ) self.__setFileParameter( lfn, 'Status', 'Failed' ) for lfn, replicas in res['Value']['Successful'].items(): self.catalogReplicas[lfn] = replicas return S_OK() def __updateMetadataCache( self, lfns = None ): """ update metadata cache for list of LFNs :param self: self reference :param list lnfs: list of LFNs """ if not lfns: lfns = self.fileDict.keys() toUpdate = [ lfn for lfn in lfns if lfn not in self.catalogMetadata ] if not toUpdate: return S_OK() res = self.__getCatalogObject() if not res['OK']: return res res = self.oCatalog.getFileMetadata( toUpdate ) if not res['OK']: return S_ERROR( "Failed to get source catalog metadata: %s" % res['Message'] ) for lfn, error in res['Value']['Failed'].items(): self.__setFileParameter( lfn, 'Reason', error ) self.__setFileParameter( lfn, 'Status', 'Failed' ) for lfn, metadata in res['Value']['Successful'].items(): self.catalogMetadata[lfn] = metadata return S_OK() def resolveSource( self ): """ resolve source SE eligible for submission :param self: self reference """ # Avoid resolving sources twice if self.sourceResolved: return S_OK() # Only resolve files that need a transfer toResolve = [ lfn for lfn in self.fileDict if self.fileDict[lfn].get( "Status", "" ) != "Failed" ] if not toResolve: return S_OK() res = self.__updateMetadataCache( toResolve ) if not res['OK']: return res res = self.__updateReplicaCache( toResolve ) if not res['OK']: return res # Define the source URLs for lfn in toResolve: replicas = self.catalogReplicas.get( lfn, {} ) if self.sourceSE not in replicas: gLogger.warn( "resolveSource: skipping %s - not replicas at SourceSE %s" % ( lfn, self.sourceSE ) ) self.__setFileParameter( lfn, 'Reason', "No replica at SourceSE" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue res = returnSingleResult( self.oSourceSE.getURL( lfn, protocol = 'srm' ) ) if not res['OK']: gLogger.warn( "resolveSource: skipping %s - %s" % ( lfn, res["Message"] ) ) self.__setFileParameter( lfn, 'Reason', res['Message'] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue res = self.setSourceSURL( lfn, res['Value'] ) if not res['OK']: gLogger.warn( "resolveSource: skipping %s - %s" % ( lfn, res["Message"] ) ) self.__setFileParameter( lfn, 'Reason', res['Message'] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue toResolve = [] for lfn in self.fileDict: if "Source" in self.fileDict[lfn]: toResolve.append( lfn ) if not toResolve: return S_ERROR( "No eligible Source files" ) # Get metadata of the sources, to check for existance, availability and caching res = self.oSourceSE.getFileMetadata( toResolve ) if not res['OK']: return S_ERROR( "Failed to check source file metadata" ) for lfn, error in res['Value']['Failed'].items(): if re.search( 'File does not exist', error ): gLogger.warn( "resolveSource: skipping %s - source file does not exists" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source file does not exist" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) else: gLogger.warn( "resolveSource: skipping %s - failed to get source metadata" % lfn ) self.__setFileParameter( lfn, 'Reason', "Failed to get Source metadata" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) toStage = [] nbStagedFiles = 0 for lfn, metadata in res['Value']['Successful'].items(): lfnStatus = self.fileDict.get( lfn, {} ).get( 'Status' ) if metadata['Unavailable']: gLogger.warn( "resolveSource: skipping %s - source file unavailable" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source file Unavailable" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif metadata['Lost']: gLogger.warn( "resolveSource: skipping %s - source file lost" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source file Lost" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif not metadata['Cached']: if lfnStatus != 'Staging': toStage.append( lfn ) elif metadata['Size'] != self.catalogMetadata[lfn]['Size']: gLogger.warn( "resolveSource: skipping %s - source file size mismatch" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source size mismatch" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif self.catalogMetadata[lfn]['Checksum'] and metadata['Checksum'] and \ not compareAdler( metadata['Checksum'], self.catalogMetadata[lfn]['Checksum'] ): gLogger.warn( "resolveSource: skipping %s - source file checksum mismatch" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source checksum mismatch" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif lfnStatus == 'Staging': # file that was staging is now cached self.__setFileParameter( lfn, 'Status', 'Waiting' ) nbStagedFiles += 1 # Some files were being staged if nbStagedFiles: self.log.info( 'resolveSource: %d files have been staged' % nbStagedFiles ) # Launching staging of files not in cache if toStage: gLogger.warn( "resolveSource: %s source files not cached, prestaging..." % len( toStage ) ) stage = self.oSourceSE.prestageFile( toStage ) if not stage["OK"]: gLogger.error( "resolveSource: error is prestaging", stage["Message"] ) for lfn in toStage: self.__setFileParameter( lfn, 'Reason', stage["Message"] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) else: for lfn in toStage: if lfn in stage['Value']['Successful']: self.__setFileParameter( lfn, 'Status', 'Staging' ) elif lfn in stage['Value']['Failed']: self.__setFileParameter( lfn, 'Reason', stage['Value']['Failed'][lfn] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) self.sourceResolved = True return S_OK() def resolveTarget( self ): """ find target SE eligible for submission :param self: self reference """ toResolve = [ lfn for lfn in self.fileDict if self.fileDict[lfn].get( 'Status' ) not in self.noSubmitStatus ] if not toResolve: return S_OK() res = self.__updateReplicaCache( toResolve ) if not res['OK']: return res for lfn in toResolve: res = returnSingleResult( self.oTargetSE.getURL( lfn, protocol = 'srm' ) ) if not res['OK']: reason = res.get( 'Message', res['Message'] ) gLogger.warn( "resolveTarget: skipping %s - %s" % ( lfn, reason ) ) self.__setFileParameter( lfn, 'Reason', reason ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue res = self.setTargetSURL( lfn, res['Value'] ) if not res['OK']: gLogger.warn( "resolveTarget: skipping %s - %s" % ( lfn, res["Message"] ) ) self.__setFileParameter( lfn, 'Reason', res['Message'] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) continue toResolve = [] for lfn in self.fileDict: if "Target" in self.fileDict[lfn]: toResolve.append( lfn ) if not toResolve: return S_ERROR( "No eligible Target files" ) res = self.oTargetSE.exists( toResolve ) if not res['OK']: return S_ERROR( "Failed to check target existence" ) for lfn, error in res['Value']['Failed'].items(): self.__setFileParameter( lfn, 'Reason', error ) self.__setFileParameter( lfn, 'Status', 'Failed' ) toRemove = [] for lfn, exists in res['Value']['Successful'].items(): if exists: res = self.getSourceSURL( lfn ) if not res['OK']: gLogger.warn( "resolveTarget: skipping %s - target exists" % lfn ) self.__setFileParameter( lfn, 'Reason', "Target exists" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) elif res['Value'] == self.fileDict[lfn]['Target']: gLogger.warn( "resolveTarget: skipping %s - source and target pfns are the same" % lfn ) self.__setFileParameter( lfn, 'Reason', "Source and Target the same" ) self.__setFileParameter( lfn, 'Status', 'Failed' ) else: toRemove.append( lfn ) if toRemove: self.oTargetSE.removeFile( toRemove ) return S_OK() def __filesToSubmit( self ): """ check if there is at least one file to submit :return: S_OK if at least one file is present, S_ERROR otherwise """ for lfn in self.fileDict: lfnStatus = self.fileDict[lfn].get( 'Status' ) source = self.fileDict[lfn].get( 'Source' ) target = self.fileDict[lfn].get( 'Target' ) if lfnStatus not in self.noSubmitStatus and source and target: return S_OK() return S_ERROR() def __createFTSFiles( self ): """ create LFNs file for glite-transfer-submit command This file consists one line for each fiel to be transferred: sourceSURL targetSURL [CHECKSUMTYPE:CHECKSUM] :param self: self reference """ self.__updateMetadataCache() for lfn in self.fileDict: lfnStatus = self.fileDict[lfn].get( 'Status' ) if lfnStatus not in self.noSubmitStatus: cksmStr = "" # # add chsmType:cksm only if cksmType is specified, else let FTS decide by itself if self.__cksmTest and self.__cksmType: checkSum = self.catalogMetadata.get( lfn, {} ).get( 'Checksum' ) if checkSum: cksmStr = " %s:%s" % ( self.__cksmType, intAdlerToHex( hexAdlerToInt( checkSum ) ) ) ftsFile = FTSFile() ftsFile.LFN = lfn ftsFile.SourceSURL = self.fileDict[lfn].get( 'Source' ) ftsFile.TargetSURL = self.fileDict[lfn].get( 'Target' ) ftsFile.SourceSE = self.sourceSE ftsFile.TargetSE = self.targetSE ftsFile.Status = self.fileDict[lfn].get( 'Status' ) ftsFile.Checksum = cksmStr ftsFile.Size = self.catalogMetadata.get( lfn, {} ).get( 'Size' ) self.ftsFiles.append( ftsFile ) self.submittedFiles += 1 return S_OK() def __createFTSJob( self, guid = None ): self.__createFTSFiles() ftsJob = FTSJob() ftsJob.RequestID = 0 ftsJob.OperationID = 0 ftsJob.SourceSE = self.sourceSE ftsJob.TargetSE = self.targetSE ftsJob.SourceToken = self.sourceToken ftsJob.TargetToken = self.targetToken ftsJob.FTSServer = self.ftsServer if guid: ftsJob.FTSGUID = guid for ftsFile in self.ftsFiles: ftsFile.Attempt += 1 ftsFile.Error = "" ftsJob.addFile( ftsFile ) self.ftsJob = ftsJob def __submitFTSTransfer( self ): """ create and execute glite-transfer-submit CLI command :param self: self reference """ log = gLogger.getSubLogger( 'Submit' ) self.__createFTSJob() submit = self.ftsJob.submitFTS2( command = self.submitCommand ) if not submit["OK"]: log.error( "unable to submit FTSJob: %s" % submit["Message"] ) return submit log.info( "FTSJob '%s'@'%s' has been submitted" % ( self.ftsJob.FTSGUID, self.ftsJob.FTSServer ) ) # # update statuses for job files for ftsFile in self.ftsJob: ftsFile.FTSGUID = self.ftsJob.FTSGUID ftsFile.Status = "Submitted" ftsFile.Attempt += 1 log.info( "FTSJob '%s'@'%s' has been submitted" % ( self.ftsJob.FTSGUID, self.ftsJob.FTSServer ) ) self.ftsGUID = self.ftsJob.FTSGUID return S_OK() def __resolveFTSServer( self ): """ resolve FTS server to use, it should be the closest one from target SE :param self: self reference """ from DIRAC.ConfigurationSystem.Client.Helpers.Resources import getFTSServersForSites if not self.targetSE: return S_ERROR( "Target SE not set" ) res = getSitesForSE( self.targetSE ) if not res['OK'] or not res['Value']: return S_ERROR( "Could not determine target site" ) targetSites = res['Value'] targetSite = '' for targetSite in targetSites: targetFTS = getFTSServersForSites( [targetSite] ) if targetFTS['OK']: ftsTarget = targetFTS['Value'][targetSite] if ftsTarget: self.ftsServer = ftsTarget return S_OK( self.ftsServer ) else: return targetFTS return S_ERROR( 'No FTS server found for %s' % targetSite ) #################################################################### # # Methods for monitoring # def summary( self, untilTerminal = False, printOutput = False ): """ summary of FTS job :param self: self reference :param bool untilTerminal: flag to monitor FTS job to its final state :param bool printOutput: flag to print out monitoring information to the stdout """ res = self.__isSummaryValid() if not res['OK']: return res while not self.isTerminal: res = self.__parseOutput( full = True ) if not res['OK']: return res if untilTerminal: self.__print() self.isRequestTerminal() if res['Value'] or ( not untilTerminal ): break time.sleep( 1 ) if untilTerminal: print "" if printOutput and ( not untilTerminal ): return self.dumpSummary( printOutput = printOutput ) return S_OK() def monitor( self, untilTerminal = False, printOutput = False, full = True ): """ monitor FTS job :param self: self reference :param bool untilTerminal: flag to monitor FTS job to its final state :param bool printOutput: flag to print out monitoring information to the stdout """ if not self.ftsJob: self.resolveSource() self.__createFTSJob( self.ftsGUID ) res = self.__isSummaryValid() if not res['OK']: return res if untilTerminal: res = self.summary( untilTerminal = untilTerminal, printOutput = printOutput ) if not res['OK']: return res res = self.__parseOutput( full = full ) if not res['OK']: return res if untilTerminal: self.finalize() if printOutput: self.dump() return res def dumpSummary( self, printOutput = False ): """ get FTS job summary as str :param self: self reference :param bool printOutput: print summary to stdout """ outStr = '' for status in sorted( self.statusSummary ): if self.statusSummary[status]: outStr = '%s\t%-10s : %-10s\n' % ( outStr, status, str( self.statusSummary[status] ) ) outStr = outStr.rstrip( '\n' ) if printOutput: print outStr return S_OK( outStr ) def __print( self ): """ print progress bar of FTS job completeness to stdout :param self: self reference """ width = 100 bits = int( ( width * self.percentageComplete ) / 100 ) outStr = "|%s>%s| %.1f%s %s %s" % ( "="*bits, " "*( width - bits ), self.percentageComplete, "%", self.requestStatus, " "*10 ) sys.stdout.write( "%s\r" % ( outStr ) ) sys.stdout.flush() def dump( self ): """ print FTS job parameters and files to stdout :param self: self reference """ print "%-10s : %-10s" % ( "Status", self.requestStatus ) print "%-10s : %-10s" % ( "Source", self.sourceSE ) print "%-10s : %-10s" % ( "Target", self.targetSE ) print "%-10s : %-128s" % ( "Server", self.ftsServer ) print "%-10s : %-128s" % ( "GUID", self.ftsGUID ) for lfn in sorted( self.fileDict ): print "\n %-15s : %-128s" % ( 'LFN', lfn ) for key in ['Source', 'Target', 'Status', 'Reason', 'Duration']: print " %-15s : %-128s" % ( key, str( self.fileDict[lfn].get( key ) ) ) return S_OK() def __isSummaryValid( self ): """ check validity of FTS job summary report :param self: self reference """ if not self.ftsServer: return S_ERROR( "FTSServer not set" ) if not self.ftsGUID: return S_ERROR( "FTSGUID not set" ) return S_OK() def __parseOutput( self, full = False ): """ execute glite-transfer-status command and parse its output :param self: self reference :param bool full: glite-transfer-status verbosity level, when set, collect information of files as well """ monitor = self.ftsJob.monitorFTS2( command = self.monitorCommand, full = full ) if not monitor['OK']: return monitor self.percentageComplete = self.ftsJob.Completeness self.requestStatus = self.ftsJob.Status self.submitTime = self.ftsJob.SubmitTime statusSummary = monitor['Value'] if statusSummary: for state in statusSummary: self.statusSummary[state] = statusSummary[state] self.transferTime = 0 for ftsFile in self.ftsJob: lfn = ftsFile.LFN self.__setFileParameter( lfn, 'Status', ftsFile.Status ) self.__setFileParameter( lfn, 'Reason', ftsFile.Error ) self.__setFileParameter( lfn, 'Duration', ftsFile._duration ) targetURL = self.__getFileParameter( lfn, 'Target' ) if not targetURL['OK']: self.__setFileParameter( lfn, 'Target', ftsFile.TargetSURL ) self.transferTime += int( ftsFile._duration ) return S_OK() #################################################################### # # Methods for finalization # def finalize( self ): """ finalize FTS job :param self: self reference """ self.__updateMetadataCache() transEndTime = dateTime() regStartTime = time.time() res = self.getTransferStatistics() transDict = res['Value'] res = self.__registerSuccessful( transDict['transLFNs'] ) regSuc, regTotal = res['Value'] regTime = time.time() - regStartTime if self.sourceSE and self.targetSE: self.__sendAccounting( regSuc, regTotal, regTime, transEndTime, transDict ) return S_OK() def getTransferStatistics( self ): """ collect information of Transfers that can be used by Accounting :param self: self reference """ transDict = { 'transTotal': len( self.fileDict ), 'transLFNs': [], 'transOK': 0, 'transSize': 0 } for lfn in self.fileDict: if self.fileDict[lfn].get( 'Status' ) in self.successfulStates: if self.fileDict[lfn].get( 'Duration', 0 ): transDict['transLFNs'].append( lfn ) transDict['transOK'] += 1 if lfn in self.catalogMetadata: transDict['transSize'] += self.catalogMetadata[lfn].get( 'Size', 0 ) return S_OK( transDict ) def getFailedRegistrations( self ): """ get failed registrations dict :param self: self reference """ return S_OK( self.failedRegistrations ) def __registerSuccessful( self, transLFNs ): """ register successfully transferred files to the catalogs, fill failedRegistrations dict for files that failed to register :param self: self reference :param list transLFNs: LFNs in FTS job """ self.failedRegistrations = {} toRegister = {} for lfn in transLFNs: res = returnSingleResult( self.oTargetSE.getURL( self.fileDict[lfn].get( 'Target' ), protocol = 'srm' ) ) if not res['OK']: self.__setFileParameter( lfn, 'Reason', res['Message'] ) self.__setFileParameter( lfn, 'Status', 'Failed' ) else: toRegister[lfn] = { 'PFN' : res['Value'], 'SE' : self.targetSE } if not toRegister: return S_OK( ( 0, 0 ) ) res = self.__getCatalogObject() if not res['OK']: for lfn in toRegister: self.failedRegistrations = toRegister self.log.error( 'Failed to get Catalog Object', res['Message'] ) return S_OK( ( 0, len( toRegister ) ) ) res = self.oCatalog.addReplica( toRegister ) if not res['OK']: self.failedRegistrations = toRegister self.log.error( 'Failed to get Catalog Object', res['Message'] ) return S_OK( ( 0, len( toRegister ) ) ) for lfn, error in res['Value']['Failed'].items(): self.failedRegistrations[lfn] = toRegister[lfn] self.log.error( 'Registration of Replica failed', '%s : %s' % ( lfn, str( error ) ) ) return S_OK( ( len( res['Value']['Successful'] ), len( toRegister ) ) ) def __sendAccounting( self, regSuc, regTotal, regTime, transEndTime, transDict ): """ send accounting record :param self: self reference :param regSuc: number of files successfully registered :param regTotal: number of files attepted to register :param regTime: time stamp at the end of registration :param transEndTime: time stamp at the end of FTS job :param dict transDict: dict holding couters for files being transerred, their sizes and successfull transfers """ oAccounting = DataOperation() oAccounting.setEndTime( transEndTime ) oAccounting.setStartTime( self.submitTime ) accountingDict = {} accountingDict['OperationType'] = 'replicateAndRegister' result = getProxyInfo() if not result['OK']: userName = 'system' else: userName = result['Value'].get( 'username', 'unknown' ) accountingDict['User'] = userName accountingDict['Protocol'] = 'FTS' if 'fts3' not in self.ftsServer else 'FTS3' accountingDict['RegistrationTime'] = regTime accountingDict['RegistrationOK'] = regSuc accountingDict['RegistrationTotal'] = regTotal accountingDict['TransferOK'] = transDict['transOK'] accountingDict['TransferTotal'] = transDict['transTotal'] accountingDict['TransferSize'] = transDict['transSize'] accountingDict['FinalStatus'] = self.requestStatus accountingDict['Source'] = self.sourceSE accountingDict['Destination'] = self.targetSE accountingDict['TransferTime'] = self.transferTime oAccounting.setValuesFromDict( accountingDict ) self.log.verbose( "Attempting to commit accounting message..." ) oAccounting.commit() self.log.verbose( "...committed." ) return S_OK()
Java
<?php namespace de\chilan\WebsiteBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class WebsiteBundle extends Bundle { }
Java
var _ = require("lodash"); module.exports = { // ensure client accepts json json_request: function(req, res, next){ if(req.accepts("application/json")) return next(); res.stash.code = 406; _.last(req.route.stack).handle(req, res, next); }, // init response init_response: function(req, res, next){ res.stash = {}; res.response_start = new Date(); return next(); }, // respond to client handle_response: function(req, res, next){ res.setHeader("X-Navigator-Response-Time", new Date() - res.response_start); res.stash = _.defaults(res.stash, { code: 404 }); if(_.has(res.stash, "body")) res.status(res.stash.code).json(res.stash.body); else res.sendStatus(res.stash.code); } }
Java
/*========================================================================= Program: ParaView Module: $RCSfile$ Copyright (c) Kitware, Inc. All rights reserved. See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkPVKeyFrameAnimationCue // .SECTION Description // vtkPVKeyFrameAnimationCue is a specialization of vtkPVAnimationCue that uses // the vtkPVKeyFrameCueManipulator as the manipulator. #ifndef vtkPVKeyFrameAnimationCue_h #define vtkPVKeyFrameAnimationCue_h #include "vtkPVAnimationCue.h" class vtkPVKeyFrame; class vtkPVKeyFrameCueManipulator; class VTKPVANIMATION_EXPORT vtkPVKeyFrameAnimationCue : public vtkPVAnimationCue { public: vtkTypeMacro(vtkPVKeyFrameAnimationCue, vtkPVAnimationCue); void PrintSelf(ostream& os, vtkIndent indent); // Description: // Forwarded to the internal vtkPVKeyFrameCueManipulator. int AddKeyFrame (vtkPVKeyFrame* keyframe); int GetLastAddedKeyFrameIndex(); void RemoveKeyFrame(vtkPVKeyFrame*); void RemoveAllKeyFrames(); //BTX protected: vtkPVKeyFrameAnimationCue(); ~vtkPVKeyFrameAnimationCue(); vtkPVKeyFrameCueManipulator* GetKeyFrameManipulator(); private: vtkPVKeyFrameAnimationCue(const vtkPVKeyFrameAnimationCue&); // Not implemented void operator=(const vtkPVKeyFrameAnimationCue&); // Not implemented //ETX }; #endif
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <link rel="stylesheet" type="text/css" href="../css/tupi.css"> <title></title> </head><body class="tupi_background3"> <p class="title">Vexamos como está a quedar</p> <p class="paragraph">Perfecto, xa temos a metade dos fotogramas do noso proxecto rematados. Chegou o momento de aprender a utilizar o <b>Módulo de reprodución</b>. É necesario aclarar que non hai unha regra xeral sobre cuantos fotogramas debes crear antes de facer unha vista previa do teu proxecto, esta é outra habilidade que desenvolveras a partir da práctica, noutras palabras: ti escolles. </p> <center> <table> <tbody> <tr> <td> <center><img src="./images/preview01.png"></center> </td> </tr> <tr> <td> <img src="./images/preview02.png"> </td> </tr> </tbody> </table> <p class="paragraph"> <b>Fig. 57</b> Vista previa do proxecto desde o Modulo de reprodución</p> </center><p class="paragraph">Debes ter tamén en en conta que facer unha vista previa da túa animación non afecta ao proxecto en absoluto, polo tanto, poderás entrar neste módulo tantas veces como queiras, o verdadeiramente importante é que o aproveites para comprobar como de satisfeito estás co resultado final e que poidas corrixir a tempo os erros que descubras. <br>A interface de vista previa é moi doada, así que no hai nada do que preocuparse. O panel de control conten todos os botóns necesarios para reproducir a túa animación, paso a paso o de xeito continuo. </p> <center> <img src="./images/preview03.png"> <p class="paragraph"> <b>Fig. 58</b> Panel de control do Modulo de reprodución</p></center> <p class="paragraph">Se observas a parte inferior do panel, atoparas máis información sobre o proxecto: o <i>nome da escena</i>, o <i>número total de fotogramas</i> e o <i>número de fotogramas por segundo (FPS)</i>, esta última opción é editábel e permitirache axustar a velocidade á que queres reproducir a túa animación. Canto máis grande sexa o valor, máis rápido se verá e canto máis pequeno, máis lento.</p> <p class="paragraph"> <b>Consello:</b> A opción <i>Repetir</i> é moi útil se tes poucos fotogramas e queres ter unha apreciación máis precisa sobre a fluidez do teu proxecto. Podes activala ou desactivala sempre que queiras. </p> <center> <img src="../images/preview04.png"> <p class="paragraph"> <b>Fig. 59</b> Opción «Repetir» do Modulo de reprodución&gt;</p></center><p class="paragraph">Agora toca continuar debuxando novos fotogramas ata cumprir con todo o recorrido proposto no guión. Volve á sección anterior, e remata con todos os gráficos pendentes. É probábel que che apareza moi canso ter que debuxar as mesmas partes de certos obxectos ou personaxes unha e outra vez, e estamos de acordo contigo. É por iso que estamos a traballar unha funcionalidade chamada "«Interpolación» (Tweening), que serve para aforrarche moito tempo no momento de ilustrar e que agardamos ter rematada moi cedo. </p> <p class="paragraph">Xa remataches de crear todos os fotogramas? Gústache o que ves no <b>Módulo de reprodución</b>? Moi ben, é hora de crear o teu primeiro <a href="video_file.html">ficheiro de vídeo</a>!</p> </body></html>
Java
// Decompiled with JetBrains decompiler // Type: System.Web.UI.WebControls.WebParts.ProxyWebPartConnectionCollection // Assembly: System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // MVID: 7E68A73E-4066-4F24-AB0A-F147209F50EC // Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Web.dll using System; using System.Collections; using System.ComponentModel; using System.Drawing.Design; using System.Runtime; namespace System.Web.UI.WebControls.WebParts { /// <summary> /// Contains a collection of static <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> objects, which is used when the connections are declared in content pages and the <see cref="T:System.Web.UI.WebControls.WebParts.WebPartManager"/> control is declared in a master page. This class cannot be inherited. /// </summary> [Editor("System.ComponentModel.Design.CollectionEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof (UITypeEditor))] public sealed class ProxyWebPartConnectionCollection : CollectionBase { private WebPartManager _webPartManager; /// <summary> /// Gets a value indicating whether <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> objects can be added to the collection. /// </summary> /// /// <returns> /// true if connection objects cannot be added to the collection; otherwise, false. /// </returns> public bool IsReadOnly { get { if (this._webPartManager != null) return this._webPartManager.StaticConnections.IsReadOnly; return false; } } /// <summary> /// Gets or sets a connection item within the collection, based on an index number indicating the item's location in the collection. /// </summary> /// /// <returns> /// A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> at the specified index in the collection. /// </returns> /// <param name="index">An integer that indicates the index of a member of the collection. </param> public WebPartConnection this[int index] { get { return (WebPartConnection) this.List[index]; } set { this.List[index] = (object) value; } } /// <summary> /// Returns a specific member of the collection according to a unique identifier. /// </summary> /// /// <returns> /// The first <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> whose ID matches the value of the <paramref name="id"/> parameter. Returns null if no match is found. /// </returns> /// <param name="id">A string that contains the ID of a particular connection in the collection. </param> public WebPartConnection this[string id] { get { foreach (WebPartConnection webPartConnection in (IEnumerable) this.List) { if (webPartConnection != null && string.Equals(webPartConnection.ID, id, StringComparison.OrdinalIgnoreCase)) return webPartConnection; } return (WebPartConnection) null; } } /// <summary> /// Initializes a new instance of the <see cref="T:System.Web.UI.WebControls.WebParts.ProxyWebPartConnectionCollection"/> class. /// </summary> [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public ProxyWebPartConnectionCollection() { } /// <summary> /// Adds a <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> object to the collection. /// </summary> /// /// <returns> /// An integer value that indicates where the <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> was inserted into the collection. /// </returns> /// <param name="value">A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> to add to the collection. </param> public int Add(WebPartConnection value) { return this.List.Add((object) value); } /// <summary> /// Returns a value indicating whether a particular <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> object exists in the collection. /// </summary> /// /// <returns> /// true if <paramref name="value"/> exists in the collection; otherwise, false. /// </returns> /// <param name="value">A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> being checked for its existence in a collection. </param> public bool Contains(WebPartConnection value) { return this.List.Contains((object) value); } /// <summary> /// Copies the collection to an array of <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> objects. /// </summary> /// <param name="array">An array of <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> objects to contain the copied collection. </param><param name="index">An integer that indicates the starting point in the array at which to place the collection contents. </param> public void CopyTo(WebPartConnection[] array, int index) { this.List.CopyTo((Array) array, index); } /// <summary> /// Returns the position of a particular member of the collection. /// </summary> /// /// <returns> /// An integer that indicates the position of a particular object in the collection. /// </returns> /// <param name="value">A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> that is a member of the collection. </param> public int IndexOf(WebPartConnection value) { return this.List.IndexOf((object) value); } /// <summary> /// Inserts a <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> object into the collection at the specified index. /// </summary> /// <param name="index">An integer indicating the ordinal position in the collection at which a <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> should be inserted. </param><param name="value">A <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> to insert into the collection. </param> public void Insert(int index, WebPartConnection value) { this.List.Insert(index, (object) value); } protected override void OnClear() { this.CheckReadOnly(); if (this._webPartManager != null) { foreach (WebPartConnection webPartConnection in (CollectionBase) this) this._webPartManager.StaticConnections.Remove(webPartConnection); } base.OnClear(); } protected override void OnInsert(int index, object value) { this.CheckReadOnly(); if (this._webPartManager != null) this._webPartManager.StaticConnections.Insert(index, (WebPartConnection) value); base.OnInsert(index, value); } protected override void OnRemove(int index, object value) { this.CheckReadOnly(); if (this._webPartManager != null) this._webPartManager.StaticConnections.Remove((WebPartConnection) value); base.OnRemove(index, value); } protected override void OnSet(int index, object oldValue, object newValue) { this.CheckReadOnly(); if (this._webPartManager != null) this._webPartManager.StaticConnections[this._webPartManager.StaticConnections.IndexOf((WebPartConnection) oldValue)] = (WebPartConnection) newValue; base.OnSet(index, oldValue, newValue); } protected override void OnValidate(object value) { base.OnValidate(value); if (value == null) throw new ArgumentNullException("value", System.Web.SR.GetString("Collection_CantAddNull")); if (!(value is WebPartConnection)) throw new ArgumentException(System.Web.SR.GetString("Collection_InvalidType", new object[1] { (object) "WebPartConnection" })); } /// <summary> /// Removes the specified <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> object from the collection. /// </summary> /// <param name="value">The <see cref="T:System.Web.UI.WebControls.WebParts.WebPartConnection"/> to be removed. </param> public void Remove(WebPartConnection value) { this.List.Remove((object) value); } internal void SetWebPartManager(WebPartManager webPartManager) { this._webPartManager = webPartManager; foreach (WebPartConnection webPartConnection in (CollectionBase) this) this._webPartManager.StaticConnections.Add(webPartConnection); } private void CheckReadOnly() { if (this.IsReadOnly) throw new InvalidOperationException(System.Web.SR.GetString("ProxyWebPartConnectionCollection_ReadOnly")); } } }
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <!-- Created by GNU Texinfo 5.1, http://www.gnu.org/software/texinfo/ --> <!-- This file redirects to the location of a node or anchor --> <head> <title>GNU Octave: XREFbicgstab</title> <meta name="description" content="GNU Octave: XREFbicgstab"> <meta name="keywords" content="GNU Octave: XREFbicgstab"> <meta name="resource-type" content="document"> <meta name="distribution" content="global"> <meta name="Generator" content="makeinfo"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <style type="text/css"> <!-- a.summary-letter {text-decoration: none} blockquote.smallquotation {font-size: smaller} div.display {margin-left: 3.2em} div.example {margin-left: 3.2em} div.indentedblock {margin-left: 3.2em} div.lisp {margin-left: 3.2em} div.smalldisplay {margin-left: 3.2em} div.smallexample {margin-left: 3.2em} div.smallindentedblock {margin-left: 3.2em; font-size: smaller} div.smalllisp {margin-left: 3.2em} kbd {font-style:oblique} pre.display {font-family: inherit} pre.format {font-family: inherit} pre.menu-comment {font-family: serif} pre.menu-preformatted {font-family: serif} pre.smalldisplay {font-family: inherit; font-size: smaller} pre.smallexample {font-size: smaller} pre.smallformat {font-family: inherit; font-size: smaller} pre.smalllisp {font-size: smaller} span.nocodebreak {white-space:nowrap} span.nolinebreak {white-space:nowrap} span.roman {font-family:serif; font-weight:normal} span.sansserif {font-family:sans-serif; font-weight:normal} ul.no-bullet {list-style: none} --> </style> <meta http-equiv="Refresh" content="0; url=Specialized-Solvers.html#XREFbicgstab"> </head> <body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000"> <p>The node you are looking for is at <a href="Specialized-Solvers.html#XREFbicgstab">XREFbicgstab</a>.</p> </body>
Java
// Copyright (c) The University of Dundee 2018-2019 // This file is part of the Research Data Management Platform (RDMP). // RDMP 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. // RDMP 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 RDMP. If not, see <https://www.gnu.org/licenses/>. using System.Windows.Forms; using MapsDirectlyToDatabaseTable; namespace Rdmp.UI.Refreshing { /// <summary> /// <see cref="IRefreshBusSubscriber"/> for <see cref="Control"/> classes which want their lifetime to be linked to a single /// <see cref="IMapsDirectlyToDatabaseTable"/> object. This grants notifications of publish events about the object and ensures /// your <see cref="Control"/> is closed when/if the object is deleted. /// /// <para>See <see cref="RefreshBus.EstablishLifetimeSubscription"/></para> /// </summary> public interface ILifetimeSubscriber:IContainerControl,IRefreshBusSubscriber { } }
Java
import sys, os, urllib, time, socket, mt, ssl from dlmanager.NZB import NZBParser from dlmanager.NZB.nntplib2 import NNTP_SSL,NNTPError,NNTP, NNTPReplyError from dlmanager.NZB.Decoder import ArticleDecoder class StatusReport(object): def __init__(self): self.message = "Downloading.." self.total_bytes = 0 self.current_bytes = 0 self.completed = False self.error_occured = False self.start_time = 0 self.file_name = "" self.kbps = 0 self.assembly = False self.assembly_percent = 0 class NZBClient(): def __init__(self, nzbFile, save_to, nntpServer, nntpPort, nntpUser=None, nntpPassword=None, nntpSSL=False, nntpConnections=5, cache_path=""): # Settings self.save_to = save_to self.nntpServer = nntpServer self.nntpUser = nntpUser self.nntpPort = nntpPort self.nntpPassword = nntpPassword self.nntpSSL = nntpSSL self.nntpConnections = nntpConnections self.threads = [] self.running = False # setup our cache folder. self.cache_path = cache_path if ( self.cache_path == "" ): self.cache_path = "packages/dlmanager/cache/" self.clearCache() # ensure both directorys exist mt.utils.mkdir(self.save_to) mt.utils.mkdir(self.cache_path) # Open the NZB, get this show started. realFile = urllib.urlopen(nzbFile) self.nzb = NZBParser.parse(realFile) self.all_decoded = False self.connection_count = 0 # used to track status. self.status = StatusReport() self.status.file_name = nzbFile self.status.total_bytes = self.nzb.size # Segment tracking. self.cache = [] self.segment_list = [] self.segments_finished = [] self.segments_aborted = [] # Queues. self.segment_queue = [] self.failed_queue = [] # Used to track the speed. self.speedTime = 0 self.speedCounter = 0 def start(self): # keep track of running time. self.status.start_time = time.time() self.running = True # Generate a list of segments and build our queue. for file in self.nzb.files: for seg in file.segments: self.segment_list.append(seg.msgid) self.segment_queue.append(seg) # start the connections. for a in range(0, self.nntpConnections): thread = NNTPConnection(a, self.nntpServer, self.nntpPort, self.nntpUser, self.nntpPassword, self.nntpSSL, self.nextSeg, self.segComplete, self.segFailed, self.threadStopped) self.threads.append(thread) self.connection_count += 1 thread.start() # start the article decoder. self.articleDecoder = ArticleDecoder(self.decodeNextSeg, self.save_to, self.cache_path, self.decodeFinished, self.decodeSuccess, self.decodeFailed, self.assemblyStatus) self.articleDecoder.start() def getStatus(self): return self.status # Article Decoder - Next segment. def decodeNextSeg(self): # if we're not running send an instant kill switch. if ( not self.running ): return -1 # try to grab a segment from the cache to decode. seg = None try: seg = self.cache.pop() except: pass if ( seg == None ) and ( self.all_decoded ): return -1 return seg # Article Decoder - Decoded all segments. def decodeFinished(self): self.status.completed = True # Article Decoder - Decode success. def decodeSuccess(self, seg): self.status.current_bytes += seg.size self.segments_finished.append(seg.msgid) if ( (len(self.segments_finished)+len(self.segments_aborted)) >= len(self.segment_list) ): self.all_decoded = True # Article Decoder - Decode failed. def decodeFailed(self, seg): if ( seg == None ): return mt.log.debug("Segment failed to decode: " + seg.msgid) self.segFailed(seg) # Article Decoder - Assembly Status. def assemblyStatus(self, percent): self.status.assembly = True self.status.assembly_percent = percent # NNTP Connection - Thread stopped. def threadStopped(self, thread_num): self.connection_count -= 1 # NNTP Connection - Segment completed. def segComplete(self, seg): if ( seg == None ): return if ( seg.data ): data_size = len("".join(seg.data)) current_time = time.time() if ( (current_time - self.speedTime) > 1 ): self.status.kbps = self.speedCounter self.speedCounter = 0 self.speedTime = current_time else: self.speedCounter += (data_size/1024) self.cache.append(seg) #mt.log.debug("Segment Complete: " + seg.msgid) # NNTP Connection - Download of segment failed. def segFailed(self, seg): if ( seg == None ): return if ( seg.aborted() ): mt.log.error("Segment Aborted: " + seg.msgid + " after " + str(seg.retries) + " attempts.") self.segments_aborted.append(seg.msgid) seg.data = [] if ( (len(self.segments_finished)+len(self.segments_aborted)) >= len(self.segment_list) ): self.all_decoded = True return seg.retries += 1 mt.log.error("Segment Failed: " + seg.msgid + " Attempt #" + str(seg.retries) + ".") self.failed_queue.append(seg) # NNTP Connection - Next Segment def nextSeg(self): # if we're not running send an instant kill switch. if ( not self.running ): return -1 # try to get a segment from main queue or failed queue. queue_empty = False seg = None try: seg = self.segment_queue.pop() except: try: seg = self.failed_queue.pop() except: queue_empty = True pass pass # We're all outta segments, if they're done decoding, kill the threads. if ( queue_empty ) and ( self.all_decoded ): return -1 return seg # empty the cache of any files. def clearCache(self): mt.utils.rmdir(self.cache_path) def stop(self): self.running = False self.articleDecoder.stop() for thread in self.threads: thread.stop() self.clearCache() class NNTPConnection(mt.threads.Thread): def __init__(self, connection_number, server, port, username, password, ssl, nextSegFunc, onSegComplete = None, onSegFailed = None, onThreadStop = None): mt.threads.Thread.__init__(self) # Settings self.connection = None self.connection_number = connection_number self.server = server self.port = port self.username = username self.password = password self.ssl = ssl # Events. self.nextSegFunc = nextSegFunc self.onSegComplete = onSegComplete self.onSegFailed = onSegFailed self.onThreadStop = onThreadStop def connect(self): # Open either an SSL or regular NNTP connection. try: if ( self.ssl ): self.connection = NNTP_SSL(self.server, self.port, self.username, self.password, False, True, timeout=15) else: self.connection = NNTP(self.server, self.port, self.username, self.password, False, True, timeout=15) except: pass if ( self.connection ): return True return False def disconnect(self): if ( self.connection ): try: self.connection.quit() except: pass self.connection = None def run(self): connection = None seg = None # Thread has started. mt.log.debug("Thread " + str(self.connection_number) + " started.") start_time = time.time() while(self.running): seg = None connected = self.connect() if ( connected ): while(self.running): seg = self.nextSegFunc() # Out of segments, sleep for a bit and see if we get anymore. if ( seg == None ): self.sleep(0.1) continue # Download complete, bail. if ( seg == -1 ): self.running = False seg = None break # Attempt to grab a segment. try: resp, nr, id, data = self.connection.body("<%s>" % seg.msgid) if resp[0] == "2": seg.data = data if ( self.onSegComplete ): self.onSegComplete(seg) seg = None except ssl.SSLError: break except NNTPError as e: mt.log.error("Error getting segment: " + e.response) pass except: mt.log.error("Error getting segment.") pass if ( seg and self.onSegFailed ): self.onSegFailed(seg) seg = None # Disconnect when we're finished. if ( seg and self.onSegFailed ): self.onSegFailed(seg) self.disconnect() else: mt.log.error("Connection error. Reconnecting in 3 seconds.") self.sleep(3) # Thread has ended. self.disconnect() # just to be safe. end_time = time.time() mt.log.debug("Thread " + str(self.connection_number) + " stopped after " + str(end_time-start_time) + " seconds.") if ( self.onThreadStop ): self.onThreadStop(self.connection_number)
Java
"""Tests for `fix.with_fixture`.""" from __future__ import with_statement import os import shutil import tempfile from types import FunctionType from fix import with_fixture def test_exists(): """`fix.with_fixture` function exists""" assert isinstance(with_fixture, FunctionType) def test_setup_only(): """`setup_only` fixture works as expected""" def setup_only(context): """A fixture with no `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" return setup @with_fixture(setup_only) def case(context): """Check that the context has been set up.""" assert context == {"squee": "kapow"} case() # pylint: disable=E1120 def test_setup_teardown(): """`setup_teardown` fixture works as expected""" def setup_teardown(context): """A fixture with both `setup()` and `teardown()`.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "boing"} return setup, teardown @with_fixture(setup_teardown) def case(context): """Alter the context.""" assert context == {"squee": "kapow"} context.squee = "boing" case() # pylint: disable=E1120 def test_multiple_invocation(): """`multiple` fixture creates a fresh context each invocation""" def multiple(context): """A fixture to be invoked multiple times.""" def setup(): """Add something to the context.""" assert context == {} context.squee = "kapow" def teardown(): """Check that `context.squee` has changed.""" assert context == {"squee": "kapow", "boing": "thunk"} return setup, teardown @with_fixture(multiple) def case(context): """Add to the context.""" assert context == {"squee": "kapow"} context.boing = "thunk" for _ in range(3): case() # pylint: disable=E1120 def test_external(): """`external` fixture interacts as expected with the 'real world'.""" def external(context, files=3): """A fixture to manipulate temporary files and directories.""" def setup(): """Create some temporary files.""" context.temp_dir = tempfile.mkdtemp() context.filenames = ["file_%03d" % i for i in range(files)] for filename in context.filenames: with open(os.path.join(context.temp_dir, filename), "w") as f: f.write("This is the file %r.\n" % filename) def teardown(): """Delete the temporary files created in `setup()`.""" shutil.rmtree(context.temp_dir) return setup, teardown @with_fixture(external, files=5) def check_files(context): """Return the number of present and absent files.""" present = 0 absent = 0 for filename in context.filenames: if os.path.exists(os.path.join(context.temp_dir, filename)): present += 1 else: absent += 1 return context.temp_dir, present, absent temp_dir, present, absent = check_files() # pylint: disable=E1120 assert not os.path.exists(temp_dir) assert present == 5 assert absent == 0
Java
# Copyright (C) 2012,2013 # Max Planck Institute for Polymer Research # Copyright (C) 2008,2009,2010,2011 # Max-Planck-Institute for Polymer Research & Fraunhofer SCAI # # This file is part of ESPResSo++. # # ESPResSo++ 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. # # ESPResSo++ is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. r""" ****************************** espressopp.integrator.CapForce ****************************** This class can be used to forcecap all particles or a group of particles. Force capping means that the force vector of a particle is rescaled so that the length of the force vector is <= capforce Example Usage: >>> capforce = espressopp.integrator.CapForce(system, 1000.0) >>> integrator.addExtension(capForce) CapForce can also be used to forcecap only a group of particles: >>> particle_group = [45, 67, 89, 103] >>> capforce = espressopp.integrator.CapForce(system, 1000.0, particle_group) >>> integrator.addExtension(capForce) .. function:: espressopp.integrator.CapForce(system, capForce, particleGroup) :param system: :param capForce: :param particleGroup: (default: None) :type system: :type capForce: :type particleGroup: """ from espressopp.esutil import cxxinit from espressopp import pmi from espressopp.integrator.Extension import * from _espressopp import integrator_CapForce class CapForceLocal(ExtensionLocal, integrator_CapForce): def __init__(self, system, capForce, particleGroup = None): if not (pmi._PMIComm and pmi._PMIComm.isActive()) or pmi._MPIcomm.rank in pmi._PMIComm.getMPIcpugroup(): if (particleGroup == None) or (particleGroup.size() == 0): cxxinit(self, integrator_CapForce, system, capForce) else: cxxinit(self, integrator_CapForce, system, capForce, particleGroup) if pmi.isController : class CapForce(Extension, metaclass=pmi.Proxy): pmiproxydefs = dict( cls = 'espressopp.integrator.CapForceLocal', pmicall = ['setCapForce', 'setAbsCapForce', 'getCapForce', 'getAbsCapForce'], pmiproperty = [ 'particleGroup', 'adress' ] )
Java
#!/bin/bash gnuplot temp/TermodinamicalStat_L=14_PP=4/*.plot gnuplot temp/DensityStat_L=14_PP=4/*.plot
Java
# @author Peter Kappelt # @author Clemens Bergmann # @version 1.16.dev-cf.9 package main; use strict; use warnings; use Data::Dumper; use JSON; use TradfriUtils; sub TradfriGroup_Initialize($) { my ($hash) = @_; $hash->{DefFn} = 'Tradfri_Define'; $hash->{UndefFn} = 'Tradfri_Undef'; $hash->{SetFn} = 'Tradfri_Set'; $hash->{GetFn} = 'Tradfri_Get'; $hash->{AttrFn} = 'Tradfri_Attr'; $hash->{ReadFn} = 'Tradfri_Read'; $hash->{ParseFn} = 'TradfriGroup_Parse'; $hash->{Match} = '(^subscribedGroupUpdate::)|(^moodList::)'; $hash->{AttrList} = "usePercentDimming:1,0 " . $readingFnAttributes; } #messages look like this: (without newlines) # subscribedGroupUpdate::group-id::{ # "createdAt":1494088484, # "mood":198884, # "groupid":173540, # "members":[ # { # "name":"Fenster Links", # "deviceid":65537 # }, # { # "deviceid":65536 # }, # { # "name":"Fenster Rechts", # "deviceid":65538 # } # ], # "name":"Wohnzimmer", # "dimvalue":200, # "onoff":0 # } sub TradfriGroup_Parse($$){ my ($io_hash, $message) = @_; my @parts = split('::', $message); if(int(@parts) < 3){ #expecting at least three parts return undef; } my $messageID = $parts[1]; #check if group with the id exists if(my $hash = $modules{'TradfriGroup'}{defptr}{$messageID}) { #parse the JSON data my $jsonData = eval{ JSON->new->utf8->decode($parts[2]) }; if($@){ return undef; #the string was probably not valid JSON } if('subscribedGroupUpdate' eq $parts[0]){ my $createdAt = FmtDateTimeRFC1123($jsonData->{'createdAt'} || ''); my $name = $jsonData->{'name'} || ''; my $members = JSON->new->pretty->encode($jsonData->{'members'}); #dimvalue is in range 0 - 254 my $dimvalue = $jsonData->{'dimvalue'} || '0'; #dimpercent is always in range 0 - 100 my $dimpercent = int($dimvalue / 2.54 + 0.5); $dimpercent = 1 if($dimvalue == 1); $dimvalue = $dimpercent if (AttrVal($hash->{name}, 'usePercentDimming', 0) == 1); my $state = 'off'; if($jsonData->{'onoff'} eq '0'){ $dimpercent = 0; }else{ $state = Tradfri_stateString($dimpercent); } my $onoff = ($jsonData->{'onoff'} || '0') ? 'on':'off'; readingsBeginUpdate($hash); readingsBulkUpdateIfChanged($hash, 'createdAt', $createdAt, 1); readingsBulkUpdateIfChanged($hash, 'name', $name, 1); readingsBulkUpdateIfChanged($hash, 'members', $members, 1); readingsBulkUpdateIfChanged($hash, 'dimvalue', $dimvalue, 1); readingsBulkUpdateIfChanged($hash, 'pct', $dimpercent, 1); readingsBulkUpdateIfChanged($hash, 'onoff', $onoff, 1) ; readingsBulkUpdateIfChanged($hash, 'state', $state, 1); readingsEndUpdate($hash, 1); }elsif('moodList' eq $parts[0]){ #update of mood list readingsSingleUpdate($hash, 'moods', JSON->new->pretty->encode($jsonData), 1); $hash->{helper}{moods} = undef; foreach (@{$jsonData}){ $hash->{helper}{moods}->{$_->{name}} = $_; } } #$attr{$hash->{NAME}}{webCmd} = 'pct:toggle:on:off'; #$attr{$hash->{NAME}}{devStateIcon} = '{(Tradfri_devStateIcon($name),"toggle")}' if( !defined( $attr{$hash->{name}}{devStateIcon} ) ); #return the appropriate group's name return $hash->{NAME}; } return undef; } 1; =pod =item device =item summary controls an IKEA Trådfri lighting group =item summary_DE steuert eine IKEA Trådfri Beleuchtungsgruppe =begin html <a name="TradfriGroup"></a> <h3>TradfriGroup</h3> <ul> <i>TradfriGroup</i> is a module for controlling an IKEA Trådfri lighting group. You currently need a gateway for the connection. See TradfriGateway. <br><br> <a name="TradfriGroupdefine"></a> <b>Define</b> <ul> <code>define &lt;name&gt; TradfriGroup &lt;group-address&gt;</code> <br><br> Example: <code>define trGroupOne TradfriGroup 193768</code> <br><br> You can get the ID of the lighting groups by calling "get TradfriGW groupList" on the gateway device </ul> <br> <a name="TradfriGroupset"></a> <b>Set</b><br> <ul> <code>set &lt;name&gt; &lt;option&gt; [&lt;value&gt;]</code> <br><br> You can set the following options. See <a href="http://fhem.de/commandref.html#set">commandref#set</a> for more info about the set command. <br><br> Options: <ul> <li><i>on</i><br> Turns all devices in the group on.<br>The brightness is the one, before the devices were turned off</li> <li><i>off</i><br> Turn all devices in the group off.</li> <li><i>dimvalue</i><br> Set the brightness of all devices in the group.<br> You need to specify the brightness value as an integer between 0 and 100/254.<br> The largest value depends on the attribute "usePercentDimming".<br> If this attribute is set, the largest value will be 100.<br> By default, it isn't set, so the largest value is 254.<br> A brightness value of 0 turns the devices off.<br> If the devices are off, and you set a value greater than 0, they'll turn on.</li> <li><i>mood</i><br> Set the mood of the group.<br> Moods are preconfigured color temperatures, brightnesses and states for each device of the group<br> In order to set the mood, you need a mood ID or the mood's name.<br> You can list the moods that are available for this group by running "get moods".<br> Note, that the mood's name isn't necessarily the same that you've defined in the IKEA app. This module is currently unable to handle whitespaces in mood names, so whitespaces get removed internally. Check the reading "moods" after running "get moods" in order to get the names, that you may use with this module.<br> Mood names are case-sensitive. Mood names, that are only made out of numbers are not supported.</li> </ul> </ul> <br> <a name="TradfriGroupget"></a> <b>Get</b><br> <ul> <code>get &lt;name&gt; &lt;option&gt;</code> <br><br> You can get the following information about the group. See <a href="http://fhem.de/commandref.html#get">commandref#get</a> for more info about the get command. <br><br> Options: <ul> <li><i>moods</i><br> Get all moods (their name and their ID) that are configured for this group<br> The JSON-formatted result is stored in the Reading "moods"</br> Please note, that the mood IDs may differ between different groups (though they are the same moods) -> check them for each group</li> </ul> </ul> <br> <a name="TradfriGroupreadings"></a> <b>Readings</b><br> <ul> The following readings are displayed for a group. Once there is a change and the connection to the gateway is made, they get updated automatically. <br><br> Readings: <ul> <li><i>createdAt</i><br> A timestamp string, like "Sat, 15 Apr 2017 18:29:24 GMT", that indicates, when the group was created in the gateway.</li> <li><i>dimvalue</i><br> The brightness that is set for this group. It is a integer in the range of 0 to 100/ 254.<br> The greatest dimvalue depends on the attribute "usePercentDimming", see below.</li> <li><i>pct</i><br> The brightness that is set for this device in percent.</li> <li><i>members</i><br> JSON-String that contains all member-IDs and their names.</li> <li><i>moods</i><br> JSON info of all moods and their names, e.g.:<br> [ { "groupid" : 173540, "moodid" : 198884, "name" : "EVERYDAY" }, { "moodid" : 213983, "name" : "RELAX", "groupid" : 173540 }, { "groupid" : 173540, "name" : "FOCUS", "moodid" : 206399 } ]<br> This reading isn't updated automatically, you've to call "get moods" in order to refresh them.</li> <li><i>name</i><br> The name of the group that you've set in the app.</li> <li><i>onoff</i><br> Indicates whether the device is on or off, can be the strings 'on' or 'off'</li> <li><i>state</i><br> Indicates, whether the group is on or off. Thus, the reading's value is either "on" or "off", too.</li> </ul> </ul> <br> <a name="TradfriGroupattr"></a> <b>Attributes</b> <ul> <code>attr &lt;name&gt; &lt;attribute&gt; &lt;value&gt;</code> <br><br> See <a href="http://fhem.de/commandref.html#attr">commandref#attr</a> for more info about the attr command. <br><br> Attributes: <ul> <li><i>usePercentDimming</i> 0/1<br> If this attribute is one, the largest value for "set dimvalue" will be 100.<br> Otherwise, the largest value is 254.<br> This attribute is useful, if you need to control the brightness in percent (0-100%)<br> For backward compatibility, it is disabled by default, so the largest dimvalue is 254 by default. </li> </ul> </ul> </ul> =end html =cut
Java
/* EPANET 3 * * Copyright (c) 2016 Open Water Analytics * Distributed under the MIT License (see the LICENSE file for details). * */ #include "demandmodel.h" #include "Elements/junction.h" #include <cmath> #include <algorithm> using namespace std; //----------------------------------------------------------------------------- // Parent constructor and destructor //----------------------------------------------------------------------------- DemandModel::DemandModel() : expon(0.0) {} DemandModel::DemandModel(double expon_) : expon(expon_) {} DemandModel::~DemandModel() {} //----------------------------------------------------------------------------- // Demand model factory //----------------------------------------------------------------------------- DemandModel* DemandModel::factory(const string model, const double expon_) { if ( model == "FIXED" ) return new FixedDemandModel(); else if ( model == "CONSTRAINED" ) return new ConstrainedDemandModel(); else if ( model == "POWER" ) return new PowerDemandModel(expon_); else if ( model == "LOGISTIC" ) return new LogisticDemandModel(expon_); else return nullptr; } //----------------------------------------------------------------------------- // Default functions //----------------------------------------------------------------------------- double DemandModel::findDemand(Junction* junc, double p, double& dqdh) { dqdh = 0.0; return junc->fullDemand; } //----------------------------------------------------------------------------- /// Fixed Demand Model //----------------------------------------------------------------------------- FixedDemandModel::FixedDemandModel() {} //----------------------------------------------------------------------------- /// Constrained Demand Model //----------------------------------------------------------------------------- ConstrainedDemandModel::ConstrainedDemandModel() {} bool ConstrainedDemandModel::isPressureDeficient(Junction* junc) { //if ( junc->fixedGrade || // ... return false if normal full demand is non-positive if (junc->fullDemand <= 0.0 ) return false; double hMin = junc->elev + junc->pMin; if ( junc->head < hMin ) { junc->fixedGrade = true; junc->head = hMin; return true; } return false; } double ConstrainedDemandModel::findDemand(Junction* junc, double p, double& dqdh) { dqdh = 0.0; return junc->actualDemand; } //----------------------------------------------------------------------------- /// Power Demand Model //----------------------------------------------------------------------------- PowerDemandModel::PowerDemandModel(double expon_) : DemandModel(expon_) {} double PowerDemandModel::findDemand(Junction* junc, double p, double& dqdh) { // ... initialize demand and demand derivative double qFull = junc->fullDemand; double q = qFull; dqdh = 0.0; // ... check for positive demand and pressure range double pRange = junc->pFull - junc->pMin; if ( qFull > 0.0 && pRange > 0.0) { // ... find fraction of full pressure met (f) double factor = 0.0; double f = (p - junc->pMin) / pRange; // ... apply power function if (f <= 0.0) factor = 0.0; else if (f >= 1.0) factor = 1.0; else { factor = pow(f, expon); dqdh = expon / pRange * factor / f; } // ... update total demand and its derivative q = qFull * factor; dqdh = qFull * dqdh; } return q; } //----------------------------------------------------------------------------- /// Logistic Demand Model //----------------------------------------------------------------------------- LogisticDemandModel::LogisticDemandModel(double expon_) : DemandModel(expon_), a(0.0), b(0.0) {} double LogisticDemandModel::findDemand(Junction* junc, double p, double& dqdh) { double f = 1.0; // fraction of full demand double q = junc->fullDemand; // demand flow (cfs) double arg; // argument of exponential term double dfdh; // gradient of f w.r.t. pressure head // ... initialize derivative dqdh = 0.0; // ... check for positive demand and pressure range if ( junc->fullDemand > 0.0 && junc->pFull > junc->pMin ) { // ... find logistic function coeffs. a & b setCoeffs(junc->pMin, junc->pFull); // ... prevent against numerical over/underflow arg = a + b*p; if (arg < -100.) arg = -100.0; else if (arg > 100.0) arg = 100.0; // ... find fraction of full demand (f) and its derivative (dfdh) f = exp(arg); f = f / (1.0 + f); f = max(0.0, min(1.0, f)); dfdh = b * f * (1.0 - f); // ... evaluate demand and its derivative q = junc->fullDemand * f; dqdh = junc->fullDemand * dfdh; } return q; } void LogisticDemandModel::setCoeffs(double pMin, double pFull) { // ... computes logistic function coefficients // assuming 99.9% of full demand at full pressure // and 1% of full demand at minimum pressure. double pRange = pFull - pMin; a = (-4.595 * pFull - 6.907 * pMin) / pRange; b = 11.502 / pRange; }
Java
// <osiris_sps_source_header> // This file is part of Osiris Serverless Portal System. // Copyright (C)2005-2012 Osiris Team (info@osiris-sps.org) / http://www.osiris-sps.org ) // // Osiris Serverless Portal System 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. // // Osiris Serverless Portal System 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 Osiris Serverless Portal System. If not, see <http://www.gnu.org/licenses/>. // </osiris_sps_source_header> #ifndef _OS_ENGINE_IDEPICKERCOMPONENT_H #define _OS_ENGINE_IDEPICKERCOMPONENT_H #include "ideportalcontrol.h" #include "idepickerselect.h" #include "entitiesentities.h" ////////////////////////////////////////////////////////////////////// OS_NAMESPACE_BEGIN() ////////////////////////////////////////////////////////////////////// class IExtensionsComponent; ////////////////////////////////////////////////////////////////////// class EngineExport IdePickerComponent : public IdePickerSelect { typedef IdePickerSelect ControlBase; // Construction public: IdePickerComponent(); virtual ~IdePickerComponent(); // Attributes public: // Events private: // Operations private: void addComponent(shared_ptr<IExtensionsComponent> component); // IControl interface public: virtual void onLoad(); virtual void onPreRender(); protected: }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// OS_NAMESPACE_END() ////////////////////////////////////////////////////////////////////// #endif // _OS_ENGINE_IDEPICKERCOMPONENT_H
Java
class AddVersionDone < ActiveRecord::Migration def up add_column :versions, :is_done, :boolean end def down remove_column :versions, :is_done end end
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hometask 7-8</title> <link rel="stylesheet" href="сss/reset.css"> <link rel="stylesheet" href="сss/style.css"> <link rel="stylesheet" media="screen and (min-width:0px) and (max-width:480px)" href="сss/style_320px.css" /> <link rel="stylesheet" media="screen and (min-width:480px) and (max-width:768px)" href="сss/style_480px.css" /> <link rel="stylesheet" media="screen and (min-width:768px) and (max-width:960px)" href="сss/style_768px.css" /> </head> <body> <div class="background background__top"> <header> <div class="wrapper top__bar"> <div class="logo"><img src="img/logo.png" alt="PINGBULLER"></div> <ul class="menu"> <li><a href="#" class="menu__item">HOME</a></li> <li><a href="#" class="menu__item">ABOUT</a></li> <li><a href="#" class="menu__item">BLOG</a></li> <li><a href="#" class="menu__item">PRODUCTS</a></li> <li><a href="#" class="menu__item">LOREM IPSUM</a></li> <li><a href="#" class="menu__item">DOLOR SIT AMET</a></li> </ul> </div> <div class="clearfix" style="clear: both;"></div> <div class="banner"> <div class="banner__inner"> <div class="wrapper banner_content"> <div class="iphone"><img src="img/iphone.png" alt=""></div> <div class="content_text"> <h1>Lorem Ipsum Dolor</h1> <h3>IT WILL MAKE ALL OF YOUR DREAMS COME <span class="invisible invisible_320">TRUE</span></h3> <p>Semper sollicitudin gravida eget, vestibulum sit amet sapien. Nunc dignissim tincidunt est, et auctor turpis ornare a. Nam venenatis hendrerit est <span class="invisible">at volutpat. Morbi elementum euismod lacus id semper. In odio nunc, imperdiet eget aliquam quis, euismod id lectus. Nulla interdum arcu et felis aliquam a tempus lectus lobortis.</span></p> </div> <div class="arrows"> <div class="arrow__right"><a href="#"><img src="img/arrow_r.png" alt=""></a></div> <div class="arrow__left"><a href="#"><img src="img/arrow_l.png" alt=""></a></div> </div> <div class="slider_circles"> <a href="#" class="circle"></a> <a href="#" class="circle"></a> <a href="#" class="circle"></a> <a href="#" class="circle"></a> </div> </div> </div> </div> </header> </div> <div class="background background__articles"> <div class="wrapper articles"> <div class="articles__item"> <div class="sprite icon__1"></div> <h2>ABOUT OUR COMPANY</h2> <p>Nunc turpis neque, feugiat eget eleifend et, lacinia non neque. Praesent rhoncus<span class="invisible_320"> ultrices posuere. Pellentesque vel lacus <span class="invisible"> eget nisi convallis auctor. Nam</span></span></p> <a href="#">READ MORE</a> </div> <div class="articles__item"> <div class="sprite icon__2"></div> <h2>ABOUT OUR COMPANY</h2> <p>Nunc turpis neque, feugiat eget eleifend et, lacinia non neque. Praesent rhoncus<span class="invisible_320"> ultrices posuere. Pellentesque vel lacus <span class="invisible"> eget nisi convallis auctor. Nam</span></span></p> <a href="#">READ MORE</a> </div> <div class="articles__item"> <div class="sprite icon__3"></div> <h2>ABOUT OUR COMPANY</h2> <p>Nunc turpis neque, feugiat eget eleifend et, lacinia non neque. Praesent rhoncus<span class="invisible_320"> ultrices posuere. Pellentesque vel lacus <span class="invisible"> eget nisi convallis auctor. Nam</span></span></p> <a href="#">READ MORE</a> </div> </div> </div> <div class="background background__content"> <div class="wrapper content"> <div class="starts_back"> <div class="starts_content"> <img src="img/muzgik.png" alt="Какой-то мужик"> <h2>PINGBULLER <span>STARTS HERE</span></h2> <p>“Nunc turpis neque, feugiat eget eleifend et, lacinia non neque. Praesent rhoncus ultrices po- suere. Pellentesque vel lacus eget nisi convallis auctor. Nam vitae<span class="invisible_320"> lectus eu libero pellentesque pulvinar<span class="invisible"> urna risus, mattis pulvinar bibendum in, venenatis quis neque. Mauris nec metus ultricies erat consequat dignissim non eu nisl.”</span></span></p> </div> <div class="starts_circles"> <a href="#" class="circle"></a> <a href="#" class="circle"></a> <a href="#" class="circle"></a> <a href="#" class="circle"></a> </div> </div> <div class="updates"> <h2>RECENT UPDATES</h2> <div class="updates__item update1"> <h4>Nunc turpis neque<span class="invisible_320"> feugiat eget </span></h4> <p>Posted by Admin on March 13<span class="invisible_320"> 2012 <span class="invisible">in Recent News</span></span></p> </div> <div class="updates__item update2"> <h4>Nunc turpis neque <span class="invisible_320"> feugiat eget </span></h4> <p>Posted by Admin on March 13<span class="invisible_320"> 2012<span class="invisible"> in Category</span></span></p> </div> <div class="updates__item update3"> <h4>Nunc turpis neque <span class="invisible_320"> feugiat eget </span></h4> <p>Posted by Admin on March 13<span class="invisible_320"> 2012<span class="invisible"> in Blog Updates</span></span></p> </div> <a href="">READ MORE HERE</a> </div> </div> </div> <div class="background background_logos"> <div class="wrapper logos"> </div> </div> <div class="background content__bottom_background"> <div class="wrapper content__bottom"> <div class="content__bottom_item pigbull"> <h2>PIGBULL<span>ER</span></h2> <div class="copyright">Copyright 2013, Pingbull AS</div> <div class="visible"> <h3>NEWS CATEGORIES</h3> <p class="">Nunc turpis neque, feugiat eget eleifend et, lacinia non neque. Praesent rhoncus ultrices posuere. Pellentesque vel lacus eget nisi convallis auctor. Nam vitae lectus eu libero pellentesque <span class="invisible"> pulvinar. Quisque urna risus, mattis pulvinar bibendum in, venenatis quis</span></p> </div> <div class="invisible"><p>Nunc turpis neque, feugiat eget eleifend et, lacinia non neque. Praesent rhoncus ultrices posuere. Pellentesque vel lacus eget nisi convallis auctor. Nam vitae lectus eu libero pellentesque pul</p></div> </div> <div class="content__bottom_item"> <h3>RECENT COMMENTS</h3> <p class="">Nunc turpis neque, feugiat eget eleifend et, lacinia non neque. Praesent rhoncus ultrices posuere. Pellentesque vel lacus eget nisi convallis auctor. Nam vitae lectus eu libero pellentesque <span class="invisible"> pulvinar. Quisque urna risus, mattis pulvinar bibendum in, venenatis quis</span></p> </div> <div class="content__bottom_item"> <h3>NEWS CATEGORIES</h3> <p class="">Nunc turpis neque, feugiat eget eleifend et, lacinia non neque. Praesent rhoncus ultrices posuere. Pellentesque vel lacus eget nisi convallis auctor. Nam vitae lectus eu libero pellentesque <span class="invisible"> pulvinar. Quisque urna risus, mattis pulvinar bibendum in, venenatis quis</span></p> </div> </div> </div> <div class="background footer__background"> <div class="wrapper footer"> <div class="footer_menu"> <a href="#" class="footer_menu__item">HOME</a> <a href="#" class="footer_menu__item">ABOUT</a> <a href="#" class="footer_menu__item">BLOG</a> <a href="#" class="footer_menu__item">PRODUCTS</a> <a href="#" class="footer_menu__item">LOREM IPSUM</a> <a href="#" class="footer_menu__item">DOLOR SIT AMET</a> </div> <div class="design"> <p>Designed by <span>Pingbull AS</span></p> </div> </div> </div> </body> </html>
Java
var struct_m_s_vehicle_1_1_lane_q = [ [ "allowsContinuation", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a1491a03d3e914ce9f78fe892c6f8594b", null ], [ "bestContinuations", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a2fc7b1df76210eff08026dbd53c13312", null ], [ "bestLaneOffset", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#aa7f926a77c7d33c071c620ae7e9d0ac1", null ], [ "lane", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a3df6bd9b94a7e3e4795547feddf68bf2", null ], [ "length", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a637a05a2b120bacaf781181febc5b3bb", null ], [ "nextOccupation", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#acf8243e1febeb75b139a8b10bb679107", null ], [ "occupation", "d3/d89/struct_m_s_vehicle_1_1_lane_q.html#a51e793a9c0bfda3e315c62f579089f82", null ] ];
Java
############################################################################## # Build global options # NOTE: Can be overridden externally. # # Compiler options here. ifeq ($(USE_OPT),) USE_OPT = -O2 -ggdb -fomit-frame-pointer -falign-functions=16 endif # C specific options here (added to USE_OPT). ifeq ($(USE_COPT),) USE_COPT = endif # C++ specific options here (added to USE_OPT). ifeq ($(USE_CPPOPT),) USE_CPPOPT = -fno-rtti endif # Enable this if you want the linker to remove unused code and data ifeq ($(USE_LINK_GC),) USE_LINK_GC = yes endif # Linker extra options here. ifeq ($(USE_LDOPT),) USE_LDOPT = endif # Enable this if you want link time optimizations (LTO) ifeq ($(USE_LTO),) USE_LTO = yes endif # If enabled, this option allows to compile the application in THUMB mode. ifeq ($(USE_THUMB),) USE_THUMB = yes endif # Enable this if you want to see the full log while compiling. ifeq ($(USE_VERBOSE_COMPILE),) USE_VERBOSE_COMPILE = no endif # If enabled, this option makes the build process faster by not compiling # modules not used in the current configuration. ifeq ($(USE_SMART_BUILD),) USE_SMART_BUILD = yes endif # # Build global options ############################################################################## ############################################################################## # Architecture or project specific options # # Stack size to be allocated to the Cortex-M process stack. This stack is # the stack used by the main() thread. ifeq ($(USE_PROCESS_STACKSIZE),) USE_PROCESS_STACKSIZE = 0x400 endif # Stack size to the allocated to the Cortex-M main/exceptions stack. This # stack is used for processing interrupts and exceptions. ifeq ($(USE_EXCEPTIONS_STACKSIZE),) USE_EXCEPTIONS_STACKSIZE = 0x400 endif # Enables the use of FPU (no, softfp, hard). ifeq ($(USE_FPU),) USE_FPU = no endif # # Architecture or project specific options ############################################################################## ############################################################################## # Project, sources and paths # # Define project name here PROJECT = ch # Imported source files and paths CHIBIOS = ../../../.. # Startup files. include $(CHIBIOS)/os/common/startup/ARMCMx/compilers/GCC/mk/startup_stm32f3xx.mk # HAL-OSAL files (optional). include $(CHIBIOS)/os/hal/hal.mk include $(CHIBIOS)/os/hal/ports/STM32/STM32F37x/platform.mk include $(CHIBIOS)/os/hal/boards/ST_STM32373C_EVAL/board.mk include $(CHIBIOS)/os/hal/osal/rt/osal.mk # RTOS files (optional). include $(CHIBIOS)/os/rt/rt.mk include $(CHIBIOS)/os/common/ports/ARMCMx/compilers/GCC/mk/port_v7m.mk # Other files (optional). include $(CHIBIOS)/test/lib/test.mk include $(CHIBIOS)/test/rt/rt_test.mk include $(CHIBIOS)/test/oslib/oslib_test.mk include $(CHIBIOS)/os/hal/lib/streams/streams.mk include $(CHIBIOS)/os/various/shell/shell.mk # Define linker script file here LDSCRIPT= $(STARTUPLD)/STM32F373xC.ld # C sources that can be compiled in ARM or THUMB mode depending on the global # setting. CSRC = $(STARTUPSRC) \ $(KERNSRC) \ $(PORTSRC) \ $(OSALSRC) \ $(HALSRC) \ $(PLATFORMSRC) \ $(BOARDSRC) \ $(TESTSRC) \ $(STREAMSSRC) \ $(SHELLSRC) \ usbcfg.c main.c # C++ sources that can be compiled in ARM or THUMB mode depending on the global # setting. CPPSRC = # C sources to be compiled in ARM mode regardless of the global setting. # NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler # option that results in lower performance and larger code size. ACSRC = # C++ sources to be compiled in ARM mode regardless of the global setting. # NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler # option that results in lower performance and larger code size. ACPPSRC = # C sources to be compiled in THUMB mode regardless of the global setting. # NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler # option that results in lower performance and larger code size. TCSRC = # C sources to be compiled in THUMB mode regardless of the global setting. # NOTE: Mixing ARM and THUMB mode enables the -mthumb-interwork compiler # option that results in lower performance and larger code size. TCPPSRC = # List ASM source files here ASMSRC = ASMXSRC = $(STARTUPASM) $(PORTASM) $(OSALASM) INCDIR = $(CHIBIOS)/os/license \ $(STARTUPINC) $(KERNINC) $(PORTINC) $(OSALINC) \ $(HALINC) $(PLATFORMINC) $(BOARDINC) $(TESTINC) \ $(STREAMSINC) $(SHELLINC) # # Project, sources and paths ############################################################################## ############################################################################## # Compiler settings # MCU = cortex-m4 #TRGT = arm-elf- TRGT = arm-none-eabi- CC = $(TRGT)gcc CPPC = $(TRGT)g++ # Enable loading with g++ only if you need C++ runtime support. # NOTE: You can use C++ even without C++ support if you are careful. C++ # runtime support makes code size explode. LD = $(TRGT)gcc #LD = $(TRGT)g++ CP = $(TRGT)objcopy AS = $(TRGT)gcc -x assembler-with-cpp AR = $(TRGT)ar OD = $(TRGT)objdump SZ = $(TRGT)size HEX = $(CP) -O ihex BIN = $(CP) -O binary # ARM-specific options here AOPT = # THUMB-specific options here TOPT = -mthumb -DTHUMB # Define C warning options here CWARN = -Wall -Wextra -Wundef -Wstrict-prototypes # Define C++ warning options here CPPWARN = -Wall -Wextra -Wundef # # Compiler settings ############################################################################## ############################################################################## # Start of user section # # List all user C define here, like -D_DEBUG=1 UDEFS = # Define ASM defines here UADEFS = # List all user directories here UINCDIR = # List the user directory to look for the libraries here ULIBDIR = # List all user libraries here ULIBS = # # End of user defines ############################################################################## RULESPATH = $(CHIBIOS)/os/common/startup/ARMCMx/compilers/GCC include $(RULESPATH)/rules.mk
Java
/*------------------------------------------------------------------------- * * wparser.c * Standard interface to word parser * * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group * * * IDENTIFICATION * src/backend/tsearch/wparser.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include "funcapi.h" #include "catalog/namespace.h" #include "catalog/pg_type.h" #include "commands/defrem.h" #include "tsearch/ts_cache.h" #include "tsearch/ts_utils.h" #include "utils/builtins.h" #include "utils/jsonapi.h" #include "utils/varlena.h" /******sql-level interface******/ typedef struct { int cur; LexDescr *list; } TSTokenTypeStorage; /* state for ts_headline_json_* */ typedef struct HeadlineJsonState { HeadlineParsedText *prs; TSConfigCacheEntry *cfg; TSParserCacheEntry *prsobj; TSQuery query; List *prsoptions; bool transformed; } HeadlineJsonState; static text *headline_json_value(void *_state, char *elem_value, int elem_len); static void tt_setup_firstcall(FuncCallContext *funcctx, Oid prsid) { TupleDesc tupdesc; MemoryContext oldcontext; TSTokenTypeStorage *st; TSParserCacheEntry *prs = lookup_ts_parser_cache(prsid); if (!OidIsValid(prs->lextypeOid)) elog(ERROR, "method lextype isn't defined for text search parser %u", prsid); oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); st = (TSTokenTypeStorage *) palloc(sizeof(TSTokenTypeStorage)); st->cur = 0; /* lextype takes one dummy argument */ st->list = (LexDescr *) DatumGetPointer(OidFunctionCall1(prs->lextypeOid, (Datum) 0)); funcctx->user_fctx = (void *) st; tupdesc = CreateTemplateTupleDesc(3, false); TupleDescInitEntry(tupdesc, (AttrNumber) 1, "tokid", INT4OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber) 2, "alias", TEXTOID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber) 3, "description", TEXTOID, -1, 0); funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc); MemoryContextSwitchTo(oldcontext); } static Datum tt_process_call(FuncCallContext *funcctx) { TSTokenTypeStorage *st; st = (TSTokenTypeStorage *) funcctx->user_fctx; if (st->list && st->list[st->cur].lexid) { Datum result; char *values[3]; char txtid[16]; HeapTuple tuple; sprintf(txtid, "%d", st->list[st->cur].lexid); values[0] = txtid; values[1] = st->list[st->cur].alias; values[2] = st->list[st->cur].descr; tuple = BuildTupleFromCStrings(funcctx->attinmeta, values); result = HeapTupleGetDatum(tuple); pfree(values[1]); pfree(values[2]); st->cur++; return result; } if (st->list) pfree(st->list); pfree(st); return (Datum) 0; } Datum ts_token_type_byid(PG_FUNCTION_ARGS) { FuncCallContext *funcctx; Datum result; if (SRF_IS_FIRSTCALL()) { funcctx = SRF_FIRSTCALL_INIT(); tt_setup_firstcall(funcctx, PG_GETARG_OID(0)); } funcctx = SRF_PERCALL_SETUP(); if ((result = tt_process_call(funcctx)) != (Datum) 0) SRF_RETURN_NEXT(funcctx, result); SRF_RETURN_DONE(funcctx); } Datum ts_token_type_byname(PG_FUNCTION_ARGS) { FuncCallContext *funcctx; Datum result; if (SRF_IS_FIRSTCALL()) { text *prsname = PG_GETARG_TEXT_PP(0); Oid prsId; funcctx = SRF_FIRSTCALL_INIT(); prsId = get_ts_parser_oid(textToQualifiedNameList(prsname), false); tt_setup_firstcall(funcctx, prsId); } funcctx = SRF_PERCALL_SETUP(); if ((result = tt_process_call(funcctx)) != (Datum) 0) SRF_RETURN_NEXT(funcctx, result); SRF_RETURN_DONE(funcctx); } typedef struct { int type; char *lexeme; } LexemeEntry; typedef struct { int cur; int len; LexemeEntry *list; } PrsStorage; static void prs_setup_firstcall(FuncCallContext *funcctx, Oid prsid, text *txt) { TupleDesc tupdesc; MemoryContext oldcontext; PrsStorage *st; TSParserCacheEntry *prs = lookup_ts_parser_cache(prsid); char *lex = NULL; int llen = 0, type = 0; void *prsdata; oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); st = (PrsStorage *) palloc(sizeof(PrsStorage)); st->cur = 0; st->len = 16; st->list = (LexemeEntry *) palloc(sizeof(LexemeEntry) * st->len); prsdata = (void *) DatumGetPointer(FunctionCall2(&prs->prsstart, PointerGetDatum(VARDATA_ANY(txt)), Int32GetDatum(VARSIZE_ANY_EXHDR(txt)))); while ((type = DatumGetInt32(FunctionCall3(&prs->prstoken, PointerGetDatum(prsdata), PointerGetDatum(&lex), PointerGetDatum(&llen)))) != 0) { if (st->cur >= st->len) { st->len = 2 * st->len; st->list = (LexemeEntry *) repalloc(st->list, sizeof(LexemeEntry) * st->len); } st->list[st->cur].lexeme = palloc(llen + 1); memcpy(st->list[st->cur].lexeme, lex, llen); st->list[st->cur].lexeme[llen] = '\0'; st->list[st->cur].type = type; st->cur++; } FunctionCall1(&prs->prsend, PointerGetDatum(prsdata)); st->len = st->cur; st->cur = 0; funcctx->user_fctx = (void *) st; tupdesc = CreateTemplateTupleDesc(2, false); TupleDescInitEntry(tupdesc, (AttrNumber) 1, "tokid", INT4OID, -1, 0); TupleDescInitEntry(tupdesc, (AttrNumber) 2, "token", TEXTOID, -1, 0); funcctx->attinmeta = TupleDescGetAttInMetadata(tupdesc); MemoryContextSwitchTo(oldcontext); } static Datum prs_process_call(FuncCallContext *funcctx) { PrsStorage *st; st = (PrsStorage *) funcctx->user_fctx; if (st->cur < st->len) { Datum result; char *values[2]; char tid[16]; HeapTuple tuple; values[0] = tid; sprintf(tid, "%d", st->list[st->cur].type); values[1] = st->list[st->cur].lexeme; tuple = BuildTupleFromCStrings(funcctx->attinmeta, values); result = HeapTupleGetDatum(tuple); pfree(values[1]); st->cur++; return result; } else { if (st->list) pfree(st->list); pfree(st); } return (Datum) 0; } Datum ts_parse_byid(PG_FUNCTION_ARGS) { FuncCallContext *funcctx; Datum result; if (SRF_IS_FIRSTCALL()) { text *txt = PG_GETARG_TEXT_PP(1); funcctx = SRF_FIRSTCALL_INIT(); prs_setup_firstcall(funcctx, PG_GETARG_OID(0), txt); PG_FREE_IF_COPY(txt, 1); } funcctx = SRF_PERCALL_SETUP(); if ((result = prs_process_call(funcctx)) != (Datum) 0) SRF_RETURN_NEXT(funcctx, result); SRF_RETURN_DONE(funcctx); } Datum ts_parse_byname(PG_FUNCTION_ARGS) { FuncCallContext *funcctx; Datum result; if (SRF_IS_FIRSTCALL()) { text *prsname = PG_GETARG_TEXT_PP(0); text *txt = PG_GETARG_TEXT_PP(1); Oid prsId; funcctx = SRF_FIRSTCALL_INIT(); prsId = get_ts_parser_oid(textToQualifiedNameList(prsname), false); prs_setup_firstcall(funcctx, prsId, txt); } funcctx = SRF_PERCALL_SETUP(); if ((result = prs_process_call(funcctx)) != (Datum) 0) SRF_RETURN_NEXT(funcctx, result); SRF_RETURN_DONE(funcctx); } Datum ts_headline_byid_opt(PG_FUNCTION_ARGS) { Oid tsconfig = PG_GETARG_OID(0); text *in = PG_GETARG_TEXT_PP(1); TSQuery query = PG_GETARG_TSQUERY(2); text *opt = (PG_NARGS() > 3 && PG_GETARG_POINTER(3)) ? PG_GETARG_TEXT_PP(3) : NULL; HeadlineParsedText prs; List *prsoptions; text *out; TSConfigCacheEntry *cfg; TSParserCacheEntry *prsobj; cfg = lookup_ts_config_cache(tsconfig); prsobj = lookup_ts_parser_cache(cfg->prsId); if (!OidIsValid(prsobj->headlineOid)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("text search parser does not support headline creation"))); memset(&prs, 0, sizeof(HeadlineParsedText)); prs.lenwords = 32; prs.words = (HeadlineWordEntry *) palloc(sizeof(HeadlineWordEntry) * prs.lenwords); hlparsetext(cfg->cfgId, &prs, query, VARDATA_ANY(in), VARSIZE_ANY_EXHDR(in)); if (opt) prsoptions = deserialize_deflist(PointerGetDatum(opt)); else prsoptions = NIL; FunctionCall3(&(prsobj->prsheadline), PointerGetDatum(&prs), PointerGetDatum(prsoptions), PointerGetDatum(query)); out = generateHeadline(&prs); PG_FREE_IF_COPY(in, 1); PG_FREE_IF_COPY(query, 2); if (opt) PG_FREE_IF_COPY(opt, 3); pfree(prs.words); pfree(prs.startsel); pfree(prs.stopsel); PG_RETURN_POINTER(out); } Datum ts_headline_byid(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall3(ts_headline_byid_opt, PG_GETARG_DATUM(0), PG_GETARG_DATUM(1), PG_GETARG_DATUM(2))); } Datum ts_headline(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall3(ts_headline_byid_opt, ObjectIdGetDatum(getTSCurrentConfig(true)), PG_GETARG_DATUM(0), PG_GETARG_DATUM(1))); } Datum ts_headline_opt(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall4(ts_headline_byid_opt, ObjectIdGetDatum(getTSCurrentConfig(true)), PG_GETARG_DATUM(0), PG_GETARG_DATUM(1), PG_GETARG_DATUM(2))); } Datum ts_headline_jsonb_byid_opt(PG_FUNCTION_ARGS) { Oid tsconfig = PG_GETARG_OID(0); Jsonb *jb = PG_GETARG_JSONB_P(1); TSQuery query = PG_GETARG_TSQUERY(2); text *opt = (PG_NARGS() > 3 && PG_GETARG_POINTER(3)) ? PG_GETARG_TEXT_P(3) : NULL; Jsonb *out; JsonTransformStringValuesAction action = (JsonTransformStringValuesAction) headline_json_value; HeadlineParsedText prs; HeadlineJsonState *state = palloc0(sizeof(HeadlineJsonState)); memset(&prs, 0, sizeof(HeadlineParsedText)); prs.lenwords = 32; prs.words = (HeadlineWordEntry *) palloc(sizeof(HeadlineWordEntry) * prs.lenwords); state->prs = &prs; state->cfg = lookup_ts_config_cache(tsconfig); state->prsobj = lookup_ts_parser_cache(state->cfg->prsId); state->query = query; if (opt) state->prsoptions = deserialize_deflist(PointerGetDatum(opt)); else state->prsoptions = NIL; if (!OidIsValid(state->prsobj->headlineOid)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("text search parser does not support headline creation"))); out = transform_jsonb_string_values(jb, state, action); PG_FREE_IF_COPY(jb, 1); PG_FREE_IF_COPY(query, 2); if (opt) PG_FREE_IF_COPY(opt, 3); pfree(prs.words); if (state->transformed) { pfree(prs.startsel); pfree(prs.stopsel); } PG_RETURN_JSONB_P(out); } Datum ts_headline_jsonb(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall3(ts_headline_jsonb_byid_opt, ObjectIdGetDatum(getTSCurrentConfig(true)), PG_GETARG_DATUM(0), PG_GETARG_DATUM(1))); } Datum ts_headline_jsonb_byid(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall3(ts_headline_jsonb_byid_opt, PG_GETARG_DATUM(0), PG_GETARG_DATUM(1), PG_GETARG_DATUM(2))); } Datum ts_headline_jsonb_opt(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall4(ts_headline_jsonb_byid_opt, ObjectIdGetDatum(getTSCurrentConfig(true)), PG_GETARG_DATUM(0), PG_GETARG_DATUM(1), PG_GETARG_DATUM(2))); } Datum ts_headline_json_byid_opt(PG_FUNCTION_ARGS) { Oid tsconfig = PG_GETARG_OID(0); text *json = PG_GETARG_TEXT_P(1); TSQuery query = PG_GETARG_TSQUERY(2); text *opt = (PG_NARGS() > 3 && PG_GETARG_POINTER(3)) ? PG_GETARG_TEXT_P(3) : NULL; text *out; JsonTransformStringValuesAction action = (JsonTransformStringValuesAction) headline_json_value; HeadlineParsedText prs; HeadlineJsonState *state = palloc0(sizeof(HeadlineJsonState)); memset(&prs, 0, sizeof(HeadlineParsedText)); prs.lenwords = 32; prs.words = (HeadlineWordEntry *) palloc(sizeof(HeadlineWordEntry) * prs.lenwords); state->prs = &prs; state->cfg = lookup_ts_config_cache(tsconfig); state->prsobj = lookup_ts_parser_cache(state->cfg->prsId); state->query = query; if (opt) state->prsoptions = deserialize_deflist(PointerGetDatum(opt)); else state->prsoptions = NIL; if (!OidIsValid(state->prsobj->headlineOid)) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("text search parser does not support headline creation"))); out = transform_json_string_values(json, state, action); PG_FREE_IF_COPY(json, 1); PG_FREE_IF_COPY(query, 2); if (opt) PG_FREE_IF_COPY(opt, 3); pfree(prs.words); if (state->transformed) { pfree(prs.startsel); pfree(prs.stopsel); } PG_RETURN_TEXT_P(out); } Datum ts_headline_json(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall3(ts_headline_json_byid_opt, ObjectIdGetDatum(getTSCurrentConfig(true)), PG_GETARG_DATUM(0), PG_GETARG_DATUM(1))); } Datum ts_headline_json_byid(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall3(ts_headline_json_byid_opt, PG_GETARG_DATUM(0), PG_GETARG_DATUM(1), PG_GETARG_DATUM(2))); } Datum ts_headline_json_opt(PG_FUNCTION_ARGS) { PG_RETURN_DATUM(DirectFunctionCall4(ts_headline_json_byid_opt, ObjectIdGetDatum(getTSCurrentConfig(true)), PG_GETARG_DATUM(0), PG_GETARG_DATUM(1), PG_GETARG_DATUM(2))); } /* * Return headline in text from, generated from a json(b) element */ static text * headline_json_value(void *_state, char *elem_value, int elem_len) { HeadlineJsonState *state = (HeadlineJsonState *) _state; HeadlineParsedText *prs = state->prs; TSConfigCacheEntry *cfg = state->cfg; TSParserCacheEntry *prsobj = state->prsobj; TSQuery query = state->query; List *prsoptions = state->prsoptions; prs->curwords = 0; hlparsetext(cfg->cfgId, prs, query, elem_value, elem_len); FunctionCall3(&(prsobj->prsheadline), PointerGetDatum(prs), PointerGetDatum(prsoptions), PointerGetDatum(query)); state->transformed = true; return generateHeadline(prs); }
Java
/* * This file is part of JGCGen. * * JGCGen 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. * * JGCGen 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 JGCGen. If not, see <http://www.gnu.org/licenses/>. */ package org.luolamies.jgcgen.text; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import org.luolamies.jgcgen.RenderException; public class Fonts { private final File workdir; public Fonts(File workdir) { this.workdir = workdir; } public Font get(String name) { String type; if(name.endsWith(".jhf")) type = "Hershey"; else throw new RenderException("Can't figure out font type from filename! Use $fonts.get(\"file\", \"type\")"); return get(name, type); } @SuppressWarnings("unchecked") public Font get(String name, String type) { Class<? extends Font> fclass; try { fclass = (Class<? extends Font>) Class.forName(getClass().getPackage().getName() + "." + type + "Font"); } catch (ClassNotFoundException e1) { throw new RenderException("Font type \"" + type + "\" not supported!"); } InputStream in; File file = new File(workdir, name); if(file.isFile()) { try { in = new FileInputStream(file); } catch (FileNotFoundException e) { in = null; } } else in = getClass().getResourceAsStream("/fonts/" + name); if(in==null) throw new RenderException("Can't find font: " + name); try { return fclass.getConstructor(InputStream.class).newInstance(in); } catch(Exception e) { throw new RenderException("Error while trying to construct handler for font \"" + type + "\": " + e.getMessage(), e); } finally { try { in.close(); } catch (IOException e) { } } } }
Java
#!/bin/bash -f # Vivado (TM) v2015.4.2 (64-bit) # # Filename : design_TEST.sh # Simulator : Cadence Incisive Enterprise Simulator # Description : Simulation script for compiling, elaborating and verifying the project source files. # The script will automatically create the design libraries sub-directories in the run # directory, add the library logical mappings in the simulator setup file, create default # 'do/prj' file, execute compilation, elaboration and simulation steps. # # Generated by Vivado on Thu Sep 01 17:23:17 +0200 2016 # IP Build 1491208 on Wed Feb 24 03:25:39 MST 2016 # # usage: design_TEST.sh [-help] # usage: design_TEST.sh [-lib_map_path] # usage: design_TEST.sh [-noclean_files] # usage: design_TEST.sh [-reset_run] # # Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the # 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the # Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch # that points to these libraries and rerun export_simulation. For more information about this switch please # type 'export_simulation -help' in the Tcl shell. # # You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this # script with the compiled library directory path or specify this path with the '-lib_map_path' switch when # executing this script. Please type 'design_TEST.sh -help' for more information. # # Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)' # # ******************************************************************************************************** # Script info echo -e "design_TEST.sh - Script generated by export_simulation (Vivado v2015.4.2 (64-bit)-id)\n" # Script usage usage() { msg="Usage: design_TEST.sh [-help]\n\ Usage: design_TEST.sh [-lib_map_path]\n\ Usage: design_TEST.sh [-reset_run]\n\ Usage: design_TEST.sh [-noclean_files]\n\n\ [-help] -- Print help information for this script\n\n\ [-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\n\ using the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\n\n\ [-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\n\ from the previous run will be removed. If you don't want to remove the simulator generated files, use the\n\ -noclean_files switch.\n\n\ [-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\n\n" echo -e $msg exit 1 } if [[ ($# == 1 ) && ($1 != "-lib_map_path" && $1 != "-noclean_files" && $1 != "-reset_run" && $1 != "-help" && $1 != "-h") ]]; then echo -e "ERROR: Unknown option specified '$1' (type \"./design_TEST.sh -help\" for more information)\n" exit 1 fi if [[ ($1 == "-help" || $1 == "-h") ]]; then usage fi # STEP: setup setup() { case $1 in "-lib_map_path" ) if [[ ($2 == "") ]]; then echo -e "ERROR: Simulation library directory path not specified (type \"./design_TEST.sh -help\" for more information)\n" exit 1 fi # precompiled simulation library directory path create_lib_mappings $2 touch hdl.var ;; "-reset_run" ) reset_run echo -e "INFO: Simulation run files deleted.\n" exit 0 ;; "-noclean_files" ) # do not remove previous data ;; * ) create_lib_mappings $2 touch hdl.var esac # Add any setup/initialization commands here:- # <user specific commands> } # Remove generated data from the previous run and re-create setup files/library mappings reset_run() { files_to_remove=(ncsim.key irun.key ncvlog.log ncvhdl.log compile.log elaborate.log simulate.log run.log waves.shm INCA_libs) for (( i=0; i<${#files_to_remove[*]}; i++ )); do file="${files_to_remove[i]}" if [[ -e $file ]]; then rm -rf $file fi done } # Main steps run() { setup $1 $2 compile elaborate simulate } # Create design library directory paths and define design library mappings in cds.lib create_lib_mappings() { libs=(xil_defaultlib lib_pkg_v1_0_2 fifo_generator_v13_0_1 lib_fifo_v1_0_4 lib_srl_fifo_v1_0_2 lib_cdc_v1_0_2 axi_datamover_v5_1_9 axi_sg_v4_1_2 axi_dma_v7_1_8 proc_sys_reset_v5_0_8 generic_baseblocks_v2_1_0 axi_infrastructure_v1_1_0 axi_register_slice_v2_1_7 axi_data_fifo_v2_1_6 axi_crossbar_v2_1_8 axi_protocol_converter_v2_1_7) file="cds.lib" dir="ies" if [[ -e $file ]]; then rm -f $file fi if [[ -e $dir ]]; then rm -rf $dir fi touch $file lib_map_path="<SPECIFY_COMPILED_LIB_PATH>" if [[ ($1 != "" && -e $1) ]]; then lib_map_path="$1" else echo -e "ERROR: Compiled simulation library directory path not specified or does not exist (type "./top.sh -help" for more information)\n" fi incl_ref="INCLUDE $lib_map_path/cds.lib" echo $incl_ref >> $file for (( i=0; i<${#libs[*]}; i++ )); do lib="${libs[i]}" lib_dir="$dir/$lib" if [[ ! -e $lib_dir ]]; then mkdir -p $lib_dir mapping="DEFINE $lib $dir/$lib" echo $mapping >> $file fi done } # RUN_STEP: <compile> compile() { # Directory path for design sources and include directories (if any) wrt this path ref_dir="." # Command line options opts_ver="-64bit -messages -logfile ncvlog.log -append_log" opts_vhd="-64bit -V93 -RELAX -logfile ncvhdl.log -append_log" # Compile design files ncvlog -work xil_defaultlib $opts_ver +incdir+"$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_arb_wr.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_arb_rd.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_arb_wr_4.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_arb_rd_4.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_arb_hp2_3.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_arb_hp0_1.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_ssw_hp.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_sparse_mem.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_reg_map.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_ocm_mem.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_intr_wr_mem.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_intr_rd_mem.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_fmsw_gp.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_regc.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_ocmc.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_interconnect_model.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_gen_reset.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_gen_clock.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_ddrc.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_axi_slave.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_axi_master.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_afi_slave.v" \ "$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl/processing_system7_bfm_v2_0_processing_system7_bfm.v" \ "$ref_dir/../../../bd/design_TEST/ip/design_TEST_processing_system7_0_0/sim/design_TEST_processing_system7_0_0.v" \ ncvhdl -work lib_pkg_v1_0_2 $opts_vhd \ "$ref_dir/../../../ipstatic/lib_pkg_v1_0/hdl/src/vhdl/lib_pkg.vhd" \ ncvhdl -work fifo_generator_v13_0_1 $opts_vhd \ "$ref_dir/../../../ipstatic/fifo_generator_v13_0/simulation/fifo_generator_vhdl_beh.vhd" \ "$ref_dir/../../../ipstatic/fifo_generator_v13_0/hdl/fifo_generator_v13_0_rfs.vhd" \ ncvhdl -work lib_fifo_v1_0_4 $opts_vhd \ "$ref_dir/../../../ipstatic/lib_fifo_v1_0/hdl/src/vhdl/async_fifo_fg.vhd" \ "$ref_dir/../../../ipstatic/lib_fifo_v1_0/hdl/src/vhdl/sync_fifo_fg.vhd" \ ncvhdl -work lib_srl_fifo_v1_0_2 $opts_vhd \ "$ref_dir/../../../ipstatic/lib_srl_fifo_v1_0/hdl/src/vhdl/cntr_incr_decr_addn_f.vhd" \ "$ref_dir/../../../ipstatic/lib_srl_fifo_v1_0/hdl/src/vhdl/dynshreg_f.vhd" \ "$ref_dir/../../../ipstatic/lib_srl_fifo_v1_0/hdl/src/vhdl/srl_fifo_rbu_f.vhd" \ "$ref_dir/../../../ipstatic/lib_srl_fifo_v1_0/hdl/src/vhdl/srl_fifo_f.vhd" \ ncvhdl -work lib_cdc_v1_0_2 $opts_vhd \ "$ref_dir/../../../ipstatic/lib_cdc_v1_0/hdl/src/vhdl/cdc_sync.vhd" \ ncvhdl -work axi_datamover_v5_1_9 $opts_vhd \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_reset.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_afifo_autord.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_sfifo_autord.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_fifo.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_cmd_status.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_scc.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_strb_gen2.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_pcc.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_addr_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_rdmux.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_rddata_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_rd_status_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_wr_demux.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_wrdata_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_wr_status_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_skid2mm_buf.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_skid_buf.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_rd_sf.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_wr_sf.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_stbs_set.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_stbs_set_nodre.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_ibttcc.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_indet_btt.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_dre_mux2_1_x_n.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_dre_mux4_1_x_n.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_dre_mux8_1_x_n.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_mm2s_dre.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_s2mm_dre.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_ms_strb_set.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_mssai_skid_buf.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_slice.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_s2mm_scatter.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_s2mm_realign.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_s2mm_basic_wrap.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_s2mm_omit_wrap.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_s2mm_full_wrap.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_mm2s_basic_wrap.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_mm2s_omit_wrap.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover_mm2s_full_wrap.vhd" \ "$ref_dir/../../../ipstatic/axi_datamover_v5_1/hdl/src/vhdl/axi_datamover.vhd" \ ncvhdl -work axi_sg_v4_1_2 $opts_vhd \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_pkg.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_reset.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_sfifo_autord.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_afifo_autord.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_fifo.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_cmd_status.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_rdmux.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_addr_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_rddata_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_rd_status_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_scc.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_wr_demux.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_scc_wr.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_skid2mm_buf.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_wrdata_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_wr_status_cntl.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_skid_buf.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_mm2s_basic_wrap.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_s2mm_basic_wrap.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_datamover.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_sm.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_pntr.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_cmdsts_if.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_mngr.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_cntrl_strm.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_queue.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_noqueue.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_ftch_q_mngr.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_updt_cmdsts_if.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_updt_sm.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_updt_mngr.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_updt_queue.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_updt_noqueue.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_updt_q_mngr.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg_intrpt.vhd" \ "$ref_dir/../../../ipstatic/axi_sg_v4_1/hdl/src/vhdl/axi_sg.vhd" \ ncvhdl -work axi_dma_v7_1_8 $opts_vhd \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_pkg.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_reset.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_rst_module.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_lite_if.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_register.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_register_s2mm.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_reg_module.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_skid_buf.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_afifo_autord.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_s2mm.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_sofeof_gen.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_smple_sm.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_mm2s_sg_if.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_mm2s_sm.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_mm2s_cmdsts_if.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_mm2s_sts_mngr.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_mm2s_cntrl_strm.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_mm2s_mngr.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_s2mm_sg_if.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_s2mm_sm.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_s2mm_cmdsts_if.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_s2mm_sts_mngr.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_s2mm_sts_strm.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_s2mm_mngr.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma_cmd_split.vhd" \ "$ref_dir/../../../ipstatic/axi_dma_v7_1/hdl/src/vhdl/axi_dma.vhd" \ ncvhdl -work xil_defaultlib $opts_vhd \ "$ref_dir/../../../bd/design_TEST/ip/design_TEST_axi_dma_0_0/sim/design_TEST_axi_dma_0_0.vhd" \ "$ref_dir/../../../bd/design_TEST/ip/design_TEST_axi_dma_1_0/sim/design_TEST_axi_dma_1_0.vhd" \ ncvhdl -work proc_sys_reset_v5_0_8 $opts_vhd \ "$ref_dir/../../../ipstatic/proc_sys_reset_v5_0/hdl/src/vhdl/upcnt_n.vhd" \ "$ref_dir/../../../ipstatic/proc_sys_reset_v5_0/hdl/src/vhdl/sequence_psr.vhd" \ "$ref_dir/../../../ipstatic/proc_sys_reset_v5_0/hdl/src/vhdl/lpf.vhd" \ "$ref_dir/../../../ipstatic/proc_sys_reset_v5_0/hdl/src/vhdl/proc_sys_reset.vhd" \ ncvhdl -work xil_defaultlib $opts_vhd \ "$ref_dir/../../../bd/design_TEST/ip/design_TEST_rst_processing_system7_0_100M_0/sim/design_TEST_rst_processing_system7_0_100M_0.vhd" \ ncvlog -work generic_baseblocks_v2_1_0 $opts_ver +incdir+"$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_carry_and.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_carry_latch_and.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_carry_latch_or.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_carry_or.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_carry.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_command_fifo.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_comparator_mask_static.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_comparator_mask.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_comparator_sel_mask_static.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_comparator_sel_mask.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_comparator_sel_static.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_comparator_sel.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_comparator_static.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_comparator.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_mux_enc.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_mux.v" \ "$ref_dir/../../../ipstatic/generic_baseblocks_v2_1/hdl/verilog/generic_baseblocks_v2_1_nto1_mux.v" \ ncvlog -work axi_infrastructure_v1_1_0 $opts_ver +incdir+"$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl" \ "$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog/axi_infrastructure_v1_1_axi2vector.v" \ "$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog/axi_infrastructure_v1_1_axic_srl_fifo.v" \ "$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog/axi_infrastructure_v1_1_vector2axi.v" \ ncvlog -work axi_register_slice_v2_1_7 $opts_ver +incdir+"$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl" \ "$ref_dir/../../../ipstatic/axi_register_slice_v2_1/hdl/verilog/axi_register_slice_v2_1_axic_register_slice.v" \ "$ref_dir/../../../ipstatic/axi_register_slice_v2_1/hdl/verilog/axi_register_slice_v2_1_axi_register_slice.v" \ ncvlog -work axi_data_fifo_v2_1_6 $opts_ver +incdir+"$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl" \ "$ref_dir/../../../ipstatic/axi_data_fifo_v2_1/hdl/verilog/axi_data_fifo_v2_1_axic_fifo.v" \ "$ref_dir/../../../ipstatic/axi_data_fifo_v2_1/hdl/verilog/axi_data_fifo_v2_1_fifo_gen.v" \ "$ref_dir/../../../ipstatic/axi_data_fifo_v2_1/hdl/verilog/axi_data_fifo_v2_1_axic_srl_fifo.v" \ "$ref_dir/../../../ipstatic/axi_data_fifo_v2_1/hdl/verilog/axi_data_fifo_v2_1_axic_reg_srl_fifo.v" \ "$ref_dir/../../../ipstatic/axi_data_fifo_v2_1/hdl/verilog/axi_data_fifo_v2_1_ndeep_srl.v" \ "$ref_dir/../../../ipstatic/axi_data_fifo_v2_1/hdl/verilog/axi_data_fifo_v2_1_axi_data_fifo.v" \ ncvlog -work axi_crossbar_v2_1_8 $opts_ver +incdir+"$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_addr_arbiter_sasd.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_addr_arbiter.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_addr_decoder.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_arbiter_resp.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_crossbar_sasd.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_crossbar.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_decerr_slave.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_si_transactor.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_splitter.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_wdata_mux.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_wdata_router.v" \ "$ref_dir/../../../ipstatic/axi_crossbar_v2_1/hdl/verilog/axi_crossbar_v2_1_axi_crossbar.v" \ ncvlog -work xil_defaultlib $opts_ver +incdir+"$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl" \ "$ref_dir/../../../bd/design_TEST/ip/design_TEST_xbar_0/sim/design_TEST_xbar_0.v" \ "$ref_dir/../../../bd/design_TEST/ip/design_TEST_xbar_1/sim/design_TEST_xbar_1.v" \ ncvlog -work axi_protocol_converter_v2_1_7 $opts_ver +incdir+"$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_a_axi3_conv.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_axi3_conv.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_axilite_conv.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_r_axi3_conv.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_w_axi3_conv.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b_downsizer.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_decerr_slave.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_simple_fifo.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_wrap_cmd.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_incr_cmd.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_wr_cmd_fsm.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_rd_cmd_fsm.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_cmd_translator.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_b_channel.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_r_channel.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_aw_channel.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s_ar_channel.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_b2s.v" \ "$ref_dir/../../../ipstatic/axi_protocol_converter_v2_1/hdl/verilog/axi_protocol_converter_v2_1_axi_protocol_converter.v" \ ncvlog -work xil_defaultlib $opts_ver +incdir+"$ref_dir/../../../ipstatic/axi_infrastructure_v1_1/hdl/verilog" +incdir+"$ref_dir/../../../ipstatic/processing_system7_bfm_v2_0/hdl" \ "$ref_dir/../../../bd/design_TEST/ip/design_TEST_auto_pc_0/sim/design_TEST_auto_pc_0.v" \ "$ref_dir/../../../bd/design_TEST/ip/design_TEST_auto_pc_1/sim/design_TEST_auto_pc_1.v" \ ncvhdl -work xil_defaultlib $opts_vhd \ "$ref_dir/../../../bd/design_TEST/hdl/design_TEST.vhd" \ ncvlog $opts_ver -work xil_defaultlib \ "glbl.v" } # RUN_STEP: <elaborate> elaborate() { opts="-loadvpi "C:/Xilinx/Vivado/2015.4/lib/win64.o/libxil_ncsim.dll:xilinx_register_systf" -64bit -relax -access +rwc -messages -logfile elaborate.log -timescale 1ps/1ps" libs="-libname unisims_ver -libname unimacro_ver -libname secureip -libname xil_defaultlib -libname lib_pkg_v1_0_2 -libname fifo_generator_v13_0_1 -libname lib_fifo_v1_0_4 -libname lib_srl_fifo_v1_0_2 -libname lib_cdc_v1_0_2 -libname axi_datamover_v5_1_9 -libname axi_sg_v4_1_2 -libname axi_dma_v7_1_8 -libname proc_sys_reset_v5_0_8 -libname generic_baseblocks_v2_1_0 -libname axi_infrastructure_v1_1_0 -libname axi_register_slice_v2_1_7 -libname axi_data_fifo_v2_1_6 -libname axi_crossbar_v2_1_8 -libname axi_protocol_converter_v2_1_7" ncelab $opts xil_defaultlib.design_TEST xil_defaultlib.glbl $libs } # RUN_STEP: <simulate> simulate() { opts="-64bit -logfile simulate.log" ncsim $opts xil_defaultlib.design_TEST -input simulate.do } # Script usage usage() { msg="Usage: design_TEST.sh [-help]\n\ Usage: design_TEST.sh [-lib_map_path]\n\ Usage: design_TEST.sh [-reset_run]\n\ Usage: design_TEST.sh [-noclean_files]\n\n\ [-help] -- Print help information for this script\n\n\ [-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\n\ using the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\n\n\ [-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\n\ from the previous run will be removed. If you don't want to remove the simulator generated files, use the\n\ -noclean_files switch.\n\n\ [-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\n\n" echo -e $msg exit 1 } # Launch script run $1 $2
Java
\subsection{Instruction Working Set Signature} An instruction working set (IWS)~\cite{Dhodapkar:2002:MMH} is the set of instructions touched over a fixed interval of time. The relative working set distance between intervals $i$ and $i-1$ is defined as \begin{center} $\delta_{i,i-1} = \frac{||W_i \bigcup W_{i-1}||-||W_i \bigcap W_{i-1}||}{||W_i \bigcup W_{i-1}||}$ \end{center} where $W_i$ is the working set for interval $i$. A working set signature is a lossy-compressed representation of a working set. The program counter is sampled over a fixed interval of instructions. A hashing function is applied to the sample to set a bit in an $n$-bit vector, which represents the signature (See Figure~\ref{fig:signature}). Phase changes are detected by computing the relative signature distance between intervals and comparing the distance against some pre-determined threshold. The hardware complexity of this technique is dependent on the working set size. \begin{figure}[htbp] \begin{center} \includegraphics[width=0.60\columnwidth]{figs/workingsetsignature} \end{center} \caption{Generating the working set signature.} \label{fig:signature} \end{figure}
Java
// -*- mode: csharp; encoding: utf-8; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- // vim:set ft=cs fenc=utf-8 ts=4 sw=4 sts=4 et: // $Id$ /* MetaTweet * Hub system for micro-blog communication services * SqlServerStorage * MetaTweet Storage module which is provided by Microsoft SQL Server RDBMS. * Part of MetaTweet * Copyright © 2008-2011 Takeshi KIRIYA (aka takeshik) <takeshik@users.sf.net> * All rights reserved. * * This file is part of SqlServerStorage. * * 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 program. If not, see <http://www.gnu.org/licenses/>, * or write to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301, USA. */ using System; using System.Data.EntityClient; using System.Data.Objects; using System.Reflection; namespace XSpect.MetaTweet.Objects { public class StorageObjectContext : ObjectContext { public const String ContainerName = "StorageObjectContext"; private ObjectSet<Account> _accounts; private ObjectSet<Activity> _activities; private ObjectSet<Advertisement> _advertisements; public StorageObjectContext(String connectionString) : base(connectionString, ContainerName) { this.ContextOptions.LazyLoadingEnabled = false; this.ContextOptions.ProxyCreationEnabled = false; } public StorageObjectContext(EntityConnection connection) : base(connection, ContainerName) { this.ContextOptions.LazyLoadingEnabled = false; this.ContextOptions.ProxyCreationEnabled = false; } public ObjectSet<Account> Accounts { get { return this._accounts ?? (this._accounts = this.CreateObjectSet<Account>("Accounts")); } } public ObjectSet<Activity> Activities { get { return this._activities ?? (this._activities = this.CreateObjectSet<Activity>("Activities")); } } public ObjectSet<Advertisement> Advertisements { get { return this._advertisements ?? (this._advertisements = this.CreateObjectSet<Advertisement>("Advertisements")); } } public Boolean IsDisposed { get { // HACK: Depends on internal structure, accessing non-public field return typeof(ObjectContext) .GetField("_connection", BindingFlags.Instance | BindingFlags.NonPublic) .GetValue(this) == null; } } public ObjectSet<TObject> GetObjectSet<TObject>() where TObject : StorageObject { return (ObjectSet<TObject>) (typeof(TObject) == typeof(Account) ? (Object) this.Accounts : typeof(TObject) == typeof(Activity) ? (Object) this.Activities : this.Advertisements ); } public String GetEntitySetName<TObject>() where TObject : StorageObject { return typeof(TObject) == typeof(Account) ? ContainerName + ".Accounts" : typeof(TObject) == typeof(Activity) ? ContainerName + ".Activities" : ContainerName + ".Advertisements"; } public String GetEntitySetName(StorageObject obj) { return obj is Account ? ContainerName + ".Accounts" : obj is Activity ? ContainerName + ".Activities" : ContainerName + ".Advertisements"; } } }
Java
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- qpieseries.cpp --> <title>PieSeries QML Type | Qt Charts 5.7</title> <link rel="stylesheet" type="text/css" href="style/offline-simple.css" /> <script type="text/javascript"> window.onload = function(){document.getElementsByTagName("link").item(0).setAttribute("href", "style/offline.css");}; </script> </head> <body> <div class="header" id="qtdocheader"> <div class="main"> <div class="main-rounded"> <div class="navigationbar"> <table><tr> <td ><a href="../qtdoc/supported-platforms-and-configurations.html#qt-5-7">Qt 5.7</a></td><td ><a href="qtcharts-index.html">Qt Charts</a></td><td ><a href="qtcharts-qmlmodule.html">QML Types</a></td><td >PieSeries QML Type</td></tr></table><table class="buildversion"><tr> <td id="buildversion" width="100%" align="right">Qt 5.7.0 Reference Documentation</td> </tr></table> </div> </div> <div class="content"> <div class="line"> <div class="content mainContent"> <div class="sidebar"> <div class="toc"> <h3><a name="toc">Contents</a></h3> <ul> <li class="level1"><a href="#properties">Properties</a></li> <li class="level1"><a href="#signals">Signals</a></li> <li class="level1"><a href="#methods">Methods</a></li> <li class="level1"><a href="#details">Detailed Description</a></li> </ul> </div> <div class="sidebar-content" id="sidebar-content"></div></div> <h1 class="title">PieSeries QML Type</h1> <span class="subtitle"></span> <!-- $$$PieSeries-brief --> <p>The <a href="qml-qtcharts-pieseries.html">PieSeries</a> type is used for making pie charts. <a href="#details">More...</a></p> <!-- @@@PieSeries --> <div class="table"><table class="alignedsummary"> <tr><td class="memItemLeft rightAlign topAlign"> Import Statement:</td><td class="memItemRight bottomAlign"> import QtCharts 2.1</td></tr><tr><td class="memItemLeft rightAlign topAlign"> Instantiates:</td><td class="memItemRight bottomAlign"> <a href="qml-qtcharts-pieseries.html"><a href="qpieseries.html">QPieSeries</a></td></tr><tr><td class="memItemLeft rightAlign topAlign"> Inherits:</td><td class="memItemRight bottomAlign"> <p><a href="qml-qtcharts-abstractseries.html">AbstractSeries</a></p> </td></tr></table></div><ul> <li><a href="qml-qtcharts-pieseries-members.html">List of all members, including inherited members</a></li> </ul> <a name="properties"></a> <h2 id="properties">Properties</h2> <ul> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#count-prop">count</a></b></b> : int</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#endAngle-prop">endAngle</a></b></b> : real</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#holeSize-prop">holeSize</a></b></b> : real</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#horizontalPosition-prop">horizontalPosition</a></b></b> : real</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#size-prop">size</a></b></b> : real</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#startAngle-prop">startAngle</a></b></b> : real</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#sum-prop">sum</a></b></b> : real</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#verticalPosition-prop">verticalPosition</a></b></b> : real</li> </ul> <a name="signals"></a> <h2 id="signals">Signals</h2> <ul> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onAdded-signal">onAdded</a></b></b>(list&lt;PieSlice&gt; <i>slices</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onClicked-signal">onClicked</a></b></b>(PieSlice <i>slice</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onCountChanged-signal">onCountChanged</a></b></b>()</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onDoubleClicked-signal">onDoubleClicked</a></b></b>(PieSlice <i>slice</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onHovered-signal">onHovered</a></b></b>(PieSlice <i>slice</i>, bool <i>state</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onPressed-signal">onPressed</a></b></b>(PieSlice <i>slice</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onReleased-signal">onReleased</a></b></b>(PieSlice <i>slice</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onRemoved-signal">onRemoved</a></b></b>(list&lt;PieSlice&gt; <i>slices</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onSliceAdded-signal">onSliceAdded</a></b></b>(PieSlice <i>slice</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onSliceRemoved-signal">onSliceRemoved</a></b></b>(PieSlice <i>slice</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#onSumChanged-signal">onSumChanged</a></b></b>()</li> </ul> <a name="methods"></a> <h2 id="methods">Methods</h2> <ul> <li class="fn">PieSlice <b><b><a href="qml-qtcharts-pieseries.html#append-method">append</a></b></b>(string <i>label</i>, real <i>value</i>)</li> <li class="fn">PieSlice <b><b><a href="qml-qtcharts-pieseries.html#at-method">at</a></b></b>(int <i>index</i>)</li> <li class="fn"><b><b><a href="qml-qtcharts-pieseries.html#clear-method">clear</a></b></b>()</li> <li class="fn">PieSlice <b><b><a href="qml-qtcharts-pieseries.html#find-method">find</a></b></b>(string <i>label</i>)</li> <li class="fn">bool <b><b><a href="qml-qtcharts-pieseries.html#remove-method">remove</a></b></b>(PieSlice <i>slice</i>)</li> </ul> <!-- $$$PieSeries-description --> <a name="details"></a> <h2 id="details">Detailed Description</h2> </p> <p>The following QML shows how to create a simple pie chart.</p> <pre class="qml"> <span class="type"><a href="qml-qtcharts-chartview.html">ChartView</a></span> { <span class="name">id</span>: <span class="name">chart</span> <span class="name">title</span>: <span class="string">&quot;Top-5 car brand shares in Finland&quot;</span> <span class="name">anchors</span>.fill: <span class="name">parent</span> <span class="name">legend</span>.alignment: <span class="name">Qt</span>.<span class="name">AlignBottom</span> <span class="name">antialiasing</span>: <span class="number">true</span> <span class="type"><a href="qml-qtcharts-pieseries.html">PieSeries</a></span> { <span class="name">id</span>: <span class="name">pieSeries</span> <span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> { <span class="name">label</span>: <span class="string">&quot;Volkswagen&quot;</span>; <span class="name">value</span>: <span class="number">13.5</span> } <span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> { <span class="name">label</span>: <span class="string">&quot;Toyota&quot;</span>; <span class="name">value</span>: <span class="number">10.9</span> } <span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> { <span class="name">label</span>: <span class="string">&quot;Ford&quot;</span>; <span class="name">value</span>: <span class="number">8.6</span> } <span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> { <span class="name">label</span>: <span class="string">&quot;Skoda&quot;</span>; <span class="name">value</span>: <span class="number">8.2</span> } <span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> { <span class="name">label</span>: <span class="string">&quot;Volvo&quot;</span>; <span class="name">value</span>: <span class="number">6.8</span> } } } <span class="name">Component</span>.onCompleted: { <span class="comment">// You can also manipulate slices dynamically</span> <span class="name">othersSlice</span> <span class="operator">=</span> <span class="name">pieSeries</span>.<span class="name">append</span>(<span class="string">&quot;Others&quot;</span>, <span class="number">52.0</span>); <span class="name">pieSeries</span>.<span class="name">find</span>(<span class="string">&quot;Volkswagen&quot;</span>).<span class="name">exploded</span> <span class="operator">=</span> <span class="number">true</span>; } </pre> <div style="float: left; margin-right: 2em"><p class="centerAlign"><img src="images/examples_qmlchart1.png" alt="" /></p></div><br style="clear: both" /><!-- @@@PieSeries --> <h2>Property Documentation</h2> <!-- $$$count --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="count-prop"> <td class="tblQmlPropNode"><p> <a name="count-prop"></a><span class="name">count</span> : <span class="type">int</span></p></td></tr> </table></div> </div><div class="qmldoc"><p>Number of slices in the series.</p> </div></div><!-- @@@count --> <br/> <!-- $$$endAngle --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="endAngle-prop"> <td class="tblQmlPropNode"><p> <a name="endAngle-prop"></a><span class="name">endAngle</span> : <span class="type">real</span></p></td></tr> </table></div> </div><div class="qmldoc"><p>Defines the ending angle of the pie.</p> <p>Full pie is 360 degrees where 0 degrees is at 12 a'clock.</p> <p>Default is value is 360.</p> </div></div><!-- @@@endAngle --> <br/> <!-- $$$holeSize --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="holeSize-prop"> <td class="tblQmlPropNode"><p> <a name="holeSize-prop"></a><span class="name">holeSize</span> : <span class="type">real</span></p></td></tr> </table></div> </div><div class="qmldoc"><p>Defines the donut hole size.</p> <p>The value is a relative value to the chart rectangle where:</p> <ul> <li>0.0 is the minimum size (full pie drawn, without any hole inside).</li> <li>1.0 is the maximum size that can fit the chart. (donut has no width)</li> </ul> <p>When setting this property the size property is adjusted if necessary, to ensure that the inner size is not greater than the outer size.</p> <p>Default value is 0.0&#x2e;</p> </div></div><!-- @@@holeSize --> <br/> <!-- $$$horizontalPosition --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="horizontalPosition-prop"> <td class="tblQmlPropNode"><p> <a name="horizontalPosition-prop"></a><span class="name">horizontalPosition</span> : <span class="type">real</span></p></td></tr> </table></div> </div><div class="qmldoc"><p>Defines the horizontal position of the pie.</p> <p>The value is a relative value to the chart rectangle where:</p> <ul> <li>0.0 is the absolute left.</li> <li>1.0 is the absolute right.</li> </ul> <p>Default value is 0.5 (center).</p> <p><b>See also </b><a href="qml-qtcharts-pieseries.html#verticalPosition-prop">verticalPosition</a>.</p> </div></div><!-- @@@horizontalPosition --> <br/> <!-- $$$size --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="size-prop"> <td class="tblQmlPropNode"><p> <a name="size-prop"></a><span class="name">size</span> : <span class="type">real</span></p></td></tr> </table></div> </div><div class="qmldoc"><p>Defines the pie size.</p> <p>The value is a relative value to the chart rectangle where:</p> <ul> <li>0.0 is the minimum size (pie not drawn).</li> <li>1.0 is the maximum size that can fit the chart.</li> </ul> <p>Default value is 0.7&#x2e;</p> </div></div><!-- @@@size --> <br/> <!-- $$$startAngle --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="startAngle-prop"> <td class="tblQmlPropNode"><p> <a name="startAngle-prop"></a><span class="name">startAngle</span> : <span class="type">real</span></p></td></tr> </table></div> </div><div class="qmldoc"><p>Defines the starting angle of the pie.</p> <p>Full pie is 360 degrees where 0 degrees is at 12 a'clock.</p> <p>Default is value is 0.</p> </div></div><!-- @@@startAngle --> <br/> <!-- $$$sum --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="sum-prop"> <td class="tblQmlPropNode"><p> <a name="sum-prop"></a><span class="name">sum</span> : <span class="type">real</span></p></td></tr> </table></div> </div><div class="qmldoc"><p>Sum of all slices.</p> <p>The series keeps track of the sum of all slices it holds.</p> </div></div><!-- @@@sum --> <br/> <!-- $$$verticalPosition --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="verticalPosition-prop"> <td class="tblQmlPropNode"><p> <a name="verticalPosition-prop"></a><span class="name">verticalPosition</span> : <span class="type">real</span></p></td></tr> </table></div> </div><div class="qmldoc"><p>Defines the vertical position of the pie.</p> <p>The value is a relative value to the chart rectangle where:</p> <ul> <li>0.0 is the absolute top.</li> <li>1.0 is the absolute bottom.</li> </ul> <p>Default value is 0.5 (center).</p> <p><b>See also </b><a href="qml-qtcharts-pieseries.html#horizontalPosition-prop">horizontalPosition</a>.</p> </div></div><!-- @@@verticalPosition --> <br/> <h2>Signal Documentation</h2> <!-- $$$onAdded --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onAdded-signal"> <td class="tblQmlFuncNode"><p> <a name="onAdded-signal"></a><span class="name">onAdded</span>(<span class="type">list</span>&lt;<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span>&gt; <i>slices</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>Emitted when <i>slices</i> have been added to the series.</p> </div></div><!-- @@@onAdded --> <br/> <!-- $$$onClicked --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onClicked-signal"> <td class="tblQmlFuncNode"><p> <a name="onClicked-signal"></a><span class="name">onClicked</span>(<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <i>slice</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>This signal is emitted when a <i>slice</i> has been clicked.</p> </div></div><!-- @@@onClicked --> <br/> <!-- $$$onCountChanged --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onCountChanged-signal"> <td class="tblQmlFuncNode"><p> <a name="onCountChanged-signal"></a><span class="name">onCountChanged</span>()</p></td></tr> </table></div> </div><div class="qmldoc"><p>Emitted when the slice count has changed.</p> </div></div><!-- @@@onCountChanged --> <br/> <!-- $$$onDoubleClicked --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onDoubleClicked-signal"> <td class="tblQmlFuncNode"><p> <a name="onDoubleClicked-signal"></a><span class="name">onDoubleClicked</span>(<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <i>slice</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>This signal is emitted when a <i>slice</i> has been doubleClicked.</p> </div></div><!-- @@@onDoubleClicked --> <br/> <!-- $$$onHovered --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onHovered-signal"> <td class="tblQmlFuncNode"><p> <a name="onHovered-signal"></a><span class="name">onHovered</span>(<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <i>slice</i>, <span class="type">bool</span> <i>state</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>This signal is emitted when user has hovered over or away from the <i>slice</i>. <i>state</i> is true when user has hovered over the slice and false when hover has moved away from the slice.</p> </div></div><!-- @@@onHovered --> <br/> <!-- $$$onPressed --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onPressed-signal"> <td class="tblQmlFuncNode"><p> <a name="onPressed-signal"></a><span class="name">onPressed</span>(<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <i>slice</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>This signal is emitted when a <i>slice</i> has been pressed.</p> </div></div><!-- @@@onPressed --> <br/> <!-- $$$onReleased --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onReleased-signal"> <td class="tblQmlFuncNode"><p> <a name="onReleased-signal"></a><span class="name">onReleased</span>(<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <i>slice</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>This signal is emitted when a <i>slice</i> has been released.</p> </div></div><!-- @@@onReleased --> <br/> <!-- $$$onRemoved --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onRemoved-signal"> <td class="tblQmlFuncNode"><p> <a name="onRemoved-signal"></a><span class="name">onRemoved</span>(<span class="type">list</span>&lt;<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span>&gt; <i>slices</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>Emitted when <i>slices</i> have been removed from the series.</p> </div></div><!-- @@@onRemoved --> <br/> <!-- $$$onSliceAdded --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onSliceAdded-signal"> <td class="tblQmlFuncNode"><p> <a name="onSliceAdded-signal"></a><span class="name">onSliceAdded</span>(<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <i>slice</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>Emitted when <i>slice</i> has been added to the series.</p> </div></div><!-- @@@onSliceAdded --> <br/> <!-- $$$onSliceRemoved --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onSliceRemoved-signal"> <td class="tblQmlFuncNode"><p> <a name="onSliceRemoved-signal"></a><span class="name">onSliceRemoved</span>(<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <i>slice</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>Emitted when <i>slice</i> has been removed from the series.</p> </div></div><!-- @@@onSliceRemoved --> <br/> <!-- $$$onSumChanged --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="onSumChanged-signal"> <td class="tblQmlFuncNode"><p> <a name="onSumChanged-signal"></a><span class="name">onSumChanged</span>()</p></td></tr> </table></div> </div><div class="qmldoc"><p>Emitted when the sum of all slices has changed. This may happen for example if you add or remove slices, or if you change value of a slice.</p> </div></div><!-- @@@onSumChanged --> <br/> <h2>Method Documentation</h2> <!-- $$$append --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="append-method"> <td class="tblQmlFuncNode"><p> <a name="append-method"></a><span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <span class="name">append</span>(<span class="type">string</span> <i>label</i>, <span class="type">real</span> <i>value</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>Adds a new slice with <i>label</i> and <i>value</i> to the pie.</p> </div></div><!-- @@@append --> <br/> <!-- $$$at --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="at-method"> <td class="tblQmlFuncNode"><p> <a name="at-method"></a><span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <span class="name">at</span>(<span class="type">int</span> <i>index</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>Returns slice at <i>index</i>. Returns null if the index is not valid.</p> </div></div><!-- @@@at --> <br/> <!-- $$$clear --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="clear-method"> <td class="tblQmlFuncNode"><p> <a name="clear-method"></a><span class="name">clear</span>()</p></td></tr> </table></div> </div><div class="qmldoc"><p>Removes all slices from the pie.</p> </div></div><!-- @@@clear --> <br/> <!-- $$$find --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="find-method"> <td class="tblQmlFuncNode"><p> <a name="find-method"></a><span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <span class="name">find</span>(<span class="type">string</span> <i>label</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>Returns the first slice with <i>label</i>. Returns null if the index is not valid.</p> </div></div><!-- @@@find --> <br/> <!-- $$$remove --> <div class="qmlitem"><div class="qmlproto"> <div class="table"><table class="qmlname"> <tr valign="top" class="odd" id="remove-method"> <td class="tblQmlFuncNode"><p> <a name="remove-method"></a><span class="type">bool</span> <span class="name">remove</span>(<span class="type"><a href="qml-qtcharts-pieslice.html">PieSlice</a></span> <i>slice</i>)</p></td></tr> </table></div> </div><div class="qmldoc"><p>Removes the <i>slice</i> from the pie. Returns true if the removal was successful, false otherwise.</p> </div></div><!-- @@@remove --> <br/> </div> </div> </div> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2016 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners.<br> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.<br> Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners. </p> </div> </body> </html>
Java
# -*- coding: utf-8 -*- """proyectoP4 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, patterns from django.contrib import admin from Workinout import views from django.conf import settings urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^Workinout/', include('Workinout.urls')), # ADD THIS NEW TUPLE!media/(?P<path>.*) ] if settings.DEBUG: urlpatterns += patterns( 'django.views.static', (r'media/(?P<path>.*)', 'serve', {'document_root': settings.MEDIA_ROOT}), ) else: urlpatterns += patterns('', url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_PATH}), )
Java
#region using directives using POGOProtos.Enums; using POGOProtos.Settings.Master.Pokemon; #endregion namespace PoGo.PokeMobBot.Logic.Event.Pokemon { public class BaseNewPokemonEvent : IEvent { public int Cp; public ulong Uid; public PokemonId Id; public double Perfection; public PokemonFamilyId Family; public int Candy; public double Level; public PokemonMove Move1; public PokemonMove Move2; public PokemonType Type1; public PokemonType Type2; public StatsAttributes Stats; public int MaxCp; public int Stamina; public int IvSta; public int PossibleCp; public int CandyToEvolve; public int IvAtk; public int IvDef; public float Cpm; public float Weight; public int StaminaMax; public PokemonId[] Evolutions; public double Latitude; public double Longitude; } }
Java
#!/usr/bin/python # This programs is intended to manage patches and apply them automatically # through email in an automated fashion. # # Copyright (C) 2008 Imran M Yousuf (imran@smartitengineering.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., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import poplib, email, re, sys, xmlConfigs, utils; class ReferenceNode : def __init__(self, node, emailMessage, references=list(), children=dict(), slotted=bool("false")): self.node = node self.children = dict(children) self.references = references[:] self.slotted = slotted self.emailMessage = emailMessage def get_node(self): return self.node def get_children(self): return self.children def set_node(self, node): self.node = node def set_children(self, children): self.children = children def get_references(self): return self.references def is_slotted(self): return self.slotted def set_slotted(self, slotted): self.slotted = slotted def get_message(self): return self.emailMessage def __repr__(self): return self.node + "\nREF: " + str(self.references) + "\nChildren: " + str(self.children.keys()) + "\n" def handleNode(currentNodeInAction, referenceNodeNow, referencesToCheck, patchMessageReferenceNode): for reference in referencesToCheck[:] : if reference in referenceNodeNow.get_children() : referencesToCheck.remove(reference) return patchMessageReferenceNode[reference] if len(referencesToCheck) == 0 : referenceNodeNow.get_children()[currentNodeInAction.get_node()] = currentNodeInAction def makeChildren(patchMessageReferenceNode) : ref_keys = patchMessageReferenceNode.keys() ref_keys.sort() for messageId in ref_keys: referenceNode = patchMessageReferenceNode[messageId] utils.verboseOutput(verbose, "Managing Message Id:", referenceNode.get_node()) referenceIds = referenceNode.get_references() referenceIdsClone = referenceIds[:] utils.verboseOutput(verbose, "Cloned References: ", referenceIdsClone) if len(referenceIds) > 0 : nextNode = patchMessageReferenceNode[referenceIdsClone[0]] referenceIdsClone.remove(referenceIdsClone[0]) while nextNode != None : utils.verboseOutput(verbose, "Next Node: ", nextNode.get_node()) utils.verboseOutput(verbose, "Curent Node: ", referenceNode.get_node()) utils.verboseOutput(verbose, "REF: ", referenceIdsClone) nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode) if __name__ == "__main__": arguments = sys.argv verbose = "false" pseudoArgs = arguments[:] while len(pseudoArgs) > 1 : argument = pseudoArgs[1] if argument == "-v" or argument == "--verbose" : verbose = "true" pseudoArgs.remove(argument) utils.verboseOutput(verbose, "Checking POP3 for gmail") try: emailConfig = xmlConfigs.initializePopConfig("./email-configuration.xml") myPop = emailConfig.get_pop3_connection() numMessages = len(myPop.list()[1]) patchMessages = dict() for i in range(numMessages): utils.verboseOutput(verbose, "Index: ", i) totalContent = "" for content in myPop.retr(i+1)[1]: totalContent += content + '\n' msg = email.message_from_string(totalContent) if 'subject' in msg : subject = msg['subject'] subjectPattern = "^\[.*PATCH.*\].+" subjectMatch = re.match(subjectPattern, subject) utils.verboseOutput(verbose, "Checking subject: ", subject) if subjectMatch == None : continue else : continue messageId = "" if 'message-id' in msg: messageId = re.search("<(.*)>", msg['message-id']).group(1) utils.verboseOutput(verbose, 'Message-ID:', messageId) referenceIds = [] if 'references' in msg: references = msg['references'] referenceIds = re.findall("<(.*)>", references) utils.verboseOutput(verbose, "References: ", referenceIds) currentNode = ReferenceNode(messageId, msg, referenceIds) patchMessages[messageId] = currentNode currentNode.set_slotted(bool("false")) utils.verboseOutput(verbose, "**************Make Children**************") makeChildren(patchMessages) utils.verboseOutput(verbose, "--------------RESULT--------------") utils.verboseOutput(verbose, patchMessages) except: utils.verboseOutput(verbose, "Error: ", sys.exc_info())
Java
/* LICENSE ------- Copyright (C) 2007 Ray Molenkamp This source code is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this source code or the software it produces. Permission is granted to anyone to use this source code for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this source code must not be misrepresented; you must not claim that you wrote the original source code. If you use this source code in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original source code. 3. This notice may not be removed or altered from any source distribution. */ // modified for NAudio // milligan22963 - updated to include audio session manager using System; using NAudio.CoreAudioApi.Interfaces; using System.Runtime.InteropServices; namespace NAudio.CoreAudioApi { /// <summary> /// MM Device /// </summary> public class MMDevice : IDisposable { #region Variables private readonly IMMDevice deviceInterface; private PropertyStore propertyStore; private AudioMeterInformation audioMeterInformation; private AudioEndpointVolume audioEndpointVolume; private AudioSessionManager audioSessionManager; #endregion #region Guids private static Guid IID_IAudioMeterInformation = new Guid("C02216F6-8C67-4B5B-9D00-D008E73E0064"); private static Guid IID_IAudioEndpointVolume = new Guid("5CDF2C82-841E-4546-9722-0CF74078229A"); private static Guid IID_IAudioClient = new Guid("1CB9AD4C-DBFA-4c32-B178-C2F568A703B2"); private static Guid IDD_IAudioSessionManager = new Guid("BFA971F1-4D5E-40BB-935E-967039BFBEE4"); #endregion #region Init /// <summary> /// Initializes the device's property store. /// </summary> /// <param name="stgmAccess">The storage-access mode to open store for.</param> /// <remarks>Administrative client is required for Write and ReadWrite modes.</remarks> public void GetPropertyInformation(StorageAccessMode stgmAccess = StorageAccessMode.Read) { IPropertyStore propstore; Marshal.ThrowExceptionForHR(deviceInterface.OpenPropertyStore(stgmAccess, out propstore)); propertyStore = new PropertyStore(propstore); } private AudioClient GetAudioClient() { object result; Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref IID_IAudioClient, ClsCtx.ALL, IntPtr.Zero, out result)); return new AudioClient(result as IAudioClient); } private void GetAudioMeterInformation() { object result; Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref IID_IAudioMeterInformation, ClsCtx.ALL, IntPtr.Zero, out result)); audioMeterInformation = new AudioMeterInformation(result as IAudioMeterInformation); } private void GetAudioEndpointVolume() { object result; Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref IID_IAudioEndpointVolume, ClsCtx.ALL, IntPtr.Zero, out result)); audioEndpointVolume = new AudioEndpointVolume(result as IAudioEndpointVolume); } private void GetAudioSessionManager() { object result; Marshal.ThrowExceptionForHR(deviceInterface.Activate(ref IDD_IAudioSessionManager, ClsCtx.ALL, IntPtr.Zero, out result)); audioSessionManager = new AudioSessionManager(result as IAudioSessionManager); } #endregion #region Properties /// <summary> /// Audio Client /// </summary> public AudioClient AudioClient { get { // now makes a new one each call to allow caller to manage when to dispose // n.b. should probably not be a property anymore return GetAudioClient(); } } /// <summary> /// Audio Meter Information /// </summary> public AudioMeterInformation AudioMeterInformation { get { if (audioMeterInformation == null) GetAudioMeterInformation(); return audioMeterInformation; } } /// <summary> /// Audio Endpoint Volume /// </summary> public AudioEndpointVolume AudioEndpointVolume { get { if (audioEndpointVolume == null) GetAudioEndpointVolume(); return audioEndpointVolume; } } /// <summary> /// AudioSessionManager instance /// </summary> public AudioSessionManager AudioSessionManager { get { if (audioSessionManager == null) { GetAudioSessionManager(); } return audioSessionManager; } } /// <summary> /// Properties /// </summary> public PropertyStore Properties { get { if (propertyStore == null) GetPropertyInformation(); return propertyStore; } } /// <summary> /// Friendly name for the endpoint /// </summary> public string FriendlyName { get { if (propertyStore == null) { GetPropertyInformation(); } if (propertyStore.Contains(PropertyKeys.PKEY_Device_FriendlyName)) { return (string) propertyStore[PropertyKeys.PKEY_Device_FriendlyName].Value; } else return "Unknown"; } } /// <summary> /// Friendly name of device /// </summary> public string DeviceFriendlyName { get { if (propertyStore == null) { GetPropertyInformation(); } if (propertyStore.Contains(PropertyKeys.PKEY_DeviceInterface_FriendlyName)) { return (string) propertyStore[PropertyKeys.PKEY_DeviceInterface_FriendlyName].Value; } else { return "Unknown"; } } } /// <summary> /// Icon path of device /// </summary> public string IconPath { get { if (propertyStore == null) { GetPropertyInformation(); } if (propertyStore.Contains(PropertyKeys.PKEY_Device_IconPath)) { return (string) propertyStore[PropertyKeys.PKEY_Device_IconPath].Value; } else return "Unknown"; } } /// <summary> /// Device ID /// </summary> public string ID { get { string result; Marshal.ThrowExceptionForHR(deviceInterface.GetId(out result)); return result; } } /// <summary> /// Data Flow /// </summary> public DataFlow DataFlow { get { DataFlow result; var ep = deviceInterface as IMMEndpoint; ep.GetDataFlow(out result); return result; } } /// <summary> /// Device State /// </summary> public DeviceState State { get { DeviceState result; Marshal.ThrowExceptionForHR(deviceInterface.GetState(out result)); return result; } } #endregion #region Constructor internal MMDevice(IMMDevice realDevice) { deviceInterface = realDevice; } #endregion /// <summary> /// To string /// </summary> public override string ToString() { return FriendlyName; } /// <summary> /// Dispose /// </summary> public void Dispose() { this.audioEndpointVolume?.Dispose(); this.audioSessionManager?.Dispose(); GC.SuppressFinalize(this); } /// <summary> /// Finalizer /// </summary> ~MMDevice() { Dispose(); } } }
Java
// // MIT License // // Copyright (c) Deif Lou // // 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 <opencv2/imgproc.hpp> #include <vector> #include "filter.h" #include "filterwidget.h" #include <imgproc/types.h> #include <imgproc/thresholding.h> #include <imgproc/util.h> Filter::Filter() : mThresholdMode(0), mColorMode(0) { for (int i = 0; i < 5; i++) mAffectedChannel[i] = false; } Filter::~Filter() { } ImageFilter *Filter::clone() { Filter * f = new Filter(); f->mThresholdMode = mThresholdMode; f->mColorMode = mColorMode; for (int i = 0; i < 5; i++) f->mAffectedChannel[i] = mAffectedChannel[i]; return f; } extern "C" QHash<QString, QString> getIBPPluginInfo(); QHash<QString, QString> Filter::info() { return getIBPPluginInfo(); } QImage Filter::process(const QImage &inputImage) { if (inputImage.isNull() || inputImage.format() != QImage::Format_ARGB32) return inputImage; QImage i = inputImage.copy(); cv::Mat dstMat(i.height(), i.width(), CV_8UC4, i.bits(), i.bytesPerLine()); const int radius = 10; const int windowSize = radius * 2 + 1; const double k = .05; if (mColorMode == 0) { if (!mAffectedChannel[0] && !mAffectedChannel[4]) return i; if (mAffectedChannel[0]) { register BGRA * bitsSrc = (BGRA *)inputImage.bits(); register BGRA * bitsDst = (BGRA *)i.bits(); register int totalPixels = i.width() * i.height(); while (totalPixels--) { bitsDst->b = IBP_pixelIntensity4(bitsSrc->r, bitsSrc->g, bitsSrc->b); bitsSrc++; bitsDst++; } } cv::Mat mSrcGray, mSrcAlpha; if (mAffectedChannel[0]) { mSrcGray = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1); int from_to[] = { 0,0 }; cv::mixChannels(&dstMat, 1, &mSrcGray, 1, from_to, 1); } if (mAffectedChannel[4]) { mSrcAlpha = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1); int from_to[] = { 3,0 }; cv::mixChannels(&dstMat, 1, &mSrcAlpha, 1, from_to, 1); } if (mThresholdMode == 0) { if (mAffectedChannel[0]) cv::threshold(mSrcGray, mSrcGray, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); if (mAffectedChannel[4]) cv::threshold(mSrcAlpha, mSrcAlpha, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); } else { if (mAffectedChannel[0]) adaptiveThresholdIntegral(mSrcGray, mSrcGray, windowSize, k); if (mAffectedChannel[4]) adaptiveThresholdIntegral(mSrcAlpha, mSrcAlpha, windowSize, k); } if (mAffectedChannel[0]) { int from_to[] = { 0,0, 0,1, 0,2 }; cv::mixChannels(&mSrcGray, 1, &dstMat, 1, from_to, 3); } if (mAffectedChannel[4]) { int from_to[] = { 0,3 }; cv::mixChannels(&mSrcAlpha, 1, &dstMat, 1, from_to, 1); } } else { if (!mAffectedChannel[1] && !mAffectedChannel[2] && !mAffectedChannel[3] && !mAffectedChannel[4]) return i; cv::Mat mSrcRed, mSrcGreen, mSrcBlue, mSrcAlpha; if (mAffectedChannel[1]) { mSrcBlue = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1); int from_to[] = { 0,0 }; cv::mixChannels(&dstMat, 1, &mSrcBlue, 1, from_to, 1); } if (mAffectedChannel[2]) { mSrcGreen = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1); int from_to[] = { 1,0 }; cv::mixChannels(&dstMat, 1, &mSrcGreen, 1, from_to, 1); } if (mAffectedChannel[3]) { mSrcRed = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1); int from_to[] = { 2,0 }; cv::mixChannels(&dstMat, 1, &mSrcRed, 1, from_to, 1); } if (mAffectedChannel[4]) { mSrcAlpha = cv::Mat(dstMat.rows, dstMat.cols, CV_8UC1); int from_to[] = { 3,0 }; cv::mixChannels(&dstMat, 1, &mSrcAlpha, 1, from_to, 1); } if (mThresholdMode == 0) { if (mAffectedChannel[1]) cv::threshold(mSrcBlue, mSrcBlue, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); if (mAffectedChannel[2]) cv::threshold(mSrcGreen, mSrcGreen, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); if (mAffectedChannel[3]) cv::threshold(mSrcRed, mSrcRed, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); if (mAffectedChannel[4]) cv::threshold(mSrcAlpha, mSrcAlpha, 0, 255, cv::THRESH_BINARY | cv::THRESH_OTSU); } else { if (mAffectedChannel[1]) adaptiveThresholdIntegral(mSrcBlue, mSrcBlue, windowSize, k); if (mAffectedChannel[2]) adaptiveThresholdIntegral(mSrcGreen, mSrcGreen, windowSize, k); if (mAffectedChannel[3]) adaptiveThresholdIntegral(mSrcRed, mSrcRed, windowSize, k); if (mAffectedChannel[4]) adaptiveThresholdIntegral(mSrcAlpha, mSrcAlpha, windowSize, k); } if (mAffectedChannel[1]) { int from_to[] = { 0,0 }; cv::mixChannels(&mSrcBlue, 1, &dstMat, 1, from_to, 1); } if (mAffectedChannel[2]) { int from_to[] = { 0,1 }; cv::mixChannels(&mSrcGreen, 1, &dstMat, 1, from_to, 1); } if (mAffectedChannel[3]) { int from_to[] = { 0,2 }; cv::mixChannels(&mSrcRed, 1, &dstMat, 1, from_to, 1); } if (mAffectedChannel[4]) { int from_to[] = { 0,3 }; cv::mixChannels(&mSrcAlpha, 1, &dstMat, 1, from_to, 1); } } return i; } bool Filter::loadParameters(QSettings &s) { QString thresholdModeStr, colorModeStr, affectedChannelStr; int thresholdMode, colorMode; QStringList affectedChannelList; bool affectedChannel[5] = { false }; thresholdModeStr = s.value("thresholdmode", "global").toString(); if (thresholdModeStr == "global") thresholdMode = 0; else if (thresholdModeStr == "local") thresholdMode = 1; else return false; colorModeStr = s.value("colormode", "luma").toString(); if (colorModeStr == "luma") colorMode = 0; else if (colorModeStr == "rgb") colorMode = 1; else return false; affectedChannelStr = s.value("affectedchannels", "").toString(); affectedChannelList = affectedChannelStr.split(" ", QString::SkipEmptyParts); for (int i = 0; i < affectedChannelList.size(); i++) { affectedChannelStr = affectedChannelList.at(i); if (affectedChannelList.at(i) == "luma") affectedChannel[0] = true; else if (affectedChannelList.at(i) == "red") affectedChannel[1] = true; else if (affectedChannelList.at(i) == "green") affectedChannel[2] = true; else if (affectedChannelList.at(i) == "blue") affectedChannel[3] = true; else if (affectedChannelList.at(i) == "alpha") affectedChannel[4] = true; else return false; } setThresholdMode(thresholdMode); setColorMode(colorMode); for (int i = 0; i < 5; i++) setAffectedChannel(i, affectedChannel[i]); return true; } bool Filter::saveParameters(QSettings &s) { s.setValue("thresholdmode", mThresholdMode == 0 ? "global" : "local"); s.setValue("colormode", mColorMode == 0 ? "luma" : "rgb"); QStringList affectedChannelList; if (mAffectedChannel[0]) affectedChannelList.append("luma"); if (mAffectedChannel[1]) affectedChannelList.append("red"); if (mAffectedChannel[2]) affectedChannelList.append("green"); if (mAffectedChannel[3]) affectedChannelList.append("blue"); if (mAffectedChannel[4]) affectedChannelList.append("alpha"); s.setValue("affectedchannels", affectedChannelList.join(" ")); return true; } QWidget *Filter::widget(QWidget *parent) { FilterWidget * fw = new FilterWidget(parent); fw->setThresholdMode(mThresholdMode); fw->setColorMode(mColorMode); for (int i = 0; i < 5; i++) fw->setAffectedChannel(i, mAffectedChannel[i]); connect(this, SIGNAL(thresholdModeChanged(int)), fw, SLOT(setThresholdMode(int))); connect(this, SIGNAL(colorModeChanged(int)), fw, SLOT(setColorMode(int))); connect(this, SIGNAL(affectedChannelChanged(int,bool)), fw, SLOT(setAffectedChannel(int,bool))); connect(fw, SIGNAL(thresholdModeChanged(int)), this, SLOT(setThresholdMode(int))); connect(fw, SIGNAL(colorModeChanged(int)), this, SLOT(setColorMode(int))); connect(fw, SIGNAL(affectedChannelChanged(int,bool)), this, SLOT(setAffectedChannel(int,bool))); return fw; } void Filter::setThresholdMode(int m) { if (m == mThresholdMode) return; mThresholdMode = m; emit thresholdModeChanged(m); emit parametersChanged(); } void Filter::setColorMode(int m) { if (m == mColorMode) return; mColorMode = m; emit colorModeChanged(m); emit parametersChanged(); } void Filter::setAffectedChannel(int c, bool a) { if (a == mAffectedChannel[c]) return; mAffectedChannel[c] = a; emit affectedChannelChanged(c, a); emit parametersChanged(); }
Java
<!DOCTYPE html> <html> <head> <title>SenseNet : modul Senzory</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="./SenseNet_Files/over.css"> <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css"> <link rel="stylesheet" href="./SenseNet_Files/font-awesome.min.css"> <link href='http://fonts.googleapis.com/css?family=Arvo' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=PT+Sans' rel='stylesheet' type='text/css'> <link rel="icon" href="./SenseNet_Files/favicon.ico"> <meta name="author" content="labka.cz" /> <meta name="description" content="SenseNet platform which is able to measure, parse, and predict data about air polution in industrial region Ostrava" /> <meta name="keywords" content="SenseNet, SensoricNet, Sense Net, Sensoric Net, AI, platform, prediction, parser, neural network, hackerspace, labka.cz, labka, ostrava, hackerspaces, polution, air, environmental, environment"/> </head> <body> <!-- Imported floating menu --> <div class="obal"> <div class="menu"> <iframe src="menu.html" seamless></iframe> </div> </div> <div class="celek"> <img class="obrR" src="./SenseNet_Files/pavel_s.png" width="350px"> <h2>Modul NET : infrastruktura </h2> <div> Mezi moduly Smysly [Sense] a Mozek [Brain] musí samozřejmě existovat nějaké spojení, tak jako jsou jím v lidském těle nervy.br /> V našem případě je takových spojení potřeba několik. Budou se budou vzájemně překrývat, protože komunikace je zásadní pro každý projekt a proto je potřebné mít oněch pomyslných nervových soustav několik a na několika různých vrstvách.<br /> <br /> Cílem projektu je vytvoření rozhraní mezi senzory a servery, na kterých se budou data zpracovávat, a to tak, aby bylo možné projekt zveřejnit jak pod OpenSource licencemi, jako kompletní, preprodukovatelné řešení, tak aby na druhou stranu bylo možné enterprise nasazení za pomoci patentovaných technologií a garantovaných vysílacích pásem.<br /> <h3>NB-IoT</h3> NB-IoT je experimentální standardizovaná techologie bezdrátového přenosu malých množtví dat pomocí existující bezdrátové telefonní a datové sítě.<br /> <br /> Technologie NB-IoT je založena na standardech Low Power Wide Area (LPWA) a díky její nízké spotřebě a vysoké propustnosti se Internet věcí může masivně rozšířit. Podporuje řešení jak v průmyslu (např. v energetice, automobilovém průmyslu, strojírenství, zemědělství, atd.), zdravotnictví a v projektech chytrých měst, tak i v oblasti běžného života (monitorování a zabezpečení domácností, vozidel, domácích mazlíčků atd.). Mezi největší výhody patří výborná prostupnost signálu překážkami, signál se tak dostane i do sklepů nebo garáží, dále provoz na licencovaném frekvenčním pásmu zajišťujícím uživatelům spolehlivější a bezpečnější komunikaci, roaming, nízká spotřeba energie koncovými zařízeními (výdrž baterie až 10 – 15 let) a také jejich nízká cena. <br /> <br /> Našemu týmu se podařilo okolo testovacícho čipu vybudovat celou hardwarovou platformu tak, že tato může být připojena k senzorickému modulu, a bude možné testovat její stabilitu, pokrytí a náročnost na napájení.<br /> Tato část projektu je již téměř dokončena a nachází se ve stádiu pre-produkčního testování.<br /> <br /> Díky tomu, že se jedná o technologii patentovanou a ke své fuknci využívající produkční komerční frekvence vlastněné společností Vodafone, nebude tato část modulu zařazena v OpenSource verzi projektu SenseNet<br /> <h3>LoraWan</h3> Nekomerční, OpenSource obdoba NB-IoT sestávající z open hardware i open software, která využívá nekomerční, ale také negarantovaná vysílací pásma pro rádiový přenos.<br /> Modul bude zařazen do OpenSource dokumentace SenseNet a měl by být plně schopen nahradit komerční, patentované řešení.<br /> V součastné době ještě neproběhlo testování v Labce, nicméně hardware senzorů je pro LoraWan nasazení připraven.<br /> <h3>Interní síťová infrastruktura</h3> Interně bude pro síťování projektu použita standarndní implementace IPv4 a do budoucna IPv6.<br /> Tato část projektu je již hotová v pre-produkčním stadiu, bude vytvořena ještě dokumentace pro jiné než testovací a laboratorní použití. </body> </html>
Java
/* This file is part of sudoku_systemc Copyright (C) 2012 Julien Thevenon ( julien_thevenon at yahoo.fr ) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ #ifndef SUDOKU_INTERNAL_STATE_H #define SUDOKU_INTERNAL_STATE_H #include "sudoku_types.h" #include "cell_listener_if.h" namespace sudoku_systemc { template<unsigned int SIZE> class sudoku_internal_state { public: sudoku_internal_state(const unsigned int & p_sub_x,const unsigned int & p_sub_y,const unsigned int & p_initial_value, cell_listener_if & p_listener); sudoku_internal_state(const sudoku_internal_state<SIZE> & p_initial_state,const unsigned int & p_hypothesis_level); unsigned int get_real_value(const typename sudoku_types<SIZE>::t_data_type & p_value)const; void remove_vertical_candidate(const typename sudoku_types<SIZE>::t_data_type & p_value); void remove_horizontal_candidate(const typename sudoku_types<SIZE>::t_data_type & p_value); void remove_square_candidate(const typename sudoku_types<SIZE>::t_data_type & p_value); void remove_available_value(const typename sudoku_types<SIZE>::t_data_type & p_value); const typename sudoku_types<SIZE>::t_nb_available_values & get_nb_available_values(void)const; const typename sudoku_types<SIZE>::t_data_type make_hypothesis(void); const typename sudoku_types<SIZE>::t_available_values & get_values_to_release(void)const; const typename sudoku_types<SIZE>::t_data_type get_remaining_value(void); // Value management inline const typename sudoku_types<SIZE>::t_data_type & get_value(void)const; inline const bool is_value_set(void)const; void set_value(const typename sudoku_types<SIZE>::t_data_type & p_value); const unsigned int & get_hypothesis_level(void)const; bool is_modified(void)const ; void notify_listener(void); private: void set_horizontal_candidate(const unsigned int & p_index, const typename sudoku_types<SIZE>::t_group_candidate & p_value); void set_vertical_candidate(const unsigned int & p_index, const typename sudoku_types<SIZE>::t_group_candidate & p_value); void set_square_candidate(const unsigned int & p_index, const typename sudoku_types<SIZE>::t_group_candidate & p_value); void set_available_value(const unsigned int & p_index, bool p_value); void set_release_value(const unsigned int & p_index, bool p_value); cell_listener_if & m_listener; typename sudoku_types<SIZE>::t_group_candidate m_vertical_candidates[sudoku_configuration<SIZE>::m_nb_value]; typename sudoku_types<SIZE>::t_group_candidate m_horizontal_candidates[sudoku_configuration<SIZE>::m_nb_value]; typename sudoku_types<SIZE>::t_group_candidate m_square_candidates[sudoku_configuration<SIZE>::m_nb_value]; typename sudoku_types<SIZE>::t_available_values m_available_values; typename sudoku_types<SIZE>::t_nb_available_values m_nb_available_values; typename sudoku_types<SIZE>::t_available_values m_values_to_release; typename sudoku_types<SIZE>::t_data_type m_value; bool m_value_set; unsigned int m_hypothesis_level; bool m_modified; }; } #include "sudoku_internal_state.hpp" #endif // SUDOKU_INTERNAL_STATE_H //EOF
Java
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-02-20 22:01 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('erudit', '0065_auto_20170202_1152'), ] operations = [ migrations.AddField( model_name='issue', name='force_free_access', field=models.BooleanField(default=False, verbose_name='Contraindre en libre accès'), ), ]
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Modules.InstantAction.Views { /// <summary> /// InstantActionPage.xaml の相互作用ロジック /// </summary> public partial class InstantActionPage : UserControl { public InstantActionPage() { InitializeComponent(); } } public class InstantActionStepDataTemplateSelecter : DataTemplateSelector { public DataTemplate EmptyTemplate { get; set; } public DataTemplate FileSelectTemplate { get; set; } public DataTemplate ActionSelectTemplate { get; set; } public DataTemplate FinishingTemplate { get; set; } public override DataTemplate SelectTemplate(object item, DependencyObject container) { if (item == null) { return EmptyTemplate; } else if (item is ViewModels.FileSelectInstantActionStepViewModel) { return FileSelectTemplate; } else if (item is ViewModels.ActionsSelectInstantActionStepViewModel) { return ActionSelectTemplate; } else if (item is ViewModels.FinishingInstantActionStepViewModel) { return FinishingTemplate; } return base.SelectTemplate(item, container); } } }
Java
package bartburg.nl.backbaseweather.provision.remote.controller; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.annotation.Annotation; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import bartburg.nl.backbaseweather.AppConstants; import bartburg.nl.backbaseweather.provision.remote.annotation.ApiController; import bartburg.nl.backbaseweather.provision.remote.util.QueryStringUtil; import static bartburg.nl.backbaseweather.AppConstants.OPEN_WEATHER_MAP_BASE_URL; import static bartburg.nl.backbaseweather.AppConstants.OPEN_WEATHER_PROTOCOL; /** * Created by Bart on 6/3/2017. */ public abstract class BaseApiController { /** * Do the actual work of requesting data from the server. Note, should not run on main thread. * * @param parameters Parameters that will be added to the query string. * @param onErrorListener Listener that will get called when status code is not 200 * @return The result string or *null* when failed. */ @Nullable public String get(HashMap<String, String> parameters, @Nullable OnErrorListener onErrorListener) { return get(parameters, onErrorListener, null); } /** * Do the actual work of requesting data from the server. Note, should not run on main thread. * * @param parameters Parameters that will be added to the query string. * @param onErrorListener Listener that will get called when status code is not 200 * @param customRelativePath Use this if you want to provide a custom relative path (not the one from the annotation). * @return The result string or *null* when failed. */ @Nullable public String get(HashMap<String, String> parameters, @Nullable OnErrorListener onErrorListener, @Nullable String customRelativePath) { try { parameters.put("appid", AppConstants.OPEN_WEATHER_MAP_KEY); URL url = new URL(OPEN_WEATHER_PROTOCOL + OPEN_WEATHER_MAP_BASE_URL + getRelativePath(customRelativePath) + QueryStringUtil.mapToQueryString(parameters)); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); int responseCode = urlConnection.getResponseCode(); String responseMessage = urlConnection.getResponseMessage(); if (responseCode != 200 && onErrorListener != null) { onErrorListener.onError(responseCode, responseMessage); } else { return readInputStream(urlConnection); } } catch (IOException e) { e.printStackTrace(); } return null; } @NonNull private String readInputStream(HttpURLConnection urlConnection) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line).append("\n"); } br.close(); return sb.toString(); } public interface OnErrorListener { void onError(int responseCode, String responseMessage); } private String getRelativePath(String customRelativePath) { if (customRelativePath != null) { return customRelativePath; } Class<? extends BaseApiController> aClass = getClass(); if (aClass.isAnnotationPresent(ApiController.class)) { Annotation annotation = aClass.getAnnotation(ApiController.class); ApiController apiController = (ApiController) annotation; return apiController.relativePath(); } return ""; } }
Java
/***************************************************************** * This file is part of CCAFS Planning and Reporting Platform. * CCAFS P&R 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. * CCAFS P&R 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 CCAFS P&R. If not, see <http://www.gnu.org/licenses/>. * *************************************************************** */ package org.cgiar.ccafs.ap.data.dao.mysql; import org.cgiar.ccafs.ap.data.dao.ProjectOtherContributionDAO; import org.cgiar.ccafs.utils.db.DAOManager; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import com.google.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Javier Andrés Gallego B. */ public class MySQLProjectOtherContributionDAO implements ProjectOtherContributionDAO { // Logger private static Logger LOG = LoggerFactory.getLogger(MySQLProjectOtherContributionDAO.class); private DAOManager databaseManager; @Inject public MySQLProjectOtherContributionDAO(DAOManager databaseManager) { this.databaseManager = databaseManager; } @Override public Map<String, String> getIPOtherContributionById(int ipOtherContributionId) { Map<String, String> ipOtherContributionData = new HashMap<String, String>(); LOG.debug(">> getIPOtherContributionById( ipOtherContributionId = {} )", ipOtherContributionId); StringBuilder query = new StringBuilder(); query.append("SELECT ipo.* "); query.append("FROM project_other_contributions as ipo "); query.append("WHERE ipo.id= "); query.append(ipOtherContributionId); try (Connection con = databaseManager.getConnection()) { ResultSet rs = databaseManager.makeQuery(query.toString(), con); if (rs.next()) { ipOtherContributionData.put("id", rs.getString("id")); ipOtherContributionData.put("project_id", rs.getString("project_id")); ipOtherContributionData.put("contribution", rs.getString("contribution")); ipOtherContributionData.put("additional_contribution", rs.getString("additional_contribution")); ipOtherContributionData.put("crp_contributions_nature", rs.getString("crp_contributions_nature")); } con.close(); } catch (SQLException e) { LOG.error("Exception arised getting the IP Other Contribution {}.", ipOtherContributionId, e); } LOG.debug("-- getIPOtherContributionById() > Calling method executeQuery to get the results"); return ipOtherContributionData; } @Override public Map<String, String> getIPOtherContributionByProjectId(int projectID) { LOG.debug(">> getIPOtherContributionByProjectId (projectID = {} )", projectID); Map<String, String> ipOtherContributionData = new HashMap<String, String>(); StringBuilder query = new StringBuilder(); query.append("SELECT ipo.* "); query.append("FROM project_other_contributions as ipo "); query.append("INNER JOIN projects p ON ipo.project_id = p.id "); query.append("WHERE ipo.project_id= "); query.append(projectID); try (Connection con = databaseManager.getConnection()) { ResultSet rs = databaseManager.makeQuery(query.toString(), con); if (rs.next()) { ipOtherContributionData.put("id", rs.getString("id")); ipOtherContributionData.put("project_id", rs.getString("project_id")); ipOtherContributionData.put("contribution", rs.getString("contribution")); ipOtherContributionData.put("additional_contribution", rs.getString("additional_contribution")); ipOtherContributionData.put("crp_contributions_nature", rs.getString("crp_contributions_nature")); } con.close(); } catch (SQLException e) { LOG.error("Exception arised getting the IP Other Contribution by the projectID {}.", projectID, e); } LOG.debug("-- getIPOtherContributionByProjectId() : {}", ipOtherContributionData); return ipOtherContributionData; } @Override public int saveIPOtherContribution(int projectID, Map<String, Object> ipOtherContributionData) { LOG.debug(">> saveIPOtherContribution(ipOtherContributionDataData={})", ipOtherContributionData); StringBuilder query = new StringBuilder(); int result = -1; Object[] values; if (ipOtherContributionData.get("id") == null) { // Insert new IP Other Contribution record query.append("INSERT INTO project_other_contributions (project_id, contribution, additional_contribution, "); query.append("crp_contributions_nature, created_by, modified_by, modification_justification) "); query.append("VALUES (?,?,?,?,?,?,?) "); values = new Object[7]; values[0] = projectID; values[1] = ipOtherContributionData.get("contribution"); values[2] = ipOtherContributionData.get("additional_contribution"); values[3] = ipOtherContributionData.get("crp_contributions_nature"); values[4] = ipOtherContributionData.get("user_id"); values[5] = ipOtherContributionData.get("user_id"); values[6] = ipOtherContributionData.get("justification"); result = databaseManager.saveData(query.toString(), values); if (result <= 0) { LOG.error("A problem happened trying to add a new IP Other Contribution with project id={}", projectID); return -1; } } else { // update IP Other Contribution record query.append("UPDATE project_other_contributions SET project_id = ?, contribution = ?, "); query.append("additional_contribution = ?, crp_contributions_nature = ?, modified_by = ?, "); query.append("modification_justification = ? WHERE id = ? "); values = new Object[7]; values[0] = projectID; values[1] = ipOtherContributionData.get("contribution"); values[2] = ipOtherContributionData.get("additional_contribution"); values[3] = ipOtherContributionData.get("crp_contributions_nature"); values[4] = ipOtherContributionData.get("user_id"); values[5] = ipOtherContributionData.get("justification"); values[6] = ipOtherContributionData.get("id"); result = databaseManager.saveData(query.toString(), values); if (result == -1) { LOG.error("A problem happened trying to update the IP Other Contribution identified with the id = {}", ipOtherContributionData.get("id")); return -1; } } LOG.debug("<< saveIPOtherContribution():{}", result); return result; } }
Java
<?php // Heading $_['heading_title'] = 'TargetPay Sofort Banking'; // Text $_['text_payment'] = 'Betaling'; $_['text_success'] = 'Gelukt: de TargetPay instellingen zijn gewijzigd!'; $_['text_edit'] = 'Bewerk TargetPay ' . $_['heading_title']; $_['text_sofort'] = '<a href="https://www.targetpay.com/signup?p_actiecode=YM3R2A" target="_blank"><img src="view/image/payment/sofort.png" alt="Sofort Banking via TargetPay" title="Sofort Banking via TargetPay" style="border: none;" /></a>'; $_['text_sale'] = 'Verkopen'; // Entry $_['entry_rtlo'] = 'TargetPay Layoutcode'; $_['entry_test'] = 'Test Mode'; $_['entry_total'] = 'Min.bedrag'; $_['entry_canceled_status'] = 'Afgebroken betaling'; $_['entry_pending_status'] = 'Succesvolle betaling'; $_['entry_geo_zone'] = 'Geo Zone'; $_['entry_status'] = 'Status'; $_['entry_sort_order'] = 'Sorteer volgorde'; // Error $_['error_permission'] = 'Waarschuwing: je bent niet gemachtigd om deze instellingen te wijzigen'; $_['error_rtlo'] = 'TargetPay layoutcode (rtlo) is verplicht!'; // Tab $_['tab_general'] = 'Algemeen'; $_['tab_status'] = 'Bestelstatussen'; // Help $_['help_test'] = 'Als ingeschakeld: alle transacties worden goedgekeurd, ook als de betaling geannuleerd is.'; $_['help_rtlo'] = 'Ga naar www.targetpay.com voor een gratis account, als je nog geen account hebt'; $_['help_total'] = 'Het orderbedrag waarboven deze betaalwijze beschikbaar is'; // Error $_['error_permission'] = 'Waarschuwing: je bent niet gemachtigd om deze instellingen te wijzigen'; $_['error_rtlo'] = 'Layoutcode is verplicht!';
Java
// ReSharper disable CheckNamespace using System; using System.Collections.Generic; public class Program { public static void Main() { var people = new Dictionary<string, Person>(); string input; while ((input = Console.ReadLine()) != "End") { var split = input.Split(); string name = split[0]; if (!people.ContainsKey(name)) { people.Add(name, new Person()); } Person person = people[name]; string infoType = split[1]; if (infoType == "company") { person.Company = new Company(split[2], split[3], double.Parse(split[4])); } else if (infoType == "pokemon") { person.Pokemon.Add(new Pokemon(split[2], split[3])); } else if (infoType == "parents") { person.Parents.Add(new Parent(split[2], split[3])); } else if (infoType == "children") { person.Children.Add(new Child(split[2], split[3])); } else if (infoType == "car") { person.Car = new Car(split[2], int.Parse(split[3])); } } string nameToPrint = Console.ReadLine(); Console.WriteLine(nameToPrint); people[nameToPrint].PrintInformation(); } }
Java
<?php /** * Zend Framework * * LICENSE * * This source file is subject to the new BSD license that is bundled * with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://framework.zend.com/license/new-bsd * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Form * @subpackage Element * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @version $Id: Exception.php 24594 2012-01-05 21:27:01Z matthew $ * @license http://framework.zend.com/license/new-bsd New BSD License */ /** Zend_Form_Exception */ require_once 'Zend/Form/Exception.php'; /** * Exception for Zend_Form component. * * @category Zend * @package Zend_Form * @subpackage Element * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Form_Element_Exception extends Zend_Form_Exception { }
Java
// +build linux package subsystem import ( "bufio" "errors" "fmt" "io" "os" "os/exec" "runtime" "strconv" "strings" ) type PlatformHeader LinuxHeader func NewPlatformHeader() *LinuxHeader { header := new(LinuxHeader) header.Devices = make(map[string]LinuxDevice) header.getDevsParts() return header } func (header *LinuxHeader) getDevsParts() { f, err := os.Open("/proc/diskstats") if err != nil { panic(err) } defer f.Close() scan := bufio.NewScanner(f) for scan.Scan() { var major, minor int var name string c, err := fmt.Sscanf(scan.Text(), "%d %d %s", &major, &minor, &name) if err != nil { panic(err) } if c != 3 { continue } header.DevsParts = append(header.DevsParts, name) if isDevice(name) { header.Devices[name] = LinuxDevice{ name, getPartitions(name), } } } } func isDevice(name string) bool { stat, err := os.Stat(fmt.Sprintf("/sys/block/%s", name)) if err == nil && stat.IsDir() { return true } return false } func getPartitions(name string) []string { var dir *os.File var fis []os.FileInfo var err error var parts = []string{} dir, err = os.Open(fmt.Sprintf("/sys/block/%s", name)) if err != nil { panic(err) } fis, err = dir.Readdir(0) if err != nil { panic(err) } for _, fi := range fis { _, err := os.Stat(fmt.Sprintf("/sys/block/%s/%s/stat", name, fi.Name())) if err == nil { // partition exists parts = append(parts, fi.Name()) } } return parts } func ReadCpuStat(record *StatRecord) error { f, ferr := os.Open("/proc/stat") if ferr != nil { return ferr } defer f.Close() if record.Cpu == nil { num_core := 0 out, err := exec.Command("nproc", "--all").Output() out_str := strings.TrimSpace(string(out)) if err == nil { num_core, err = strconv.Atoi(out_str) if err != nil { num_core = 0 } } if num_core == 0 { num_core = runtime.NumCPU() } record.Cpu = NewCpuStat(num_core) } else { record.Cpu.Clear() } if record.Proc == nil { record.Proc = NewProcStat() } else { record.Proc.Clear() } scan := bufio.NewScanner(f) for scan.Scan() { var err error var cpu string line := scan.Text() if line[0:4] == "cpu " { // Linux 2.6.33 or later _, err = fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d %d", &cpu, &record.Cpu.All.User, &record.Cpu.All.Nice, &record.Cpu.All.Sys, &record.Cpu.All.Idle, &record.Cpu.All.Iowait, &record.Cpu.All.Hardirq, &record.Cpu.All.Softirq, &record.Cpu.All.Steal, &record.Cpu.All.Guest, &record.Cpu.All.GuestNice) if err == io.EOF { // Linux 2.6.24 or later _, err = fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d", &cpu, &record.Cpu.All.User, &record.Cpu.All.Nice, &record.Cpu.All.Sys, &record.Cpu.All.Idle, &record.Cpu.All.Iowait, &record.Cpu.All.Hardirq, &record.Cpu.All.Softirq, &record.Cpu.All.Steal, &record.Cpu.All.Guest) record.Cpu.All.GuestNice = 0 } if err != nil { panic(err) } } else if line[0:3] == "cpu" { var n_core int var core_stat *CpuCoreStat // assume n_core < 10000 _, err = fmt.Sscanf(line[3:7], "%d", &n_core) if err != nil { panic(err) } core_stat = &record.Cpu.CoreStats[n_core] // Linux 2.6.33 or later _, err = fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d %d", &cpu, &core_stat.User, &core_stat.Nice, &core_stat.Sys, &core_stat.Idle, &core_stat.Iowait, &core_stat.Hardirq, &core_stat.Softirq, &core_stat.Steal, &core_stat.Guest, &core_stat.GuestNice) if err == io.EOF { // Linux 2.6.24 or later _, err = fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d", &cpu, &core_stat.User, &core_stat.Nice, &core_stat.Sys, &core_stat.Idle, &core_stat.Iowait, &core_stat.Hardirq, &core_stat.Softirq, &core_stat.Steal, &core_stat.Guest) } if err != nil { panic(err) } } else if line[0:5] == "ctxt " { _, err = fmt.Sscanf(line[4:], "%d", &record.Proc.ContextSwitch) if err != nil { panic(err) } } else if line[0:10] == "processes " { _, err = fmt.Sscanf(line[10:], "%d", &record.Proc.Fork) if err != nil { panic(err) } } } return nil } func parseInterruptStatEntry(line string, num_core int) (*InterruptStatEntry, error) { entry := new(InterruptStatEntry) entry.NumCore = num_core entry.IntrCounts = make([]int, num_core) tokens := strings.Fields(line) idx := 0 tok := tokens[0] tok = strings.TrimRight(tok, ":") if irqno, err := strconv.Atoi(tok); err == nil { entry.IrqNo = irqno entry.IrqType = "" } else { entry.IrqNo = -1 entry.IrqType = tok } for idx := 1; idx < num_core+1; idx += 1 { var c int var err error if idx >= len(tokens) { break } tok = tokens[idx] if c, err = strconv.Atoi(tok); err != nil { return nil, errors.New("Invalid string for IntrCounts element: " + tok) } entry.IntrCounts[idx-1] = c } idx = num_core + 1 if idx < len(tokens) { entry.Descr = strings.Join(tokens[idx:], " ") } else { entry.Descr = "" } return entry, nil } func ReadInterruptStat(record *StatRecord) error { intr_stat := NewInterruptStat() if record == nil { return errors.New("Valid *StatRecord is required.") } f, err := os.Open("/proc/interrupts") if err != nil { panic(err) } defer f.Close() scan := bufio.NewScanner(f) if !scan.Scan() { return errors.New("/proc/interrupts seems to be empty") } cores := strings.Fields(scan.Text()) num_core := len(cores) for scan.Scan() { entry, err := parseInterruptStatEntry(scan.Text(), num_core) if err != nil { return err } intr_stat.Entries = append(intr_stat.Entries, entry) intr_stat.NumEntries += 1 } record.Interrupt = intr_stat return nil } func ReadDiskStats(record *StatRecord, targets *map[string]bool) error { if record == nil { return errors.New("Valid *StatRecord is required.") } f, ferr := os.Open("/proc/diskstats") if ferr != nil { panic(ferr) } defer f.Close() if record.Disk == nil { record.Disk = NewDiskStat() } else { record.Disk.Clear() } scan := bufio.NewScanner(f) var num_items int var err error for scan.Scan() { var rdmerge_or_rdsec int64 var rdsec_or_wrios int64 var rdticks_or_wrsec int64 line := scan.Text() entry := NewDiskStatEntry() num_items, err = fmt.Sscanf(line, "%d %d %s %d %d %d %d %d %d %d %d %d %d %d", &entry.Major, &entry.Minor, &entry.Name, &entry.RdIos, &rdmerge_or_rdsec, &rdsec_or_wrios, &rdticks_or_wrsec, &entry.WrIos, &entry.WrMerges, &entry.WrSectors, &entry.WrTicks, &entry.IosPgr, &entry.TotalTicks, &entry.ReqTicks) if err != nil { return err } if num_items == 14 { entry.RdMerges = rdmerge_or_rdsec entry.RdSectors = rdsec_or_wrios entry.RdTicks = rdticks_or_wrsec } else if num_items == 7 { entry.RdSectors = rdmerge_or_rdsec entry.WrIos = rdsec_or_wrios entry.WrSectors = rdticks_or_wrsec } else { continue } if entry.RdIos == 0 && entry.WrIos == 0 { continue } if targets != nil { if _, ok := (*targets)[entry.Name]; !ok { // device not in targets continue } } else { if !isDevice(entry.Name) { continue } } record.Disk.Entries = append(record.Disk.Entries, entry) } return nil } func ReadNetStat(record *StatRecord) error { if record == nil { return errors.New("Valid *StatRecord is required.") } net_stat := NewNetStat() f, err := os.Open("/proc/net/dev") if err != nil { return err } defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { line := scanner.Text() switch { case line[0:7] == "Inter-|": continue case line[0:7] == " face |": continue } line = strings.Replace(line, ":", " ", -1) e := NewNetStatEntry() var devname string n, err := fmt.Sscanf(line, "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d", &devname, &e.RxBytes, &e.RxPackets, &e.RxErrors, &e.RxDrops, &e.RxFifo, &e.RxFrame, &e.RxCompressed, &e.RxMulticast, &e.TxBytes, &e.TxPackets, &e.TxErrors, &e.TxDrops, &e.TxFifo, &e.TxFrame, &e.TxCompressed, &e.TxMulticast) if err == io.EOF { break } else if err != nil { return err } if n != 17 { continue } // trim trailing ":" from devname if devname[len(devname)-1] == ':' { devname = devname[0 : len(devname)-1] } e.Name = devname net_stat.Entries = append(net_stat.Entries, e) } record.Net = net_stat return nil } func ReadMemStat(record *StatRecord) error { if record == nil { return errors.New("Valid *StatRecord is required.") } mem_stat := NewMemStat() f, err := os.Open("/proc/meminfo") if err != nil { return err } defer f.Close() scanner := bufio.NewScanner(f) for scanner.Scan() { var key string var val int64 line := scanner.Text() n, err := fmt.Sscanf(line, "%s %d", &key, &val) if err == io.EOF { break } else if err != nil { return err } if n != 2 { continue } switch key { case "HugePages_Surp:": mem_stat.HugePages_Surp = val case "HugePages_Rsvd:": mem_stat.HugePages_Rsvd = val case "HugePages_Free:": mem_stat.HugePages_Free = val case "HugePages_Total:": mem_stat.HugePages_Total = val case "Hugepagesize:": mem_stat.Hugepagesize = val case "AnonHugePages:": mem_stat.AnonHugePages = val case "Committed_AS:": mem_stat.Committed_AS = val case "CommitLimit:": mem_stat.CommitLimit = val case "Bounce:": mem_stat.Bounce = val case "NFS_Unstable:": mem_stat.NFS_Unstable = val case "Shmem:": mem_stat.Shmem = val case "Slab:": mem_stat.Slab = val case "SReclaimable:": mem_stat.SReclaimable = val case "SUnreclaim:": mem_stat.SUnreclaim = val case "KernelStack:": mem_stat.KernelStack = val case "PageTables:": mem_stat.PageTables = val case "Mapped:": mem_stat.Mapped = val case "AnonPages:": mem_stat.AnonPages = val case "Writeback:": mem_stat.Writeback = val case "Dirty:": mem_stat.Dirty = val case "SwapFree:": mem_stat.SwapFree = val case "SwapTotal:": mem_stat.SwapTotal = val case "Inactive:": mem_stat.Inactive = val case "Active:": mem_stat.Active = val case "SwapCached:": mem_stat.SwapCached = val case "Cached:": mem_stat.Cached = val case "Buffers:": mem_stat.Buffers = val case "MemFree:": mem_stat.MemFree = val case "MemTotal:": mem_stat.MemTotal = val } } record.Mem = mem_stat return nil }
Java
/* * tca6416 keypad platform support * * Copyright (C) 2010 Texas Instruments * * Author: Sriramakrishnan <srk@ti.com> * * 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. */ #ifndef _TCA6416_KEYS_H #define _TCA6416_KEYS_H #include <linux/types.h> struct tca6416_button { /* Configuration parameters */ int code; /* input event code (KEY_*, SW_*) */ int active_low; int type; /* input event type (EV_KEY, EV_SW) */ }; struct tca6416_keys_platform_data { struct tca6416_button *buttons; int nbuttons; unsigned int rep: 1; /* enable input subsystem auto repeat */ uint16_t pinmask; uint16_t invert; int irq_is_gpio; int use_polling; /* use polling if Interrupt is not connected*/ }; #endif
Java
////////// // item // ////////// datablock ItemData(YoyoItem) { category = "Weapon"; // Mission editor category className = "Weapon"; // For inventory system // Basic Item Properties shapeFile = "./Yoyo.dts"; rotate = false; mass = 1; density = 0.2; elasticity = 0.2; friction = 0.6; emap = true; //gui stuff uiName = "Yo-yo"; iconName = "./icon_Yoyo"; doColorShift = true; colorShiftColor = "0 1 1 1.000"; // Dynamic properties defined by the scripts image = YoyoImage; canDrop = true; }; //////////////// //weapon image// //////////////// datablock ShapeBaseImageData(YoyoImage) { // Basic Item properties shapeFile = "./Yoyo.dts"; emap = true; // Specify mount point & offset for 3rd person, and eye offset // for first person rendering. mountPoint = 0; offset = "0 0 0"; eyeOffset = 0; //"0.7 1.2 -0.5"; rotation = eulerToMatrix( "0 0 0" ); // When firing from a point offset from the eye, muzzle correction // will adjust the muzzle vector to point to the eye LOS point. // Since this weapon doesn't actually fire from the muzzle point, // we need to turn this off. correctMuzzleVector = true; // Add the WeaponImage namespace as a parent, WeaponImage namespace // provides some hooks into the inventory system. className = "WeaponImage"; // Projectile && Ammo. item = YoyoItem; projectile = emptyProjectile; projectileType = Projectile; ammo = " "; //melee particles shoot from eye node for consistancy melee = false; //raise your arm up or not armReady = true; doColorShift = true; colorShiftColor = YoyoItem.colorShiftColor;//"0.400 0.196 0 1.000"; //casing = " "; // Images have a state system which controls how the animations // are run, which sounds are played, script callbacks, etc. This // state system is downloaded to the client so that clients can // predict state changes and animate accordingly. The following // system supports basic ready->fire->reload transitions as // well as a no-ammo->dryfire idle state. // Initial start up state stateName[0] = "Activate"; stateTimeoutValue[0] = 0.15; stateTransitionOnTimeout[0] = "Ready"; stateSound[0] = weaponSwitchSound; stateName[1] = "Ready"; stateTransitionOnTriggerDown[1] = "Fire"; stateAllowImageChange[1] = true; stateSequence[1] = "Ready"; stateName[2] = "Fire"; stateTimeoutValue[2] = 1.1; stateTransitionOnTimeout[2] = "Reload"; stateSequence[2] = "fire"; stateScript[2] = "OnFire"; stateName[3] = "Reload"; stateSequence[3] = "Reload"; stateTransitionOnTriggerUp[3] = "Ready"; stateSequence[3] = "Ready"; };
Java
/** ****************************************************************************** * @file EEPROM/EEPROM_Emulation/Inc/stm32f4xx_it.h * @author MCD Application Team * @version V1.3.6 * @date 17-February-2017 * @brief This file contains the headers of the interrupt handlers. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2> * * 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. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F4xx_IT_H #define __STM32F4xx_IT_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "main.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void NMI_Handler(void); void HardFault_Handler(void); void MemManage_Handler(void); void BusFault_Handler(void); void UsageFault_Handler(void); void SVC_Handler(void); void DebugMon_Handler(void); void PendSV_Handler(void); void SysTick_Handler(void); #ifdef __cplusplus } #endif #endif /* __STM32F4xx_IT_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
Java
// Copyright 2016 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. #include "services/video_capture/device_mojo_mock_to_media_adapter.h" #include "services/video_capture/device_client_media_to_mojo_mock_adapter.h" namespace video_capture { DeviceMojoMockToMediaAdapter::DeviceMojoMockToMediaAdapter( mojom::MockMediaDevicePtr* device) : device_(device) {} DeviceMojoMockToMediaAdapter::~DeviceMojoMockToMediaAdapter() = default; void DeviceMojoMockToMediaAdapter::AllocateAndStart( const media::VideoCaptureParams& params, std::unique_ptr<Client> client) { mojom::MockDeviceClientPtr client_proxy; auto client_request = mojo::GetProxy(&client_proxy); mojo::MakeStrongBinding( base::MakeUnique<DeviceClientMediaToMojoMockAdapter>(std::move(client)), std::move(client_request)); (*device_)->AllocateAndStart(std::move(client_proxy)); } void DeviceMojoMockToMediaAdapter::RequestRefreshFrame() {} void DeviceMojoMockToMediaAdapter::StopAndDeAllocate() { (*device_)->StopAndDeAllocate(); } void DeviceMojoMockToMediaAdapter::GetPhotoCapabilities( GetPhotoCapabilitiesCallback callback) {} void DeviceMojoMockToMediaAdapter::SetPhotoOptions( media::mojom::PhotoSettingsPtr settings, SetPhotoOptionsCallback callback) {} void DeviceMojoMockToMediaAdapter::TakePhoto(TakePhotoCallback callback) {} } // namespace video_capture
Java
package com.ocams.andre; import javax.swing.table.DefaultTableModel; public class MasterJurnal extends javax.swing.JFrame { public MasterJurnal() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jTextField3 = new javax.swing.JTextField(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jScrollPane2 = new javax.swing.JScrollPane(); jTable2 = new javax.swing.JTable(); jTextField4 = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("Kode:"); jLabel2.setText("Perkiraan:"); jLabel3.setText("Nomor Referensi:"); jLabel4.setText("Posisi:"); jLabel5.setText("Harga:"); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); buttonGroup1.add(jRadioButton1); jRadioButton1.setText("Debit"); buttonGroup1.add(jRadioButton2); jRadioButton2.setText("Kredit"); jLabel6.setText("User:"); jLabel7.setText("NamaUser"); jButton1.setText("Logout"); jButton2.setText("Insert"); jButton2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton2MouseClicked(evt); } }); jButton3.setText("Update"); jButton3.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton3MouseClicked(evt); } }); jButton4.setText("Delete"); jButton4.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jButton4MouseClicked(evt); } }); jTable2.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Kode", "Perkiraan", "No. Ref.", "Posisi", "Harga" } )); jTable2.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTable2MouseClicked(evt); } }); jScrollPane2.setViewportView(jTable2); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel2) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel7)) .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton4)) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jRadioButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jRadioButton2)) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6) .addComponent(jLabel7)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jRadioButton1) .addComponent(jRadioButton2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jButton3) .addComponent(jButton4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked String kode = jTextField1.getText(); String perkiraan = jTextField2.getText(); String noref = jTextField3.getText(); String posisi = ""; if (jRadioButton1.isSelected() == true){ posisi = "Debit"; }else if (jRadioButton2.isSelected() == true){ posisi = "Kredit"; } String harga = jTextField4.getText(); Object[] row = {kode,perkiraan,noref,posisi,harga}; DefaultTableModel model = (DefaultTableModel) jTable2.getModel(); model.addRow(row); }//GEN-LAST:event_jButton2MouseClicked private void jButton3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MouseClicked int baris = jTable2.rowAtPoint(evt.getPoint()); String kode = jTextField1.getText(); String perkiraan = jTextField2.getText(); String noref = jTextField3.getText(); String posisi = ""; if (jRadioButton1.isSelected() == true){ posisi = "Debit"; }else if (jRadioButton2.isSelected() == true){ posisi = "Kredit"; } String harga = jTextField4.getText(); DefaultTableModel model = (DefaultTableModel) jTable2.getModel(); model.setValueAt(kode, baris, 0); model.setValueAt(perkiraan, baris, 1); model.setValueAt(noref, baris, 2); model.setValueAt(posisi, baris, 3); model.setValueAt(harga, baris, 4); }//GEN-LAST:event_jButton3MouseClicked private void jButton4MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton4MouseClicked DefaultTableModel model = (DefaultTableModel) jTable2.getModel(); model.removeRow(jTable2.rowAtPoint(evt.getPoint())); }//GEN-LAST:event_jButton4MouseClicked private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable2MouseClicked int baris = jTable2.rowAtPoint(evt.getPoint()); jTextField1.setText(String.valueOf(jTable2.getValueAt(baris, 0))); jTextField2.setText(String.valueOf(jTable2.getValueAt(baris, 1))); jTextField3.setText(String.valueOf(jTable2.getValueAt(baris,2))); String posisi = String.valueOf(jTable2.getValueAt(baris, 3)); if ("debit".equalsIgnoreCase(posisi)){ jRadioButton1.setSelected(true); }else if ("kredit".equalsIgnoreCase(posisi)){ jRadioButton2.setSelected(true); } jTextField4.setText(String.valueOf(jTable2.getValueAt(baris, 4))); }//GEN-LAST:event_jTable2MouseClicked private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MasterJurnal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MasterJurnal().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTable jTable2; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JTextField jTextField3; private javax.swing.JTextField jTextField4; // End of variables declaration//GEN-END:variables }
Java
// Copyright (c) Athena Dev Teams - Licensed under GNU GPL // For more information, see LICENCE in the main folder #ifndef _DUEL_H_ #define _DUEL_H_ struct duel { int members_count; int invites_count; int max_players_limit; }; #define MAX_DUEL 1024 extern struct duel duel_list[MAX_DUEL]; extern int duel_count; //Duel functions // [LuzZza] int duel_create (struct map_session_data *sd, const unsigned int maxpl); int duel_invite (const unsigned int did, struct map_session_data *sd, struct map_session_data *target_sd); int duel_accept (const unsigned int did, struct map_session_data *sd); int duel_reject (const unsigned int did, struct map_session_data *sd); int duel_leave (const unsigned int did, struct map_session_data *sd); int duel_showinfo (const unsigned int did, struct map_session_data *sd); int duel_checktime (struct map_session_data *sd); int do_init_duel (void); void do_final_duel (void); #endif /* _DUEL_H_ */
Java
# containers
Java
/* * generated by Xtext */ package org.eclectic.frontend.parser.antlr; import com.google.inject.Inject; import org.eclipse.xtext.parser.antlr.XtextTokenStream; import org.eclectic.frontend.services.TaoGrammarAccess; public class TaoParser extends org.eclipse.xtext.parser.antlr.AbstractAntlrParser { @Inject private TaoGrammarAccess grammarAccess; @Override protected void setInitialHiddenTokens(XtextTokenStream tokenStream) { tokenStream.setInitialHiddenTokens("RULE_WS", "RULE_ML_COMMENT", "RULE_SL_COMMENT"); } @Override protected org.eclectic.frontend.parser.antlr.internal.InternalTaoParser createParser(XtextTokenStream stream) { return new org.eclectic.frontend.parser.antlr.internal.InternalTaoParser(stream, getGrammarAccess()); } @Override protected String getDefaultRuleName() { return "TaoTransformation"; } public TaoGrammarAccess getGrammarAccess() { return this.grammarAccess; } public void setGrammarAccess(TaoGrammarAccess grammarAccess) { this.grammarAccess = grammarAccess; } }
Java
<?php require "common.inc.php"; verifica_seguranca($_SESSION[PAP_RESP_MUTIRAO]); top(); ?> <?php $action = request_get("action",-1); if($action==-1) $action=ACAO_EXIBIR_LEITURA; $est_cha=request_get("est_cha",-1); if($est_cha==-1) { if(isset($_SESSION['cha_id_pref'])) { $est_cha=$_SESSION['cha_id_pref']; } } $_SESSION['cha_id_pref']=$est_cha; if ($est_cha<>-1) { $sql = "SELECT prodt_nome, DATE_FORMAT(cha_dt_entrega,'%d/%m/%Y') cha_dt_entrega, cha_taxa_percentual, ((cha_dt_prazo_contabil is null) OR (cha_dt_prazo_contabil > now() ) ) as cha_dentro_prazo, date_format(cha_dt_prazo_contabil,'%d/%m/%Y %H:%i') cha_dt_prazo_contabil "; $sql.= "FROM chamadas LEFT JOIN produtotipos ON prodt_id = cha_prodt "; $sql.= "WHERE cha_id = " . prep_para_bd($est_cha); $res = executa_sql($sql); if ($row = mysqli_fetch_array($res,MYSQLI_ASSOC)) { $prodt_nome = $row["prodt_nome"]; $cha_dt_entrega = $row["cha_dt_entrega"]; $cha_taxa_percentual = $row["cha_taxa_percentual"]; $cha_dt_prazo_contabil = $row["cha_dt_prazo_contabil"]; $cha_dentro_prazo = $row["cha_dentro_prazo"]; } } if ($action == ACAO_SALVAR) // salvar formulário preenchido { // salva disponibilidade de produtos $n = isset($_REQUEST['est_prod']) ? sizeof($_REQUEST['est_prod']) : 0; for($i=0;$i<$n;$i++) { $est_cha_bd = prep_para_bd($est_cha); $qtde_antes_bd = $_REQUEST['est_prod_qtde_antes'][$i] <>"" ? prep_para_bd(formata_numero_para_mysql($_REQUEST['est_prod_qtde_antes'][$i])) : 'NULL'; $obs_antes_bd = $_REQUEST['est_obs_antes'][$i] <>"" ? prep_para_bd($_REQUEST['est_obs_antes'][$i]) : 'NULL'; $sql = "INSERT INTO estoque (est_cha, est_prod, est_prod_qtde_antes, est_obs_antes ) "; $sql.= "VALUES ( " . $est_cha_bd . " ," . prep_para_bd($_REQUEST['est_prod'][$i]) . ", "; $sql.= $qtde_antes_bd . ", " . $obs_antes_bd . ") "; $sql.= "ON DUPLICATE KEY UPDATE "; $sql.= " est_prod_qtde_antes = " . $qtde_antes_bd . ", "; $sql.= " est_obs_antes = " . $obs_antes_bd . " "; $res = executa_sql($sql); } if($res) { $action=ACAO_EXIBIR_LEITURA; //volta para modo visualização somente leitura adiciona_mensagem_status(MSG_TIPO_SUCESSO,"As informações de estoque relacionado à chamada " . $cha_dt_entrega . " foram salvas com sucesso."); } else { adiciona_mensagem_status(MSG_TIPO_ERRO,"Erro ao tentar salvar informações de estoque da chamada para o dia " . $cha_dt_entrega . "."); } escreve_mensagem_status(); } if ($action == ACAO_EXIBIR_LEITURA || $action == ACAO_EXIBIR_EDICAO ) // exibir para visualização, ou exibir para edição { } ?> <ul class="nav nav-tabs"> <li><a href="mutirao.php">Mutirão</a></li> <li class="active"><a href="#"><i class="glyphicon glyphicon-bed"></i> Estoque Pré-Mutirão</a></li> <li><a href="recebimento.php"><i class="glyphicon glyphicon-road"></i> Recebimento</a></li> <li><a href="distribuicao_consolidado_por_produtor.php"><i class="glyphicon glyphicon-fullscreen"></i> Distribuição</a></li> <li><a href="estoque_pos.php"><i class="glyphicon glyphicon-bed"></i> Estoque Pós-Mutirão</a></li> <li><a href="mutirao_divergencias.php"><i class="glyphicon glyphicon-eye-open"></i> Divergências</a></li> </ul> <br> <div class="panel panel-default"> <div class="panel-heading"> <strong>Estoque Pré-Mutirão</strong> </div> <?php if($action==ACAO_EXIBIR_LEITURA) //visualização somente leitura { ?> <div class="panel-body"> <form class="form-inline" method="get" name="frm_filtro" id="frm_filtro"> <?php ?> <fieldset> <div class="form-group"> <label for="est_cha">Chamada: </label> <select name="est_cha" id="est_cha" onchange="javascript:frm_filtro.submit();" class="form-control"> <option value="-1">SELECIONE</option> <?php $sql = "SELECT cha_id, prodt_nome, cha_dt_entrega cha_dt_entrega_original, DATE_FORMAT(cha_dt_entrega,'%d/%m/%Y') cha_dt_entrega "; $sql.= "FROM chamadas LEFT JOIN produtotipos ON prodt_id = cha_prodt "; $sql.= "WHERE prodt_mutirao = '1' "; $sql.= "ORDER BY cha_dt_entrega_original DESC LIMIT 10"; $res = executa_sql($sql); if($res) { $achou=false; while ($row = mysqli_fetch_array($res,MYSQLI_ASSOC)) { echo("<option value='" . $row['cha_id'] . "'"); if($row['cha_id']==$est_cha) { echo(" selected"); $achou=true; } echo (">" . $row['prodt_nome'] . " - " . $row['cha_dt_entrega'] . "</option>"); } if($est_cha!=-1 && !$achou) { $sql = "SELECT cha_id, prodt_nome, cha_dt_entrega cha_dt_entrega_original, DATE_FORMAT(cha_dt_entrega,'%d/%m/%Y') cha_dt_entrega "; $sql.= "FROM chamadas LEFT JOIN produtotipos ON prodt_id = cha_prodt "; $sql.= "WHERE cha_id = " . prep_para_bd($est_cha); $res2 = executa_sql($sql); $row = mysqli_fetch_array($res2,MYSQLI_ASSOC); if($row) { echo("<option value='" . $row['cha_id'] . "' selected>"); echo ($row['prodt_nome'] . " - " . $row['cha_dt_entrega'] . "</option>"); } } } ?> </select> <?php if($est_cha!=-1) { ?> &nbsp;&nbsp; <label for="cha_dt_prazo_contabil">Prazo para Edição: </label> <?php echo($cha_dt_prazo_contabil?$cha_dt_prazo_contabil:"ainda não configurado"); ?> <?php if(!$cha_dentro_prazo) { echo("<span class='alert alert-danger'>(encerrado)</span>"); } } ?> </div> </fieldset> </form> </div> <?php if($est_cha!=-1) { $sql = "SELECT prod_id, prod_nome, estoque.est_prod_qtde_antes est_atual_prod_qtde_antes, "; $sql.= "estoque.est_obs_antes est_atual_obs_antes, "; $sql.= "estoque_anterior.est_prod_qtde_depois est_anterior_prod_qtde_depois, prod_unidade, "; $sql.= "chaprod_prod, forn_nome_curto, forn_nome_completo, forn_id FROM chamadaprodutos "; $sql.= "LEFT JOIN produtos on chaprod_prod = prod_id "; $sql.= "LEFT JOIN chamadas on chaprod_cha = cha_id "; $sql.= "LEFT JOIN fornecedores on prod_forn = forn_id "; $sql.= "LEFT JOIN estoque on est_cha = cha_id AND est_prod = chaprod_prod "; $sql.="LEFT JOIN estoque estoque_anterior ON estoque_anterior.est_prod = chaprod_prod AND estoque_anterior.est_cha = " . prep_para_bd(get_chamada_anterior($est_cha)) . " "; $sql.= "WHERE prod_ini_validade<=NOW() AND prod_fim_validade>=NOW() "; $sql.= "AND chaprod_cha = " . prep_para_bd($est_cha) . " AND chaprod_disponibilidade > 0 "; $sql.= " AND (estoque.est_prod_qtde_antes >0 OR estoque_anterior.est_prod_qtde_depois > 0 OR estoque.est_obs_antes IS NOT NULL ) "; $sql.= "ORDER BY forn_nome_curto, prod_nome, prod_unidade "; $res = executa_sql($sql); if($res && mysqli_num_rows($res)==0) { ?> <div class="panel-body"> <!-- <button type="button" class="btn btn-default btn-enviando" data-loading-text="importando..." onclick="javascript:location.href='estoque_pre.php?action=<?php echo(ACAO_EXIBIR_LEITURA);?>&est_cha=<?php echo($est_cha); ?>&importar=sim'"> <i class="icon glyphicon glyphicon-resize-small"></i> importar estoque do último mutirão </button> --> <br /><div class='well'> Sem produtos em estoque. Se de fato houver, clique em editar para registrar. </div><br /> </div> <?php } else if($res) { ?> <table class="table table-striped table-bordered table-condensed table-hover"> <thead> <tr> <th colspan="3">Informações de Estoque Pré-Mutirão da Entrega de <?php echo($prodt_nome . " - " . $cha_dt_entrega); ?></th> <th colspan="2"> <?php if($cha_dentro_prazo) { ?> <a class="btn btn-primary" href="estoque_pre.php?action=<?php echo(ACAO_EXIBIR_EDICAO); ?>&cha_id=<?php echo($est_cha); ?>"><i class="glyphicon glyphicon-edit"></i> editar</a> <?php } else { echo("&nbsp;"); } ?> </th> </tr> </thead> <tbody> <?php $ultimo_forn = ""; while ($row = mysqli_fetch_array($res,MYSQLI_ASSOC)) { if($row["forn_nome_curto"]!=$ultimo_forn) { $ultimo_forn = $row["forn_nome_curto"]; ?> <tr> <th> <?php echo($row["forn_nome_curto"]); adiciona_popover_descricao("",$row["forn_nome_completo"]); ?> </th> <th>Unidade</th> <th>Estoque Pré-Mutirão Esperado<?php adiciona_popover_descricao("Descrição", " = Estoque final informado pelo Mutirão anterior"); ?></th> <th>Estoque Pré-Mutirão Real</th> <th>Observação</th> </tr> <?php } ?> <tr> <td><?php echo($row["prod_nome"]);?></td> <td><?php echo($row["prod_unidade"]); ?></td> <td> <?php if($row["est_anterior_prod_qtde_depois"]) echo_digitos_significativos($row["est_anterior_prod_qtde_depois"]); else echo("&nbsp;"); ?> </td> <td <?php if($row["est_anterior_prod_qtde_depois"] != $row["est_atual_prod_qtde_antes"]) echo(" class='" . (($row["est_atual_obs_antes"]) ? "info" : "danger") . "'");?>> <?php if($row["est_atual_prod_qtde_antes"]) echo_digitos_significativos($row["est_atual_prod_qtde_antes"]); else echo("&nbsp;"); ?> </td> <td> <?php echo( ($row["est_atual_obs_antes"]) ? $row["est_atual_obs_antes"] : "&nbsp;") ; ?> </td> </tr> <?php } echo("</tbody></table>"); } ?> </div> <?php if($est_cha!=-1 && $cha_dentro_prazo) { ?> <div align="right"> <a class="btn btn-primary" href="estoque_pre.php?action=<?php echo(ACAO_EXIBIR_EDICAO); ?>&est_cha=<?php echo($est_cha); ?>"><i class="glyphicon glyphicon-edit glyphicon-white"></i> editar</a> </div> <?php } } // fim if est_cha !=-1 ?> <?php } else //visualização para edição { ?> <form class="form-horizontal" method="post"> <div class="panel-body"> <div align="right"> <button type="submit" class="btn btn-primary btn-enviando" data-loading-text="salvando estoque..."> <i class="glyphicon glyphicon-ok glyphicon-white"></i> salvar alterações</button> &nbsp;&nbsp; <button class="btn btn-default" type="button" onclick="javascript:location.href='estoque_pre.php?action=<?php echo(ACAO_EXIBIR_LEITURA); ?>&est_cha=<?php echo($est_cha); ?>';"><i class="glyphicon glyphicon-off"></i> descartar alterações</button> </div> </div> <fieldset> <input type="hidden" name="est_cha" value="<?php echo($est_cha); ?>" /> <input type="hidden" name="action" value="<?php echo(ACAO_SALVAR); ?>" /> <div class="form-group"> <div class="container"> <?php $sql = "SELECT prod_id, prod_nome, estoque.est_prod_qtde_antes est_atual_prod_qtde_antes, "; $sql.= "estoque.est_obs_antes est_atual_obs_antes, "; $sql.= "estoque_anterior.est_prod_qtde_depois est_anterior_prod_qtde_depois, prod_unidade, "; $sql.= "chaprod_prod, forn_nome_curto, forn_nome_completo, forn_id FROM chamadaprodutos "; $sql.= "LEFT JOIN produtos on chaprod_prod = prod_id "; $sql.= "LEFT JOIN chamadas on chaprod_cha = cha_id "; $sql.= "LEFT JOIN fornecedores on prod_forn = forn_id "; $sql.= "LEFT JOIN estoque on est_cha = cha_id AND est_prod = chaprod_prod "; $sql.="LEFT JOIN estoque estoque_anterior ON estoque_anterior.est_prod = chaprod_prod AND estoque_anterior.est_cha = " . prep_para_bd(get_chamada_anterior($est_cha)) . " "; $sql.= "WHERE prod_ini_validade<=NOW() AND prod_fim_validade>=NOW() "; $sql.= "AND chaprod_cha = " . prep_para_bd($est_cha) . " AND chaprod_disponibilidade > 0 "; $sql.= "ORDER BY forn_nome_curto, prod_nome, prod_unidade "; $res = executa_sql($sql); if($res) { ?> <table class='table table-striped table-bordered table-condensed table-hover'> <thead> <tr> <th colspan="5"> Informações de Estoque Pré-Mutirão relacionado à chamada de <?php echo($prodt_nome . " - " . $cha_dt_entrega); ?> </th> </tr> </thead> <tbody> <tr> <td>&nbsp;</td><td>&nbsp;</td> <td colspan="2"> <button type="button" class="btn btn-info" name="copia_produtos_pedido" id="copia_produtos_pedido" onclick="javascript:replicaDados('replica-origem','replica-destino');"> <i class="glyphicon glyphicon-paste"></i> replicar do estoque esperado </button> </td> <td>&nbsp;</td> </tr> <?php $ultimo_forn = ""; while ($row = mysqli_fetch_array($res,MYSQLI_ASSOC)) { if($row["forn_nome_curto"]!=$ultimo_forn) { $ultimo_forn = $row["forn_nome_curto"]; ?> <tr> <th> <?php echo($row["forn_nome_curto"]); adiciona_popover_descricao("",$row["forn_nome_completo"]); ?> </th> <th>Unidade</th> <th>Estoque Pré-Mutirão Esperado<?php adiciona_popover_descricao("Descrição", " = Estoque final informado pelo Mutirão anterior"); ?></th> <th>Estoque Pré-Mutirão Real</th> <th>Observação</th> </tr> <?php } ?> <tr> <input type="hidden" name="est_prod[]" value="<?php echo($row["prod_id"]); ?>"/> <td><?php echo($row["prod_nome"]);?></td> <td><?php echo($row["prod_unidade"]); ?></td> <td style="text-align:center"> <input type="hidden" name="est_anterior_prod_qtde_depois[]" class="replica-origem" value="<?php if($row["est_anterior_prod_qtde_depois"]) echo_digitos_significativos($row["est_anterior_prod_qtde_depois"]); ?>"> <?php if($row["est_anterior_prod_qtde_depois"]) echo_digitos_significativos($row["est_anterior_prod_qtde_depois"],"0"); ?> </td> <td> <input type="text" class="replica-destino form-control propaga-colar numero-positivo" style="font-size:18px; text-align:center;" value="<?php if($row["est_atual_prod_qtde_antes"]) echo_digitos_significativos($row["est_atual_prod_qtde_antes"],"0"); ?>" name="est_prod_qtde_antes[]" id="est_prod_qtde_antes_<?php echo($row["prod_id"]); ?>"/> </td> <td> <input type="text" class="form-control" value="<?php if($row["est_atual_obs_antes"]) echo($row["est_atual_obs_antes"]); ?>" name="est_obs_antes[]" id="est_obs_antes_<?php echo($row["prod_id"]); ?>"/> </td> </tr> <?php } echo("</tbody></table>"); } ?> </div> </div> <div align="right"> <button type="submit" class="btn btn-primary btn-enviando" data-loading-text="salvando estoque..."> <i class="glyphicon glyphicon-ok glyphicon-white"></i> salvar alterações</button> &nbsp;&nbsp; <button class="btn btn-default" type="button" onclick="javascript:location.href='estoque_pre.php?action=<?php echo(ACAO_EXIBIR_LEITURA); ?>&est_cha=<?php echo($est_cha); ?>';"><i class="glyphicon glyphicon-off"></i> descartar alterações</button> </div> </fieldset> </form> <?php } footer(); ?>
Java
jQuery(document).ready(function($) { $('#slide-left').flexslider({ animation: "slide", controlNav: "thumbnails", start: function(slider) { $('ol.flex-control-thumbs li img.flex-active').parent('li').addClass('active'); } }); }); jQuery(document).ready(function($) { $('#slide').flexslider({ animation: "slide", controlNav: false, directionNav: true }); });
Java
/* * This file is part of the command-line tool sosicon. * Copyright (C) 2014 Espen Andersen, Norwegian Broadcast Corporation (NRK) * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "converter_sosi2tsv.h" void sosicon::ConverterSosi2tsv:: run( bool* ) { }
Java
use crate::cube::Cube; use glium; use glium::{Display, Program, Surface, implement_vertex}; use glium::index::{IndexBuffer, PrimitiveType}; use std::rc::Rc; pub fn solid_fill_program(display: &Display) -> Program { let vertex_shader_src = include_str!("shaders/solid.vert"); let fragment_shader_src = include_str!("shaders/solid.frag"); Program::from_source(display, vertex_shader_src, fragment_shader_src, None).unwrap() } #[derive(Copy, Clone)] struct Vertex { position: [f32; 3] } implement_vertex!(Vertex, position); pub struct BoundingBox { vertexes: glium::VertexBuffer<Vertex>, program: Rc<Program>, indices: IndexBuffer<u16>, } impl BoundingBox { pub fn new(display: &Display, c: &Cube, program: Rc<Program>) -> BoundingBox { let vertex_data = [ Vertex { position: [c.xmin, c.ymin, c.zmin] }, Vertex { position: [c.xmax, c.ymin, c.zmin] }, Vertex { position: [c.xmax, c.ymax, c.zmin] }, Vertex { position: [c.xmin, c.ymax, c.zmin] }, Vertex { position: [c.xmin, c.ymin, c.zmax] }, Vertex { position: [c.xmax, c.ymin, c.zmax] }, Vertex { position: [c.xmax, c.ymax, c.zmax] }, Vertex { position: [c.xmin, c.ymax, c.zmax] }, ]; const INDICES: &[u16] = &[0, 1, 1, 2, 2, 3, 3, 0, // front 4, 5, 5, 6, 6, 7, 7, 4, // back 0, 4, 1, 5, 2, 6, 3, 7]; // sides BoundingBox { vertexes: glium::VertexBuffer::new(display, &vertex_data).unwrap(), program: program, indices: IndexBuffer::new(display, PrimitiveType::LinesList, INDICES).unwrap(), } } pub fn draw<U>(&self, frame: &mut glium::Frame, uniforms: &U) where U: glium::uniforms::Uniforms { let params = glium::DrawParameters { depth: glium::Depth { test: glium::draw_parameters::DepthTest::IfLess, write: true, ..Default::default() }, blend: glium::Blend::alpha_blending(), ..Default::default() }; frame.draw(&self.vertexes, &self.indices, &self.program, uniforms, &params).unwrap(); } }
Java
using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace DrakSolz.Projectiles { public class ChickenEgg : ModProjectile { public override string Texture { get { return "Terraria/Projectile_318"; } } public override void SetStaticDefaults() { DisplayName.SetDefault("Chicken Egg"); } public override void SetDefaults() { projectile.CloneDefaults(ProjectileID.RottenEgg); projectile.aiStyle = 2; projectile.friendly = false; projectile.hostile = true; projectile.penetrate = -1; projectile.timeLeft = 600; } public override bool TileCollideStyle(ref int width, ref int height, ref bool fallThrough) { width = 5; height = 5; return true; } public override void Kill(int timeLeft) { Utils.PoofOfSmoke(projectile.Center); NPC.NewNPC((int) projectile.Center.X, (int) projectile.Center.Y, ModContent.NPCType<NPCs.Enemy.PreHardMode.EvilChicken>()); } } }
Java
--- date: 2020-01-07T17:53:33+0000 title: "Hazy State" authors: "Collective Arts Brewing" rating: 3.5 drink_of: https://untappd.com/b/collective-arts-brewing-hazy-state/3104704 checkin: title: The Griffin lat: 51.525 long: -0.082 weather: summary: Overcast temperature: 11.5 badges: - title: I Believe in IPA! (Level 9) id: 619792722 posting_method: https://ownyour.beer ---
Java
<?php /* ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Free Content / Management System # # / # # # # # # Copyright 2005-2011 by webspell.org # # # # visit webSPELL.org, webspell.info to get webSPELL for free # # - Script runs under the GNU GENERAL PUBLIC LICENSE # # - It's NOT allowed to remove this copyright-tag # # -- http://www.fsf.org/licensing/licenses/gpl.html # # # # Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at), # # Far Development by Development Team - webspell.org # # # # visit webspell.org # # # ########################################################################## ########################################################################## # # # Version 4 / / / # # -----------__---/__---__------__----__---/---/- # # | /| / /___) / ) (_ ` / ) /___) / / # # _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___ # # Society / Edition # # / # # # # modified by webspell|k3rmit (Stefan Giesecke) in 2009 # # # # - Modifications are released under the GNU GENERAL PUBLIC LICENSE # # - It is NOT allowed to remove this copyright-tag # # - http://www.fsf.org/licensing/licenses/gpl.html # # # ########################################################################## */ $_language->read_module('gallery'); if(!isgalleryadmin($userID) OR mb_substr(basename($_SERVER['REQUEST_URI']),0,15) != "admincenter.php") die($_language->module['access_denied']); $galclass = new Gallery; if(isset($_GET['part'])) $part = $_GET['part']; else $part = ''; if(isset($_GET['action'])) $action = $_GET['action']; else $action = ''; if($part=="groups") { if(isset($_POST['save'])) { $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { if(checkforempty(Array('name'))) safe_query("INSERT INTO ".PREFIX."gallery_groups ( name, sort ) values( '".$_POST['name']."', '1' ) "); else echo $_language->module['information_incomplete']; } else echo $_language->module['transaction_invalid']; } elseif(isset($_POST['saveedit'])) { $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { if(checkforempty(Array('name'))) safe_query("UPDATE ".PREFIX."gallery_groups SET name='".$_POST['name']."' WHERE groupID='".$_POST['groupID']."'"); else echo $_language->module['information_incomplete']; } else echo $_language->module['transaction_invalid']; } elseif(isset($_POST['sort'])) { $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { if(isset($_POST['sortlist'])){ if(is_array($_POST['sortlist'])) { foreach($_POST['sortlist'] as $sortstring) { $sorter=explode("-", $sortstring); safe_query("UPDATE ".PREFIX."gallery_groups SET sort='$sorter[1]' WHERE groupID='$sorter[0]' "); } } } } else echo $_language->module['transaction_invalid']; } elseif(isset($_GET['delete'])) { $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_GET['captcha_hash'])) { $db_result=safe_query("SELECT * FROM ".PREFIX."gallery WHERE groupID='".$_GET['groupID']."'"); $any=mysql_num_rows($db_result); if($any){ echo $_language->module['galleries_available'].'<br /><br />'; } else{ safe_query("DELETE FROM ".PREFIX."gallery_groups WHERE groupID='".$_GET['groupID']."'"); } } else echo $_language->module['transaction_invalid']; } if($action=="add") { $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; <a href="admincenter.php?site=gallery&amp;part=groups" class="white">'.$_language->module['groups'].'</a> &raquo; '.$_language->module['add_group'].'</h1>'; echo'<form method="post" action="admincenter.php?site=gallery&amp;part=groups"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td width="15%"><b>'.$_language->module['group_name'].'</b></td> <td width="85%"><input type="text" name="name" size="60" /></td> </tr> <tr> <td><input type="hidden" name="captcha_hash" value="'.$hash.'" /></td> <td><input type="submit" name="save" value="'.$_language->module['add_group'].'" /></td> </tr> </table> </form>'; } elseif($action=="edit") { $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups WHERE groupID='".$_GET['groupID']."'"); $ds=mysql_fetch_array($ergebnis); echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; <a href="admincenter.php?site=gallery&amp;part=groups" class="white">'.$_language->module['groups'].'</a> &raquo; '.$_language->module['edit_group'].'</h1>'; echo'<form method="post" action="admincenter.php?site=gallery&amp;part=groups"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td width="15%"><b>'.$_language->module['group_name'].'</b></td> <td><input type="text" name="name" size="60" value="'.getinput($ds['name']).'" /></td> </tr> <tr> <td><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="hidden" name="groupID" value="'.$ds['groupID'].'" /></td> <td><input type="submit" name="saveedit" value="'.$_language->module['edit_group'].'" /></td> </tr> </table> </form>'; } else { echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; '.$_language->module['groups'].'</h1>'; echo'<input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=groups&amp;action=add\');return document.MM_returnValue" value="'.$_language->module['new_group'].'" /><br /><br />'; $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups ORDER BY sort"); echo'<form method="post" name="ws_gallery" action="admincenter.php?site=gallery&amp;part=groups"> <table width="100%" border="0" cellspacing="1" cellpadding="3" bgcolor="#DDDDDD"> <tr> <td width="70%" class="title"><b>'.$_language->module['group_name'].'</b></td> <td width="20%" class="title"><b>'.$_language->module['actions'].'</b></td> <td width="10%" class="title"><b>'.$_language->module['sort'].'</b></td> </tr>'; $n=1; $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); while($ds=mysql_fetch_array($ergebnis)) { if($n%2) { $td='td1'; } else { $td='td2'; } $list = '<select name="sortlist[]">'; for($i=1;$i<=mysql_num_rows($ergebnis);$i++) { $list.='<option value="'.$ds['groupID'].'-'.$i.'">'.$i.'</option>'; } $list .= '</select>'; $list = str_replace('value="'.$ds['groupID'].'-'.$ds['sort'].'"','value="'.$ds['groupID'].'-'.$ds['sort'].'" selected="selected"',$list); echo'<tr> <td class="'.$td.'">'.$ds['name'].'</td> <td class="'.$td.'" align="center"><input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=groups&amp;action=edit&amp;groupID='.$ds['groupID'].'\');return document.MM_returnValue" value="'.$_language->module['edit'].'" /> <input type="button" onclick="MM_confirm(\''.$_language->module['really_delete_group'].'\', \'admincenter.php?site=gallery&amp;part=groups&amp;delete=true&amp;groupID='.$ds['groupID'].'&amp;captcha_hash='.$hash.'\')" value="'.$_language->module['delete'].'" /></td> <td class="'.$td.'" align="center">'.$list.'</td> </tr>'; $n++; } echo'<tr> <td class="td_head" colspan="3" align="right"><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="submit" name="sort" value="'.$_language->module['to_sort'].'" /></td> </tr> </table> </form>'; } } //part: gallerys elseif($part=="gallerys") { if(isset($_POST['save'])) { $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { if(checkforempty(Array('name'))) { safe_query("INSERT INTO ".PREFIX."gallery ( name, date, groupID ) values( '".$_POST['name']."', '".time()."', '".$_POST['group']."' ) "); $id = mysql_insert_id(); } else echo $_language->module['information_incomplete']; } else echo $_language->module['transaction_invalid']; } elseif(isset($_POST['saveedit'])) { $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { if(checkforempty(Array('name'))) { if(!isset($_POST['group'])) { $_POST['group'] = 0; } safe_query("UPDATE ".PREFIX."gallery SET name='".$_POST['name']."', groupID='".$_POST['group']."' WHERE galleryID='".$_POST['galleryID']."'"); } else echo $_language->module['information_incomplete']; } else echo $_language->module['transaction_invalid']; } elseif(isset($_POST['saveftp'])) { $dir = '../images/gallery/'; $pictures = array(); if(isset($_POST['comment'])) $comment = $_POST['comment']; if(isset($_POST['name'])) $name = $_POST['name']; if(isset($_POST['pictures'])) $pictures = $_POST['pictures']; $i=0; $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { foreach($pictures as $picture) { $typ = getimagesize($dir.$picture); switch ($typ[2]) { case 1: $typ = '.gif'; break; case 2: $typ = '.jpg'; break; case 3: $typ = '.png'; break; } if($name[$i]) $insertname = $name[$i]; else $insertname = $picture; safe_query("INSERT INTO ".PREFIX."gallery_pictures ( galleryID, name, comment, comments) VALUES ('".$_POST['galleryID']."', '".$insertname."', '".$comment[$i]."', '".$_POST['comments']."' )"); $insertid = mysql_insert_id(); copy($dir.$picture, $dir.'large/'.$insertid.$typ); $galclass->savethumb($dir.'large/'.$insertid.$typ, $dir.'thumb/'.$insertid.'.jpg'); @unlink($dir.$picture); $i++; } } else echo $_language->module['transaction_invalid']; } elseif(isset($_POST['saveform'])) { $dir = '../images/gallery/'; $picture = $_FILES['picture']; $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_POST['captcha_hash'])) { if($picture['name'] != "") { if($_POST['name']) $insertname = $_POST['name']; else $insertname = $picture['name']; safe_query("INSERT INTO ".PREFIX."gallery_pictures ( galleryID, name, comment, comments) VALUES ('".$_POST['galleryID']."', '".$insertname."', '".$_POST['comment']."', '".$_POST['comments']."' )"); $insertid = mysql_insert_id(); $typ = getimagesize($picture['tmp_name']); switch ($typ[2]) { case 1: $typ = '.gif'; break; case 2: $typ = '.jpg'; break; case 3: $typ = '.png'; break; } move_uploaded_file($picture['tmp_name'], $dir.'large/'.$insertid.$typ); $galclass->savethumb($dir.'large/'.$insertid.$typ, $dir.'thumb/'.$insertid.'.jpg'); } } else echo $_language->module['transaction_invalid']; } elseif(isset($_GET['delete'])) { //SQL $CAPCLASS = new Captcha; if($CAPCLASS->check_captcha(0, $_GET['captcha_hash'])) { if(safe_query("DELETE FROM ".PREFIX."gallery WHERE galleryID='".$_GET['galleryID']."'")) { //FILES $ergebnis=safe_query("SELECT picID FROM ".PREFIX."gallery_pictures WHERE galleryID='".$_GET['galleryID']."'"); while($ds=mysql_fetch_array($ergebnis)) { @unlink('../images/gallery/thumb/'.$ds['picID'].'.jpg'); //thumbnails $path = '../images/gallery/large/'; if(file_exists($path.$ds['picID'].'.jpg')) $path = $path.$ds['picID'].'.jpg'; elseif(file_exists($path.$ds['picID'].'.png')) $path = $path.$ds['picID'].'.png'; else $path = $path.$ds['picID'].'.gif'; @unlink($path); //large safe_query("DELETE FROM ".PREFIX."comments WHERE parentID='".$ds['picID']."' AND type='ga'"); } safe_query("DELETE FROM ".PREFIX."gallery_pictures WHERE galleryID='".$_GET['galleryID']."'"); } } else echo $_language->module['transaction_invalid']; } if($action=="add") { $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups"); $any=mysql_num_rows($ergebnis); if($any){ $groups = '<select name="group">'; while($ds=mysql_fetch_array($ergebnis)) { $groups.='<option value="'.$ds['groupID'].'">'.getinput($ds['name']).'</option>'; } $groups.='</select>'; $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; <a href="admincenter.php?site=gallery&amp;part=gallerys" class="white">'.$_language->module['galleries'].'</a> &raquo; '.$_language->module['add_gallery'].'</h1>'; echo'<form method="post" action="admincenter.php?site=gallery&amp;part=gallerys&amp;action=upload"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td width="15%"><b>'.$_language->module['gallery_name'].'</b></td> <td width="85%"><input type="text" name="name" size="60" /></td> </tr> <tr> <td><b>'.$_language->module['group'].'</b></td> <td>'.$groups.'</td> </tr> <tr> <td><b>'.$_language->module['pic_upload'].'</b></td> <td><select name="upload"> <option value="ftp">'.$_language->module['ftp'].'</option> <option value="form">'.$_language->module['formular'].'</option> </select></td> </tr> <tr> <td><input type="hidden" name="captcha_hash" value="'.$hash.'" /></td> <td><input type="submit" name="save" value="'.$_language->module['add_gallery'].'" /></td> </tr> </table> </form> <br /><small>'.$_language->module['ftp_info'].' "http://'.$hp_url.'/images/gallery"</small>'; } else{ echo '<br>'.$_language->module['need_group']; } } elseif($action=="edit") { $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups"); $groups = '<select name="group">'; while($ds=mysql_fetch_array($ergebnis)) { $groups.='<option value="'.$ds['groupID'].'">'.getinput($ds['name']).'</option>'; } $groups.='</select>'; $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery WHERE galleryID='".$_GET['galleryID']."'"); $ds=mysql_fetch_array($ergebnis); $groups = str_replace('value="'.$ds['groupID'].'"','value="'.$ds['groupID'].'" selected="selected"',$groups); echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; <a href="admincenter.php?site=gallery&amp;part=gallerys" class="white">'.$_language->module['galleries'].'</a> &raquo; '.$_language->module['edit_gallery'].'</h1>'; echo'<form method="post" action="admincenter.php?site=gallery&amp;part=gallerys"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td width="15%"><b>'.$_language->module['gallery_name'].'</b></td> <td width="85%"><input type="text" name="name" value="'.getinput($ds['name']).'" /></td> </tr>'; if($ds['userID'] != 0) echo ' <tr> <td><b>'.$_language->module['usergallery_of'].'</b></td> <td><a href="../index.php?site=profile&amp;id='.$userID.'" target="_blank">'.getnickname($ds['userID']).'</a></td> </tr>'; else echo '<tr> <td><b>'.$_language->module['group'].'</b></td> <td>'.$groups.'</td> </tr>'; echo'<tr> <td><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="hidden" name="galleryID" value="'.$ds['galleryID'].'" /></td> <td><input type="submit" name="saveedit" value="'.$_language->module['edit_gallery'].'" /></td> </tr> </table> </form>'; } elseif($action=="upload") { echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; <a href="admincenter.php?site=gallery&amp;part=gallerys" class="white">'.$_language->module['galleries'].'</a> &raquo; '.$_language->module['upload'].'</h1>'; $dir = '../images/gallery/'; if(isset($_POST['upload'])) $upload_type = $_POST['upload']; elseif(isset($_GET['upload'])) $upload_type = $_GET['upload']; else $upload_type = null; if(isset($_GET['galleryID'])) $id=$_GET['galleryID']; if($upload_type == "ftp") { $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); echo'<form method="post" action="admincenter.php?site=gallery&amp;part=gallerys"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td>'; $pics = Array(); $picdir = opendir($dir); while (false !== ($file = readdir($picdir))) { if ($file != "." && $file != "..") { if(is_file($dir.$file)) { if($info = getimagesize($dir.$file)) { if($info[2]==1 OR $info[2]==2 || $info[2]==3) $pics[] = $file; } } } } closedir($picdir); natcasesort ($pics); reset ($pics); echo '<script language="JavaScript" type="text/javascript"> function fillcomments(){ document.getElementById(\'comments\').value=getselection(\'access\'); } </script> <table border="0" width="100%" cellspacing="1" cellpadding="1"> <tr> <td></td> <td><b>'.$_language->module['filename'].'</b></td> <td><b>'.$_language->module['name'].'</b></td> <td><b>'.$_language->module['comment'].'</b></td> </tr>'; foreach($pics as $val) { if(is_file($dir.$val)) { echo '<tr> <td><input type="checkbox" value="'.$val.'" name="pictures[]" checked="checked" /></td> <td><a href="'.$dir.$val.'" target="_blank">'.$val.'</a></td> <td><input type="text" name="name[]" size="40" /></td> <td><input type="text" name="comment[]" size="40" /></td> </tr>'; } } $accesses=generateaccessdropdown('access', 'access', '', 'fillcomments();'); echo '</table></td> </tr> <tr> <td><br /><b>'.$_language->module['visitor_comments'].'</b> &nbsp; '.$accesses.' <input type="hidden" value="" name="comments" id="comments" /></td> </tr> <tr> <td><br /><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="hidden" name="galleryID" value="'.$id.'" /> <input type="submit" name="saveftp" value="'.$_language->module['upload'].'" /></td> </tr> </table> </form>'; } elseif($upload_type == "form") { $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); $accesses=generateaccessdropdown('access', 'access', '', 'fillcomments();'); echo '<script language="JavaScript" type="text/javascript"> function fillcomments(){ document.getElementById(\'comments\').value=getselection(\'access\'); } </script> <form method="post" action="admincenter.php?site=gallery&amp;part=gallerys" enctype="multipart/form-data"> <table width="100%" border="0" cellspacing="1" cellpadding="3"> <tr> <td width="20%"><b>'.$_language->module['name'].'</b></td> <td width="80%"><input type="text" name="name" size="60" /></td> </tr> <tr> <td><b>'.$_language->module['comment'].'</b></td> <td><input type="text" name="comment" size="60" maxlength="255" /></td> </tr> <tr> <td valign="top"><b>'.$_language->module['visitor_comments'].'</b></td> <td> '.$accesses.' <input type="hidden" value="" name="comments" id="comments" /> </td> </tr> <tr> <td><b>'.$_language->module['picture'].'</b></td> <td><input name="picture" type="file" size="40" /></td> </tr> <tr> <td><input type="hidden" name="captcha_hash" value="'.$hash.'" /><input type="hidden" name="galleryID" value="'.$id.'" /></td> <td><input type="submit" name="saveform" value="'.$_language->module['upload'].'" /></td> </tr> </table> </form>'; } } else { echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; '.$_language->module['galleries'].'</h1>'; echo'<input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=gallerys&amp;action=add\');return document.MM_returnValue" value="'.$_language->module['new_gallery'].'" /><br /><br />'; echo'<form method="post" name="ws_gallery" action="admincenter.php?site=gallery&amp;part=gallerys"> <table width="100%" border="0" cellspacing="1" cellpadding="3" bgcolor="#DDDDDD"> <tr> <td width="50%" class="title"><b>'.$_language->module['gallery_name'].'</b></td> <td width="50%" class="title" colspan="2"><b>'.$_language->module['actions'].'</b></td> </tr>'; $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery_groups ORDER BY sort"); while($ds=mysql_fetch_array($ergebnis)) { echo'<tr> <td class="td_head" colspan="3"><b>'.getinput($ds['name']).'</b></td> </tr>'; $galleries=safe_query("SELECT * FROM ".PREFIX."gallery WHERE groupID='$ds[groupID]' AND userID='0' ORDER BY date"); $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); $i=1; while($db=mysql_fetch_array($galleries)) { if($i%2) { $td='td1'; } else { $td='td2'; } echo'<tr> <td class="'.$td.'" width="50%"><a href="../index.php?site=gallery&amp;galleryID='.$db['galleryID'].'" target="_blank">'.getinput($db['name']).'</a></td> <td class="'.$td.'" width="30%" align="center"><input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=gallerys&amp;action=upload&amp;upload=form&amp;galleryID='.$db['galleryID'].'\');return document.MM_returnValue" value="'.$_language->module['add_img'].' ('.$_language->module['per_form'].')" style="margin:1px;" /> <input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=gallerys&amp;action=upload&amp;upload=ftp&amp;galleryID='.$db['galleryID'].'\');return document.MM_returnValue" value="'.$_language->module['add_img'].' ('.$_language->module['per_ftp'].')" style="margin:1px;" /></td> <td class="'.$td.'" width="20%" align="center"><input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=gallerys&amp;action=edit&amp;galleryID='.$db['galleryID'].'\');return document.MM_returnValue" value="'.$_language->module['edit'].'" /> <input type="button" onclick="MM_confirm(\''.$_language->module['really_delete_gallery'].'\', \'admincenter.php?site=gallery&amp;part=gallerys&amp;delete=true&amp;galleryID='.$db['galleryID'].'&amp;captcha_hash='.$hash.'\')" value="'.$_language->module['delete'].'" /></td> </tr>'; $i++; } } echo'</table></form><br /><br />'; echo'<h1>&curren; <a href="admincenter.php?site=gallery" class="white">'.$_language->module['gallery'].'</a> &raquo; '.$_language->module['usergalleries'].'</h1>'; $ergebnis=safe_query("SELECT * FROM ".PREFIX."gallery WHERE userID!='0'"); echo'<form method="post" name="ws_gallery" action="admincenter.php?site=gallery&amp;part=gallerys"> <table width="100%" border="0" cellspacing="1" cellpadding="3" bgcolor="#DDDDDD"> <tr> <td width="50%" class="title"><b>'.$_language->module['gallery_name'].'</b></td> <td width="30%" class="title"><b>'.$_language->module['usergallery_of'].'</b></td> <td width="20%" class="title"><b>'.$_language->module['actions'].'</b></td> </tr>'; $CAPCLASS = new Captcha; $CAPCLASS->create_transaction(); $hash = $CAPCLASS->get_hash(); $i=1; while($ds=mysql_fetch_array($ergebnis)) { if($i%2) { $td='td1'; } else { $td='td2'; } echo'<tr> <td class="'.$td.'"><a href="../index.php?site=gallery&amp;galleryID='.$ds['galleryID'].'" target="_blank">'.getinput($ds['name']).'</a></td> <td class="'.$td.'"><a href="../index.php?site=profile&amp;id='.$userID.'" target="_blank">'.getnickname($ds['userID']).'</a></td> <td class="'.$td.'" align="center"><input type="button" onclick="MM_goToURL(\'parent\',\'admincenter.php?site=gallery&amp;part=gallerys&amp;action=edit&amp;galleryID='.$ds['galleryID'].'\');return document.MM_returnValue" value="'.$_language->module['edit'].'" /> <input type="button" onclick="MM_confirm(\''.$_language->module['really_delete_gallery'].'\', \'admincenter.php?site=gallery&amp;part=gallerys&amp;delete=true&amp;galleryID='.$ds['galleryID'].'&amp;captcha_hash='.$hash.'\')" value="'.$_language->module['delete'].'" /></td> </tr>'; $i++; } echo'</table></form>'; } } ?>
Java
# Example implementing 5 layer encoder # Original code taken from # https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/autoencoder.py # The model trained here is restored in load.py from __future__ import division, print_function, absolute_import # Import MNIST data # from tensorflow.examples.tutorials.mnist import input_data # data_set = input_data.read_data_sets("/tmp/data/", one_hot=True) # Import libraries import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import sys import scipy.io as sio sys.path.insert(0, '../..') # Add path to where TF_Model.py is, if not in the same dir from TF_Model import * from utils import * # 01 thumb # 10 pinky action_map = {} action_map[1] = [0,1] action_map[2] = [1,0] # thumb up mat_contents_t0 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_pinky_Jan5_0.mat') mat_contents_t1 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_pinky_Jan5_1.mat') mat_contents_test0 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_pinky_jan5_2.mat') data_t0 = mat_contents_t0['EMGdata'] data_t1 = mat_contents_t1['EMGdata'] data_test0 = mat_contents_test0['EMGdata'] batch_y_t0, batch_x_t0 = get_batch_from_raw_data_new_format(data_t0, action_map, [0]) batch_y_t1, batch_x_t1 = get_batch_from_raw_data_new_format(data_t1, action_map, [0]) batch_y_test0, batch_x_test0 = get_batch_from_raw_data_new_format(data_test0, action_map, [0]) # pinky up mat_contents_p0 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_thumb_Jan5_0.mat') mat_contents_p1 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_thumb_Jan5_1.mat') mat_contents_test1 = sio.loadmat('/home/linda/school/capstone/data/set2_new_format/EMGjan5/Fred_thumb_Jan5_2.mat') data_p0 = mat_contents_p0['EMGdata'] data_p1 = mat_contents_p1['EMGdata'] data_test1 = mat_contents_test1['EMGdata'] batch_y_p0, batch_x_p0 = get_batch_from_raw_data_new_format(data_p0, action_map, [0]) batch_y_p1, batch_x_p1 = get_batch_from_raw_data_new_format(data_p1, action_map, [0]) batch_y_test1, batch_x_test1 = get_batch_from_raw_data_new_format(data_test1, action_map, [0]) print("done reading data") # Create TF_Model, a wrapper for models created using tensorflow # Note that the configuration file 'config.txt' must be present in the directory model = TF_Model('model') # Parameters learning_rate = 0.05 training_epochs = 200 batch_size = 256 display_step = 1 examples_to_show = 10 # total_batch = int(data_set.train.num_examples/batch_size) dropout = tf.placeholder(tf.float32) # Create variables for inputs, outputs and predictions x = tf.placeholder(tf.float32, [None, 1000]) y = tf.placeholder(tf.float32, [None, 2]) y_true = y y_pred = model.predict(x) # Cost function cost = tf.reduce_mean(tf.pow(y_true - y_pred, 2)) optimizer = tf.train.RMSPropOptimizer(learning_rate).minimize(cost) # Initializing the variables init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) model_output = model.predict(x) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(model_output), reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(model_output,1), tf.argmax(y,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # Train for epoch in range(training_epochs): _, c = sess.run([optimizer, cost], feed_dict={x: batch_x_t0, y: batch_y_t0}) _, c = sess.run([optimizer, cost], feed_dict={x: batch_x_t1, y: batch_y_t1}) _, c = sess.run([optimizer, cost], feed_dict={x: batch_x_p0, y: batch_y_p0}) _, c = sess.run([optimizer, cost], feed_dict={x: batch_x_p1, y: batch_y_p1}) # Display logs per epoch step print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c)) print(sess.run(accuracy, feed_dict={x: batch_x_test0, y: batch_y_test0})) print(sess.run(accuracy, feed_dict={x: batch_x_test1, y: batch_y_test1})) print("===final===") print(sess.run(accuracy, feed_dict={x: batch_x_test0, y: batch_y_test0})) print(sess.run(accuracy, feed_dict={x: batch_x_test1, y: batch_y_test1})) # Save model.save(sess, 'example_3')
Java
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.github.mdsimmo.pixeldungeon.levels.painters; import com.github.mdsimmo.pixeldungeon.items.Gold; import com.github.mdsimmo.pixeldungeon.items.Heap; import com.github.mdsimmo.pixeldungeon.items.keys.IronKey; import com.github.mdsimmo.pixeldungeon.levels.Level; import com.github.mdsimmo.pixeldungeon.levels.Room; import com.github.mdsimmo.pixeldungeon.levels.Terrain; import com.github.mdsimmo.utils.Random; public class TreasuryPainter extends Painter { public static void paint( Level level, Room room ) { fill( level, room, Terrain.WALL ); fill( level, room, 1, Terrain.EMPTY ); set( level, room.center(), Terrain.STATUE ); Heap.Type heapType = Random.Int( 2 ) == 0 ? Heap.Type.CHEST : Heap.Type.HEAP; int n = Random.IntRange( 2, 3 ); for ( int i = 0; i < n; i++ ) { int pos; do { pos = room.random(); } while ( level.map[pos] != Terrain.EMPTY || level.heaps.get( pos ) != null ); level.drop( new Gold().random(), pos ).type = (i == 0 && heapType == Heap.Type.CHEST ? Heap.Type.MIMIC : heapType); } if ( heapType == Heap.Type.HEAP ) { for ( int i = 0; i < 6; i++ ) { int pos; do { pos = room.random(); } while ( level.map[pos] != Terrain.EMPTY ); level.drop( new Gold( Random.IntRange( 1, 3 ) ), pos ); } } room.entrance().set( Room.Door.Type.LOCKED ); level.addItemToSpawn( new IronKey() ); } }
Java
/* * object.c * * Copyright (C) 2012 - Dr.NP * * 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 <http://www.gnu.org/licenses/>. */ /** * Universal hash array object * * @package bsp::libbsp-core * @author Dr.NP <np@bsgroup.org> * @update 05/21/2013 * @changelog * [06/11/2012] - Creation * [08/14/2012] - Float / Double byte order * [09/28/2012] - Array support * [05/21/2013] - Remove float / double byte-order reverse * [12/17/2013] - Lightuserdata supported * [08/05/2014] - Rebuild */ #include "bsp.h" /* Set values */ /* void set_item_int8(BSP_VALUE *val, const int8_t value) { if (val) { set_int8(value, val->lval); val->type = BSP_VAL_INT8; } return; } void set_item_int16(BSP_VALUE *val, const int16_t value) { if (val) { set_int16(value, val->lval); val->type = BSP_VAL_INT16; } return; } void set_item_int32(BSP_VALUE *val, const int32_t value) { if (val) { set_int32(value, val->lval); val->type = BSP_VAL_INT32; } return; } void set_item_int64(BSP_VALUE *val, const int64_t value) { if (val) { set_int64(value, val->lval); item->value.type = BSP_VAL_INT64; } return; } */ // Set value to value void value_set_int(BSP_VALUE *val, const int64_t value) { if (val) { set_vint(value, val->lval); val->type = BSP_VAL_INT; } } void value_set_float(BSP_VALUE *val, const float value) { if (val) { set_float(value, val->lval); val->type = BSP_VAL_FLOAT; } return; } void value_set_double(BSP_VALUE *val, const double value) { if (val) { set_double(value, val->lval); val->type = BSP_VAL_DOUBLE; } return; } void value_set_boolean_true(BSP_VALUE *val) { if (val) { set_vint(1, val->lval); val->type = BSP_VAL_BOOLEAN_TRUE; } return; } void value_set_boolean_false(BSP_VALUE *val) { if (val) { set_vint(0, val->lval); val->type = BSP_VAL_BOOLEAN_FALSE; } return; } void value_set_pointer(BSP_VALUE *val, const void *p) { if (val) { val->rval = (void *) p; val->type = BSP_VAL_POINTER; } return; } void value_set_string(BSP_VALUE *val, BSP_STRING *str) { if (val && str) { val->rval = (void *) str; val->type = BSP_VAL_STRING; } return; } void value_set_object(BSP_VALUE *val, BSP_OBJECT *obj) { if (val && obj) { val->rval = (void *) obj; val->type = BSP_VAL_OBJECT; } return; } void value_set_null(BSP_VALUE *val) { if (val) { val->type = BSP_VAL_NULL; } return; } // Get value from value int64_t value_get_int(BSP_VALUE *val) { int64_t ret = 0; if (val) { if (BSP_VAL_INT == val->type) { // int64 ret = get_vint(val->lval, NULL); } else if (BSP_VAL_INT29 == val->type) { // int29 ret = get_vint29(val->lval, NULL); } } return ret; } int value_get_boolean(BSP_VALUE *val) { int ret = BSP_BOOLEAN_FALSE; if (val && BSP_VAL_BOOLEAN_TRUE == val->type) { ret = BSP_BOOLEAN_TRUE; } return ret; } float value_get_float(BSP_VALUE *val) { float ret = 0.0; if (val && BSP_VAL_FLOAT == val->type) { ret = get_float(val->rval); } return ret; } double value_get_double(BSP_VALUE *val) { double ret = 0.0; if (val && BSP_VAL_DOUBLE == val->type) { ret = get_double(val->rval); } return ret; } void * value_get_pointer(BSP_VALUE *val) { void *ret = NULL; if (val && BSP_VAL_POINTER == val->type) { ret = val->rval; } return ret; } BSP_STRING * value_get_string(BSP_VALUE *val) { BSP_STRING *ret = NULL; if (val && BSP_VAL_STRING == val->type) { ret = (BSP_STRING *) val->rval; } return ret; } BSP_OBJECT * value_get_object(BSP_VALUE *val) { BSP_OBJECT *ret = NULL; if (val && BSP_VAL_OBJECT == val->type) { ret = (BSP_OBJECT *) val->rval; } return ret; } /* Object & Value */ BSP_OBJECT * new_object(char type) { BSP_OBJECT *obj = bsp_calloc(1, sizeof(BSP_OBJECT)); if (obj) { obj->type = type; bsp_spin_init(&obj->lock); } return obj; } void del_object(BSP_OBJECT *obj) { if (!obj) { return; } BSP_VALUE *val = NULL; struct bsp_array_t *array = NULL; struct bsp_hash_t *hash = NULL; struct bsp_hash_item_t *item = NULL, *old = NULL; size_t idx, bucket, seq; bsp_spin_lock(&obj->lock); switch (obj->type) { case OBJECT_TYPE_SINGLE : val = (BSP_VALUE *) obj->node; del_value(val); break; case OBJECT_TYPE_ARRAY : array = (struct bsp_array_t *) obj->node; if (array) { for (idx = 0; idx < array->nitems; idx ++) { bucket = (idx / ARRAY_BUCKET_SIZE); seq = idx % ARRAY_BUCKET_SIZE; if (bucket < array->nbuckets && array->items[bucket]) { val = array->items[bucket][seq]; del_value(val); } } bsp_free(array); } break; case OBJECT_TYPE_HASH : hash = (struct bsp_hash_t *) obj->node; if (hash) { item = hash->head; while (item) { del_string(item->key); del_value(item->value); old = item; item = old->lnext; bsp_free(old); } bsp_free(hash); } break; case OBJECT_TYPE_UNDETERMINED : default : break; } bsp_spin_unlock(&obj->lock); bsp_free(obj); return; } BSP_VALUE * new_value() { return (BSP_VALUE *) bsp_calloc(1, sizeof(BSP_VALUE)); } void del_value(BSP_VALUE *val) { if (val) { if (BSP_VAL_POINTER == val->type) { // Just ignore, we cannot determine what you are } else if (BSP_VAL_STRING == val->type) { del_string((BSP_STRING *) val->rval); } else if (BSP_VAL_OBJECT == val->type) { del_object((BSP_OBJECT *) val->rval); } else { // Local value, Just free } } return bsp_free(val); } /* Item cursor operates */ // TODO : Not thread-safe, but maybe not neccessery BSP_VALUE * curr_item(BSP_OBJECT *obj) { if (!obj) { return NULL; } BSP_VALUE *curr = NULL; struct bsp_array_t *array = NULL; struct bsp_hash_t *hash = NULL; switch (obj->type) { case OBJECT_TYPE_SINGLE : curr = (BSP_VALUE *) obj->node; break; case OBJECT_TYPE_ARRAY : array = (struct bsp_array_t *) obj->node; if (array) { size_t bucket = (array->curr / ARRAY_BUCKET_SIZE); if (array->curr < array->nitems && bucket < array->nbuckets && array->items[bucket]) { curr = array->items[bucket][array->curr % ARRAY_BUCKET_SIZE]; } } break; case OBJECT_TYPE_HASH : hash = (struct bsp_hash_t *) obj->node; if (hash && hash->curr) { // Just value // You can get current key with curr_item_key() curr = hash->curr->value; } break; default : curr = NULL; break; } return curr; } // Current array index size_t curr_array_index(BSP_OBJECT *obj) { size_t idx = 0; if (obj && OBJECT_TYPE_ARRAY == obj->type) { struct bsp_array_t *array = (struct bsp_array_t *) obj->node; if (array) { idx = array->curr; } } return idx; } // Current hash key BSP_STRING * curr_hash_key(BSP_OBJECT *obj) { BSP_STRING *key = NULL; if (obj && OBJECT_TYPE_HASH == obj->type) { struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node; if (hash && hash->curr) { key = hash->curr->key; } } return key; } size_t object_size(BSP_OBJECT *obj) { size_t ret = 0; struct bsp_array_t *array = NULL; struct bsp_hash_t *hash = NULL; if (obj) { switch (obj->type) { case OBJECT_TYPE_SINGLE : if (obj->node) { ret = 1; } break; case OBJECT_TYPE_ARRAY : array = (struct bsp_array_t *) obj->node; if (array) { ret = array->nitems; } break; case OBJECT_TYPE_HASH : hash = (struct bsp_hash_t *) obj->node; if (hash) { ret = hash->nitems; } break; default : break; } } return ret; } void reset_object(BSP_OBJECT *obj) { if (!obj) { return; } struct bsp_array_t *array = NULL; struct bsp_hash_t *hash = NULL; switch (obj->type) { case OBJECT_TYPE_ARRAY : array = (struct bsp_array_t *) obj->node; if (array) { array->curr = 0; } break; case OBJECT_TYPE_HASH : hash = (struct bsp_hash_t *) obj->node; if (hash) { hash->curr = hash->head; } break; case OBJECT_TYPE_SINGLE : default : // Nothing to do break; } return; } void next_item(BSP_OBJECT *obj) { if (!obj) { return; } struct bsp_array_t *array = NULL; struct bsp_hash_t *hash = NULL; switch (obj->type) { case OBJECT_TYPE_ARRAY : array = (struct bsp_array_t *) obj->node; if (array && array->curr < array->nitems) { array->curr ++; } break; case OBJECT_TYPE_HASH : hash = (struct bsp_hash_t *) obj->node; if (hash && hash->curr) { hash->curr = hash->curr->lnext; } break; case OBJECT_TYPE_SINGLE : default : // Nothing to NEXT break; } return; } void prev_item(BSP_OBJECT *obj) { if (!obj) { return; } struct bsp_array_t *array = NULL; struct bsp_hash_t *hash = NULL; switch (obj->type) { case OBJECT_TYPE_ARRAY : array = (struct bsp_array_t *) obj->node; if (array && array->curr > 0) { array->curr --; } break; case OBJECT_TYPE_HASH : hash = (struct bsp_hash_t *) obj->node; if (hash && hash->curr) { hash->curr = hash->curr->lprev; } break; case OBJECT_TYPE_SINGLE : default : // Nothing to PREV break; } } /* Sort */ /* inline static int __sort_compare(const char *v1, size_t v1_len, long long int v1_int, const char *v2, size_t v2_len, long long int v2_int) { register int is_d1 = 1, is_d2 = 1; if (v1_int == 0) { if (0 != strcmp(v1, "0")) { is_d1 = 0; } } if (v2_int == 0) { if (0 != strcmp(v2, "0")) { is_d2 = 0; } } if (is_d1 && is_d2) { if (v1_int > v2_int) { return 1; } else { return -1; } } if (!is_d1 && !is_d2) { // Strings if (v1_len > v2_len) { return memcmp(v1, v2, v2_len); } else { return memcmp(v1, v2, v1_len); } } return (is_d1 > is_d2) ? -1 : 1; } inline static int _sort_compare(const char *v1, size_t v1_len, long long int v1_int, const char *v2, size_t v2_len, long long int v2_int) { return (v1_len > v2_len) ? memcmp(v1, v2, v2_len) : memcmp(v1, v2, v1_len); } inline static void _sort_qsort(BSP_OBJECT_ITEM **list, size_t nitems) { int64_t begin_stack[256]; int64_t end_stack[256]; register int64_t begin; register int64_t end; register int64_t middle; register int64_t pivot; register int64_t seg1; register int64_t seg2; register int loop, c1, c2, c3; register BSP_OBJECT_ITEM *tmp; begin_stack[0] = 0; end_stack[0] = nitems - 1; for (loop = 0; loop >= 0; loop --) { begin = begin_stack[loop]; end = end_stack[loop]; while (begin < end) { // Find pivot middle = (end - begin) >> 1; c1 = _sort_compare( list[begin]->key, list[begin]->key_len, list[begin]->key_int, list[middle]->key, list[middle]->key_len, list[middle]->key_int); c2 = _sort_compare( list[middle]->key, list[middle]->key_len, list[middle]->key_int, list[end]->key, list[end]->key_len, list[end]->key_int); c3 = _sort_compare( list[end]->key, list[end]->key_len, list[end]->key_int, list[begin]->key, list[begin]->key_len, list[begin]->key_int); if (c1 >= 0) { pivot = (c2 >= 0) ? middle : ((c3 >= 0) ? begin : end); } else { pivot = (c2 < 0) ? middle : ((c3 < 0) ? begin : end); } if (pivot != begin) { // Swap pivot & begin tmp = list[begin]; list[begin] = list[pivot]; list[pivot] = tmp; } seg1 = begin + 1; seg2 = end; while (1) { for ( ; seg1 < seg2 && _sort_compare( list[begin]->key, list[begin]->key_len, list[begin]->key_int, list[seg1]->key, list[seg1]->key_len, list[seg1]->key_int) > 0; seg1 ++); for ( ; seg2 >= seg1 && _sort_compare( list[seg2]->key, list[seg2]->key_len, list[seg2]->key_int, list[begin]->key, list[begin]->key_len, list[begin]->key_int) > 0; seg2 --); if (seg1 >= seg2) { break; } tmp = list[seg1]; list[seg1] = list[seg2]; list[seg2] = tmp; seg1 ++; seg2 --; } // Swap begin & seg2 tmp = list[begin]; list[begin] = list[seg2]; list[seg2] = tmp; if ((seg2 - begin) <= (end - seg2)) { if ((seg2 + 1) < end) { begin_stack[loop] = seg2 + 1; end_stack[loop ++] = end; } end = seg2 - 1; } else { if ((seg2 - 1) > begin) { begin_stack[loop] = begin; end_stack[loop ++] = seg2 - 1; } begin = seg2 + 1; } } } return; } // Quicksort int sort_object(BSP_OBJECT *obj) { if (!obj || 2 > obj->nitems ) { return BSP_RTN_ERROR_GENERAL; } // Make a copy of item link BSP_OBJECT_ITEM **list = bsp_calloc(obj->nitems, sizeof(BSP_OBJECT_ITEM *)); if (!list) { return BSP_RTN_ERROR_MEMORY; } bsp_spin_lock(&obj->obj_lock); BSP_OBJECT_ITEM *curr = NULL; int i = 0; reset_object(obj); curr = curr_item(obj); while (curr) { if (i > obj->nitems - 1) { break; } list[i ++] = curr; next_item(obj); curr = curr_item(obj); } _sort_qsort(list, obj->nitems); // Relink item link for (i = 1; i < obj->nitems - 1; i ++) { list[i]->lnext = list[i + 1]; list[i]->lprev = list[i - 1]; } list[0]->lnext = list[1]; list[0]->lprev = NULL; obj->head = list[0]; list[obj->nitems - 1]->lnext = NULL; list[obj->nitems - 1]->lprev = list[obj->nitems - 2]; obj->tail = list[obj->nitems - 1]; bsp_spin_unlock(&obj->obj_lock); bsp_free(list); return BSP_RTN_SUCCESS; } */ // Find item from hash static inline struct bsp_hash_item_t * _find_hash(struct bsp_hash_t *hash, BSP_STRING *key) { struct bsp_hash_item_t *ret = NULL; if (hash && key && hash->hash_table) { uint32_t hash_key = bsp_hash(STR_STR(key), STR_LEN(key)); struct bsp_hash_item_t *bucket = &hash->hash_table[hash_key % hash->hash_size]; struct bsp_hash_item_t *curr = bucket->next; while (curr) { if (STR_IS_EQUAL(key, curr->key)) { ret = curr; break; } curr = curr->next; } } return ret; } static inline struct bsp_hash_item_t * _find_hash_str(struct bsp_hash_t *hash, const char *key) { struct bsp_hash_item_t *ret = NULL; if (hash && key && hash->hash_table) { uint32_t hash_key = bsp_hash(key, -1); struct bsp_hash_item_t *bucket = &hash->hash_table[hash_key % hash->hash_size]; struct bsp_hash_item_t *curr = bucket->next; while (curr) { if (0 == strncmp(key, STR_STR(curr->key), STR_LEN(curr->key))) { ret = curr; break; } curr = curr->next; } } return ret; } // Remove item from hash static inline int _remove_hash(struct bsp_hash_t *hash, BSP_STRING *key) { int ret = 0; struct bsp_hash_item_t *item = _find_hash(hash, key); if (item) { if (hash->head == item) { hash->head = item->lnext; } if (hash->tail == item) { hash->tail = item->lprev; } if (hash->curr == item) { hash->curr = item->lnext; } if (item->lnext) { item->lnext->lprev = item->lprev; } if (item->next) { item->next->prev = item->prev; } if (item->lprev) { item->lprev->lnext = item->lnext; } if (item->prev) { item->prev->next = item->next; } ret = 1; // Delete item del_value(item->value); del_string(item->key); bsp_free(item); item = NULL; } return ret; } static inline int _remove_hash_str(struct bsp_hash_t *hash, const char *key) { int ret = 0; struct bsp_hash_item_t *item = _find_hash_str(hash, key); if (item) { if (hash->head == item) { hash->head = item->lnext; } if (hash->tail == item) { hash->tail = item->lprev; } if (hash->curr == item) { hash->curr = item->lnext; } if (item->lnext) { item->lnext->lprev = item->lprev; } if (item->next) { item->next->prev = item->prev; } if (item->lprev) { item->lprev->lnext = item->lnext; } if (item->prev) { item->prev->next = item->next; } ret = 1; // Delete item del_value(item->value); del_string(item->key); bsp_free(item); item = NULL; } return ret; } // Insert an item into hash static int _insert_hash(struct bsp_hash_t *hash, BSP_STRING *key, BSP_VALUE *val) { int ret = 0; if (hash && hash->hash_table && key && val) { struct bsp_hash_item_t *item = _find_hash(hash, key); if (item) { // Just overwrite value if (item->value) { del_value(item->value); } item->value = val; } else { item = bsp_calloc(1, sizeof(struct bsp_hash_item_t)); item->key = key; item->value = val; // Insert into link if (!hash->head) { hash->head = item; } if (hash->tail) { hash->tail->lnext = item; item->lprev = hash->tail; } hash->tail = item; // Insert into hash table uint32_t hash_key = bsp_hash(STR_STR(key), STR_LEN(key)); struct bsp_hash_item_t *bucket = &hash->hash_table[hash_key % hash->hash_size]; item->next = bucket->next; item->prev = bucket; bucket->next = item; ret = 1; } } return ret; } static int _insert_hash_str(struct bsp_hash_t *hash, const char *key, BSP_VALUE *val) { int ret = 0; if (hash && hash->hash_table && key && val) { struct bsp_hash_item_t *item = _find_hash_str(hash, key); if (item) { // Just overwrite value if (item->value) { del_value(item->value); } item->value = val; } else { item = bsp_calloc(1, sizeof(struct bsp_hash_item_t)); item->key = new_string(key, -1); item->value = val; // Insert into link if (!hash->head) { hash->head = item; } if (hash->tail) { hash->tail->lnext = item; item->lprev = hash->tail; } hash->tail = item; // Insert into hash table uint32_t hash_key = bsp_hash(key, -1); struct bsp_hash_item_t *bucket = &hash->hash_table[hash_key % hash->hash_size]; item->next = bucket->next; item->prev = bucket; bucket->next = item; ret = 1; } } return ret; } // Enlarge hash table, rebuild hash link static void _rebuild_hash(struct bsp_hash_t *hash, size_t new_hash_size) { if (hash && new_hash_size) { if (new_hash_size == hash->hash_size) { return; } if (hash->hash_table) { bsp_free(hash->hash_table); } hash->hash_table = bsp_calloc(new_hash_size, sizeof(struct bsp_hash_item_t)); hash->hash_size = new_hash_size; // Insert every item from link struct bsp_hash_item_t *curr = hash->head; struct bsp_hash_item_t *bucket; uint32_t hash_key; while (curr && curr->key) { hash_key = bsp_hash(STR_STR(curr->key), STR_LEN(curr->key)); bucket = &hash->hash_table[hash_key % hash->hash_size]; curr->next = bucket->next; curr->prev = bucket; bucket->next = curr; curr = curr->lnext; } } return; } // Evalute a single (Number / String / Boolean etc) to a object void object_set_single(BSP_OBJECT *obj, BSP_VALUE *val) { if (obj && OBJECT_TYPE_SINGLE == obj->type) { bsp_spin_lock(&obj->lock); if (obj->node) { BSP_VALUE *old = (BSP_VALUE *) obj->node; del_value(old); } obj->node = (BSP_VALUE *) val; bsp_spin_unlock(&obj->lock); } return; } // Add an item into array void object_set_array(BSP_OBJECT *obj, ssize_t idx, BSP_VALUE *val) { if (obj && OBJECT_TYPE_ARRAY == obj->type) { bsp_spin_lock(&obj->lock); struct bsp_array_t *array = (struct bsp_array_t *) obj->node; if (!array) { // Make a new array array = bsp_calloc(1, sizeof(struct bsp_array_t)); obj->node = (void *) array; } if (idx < 0) { idx = array->nitems; } size_t bucket = (idx / ARRAY_BUCKET_SIZE); size_t seq = idx % ARRAY_BUCKET_SIZE; size_t nbuckets = array->nbuckets; if (bucket >= nbuckets) { // Enlarge buckets nbuckets = 2 << (int) (log2(bucket + 1)); array->items = bsp_realloc(array->items, nbuckets * sizeof(struct BSP_VAL **)); size_t i; for (i = array->nbuckets; i < nbuckets; i ++) { array->items[i] = NULL; } array->nbuckets = nbuckets; } if (!array->items[bucket]) { // New bucket array->items[bucket] = bsp_calloc(ARRAY_BUCKET_SIZE, sizeof(struct BSP_VAL *)); } if (array->items[bucket][seq]) { // Remove old value del_value(array->items[bucket][seq]); } array->items[bucket][seq] = val; if (idx >= array->nitems) { array->nitems = idx + 1; } bsp_spin_unlock(&obj->lock); } return; } // Insert / Remove an item into / from a hash void object_set_hash(BSP_OBJECT *obj, BSP_STRING *key, BSP_VALUE *val) { if (obj && OBJECT_TYPE_HASH == obj->type && key) { bsp_spin_lock(&obj->lock); struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node; if (!hash) { // Make a new hash hash = bsp_calloc(1, sizeof(struct bsp_hash_t)); hash->hash_size = HASH_SIZE_INITIAL; hash->hash_table = bsp_calloc(HASH_SIZE_INITIAL, sizeof(struct bsp_hash_item_t)); obj->node = (void *) hash; } if (val) { // Insert hash->nitems += _insert_hash(hash, key, val); if (hash->nitems > 8 * hash->hash_size) { // Rehash _rebuild_hash(hash, hash->hash_size * 8); } } else { // Remove hash->nitems -= _remove_hash(hash, key); } bsp_spin_unlock(&obj->lock); } return; } void object_set_hash_str(BSP_OBJECT *obj, const char *key, BSP_VALUE *val) { if (obj && OBJECT_TYPE_HASH == obj->type && key) { bsp_spin_lock(&obj->lock); struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node; if (!hash) { // Make a new hash hash = bsp_calloc(1, sizeof(struct bsp_hash_t)); hash->hash_size = HASH_SIZE_INITIAL; hash->hash_table = bsp_calloc(HASH_SIZE_INITIAL, sizeof(struct bsp_hash_item_t)); obj->node = (void *) hash; } if (val) { // Insert hash->nitems += _insert_hash_str(hash, key, val); if (hash->nitems > 8 * hash->hash_size) { // Rehash _rebuild_hash(hash, hash->hash_size * 8); } } else { // Remove hash->nitems -= _remove_hash_str(hash, key); } bsp_spin_unlock(&obj->lock); } return; } // Get single value from object BSP_VALUE * object_get_single(BSP_OBJECT *obj) { BSP_VALUE *ret = NULL; if (obj && OBJECT_TYPE_SINGLE == obj->type) { bsp_spin_lock(&obj->lock); ret = (BSP_VALUE *) obj->node; bsp_spin_unlock(&obj->lock); } return ret; } // Get value from array by given index BSP_VALUE * object_get_array(BSP_OBJECT *obj, size_t idx) { BSP_VALUE *ret = NULL; if (obj && OBJECT_TYPE_ARRAY == obj->type) { bsp_spin_lock(&obj->lock); struct bsp_array_t *array = (struct bsp_array_t *) obj->node; size_t bucket = idx / ARRAY_BUCKET_SIZE; size_t seq = idx % ARRAY_BUCKET_SIZE; if (array && idx < array->nitems && bucket < array->nbuckets && array->items[bucket]) { ret = array->items[bucket][seq]; } bsp_spin_unlock(&obj->lock); } return ret; } // Get value from hash table BSP_VALUE * object_get_hash(BSP_OBJECT *obj, BSP_STRING *key) { BSP_VALUE *ret = NULL; if (obj && key && OBJECT_TYPE_HASH == obj->type) { bsp_spin_lock(&obj->lock); struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node; if (hash) { struct bsp_hash_item_t *item = _find_hash(hash, key); if (item) { ret = item->value; } } bsp_spin_unlock(&obj->lock); } return ret; } BSP_VALUE * object_get_hash_str(BSP_OBJECT *obj, const char *key) { BSP_VALUE *ret = NULL; if (obj && key && OBJECT_TYPE_HASH == obj->type) { bsp_spin_lock(&obj->lock); struct bsp_hash_t *hash = (struct bsp_hash_t *) obj->node; if (hash) { struct bsp_hash_item_t *item = _find_hash_str(hash, key); if (item) { ret = item->value; } } bsp_spin_unlock(&obj->lock); } return ret; } /* Magic path */ BSP_VALUE * object_get_value(BSP_OBJECT *obj, const char *path) { if (!obj) { return NULL; } BSP_VALUE *ret = NULL; BSP_VALUE *curr_val = NULL; BSP_OBJECT *curr_obj = obj; BSP_STRING *key = NULL; size_t idx = 0; size_t i; ssize_t start = -1; int invalid = 0; unsigned char c; char *endptr = NULL; if (OBJECT_TYPE_SINGLE == obj->type) { // Return full ret = object_get_single(obj); } else { if (!path || 0 == strlen(path)) { // No path } else { // Parse path normally for (i = 0; i <= strlen(path); i ++) { c = (unsigned char) path[i]; if ('.' == c || '\0' == c) { // Hash seg if (start < i && start >= 0 && curr_obj) { if (OBJECT_TYPE_HASH == curr_obj->type) { key = new_string_const(path + start, (i - start)); curr_val = object_get_hash(curr_obj, key); del_string(key); if (!curr_val) { // False invalid = 1; break; } curr_obj = value_get_object(curr_val); start = -1; } else if (OBJECT_TYPE_ARRAY == curr_obj->type) { idx = (size_t) strtoull(path + start, &endptr, 0); if (!idx && (path + start) == endptr) { // No digital invalid = 1; break; } curr_val = object_get_array(curr_obj, idx); if (!curr_val) { invalid = 1; break; } curr_obj = value_get_object(curr_val); start = -1; } else { // False curr_val = object_get_single(curr_obj); break; } } else { invalid = 1; break; } } else { // Normal char if (start < 0) { start = i; } } } if (!invalid) { ret = curr_val; } } } return ret; } /* Serializer & Unserializer */ static void _pack_key(BSP_STRING *str, BSP_STRING *key); static void _pack_value(BSP_STRING *str, BSP_VALUE *val); static void _pack_object(BSP_STRING *str, BSP_OBJECT *obj); static void _pack_key(BSP_STRING *str, BSP_STRING *key) { if (str) { char buf[9]; if (key) { string_append(str, buf, set_vint(STR_LEN(key), buf)); string_append(str, STR_STR(key), STR_LEN(key)); } else { string_append(str, buf, set_vint(strlen(NO_HASH_KEY), buf)); string_append(str, NO_HASH_KEY, -1); } } return; } static void _pack_value(BSP_STRING *str, BSP_VALUE *val) { char tmp[9]; int tmp_len; BSP_STRING *sub_str = NULL; BSP_OBJECT *sub_obj = NULL; if (val && str) { string_append(str, &val->type, 1); switch (val->type) { case BSP_VAL_INT : string_append(str, val->lval, vintlen(val->lval, -1)); break; case BSP_VAL_FLOAT : string_append(str, val->lval, sizeof(float)); break; case BSP_VAL_DOUBLE : string_append(str, val->lval, sizeof(float)); break; case BSP_VAL_STRING : sub_str = (BSP_STRING *) val->rval; if (sub_str) { tmp_len = set_vint(STR_LEN(sub_str), tmp); string_append(str, tmp, tmp_len); string_append(str, STR_STR(sub_str), STR_LEN(sub_str)); } else { tmp[0] = 0; string_append(str, tmp, 1); } break; case BSP_VAL_POINTER : set_pointer(val->rval, tmp); string_append(str, tmp, sizeof(void *)); break; case BSP_VAL_OBJECT : sub_obj = (BSP_OBJECT *) val->rval; if (sub_obj) { _pack_object(str, sub_obj); } break; case BSP_VAL_BOOLEAN_TRUE : case BSP_VAL_BOOLEAN_FALSE : case BSP_VAL_NULL : case BSP_VAL_UNKNOWN : default : // No value break; } } return; } static void _pack_object(BSP_STRING *str, BSP_OBJECT *obj) { char value_type[1]; BSP_VALUE *val = NULL; if (obj && str) { bsp_spin_lock(&obj->lock); switch (obj->type) { case OBJECT_TYPE_SINGLE : // A single value value_type[0] = BSP_VAL_OBJECT_SINGLE; string_append(str, value_type, 1); // Push value val = (BSP_VALUE *) obj->node; _pack_value(str, val); value_type[0] = BSP_VAL_OBJECT_SINGLE_END; string_append(str, value_type, 1); break; case OBJECT_TYPE_ARRAY : // Array value_type[0] = BSP_VAL_OBJECT_ARRAY; string_append(str, value_type, 1); // Every item struct bsp_array_t *array = (struct bsp_array_t *) obj->node; size_t idx, bucket, seq; if (array) { for (idx = 9; idx < array->nitems; idx ++) { bucket = idx / ARRAY_BUCKET_SIZE; seq = idx % ARRAY_BUCKET_SIZE; val = NULL; if (bucket < array->nbuckets && array->items[bucket]) { val = array->items[bucket][seq]; _pack_value(str, val); } else { // Empty value_type[0] = BSP_VAL_NULL; string_append(str, value_type, 1); } } } value_type[0] = BSP_VAL_OBJECT_ARRAY_END; string_append(str, value_type, 1); break; case OBJECT_TYPE_HASH : // Dict value_type[0] = BSP_VAL_OBJECT_HASH; string_append(str, value_type, 1); // Traverse items BSP_STRING *key; reset_object(obj); val = curr_item(obj); while (val) { key = curr_hash_key(obj); // Set key and value _pack_key(str, key); _pack_value(str, val); next_item(obj); val = curr_item(obj); } value_type[0] = BSP_VAL_OBJECT_HASH_END; string_append(str, value_type, 1); break; case OBJECT_TYPE_UNDETERMINED : default : // Yaaaahhh~~~? break; } bsp_spin_unlock(&obj->lock); } return; } BSP_STRING * object_serialize(BSP_OBJECT *obj) { BSP_STRING * ret = new_string(NULL, 0); if (obj && ret) { _pack_object(ret, obj); } return ret; } static BSP_STRING * _unpack_key(BSP_STRING *str); static BSP_VALUE * _unpack_value(BSP_STRING *str); static BSP_OBJECT * _unpack_object(BSP_STRING *str); static BSP_STRING * _unpack_key(BSP_STRING *str) { BSP_STRING *ret = NULL; char *data; if (str) { size_t left = STR_LEN(str) - str->cursor; size_t vlen = 0; if (left > 0) { data = STR_STR(str); vlen = vintlen(data, left); if (left >= vlen) { int nouse = 0; int64_t str_len = get_vint(data, &nouse); if (left >= vlen + str_len) { ret = new_string(data + vlen, str_len); vlen += str_len; } } } str->cursor += vlen; } return ret; } static BSP_VALUE * _unpack_value(BSP_STRING *str) { BSP_VALUE *ret = NULL; char *data; char type; if (str) { size_t left = STR_LEN(str) - str->cursor; size_t vlen = 0; BSP_OBJECT *obj = NULL; if (left > 0) { // 1st byte : Type type = STR_STR(str)[str->cursor]; data = STR_STR(str) + 1; ret = new_value(); ret->type = type; switch (type) { case BSP_VAL_INT : vlen = vintlen(data, left - 1); memcpy(ret->lval, data, vlen); break; case BSP_VAL_FLOAT : vlen = (left > sizeof(float)) ? sizeof(float) : (left - 1); memcpy(ret->lval, data, vlen); break; case BSP_VAL_DOUBLE : vlen = (left > sizeof(double)) ? sizeof(double) : (left - 1); memcpy(ret->lval, data, vlen); break; case BSP_VAL_STRING : vlen = vintlen(data, left - 1); if (left >= vlen) { int nouse = 0; int64_t str_len = get_vint(data, &nouse); if (left >= vlen + str_len) { ret->rval = (void *) new_string(data + vlen, str_len); vlen += str_len; } } break; case BSP_VAL_POINTER : vlen = (left > sizeof(void *)) ? sizeof(void *) : (left - 1); memcpy(&ret->rval, data, vlen); break; case BSP_VAL_OBJECT : obj = _unpack_object(str); ret->rval = (void *) obj; break; case BSP_VAL_BOOLEAN_TRUE : case BSP_VAL_BOOLEAN_FALSE : case BSP_VAL_NULL : case BSP_VAL_UNKNOWN : default : // Single values break; } str->cursor += vlen + 1; } } return ret; } static BSP_OBJECT * _unpack_object(BSP_STRING *str) { BSP_OBJECT *obj = NULL; if (str) { bsp_spin_lock(&str->lock); if (str->cursor < STR_LEN(str)) { // Read first BSP_VALUE *val = NULL; BSP_STRING *key = NULL; char type = STR_STR(str)[str->cursor]; obj = new_object(type); str->cursor ++; switch (type) { case BSP_VAL_OBJECT_SINGLE : val = _unpack_value(str); object_set_single(obj, val); // Pass endding str->cursor ++; break; case BSP_VAL_OBJECT_ARRAY : while (1) { val = _unpack_value(str); if (!val) { break; } if (str->cursor < STR_LEN(str) && BSP_VAL_OBJECT_ARRAY_END == STR_STR(str)[str->cursor]) { // Endding str->cursor ++; break; } object_set_array(obj, -1, val); } break; case BSP_VAL_OBJECT_HASH : while (1) { // Read key first key = _unpack_key(str); if (!key) { break; } val = _unpack_value(str); if (!val) { break; } if (str->cursor < STR_LEN(str) && BSP_VAL_OBJECT_HASH_END == STR_STR(str)[str->cursor]) { // Endding str->cursor ++; break; } object_set_hash(obj, key, val); } break; default : break; } } bsp_spin_unlock(&str->lock); } return obj; } BSP_OBJECT * object_unserialize(BSP_STRING *str) { BSP_OBJECT * ret = NULL; if (str) { str->cursor = 0; ret = _unpack_object(str); } return ret; } /* Object <-> LUA stack */ static void _push_value_to_lua(lua_State *s, BSP_VALUE *val); static void _push_object_to_lua(lua_State *s, BSP_OBJECT *obj); static void _push_value_to_lua(lua_State *s, BSP_VALUE *val) { if (!s) { return; } if (!val) { lua_pushnil(s); return; } int v_intlen = 0; uint64_t v_int = 0; float v_float = 0.0; double v_double = 0.0; BSP_STRING *v_str = NULL; void *v_ptr = NULL; BSP_OBJECT *v_obj = NULL; switch (val->type) { case BSP_VAL_INT : v_int = get_vint(val->lval, &v_intlen); lua_pushinteger(s, (lua_Integer) v_int); break; case BSP_VAL_FLOAT : v_float = get_float(val->lval); lua_pushnumber(s, (lua_Number) v_float); break; case BSP_VAL_DOUBLE : v_double = get_double(val->lval); lua_pushnumber(s, (lua_Number) v_double); break; case BSP_VAL_BOOLEAN_TRUE : lua_pushboolean(s, BSP_BOOLEAN_TRUE); break; case BSP_VAL_BOOLEAN_FALSE : lua_pushboolean(s, BSP_BOOLEAN_FALSE); break; case BSP_VAL_STRING : v_str = (BSP_STRING *) val->rval; lua_pushlstring(s, STR_STR(v_str), STR_LEN(v_str)); break; case BSP_VAL_POINTER : v_ptr = val->rval; lua_pushlightuserdata(s, v_ptr); break; case BSP_VAL_OBJECT : v_obj = (BSP_OBJECT *) val->rval; _push_object_to_lua(s, v_obj); break; case BSP_VAL_NULL : case BSP_VAL_UNKNOWN : default : lua_pushnil(s); break; } return; } static void _push_object_to_lua(lua_State *s, BSP_OBJECT *obj) { if (!s) { return; } if (!obj) { lua_pushnil(s); return; } BSP_VALUE *val = NULL; BSP_STRING *key = NULL; bsp_spin_lock(&obj->lock); lua_checkstack(s, 1); switch (obj->type) { case OBJECT_TYPE_SINGLE : // Single value val = (BSP_VALUE *) obj->node; _push_value_to_lua(s, val); break; case OBJECT_TYPE_ARRAY : // Array lua_newtable(s); struct bsp_array_t *array = (struct bsp_array_t *) obj->node; size_t idx; if (array) { for (idx = 0; idx < array->nitems; idx ++) { size_t bucket = idx / ARRAY_BUCKET_SIZE; size_t seq = idx % ARRAY_BUCKET_SIZE; if (bucket < array->nbuckets && array->items[bucket]) { val = array->items[bucket][seq]; if (val) { lua_checkstack(s, 2); lua_pushinteger(s, (lua_Integer) idx + 1); _push_value_to_lua(s, val); lua_settable(s, -3); } } } } break; case OBJECT_TYPE_HASH : // Hash lua_newtable(s); reset_object(obj); val = curr_item(obj); while (val) { key = curr_hash_key(obj); if (key) { lua_checkstack(s, 2); lua_pushlstring(s, STR_STR(key), STR_LEN(key)); _push_value_to_lua(s, val); if (lua_istable(s, -3)) { lua_settable(s, -3); } } next_item(obj); val = curr_item(obj); } break; case OBJECT_TYPE_UNDETERMINED : default : lua_pushnil(s); break; } bsp_spin_unlock(&obj->lock); return; } void object_to_lua_stack(lua_State *s, BSP_OBJECT *obj) { if (!obj || !s) { return; } _push_object_to_lua(s, obj); return; } static BSP_VALUE * _lua_value_to_value(lua_State *s); static BSP_OBJECT * _lua_table_to_object(lua_State *s); static BSP_VALUE * _lua_value_to_value(lua_State *s) { if (!s) { return NULL; } BSP_VALUE *ret = new_value(); if (ret) { lua_Number v_number = 0; int v_boolean = 0; size_t str_len = 0; const char *v_str = NULL; void *v_ptr = NULL; BSP_OBJECT *v_obj = NULL; switch (lua_type(s, -1)) { case LUA_TNIL : value_set_null(ret); break; case LUA_TNUMBER : v_number = lua_tonumber(s, -1); if (v_number == (lua_Number)(int64_t) v_number) { // Integer value_set_int(ret, (const int64_t) v_number); } else { // Double / Float value_set_double(ret, (const double) v_number); } break; case LUA_TBOOLEAN : v_boolean = lua_toboolean(s, -1); if (BSP_BOOLEAN_FALSE == v_boolean) { value_set_boolean_false(ret); } else { value_set_boolean_true(ret); } break; case LUA_TSTRING : v_str = lua_tolstring(s, -1, &str_len); value_set_string(ret, new_string(v_str, str_len)); break; case LUA_TUSERDATA : v_ptr = lua_touserdata(s, -1); value_set_pointer(ret, (const void *) v_ptr); break; case LUA_TTABLE : v_obj = _lua_table_to_object(s); value_set_object(ret, v_obj); break; default : value_set_null(ret); break; } } return ret; } static BSP_OBJECT * _lua_table_to_object(lua_State *s) { if (!s || !lua_istable(s, -1)) { return NULL; } BSP_OBJECT *ret = NULL; BSP_VALUE *val = NULL; // Is array or hash? if (luaL_len(s, -1) == lua_table_size(s, -1)) { // Array ret = new_object(OBJECT_TYPE_ARRAY); size_t idx; for (idx = 1; idx <= luaL_len(s, -1); idx ++) { lua_rawgeti(s, -1, idx); val = _lua_value_to_value(s); object_set_array(ret, idx - 1, val); } } else { // Hash ret = new_object(OBJECT_TYPE_HASH); const char *key_str = NULL; size_t key_len = 0; BSP_STRING *key = NULL; lua_checkstack(s, 2); lua_pushnil(s); while (0 != lua_next(s, -2)) { // Key key_str = lua_tolstring(s, -2, &key_len); key = new_string(key_str, key_len); // Value val = _lua_value_to_value(s); object_set_hash(ret, key, val); lua_pop(s, 1); } } return ret; } BSP_OBJECT * lua_stack_to_object(lua_State *s) { if (!s) { return NULL; } BSP_OBJECT *ret = NULL; if (lua_istable(s, -1)) { // Array or hash ret = _lua_table_to_object(s); } else { // Single ret = new_object(OBJECT_TYPE_SINGLE); object_set_single(ret, _lua_value_to_value(s)); } return ret; }
Java
/** * Copyright (c) 2012-2015 Piotr Sipika; see the AUTHORS file for more. * * 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. * * See the COPYRIGHT file for more information. */ /* Defines the layout of the location structure */ #ifndef LXWEATHER_LOCATION_HEADER #define LXWEATHER_LOCATION_HEADER #include <glib.h> #include <string.h> /* */ #define LOCATIONINFO_GROUP_NAME "Location" #define LOCATIONINFO_GROUP_NAME_LENGTH strlen(LOCATIONINFO_GROUP_NAME) /* LocationInfo struct definition */ typedef struct { gchar * alias_; gchar * city_; gchar * state_; gchar * country_; gchar * woeid_; gchar units_; guint interval_; gboolean enabled_; } LocationInfo; /* Configuration helpers */ typedef enum { ALIAS = 0, CITY, STATE, COUNTRY, WOEID, UNITS, INTERVAL, ENABLED, LOCATIONINFO_FIELD_COUNT } LocationInfoField; /* Defined in the .c file - specifies the array of field names */ extern const gchar * LocationInfoFieldNames[]; /** * Provides the mechanism to free any data associated with * the LocationInfo structure * * @param location Location entry to free. * */ void location_free(gpointer location); /** * Prints the contents of the supplied entry to stdout * * @param locatrion Location entry contents of which to print. * */ void location_print(gpointer location); /** * Sets the given property for the location * * @param location Pointer to the location to modify. * @param property Name of the property to set. * @param value Value to assign to the property. * @param len Length of the value to assign to the property (think strlen()) */ void location_property_set(gpointer location, const gchar * property, const gchar * value, gsize len); /** * Copies a location entry. * * @param dst Address of the pointer to the location to set. * @param src Pointer to the location to use/copy. * * @note Destination is first freed, if non-NULL, otherwise a new allocation * is made. Both source and destination locations must be released by * the caller. */ void location_copy(gpointer * dst, gpointer src); #endif
Java
/* Copyright (C) 2016 Sergo Pasoevi. This pragram is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Written by Sergo Pasoevi <spasoevi@gmail.com> */ #include "util.h" #include <math.h> /* Geometry helper functions */ double distance(int x1, int y1, int x2, int y2) { int dx = x1 - x2; int dy = y1 - y2; return sqrt(dx * dx + dy * dy); } void each_actor(struct engine *engine, TCOD_list_t lst, void (*action)(struct engine *engine, struct actor *actor)) { struct actor **iterator; for (iterator = (struct actor **) TCOD_list_begin(engine->actors); iterator != (struct actor **) TCOD_list_end(engine->actors); iterator++) action(engine, *iterator); } const char *generate_name(const char *filename) { TCOD_namegen_parse(filename, TCOD_random_get_instance()); return TCOD_namegen_generate("Celtic male", false); } void free_name_generator(void) { TCOD_namegen_destroy(); }
Java
# FAQ Summary 1. General information and availability 1. What is the CImg Library ? 2. What platforms are supported ? 3. How is CImg distributed ? 4. What kind of people are concerned by CImg ? 5. What are the specificities of the CeCILL license ? 6. Who is behind CImg ? 2. C++ related questions 1. What is the level of C++ knowledge needed to use CImg ? 2. How to use CImg in my own C++ program ? 3. Why is CImg entirely contained in a single header file ? 3. Other resources 1. Translations ## 1. General information and availability ### 1.1. What is the CImg Library ? The CImg Library is an open-source C++ toolkit for image processing. It mainly consists in a (big) single header file CImg.h providing a set of C++ classes and functions that can be used in your own sources, to load/save, manage/process and display generic images. It's actually a very simple and pleasant toolkit for coding image processing stuff in C++ : Just include the header file CImg.h, and you are ready to handle images in your C++ programs. ### 1.2. What platforms are supported ? CImg has been designed with portability in mind. It is regularly tested on different architectures and compilers, and should also work on any decent OS having a decent C++ compiler. Before each release, the CImg Library is compiled under these different configurations : - PC Linux 32 bits, with g++. - PC Windows 32 bits, with Visual C++ 6.0. - PC Windows 32 bits, with Visual C++ Express Edition. - Sun SPARC Solaris 32 bits, with g++. - Mac PPC with OS X and g++. CImg has a minimal number of dependencies. In its minimal version, it can be compiled only with standard C++ headers. Anyway, it has interesting extension capabilities and can use external libraries to perform specific tasks more efficiently (Fourier Transform computation using FFTW for instance). ### 1.3. How is CImg distributed ? The CImg Library is freely distributed as a complete .zip compressed package, hosted at the CImg server. The package is distributed under the CeCILL license. This package contains : - The main library file CImg.h (C++ header file). - Several C++ source code showing examples of using CImg. - A complete library documentation, in HTML and PDF formats. - Additional library plug-ins that can be used to extend library capabilities for specific uses. The CImg Library is a quite lightweight library which is easy to maintain (due to its particular structure), and thus has a fast rythm of release. A new version of the CImg package is released approximately every three months. ### 1.4. What kind of people are concerned by CImg ? The CImg library is an image processing library, primarily intended for computer scientists or students working in the fields of image processing or computer vision, and knowing bases of C++. As the library is handy and really easy to use, it can be also used by any programmer needing occasional tools for dealing with images in C++, since there are no standard library yet for this purpose. ### 1.5. What are the specificities of the CeCILL license ? The CeCILL license governs the use of the CImg Library. This is an open-source license which gives you rights to access, use, modify and redistribute the source code, under certains conditions. There are two different variants of the CeCILL license used in CImg (namely CeCILL and CeCILL-C, all open-source), corresponding to different constraints on the source files : - The CeCILL-C license is the most permissive one, close to the GNU LGPL license, and applies only on the main library file CImg.h. Basically, this license allows to use CImg.h in a closed-source product without forcing you to redistribute the entire software source code. Anyway, if one modifies the CImg.h source file, one has to redistribute the modified version of the file that must be governed by the same CeCILL-C license. - The CeCILL license applies to all other files (source examples, plug-ins and documentation) of the CImg Library package, and is close (even compatible) with the GNU GPL license. It does not allow the use of these files in closed-source products. You are invited to read the complete descriptions of the the CeCILL-C and CeCILL licenses before releasing a software based on the CImg Library. ### 1.6. Who is behind CImg ? CImg has been started by David Tschumperle at the beginning of his PhD thesis, in October 1999. He is still the main coordinator of the project. Since the first release, a growing number of contributors has appeared. Due to the very simple and compact form of the library, submitting a contribution is quite easy and can be fastly integrated into the supported releases. List of contributors can be found on the front page. ## 2. C++ related questions ### 2.1 What is the level of C++ knowledge needed to use CImg ? The CImg Library has been designed using C++ templates and object-oriented programming techniques, but in a very accessible level. There are only public classes without any derivation (just like C structures) and there is at most one template parameter for each CImg class (defining the pixel type of the images). The design is simple but clean, making the library accessible even for non professional C++ programmers, while proposing strong extension capabilities for C++ experts. ### 2.2 How to use CImg in my own C++ program ? Basically, you need to add these two lines in your C++ source code, in order to be able to work with CImg images : ```c++ #include "CImg.h" using namespace cimg_library; ``` ### 2.3 Why is CImg entirely contained in a single header file ? People are often surprised to see that the complete code of the library is contained in a single (big) C++ header file CImg.h. There are good practical and technical reasons to do that. Some arguments are listed below to justify this approach, so (I hope) you won't think this is a awkwardly C++ design of the CImg library : - First, the library is based on template datatypes (images with generic pixel type), meaning that the programmer is free to decide what type of image he instanciates in his code. Even if there are roughly a limited number of fully supported types (basically, the "atomic" types of C++ : unsigned char, int, float, ...), this is not imaginable to pre-compile the library classes and functions for all possible atomic datatypes, since many functions and methods can have two or three arguments having different template parameters. This really means a huge number of possible combinations. The size of the object binary file generated to cover all possible cases would be just colossal. Is the STL library a pre-compiled one ? No, CImg neither. CImg is not using a classical .cpp and .h mechanism, just like the STL. Architectures of C++ template-based libraries are somewhat special in this sense. This is a proven technical fact. - Second, why CImg does not have several header files, just like the STL does (one for each class for instance) ? This would be possible of course. There are only 4 classes in CImg, the two most important being CImg<T> and CImgList<T> representing respectively an image and a collection of images. But contrary to the STL library, these two CImg classes are strongly inter-dependent. All CImg algorithms are actually not defined as separate functions acting on containers (as the STL does with his header <algorithm>), but are directly methods of the image and image collection classes. This inter-dependence practically means that you will undoubtly need these two main classes at the same time if you are using CImg. If they were defined in separate header files, you would be forced to include both of them. What is the gain then ? No gain. Concerning the two other classes : You can disable the third most important class CImgDisplay of the CImg library, by setting the compilation macro cimg_display to 0, avoiding thus to compile this class if you don't use display capabilities of CImg in your code. But to be honest, this is a quite small class and doing this doesn't save much compilation time. The last and fourth class is CImgException, which is only few lines long and is obviously required in almost all methods of CImg. Including this one is mandatory. As a consequence, having a single header file instead of several ones is just a way for you to avoid including all of them, without any consequences on compilation time. This is both good technical and practical reasons to do like this. - Third, having a single header file has plenty of advantages : Simplicity for the user, and for the developers (maintenance is in fact easier). Look at the CImg.h file, it looks like a mess at a first glance, but it is in fact very well organized and structured. Finding pieces of code in CImg functions or methods is particularly easy and fast. Also, how about the fact that library installation problems just disappear ? Just bring CImg.h with you, put it in your source directory, and the library is ready to go ! I admit the compilation time of CImg-based programs can be sometime long, but don't think that it is due to the fact that you are using a single header file. Using several header files wouldn't arrange anything since you would need all of them. Having a pre-compiled library object would be the only solution to speed up compilation time, but it is not possible at all, due to the too much generic nature of the library. ## 3. Other resources ### 3.1 Translations This FAQ has been translated to Serbo-Croatian language by Web Geeks .
Java
{% extends "userspace/journal/base.html" %} {% load i18n rules %} {% block title %}{{ block.super }}{% endblock title %} {% block breadcrumb %}{{ block.super }} <li><a href="{% url 'userspace:journal:subscription:list' scope_current_journal.pk %}">{% trans "Abonnements" %}</a></li> {% endblock breadcrumb %} {% block section_title %} {% trans "Abonnements" %} {% endblock %} {% block content_main %} <ul class="tabs"> {% has_perm 'subscription.manage_individual_subscription' request.user scope_current_journal as can_manage_individual_subscription %} {% has_perm 'subscription.manage_institutional_subscription' request.user scope_current_journal as can_manage_institutional_subscription %} {% if can_manage_institutional_subscription %} <li class="tabs__item{% if view.is_org_view %} tabs__item_active{% endif %}"> <a href="{% url 'userspace:journal:subscription:org_list' scope_current_journal.pk %}">{% trans "Institutionnels" %}</a> </li> {% endif %} {% if can_manage_individual_subscription %} <li class="tabs__item{% if not view.is_org_view %} tabs__item_active{% endif %}"> <a href="{% url 'userspace:journal:subscription:list' scope_current_journal.pk %}">{% trans "Individuels" %}</a> </li> {% endif %} </ul> {% endblock content_main %}
Java
// Copyright 2014 The go-krypton Authors // This file is part of the go-krypton library. // // The go-krypton 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. // // The go-krypton 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 go-krypton library. If not, see <http://www.gnu.org/licenses/>. // Package trie implements Merkle Patricia Tries. package trie import ( "bytes" "errors" "fmt" "hash" "github.com/krypton/go-krypton/common" "github.com/krypton/go-krypton/crypto" "github.com/krypton/go-krypton/crypto/sha3" "github.com/krypton/go-krypton/logger" "github.com/krypton/go-krypton/logger/glog" "github.com/krypton/go-krypton/rlp" ) const defaultCacheCapacity = 800 var ( // The global cache stores decoded trie nodes by hash as they get loaded. globalCache = newARC(defaultCacheCapacity) // This is the known root hash of an empty trie. emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421") // This is the known hash of an empty state trie entry. emptyState = crypto.Sha3Hash(nil) ) var ErrMissingRoot = errors.New("missing root node") // Database must be implemented by backing stores for the trie. type Database interface { DatabaseWriter // Get returns the value for key from the database. Get(key []byte) (value []byte, err error) } // DatabaseWriter wraps the Put method of a backing store for the trie. type DatabaseWriter interface { // Put stores the mapping key->value in the database. // Implementations must not hold onto the value bytes, the trie // will reuse the slice across calls to Put. Put(key, value []byte) error } // Trie is a Merkle Patricia Trie. // The zero value is an empty trie with no database. // Use New to create a trie that sits on top of a database. // // Trie is not safe for concurrent use. type Trie struct { root node db Database *hasher } // New creates a trie with an existing root node from db. // // If root is the zero hash or the sha3 hash of an empty string, the // trie is initially empty and does not require a database. Otherwise, // New will panics if db is nil or root does not exist in the // database. Accessing the trie loads nodes from db on demand. func New(root common.Hash, db Database) (*Trie, error) { trie := &Trie{db: db} if (root != common.Hash{}) && root != emptyRoot { if db == nil { panic("trie.New: cannot use existing root without a database") } if v, _ := trie.db.Get(root[:]); len(v) == 0 { return nil, ErrMissingRoot } trie.root = hashNode(root.Bytes()) } return trie, nil } // Iterator returns an iterator over all mappings in the trie. func (t *Trie) Iterator() *Iterator { return NewIterator(t) } // Get returns the value for key stored in the trie. // The value bytes must not be modified by the caller. func (t *Trie) Get(key []byte) []byte { key = compactHexDecode(key) tn := t.root for len(key) > 0 { switch n := tn.(type) { case shortNode: if len(key) < len(n.Key) || !bytes.Equal(n.Key, key[:len(n.Key)]) { return nil } tn = n.Val key = key[len(n.Key):] case fullNode: tn = n[key[0]] key = key[1:] case nil: return nil case hashNode: tn = t.resolveHash(n) default: panic(fmt.Sprintf("%T: invalid node: %v", tn, tn)) } } return tn.(valueNode) } // Update associates key with value in the trie. Subsequent calls to // Get will return value. If value has length zero, any existing value // is deleted from the trie and calls to Get will return nil. // // The value bytes must not be modified by the caller while they are // stored in the trie. func (t *Trie) Update(key, value []byte) { k := compactHexDecode(key) if len(value) != 0 { t.root = t.insert(t.root, k, valueNode(value)) } else { t.root = t.delete(t.root, k) } } func (t *Trie) insert(n node, key []byte, value node) node { if len(key) == 0 { return value } switch n := n.(type) { case shortNode: matchlen := prefixLen(key, n.Key) // If the whole key matches, keep this short node as is // and only update the value. if matchlen == len(n.Key) { return shortNode{n.Key, t.insert(n.Val, key[matchlen:], value)} } // Otherwise branch out at the index where they differ. var branch fullNode branch[n.Key[matchlen]] = t.insert(nil, n.Key[matchlen+1:], n.Val) branch[key[matchlen]] = t.insert(nil, key[matchlen+1:], value) // Replace this shortNode with the branch if it occurs at index 0. if matchlen == 0 { return branch } // Otherwise, replace it with a short node leading up to the branch. return shortNode{key[:matchlen], branch} case fullNode: n[key[0]] = t.insert(n[key[0]], key[1:], value) return n case nil: return shortNode{key, value} case hashNode: // We've hit a part of the trie that isn't loaded yet. Load // the node and insert into it. This leaves all child nodes on // the path to the value in the trie. // // TODO: track whkrypton insertion changed the value and keep // n as a hash node if it didn't. return t.insert(t.resolveHash(n), key, value) default: panic(fmt.Sprintf("%T: invalid node: %v", n, n)) } } // Delete removes any existing value for key from the trie. func (t *Trie) Delete(key []byte) { k := compactHexDecode(key) t.root = t.delete(t.root, k) } // delete returns the new root of the trie with key deleted. // It reduces the trie to minimal form by simplifying // nodes on the way up after deleting recursively. func (t *Trie) delete(n node, key []byte) node { switch n := n.(type) { case shortNode: matchlen := prefixLen(key, n.Key) if matchlen < len(n.Key) { return n // don't replace n on mismatch } if matchlen == len(key) { return nil // remove n entirely for whole matches } // The key is longer than n.Key. Remove the remaining suffix // from the subtrie. Child can never be nil here since the // subtrie must contain at least two other values with keys // longer than n.Key. child := t.delete(n.Val, key[len(n.Key):]) switch child := child.(type) { case shortNode: // Deleting from the subtrie reduced it to another // short node. Merge the nodes to avoid creating a // shortNode{..., shortNode{...}}. Use concat (which // always creates a new slice) instead of append to // avoid modifying n.Key since it might be shared with // other nodes. return shortNode{concat(n.Key, child.Key...), child.Val} default: return shortNode{n.Key, child} } case fullNode: n[key[0]] = t.delete(n[key[0]], key[1:]) // Check how many non-nil entries are left after deleting and // reduce the full node to a short node if only one entry is // left. Since n must've contained at least two children // before deletion (otherwise it would not be a full node) n // can never be reduced to nil. // // When the loop is done, pos contains the index of the single // value that is left in n or -2 if n contains at least two // values. pos := -1 for i, cld := range n { if cld != nil { if pos == -1 { pos = i } else { pos = -2 break } } } if pos >= 0 { if pos != 16 { // If the remaining entry is a short node, it replaces // n and its key gets the missing nibble tacked to the // front. This avoids creating an invalid // shortNode{..., shortNode{...}}. Since the entry // might not be loaded yet, resolve it just for this // check. cnode := t.resolve(n[pos]) if cnode, ok := cnode.(shortNode); ok { k := append([]byte{byte(pos)}, cnode.Key...) return shortNode{k, cnode.Val} } } // Otherwise, n is replaced by a one-nibble short node // containing the child. return shortNode{[]byte{byte(pos)}, n[pos]} } // n still contains at least two values and cannot be reduced. return n case nil: return nil case hashNode: // We've hit a part of the trie that isn't loaded yet. Load // the node and delete from it. This leaves all child nodes on // the path to the value in the trie. // // TODO: track whkrypton deletion actually hit a key and keep // n as a hash node if it didn't. return t.delete(t.resolveHash(n), key) default: panic(fmt.Sprintf("%T: invalid node: %v (%v)", n, n, key)) } } func concat(s1 []byte, s2 ...byte) []byte { r := make([]byte, len(s1)+len(s2)) copy(r, s1) copy(r[len(s1):], s2) return r } func (t *Trie) resolve(n node) node { if n, ok := n.(hashNode); ok { return t.resolveHash(n) } return n } func (t *Trie) resolveHash(n hashNode) node { if v, ok := globalCache.Get(n); ok { return v } enc, err := t.db.Get(n) if err != nil || enc == nil { // TODO: This needs to be improved to properly distinguish errors. // Disk I/O errors shouldn't produce nil (and cause a // consensus failure or weird crash), but it is unclear how // they could be handled because the entire stack above the trie isn't // prepared to cope with missing state nodes. if glog.V(logger.Error) { glog.Errorf("Dangling hash node ref %x: %v", n, err) } return nil } dec := mustDecodeNode(n, enc) if dec != nil { globalCache.Put(n, dec) } return dec } // Root returns the root hash of the trie. // Deprecated: use Hash instead. func (t *Trie) Root() []byte { return t.Hash().Bytes() } // Hash returns the root hash of the trie. It does not write to the // database and can be used even if the trie doesn't have one. func (t *Trie) Hash() common.Hash { root, _ := t.hashRoot(nil) return common.BytesToHash(root.(hashNode)) } // Commit writes all nodes to the trie's database. // Nodes are stored with their sha3 hash as the key. // // Committing flushes nodes from memory. // Subsequent Get calls will load nodes from the database. func (t *Trie) Commit() (root common.Hash, err error) { if t.db == nil { panic("Commit called on trie with nil database") } return t.CommitTo(t.db) } // CommitTo writes all nodes to the given database. // Nodes are stored with their sha3 hash as the key. // // Committing flushes nodes from memory. Subsequent Get calls will // load nodes from the trie's database. Calling code must ensure that // the changes made to db are written back to the trie's attached // database before using the trie. func (t *Trie) CommitTo(db DatabaseWriter) (root common.Hash, err error) { n, err := t.hashRoot(db) if err != nil { return (common.Hash{}), err } t.root = n return common.BytesToHash(n.(hashNode)), nil } func (t *Trie) hashRoot(db DatabaseWriter) (node, error) { if t.root == nil { return hashNode(emptyRoot.Bytes()), nil } if t.hasher == nil { t.hasher = newHasher() } return t.hasher.hash(t.root, db, true) } type hasher struct { tmp *bytes.Buffer sha hash.Hash } func newHasher() *hasher { return &hasher{tmp: new(bytes.Buffer), sha: sha3.NewKeccak256()} } func (h *hasher) hash(n node, db DatabaseWriter, force bool) (node, error) { hashed, err := h.replaceChildren(n, db) if err != nil { return hashNode{}, err } if n, err = h.store(hashed, db, force); err != nil { return hashNode{}, err } return n, nil } // hashChildren replaces child nodes of n with their hashes if the encoded // size of the child is larger than a hash. func (h *hasher) replaceChildren(n node, db DatabaseWriter) (node, error) { var err error switch n := n.(type) { case shortNode: n.Key = compactEncode(n.Key) if _, ok := n.Val.(valueNode); !ok { if n.Val, err = h.hash(n.Val, db, false); err != nil { return n, err } } if n.Val == nil { // Ensure that nil children are encoded as empty strings. n.Val = valueNode(nil) } return n, nil case fullNode: for i := 0; i < 16; i++ { if n[i] != nil { if n[i], err = h.hash(n[i], db, false); err != nil { return n, err } } else { // Ensure that nil children are encoded as empty strings. n[i] = valueNode(nil) } } if n[16] == nil { n[16] = valueNode(nil) } return n, nil default: return n, nil } } func (h *hasher) store(n node, db DatabaseWriter, force bool) (node, error) { // Don't store hashes or empty nodes. if _, isHash := n.(hashNode); n == nil || isHash { return n, nil } h.tmp.Reset() if err := rlp.Encode(h.tmp, n); err != nil { panic("encode error: " + err.Error()) } if h.tmp.Len() < 32 && !force { // Nodes smaller than 32 bytes are stored inside their parent. return n, nil } // Larger nodes are replaced by their hash and stored in the database. h.sha.Reset() h.sha.Write(h.tmp.Bytes()) key := hashNode(h.sha.Sum(nil)) if db != nil { err := db.Put(key, h.tmp.Bytes()) return key, err } return key, nil }
Java
#!/bin/csh # --------------------------------------------------------------------------- # # Script to Read in a new substructure file to the database # # --------------------------------------------------------------------------- #set verbose on if ( $#argv != 1 ) then echo "Usage: $0 FileRoot" echo " FileROOT : The substructure information file (rootname without sdf extension)" echo " The file is assumed to be in the current directory" exit(1) endif #-------------------------------------------------------------------------- # Set up inputs, files and program #-------------------------------------------------------------------------- # The program and the input file pattern set CHEMPROG = $REACTROOT/bin/runchem.sh set REFERENCE = $REACTROOT/programs/inputs/ReadSubsFromFile.inp # The current input file and the standard (established) input file set NEWFILE = $1 # The combined input file (all the substructures are formed again) set STANDARDSUBFILE = standard set STANDARD = $REACTROOT/data/mol/subs/standard.sdf set TEMPDIR = $REACTROOT/tmp set TEMPFILE = $REACTROOT/tmp/read.prg set TEMPOUTFILE = $REACTROOT/tmp/read.out set INFILE = $NEWFILE.sdf #-------------------------------------------------------------------------- # Modify program and merge input data files #-------------------------------------------------------------------------- sed "s/XXXXX/$NEWFILE/g"\ $REFERENCE >! $TEMPFILE cat $INFILE > $STANDARD #-------------------------------------------------------------------------- # Put Substructures in Database #-------------------------------------------------------------------------- pushd $TEMPDIR $CHEMPROG read < read.prg rm $TEMPFILE popd mv $TEMPOUTFILE $NEWFILE.out
Java
class Solution { public: string addBinary(string a, string b) { string sum = ""; int carry = 0; for (int i = a.size() - 1, j = b.size() - 1; i >= 0 || j >= 0; i--, j--) { int m = (i >= 0 && a[i] == '1'); int n = (j >= 0 && b[j] == '1'); sum += to_string((m + n + carry) & 0x1); // &0x1 only get the last binary digit //It's better to avoid pattern string = char + string in loop. Use s[i] to alter string. //just directly writing the output string and reversing it at last. carry = (m + n + carry) >> 1; // >>1 is /2 } reverse(sum.begin(), sum.end()); if(carry) sum = '1' + sum; else sum = '0' + sum; //in case of two null input string size_t i=0; while(sum[i] == '0' && i < sum.length()-1) i++; sum = sum.substr(i); return sum; } };
Java
--- title: "कांग्रेस का नया नारा 'अब होगा NYAY', चुनावी कैम्पेन लांच" layout: item category: ["politics"] date: 2019-04-07T08:05:44.259Z image: 1554624344259congress.jpg --- <p>नई दिल्ली: कांग्रेस लोकसभा चुनाव के लिए रविवार को अपने प्रचार अभियान की औपचारिक रूप से शुरुआत की। इस अभियान के तहत पार्टी ने प्रिंट, इलेक्ट्रॉनिक और डिजिटल मीडिया माध्यमों पर दिए जाने वाले पार्टी के प्रचार अभियान का ब्यौरा पेश किया। कांग्रेस के वरिष्ठ नेता आनंद शर्मा की अध्यक्षता वाली प्रचार अभियान की समिति ने प्रचार अभियान का पूरा ब्यौरा देते हुए स्लोगन लॉन्च किया। स्लोगन की टैगलाइन है- अब होगा न्याय। न्याय कैम्पेन वीडियो के लिए लिरिक्स जावेद अख्तर ने लिखे हैं। निखिल अडवाणी ने इसे निर्देशित किया है।</p> <div class="tw-container"><div class="tweet" data-tweet="1114790612199333888"></div></div> <p>आनंद शर्मा ने कहा कि मोदी सरकार ने लोगों को सपने दिखाकर चकनाचूर किया। उन्होंने बताया कि &#39;परसेप्ट&#39; नाम की एजेंसी चुनाव प्रचार अभियान की अगुवाई करेगी। इसके अलावा अन्य सहयोगी एजेंसियां हैं जिनमें निक्सन और डिजाइन बॉक्स हैं। उन्होंने कहा कि कैंपेन की खास बात है कि हम स्पेशल कंटेनर ट्रक का इस्तेमाल करेंगे।</p> <div class="tw-container"><div class="tweet" data-tweet="1114798893240209408"></div></div> <p>कांग्रेस अपने प्रचार अभियान में रोजगार, नौजवान, किसान और महिलाओं पर मुख्य रूप से केंद्रित रखेगी तथा विभिन्न मुद्दों को लेकर मोदी सरकार को घेरने पर भी जोर दिया।</p> <div class="tw-container"><div class="tweet" data-tweet="1114797055937892352"></div></div>
Java
{-# LANGUAGE FlexibleContexts, CPP, JavaScriptFFI #-} module Carnap.GHCJS.Action.TreeDeductionCheck (treeDeductionCheckAction) where import Lib hiding (content) import Data.Tree import Data.Either import Data.Map as M (lookup,Map, toList) import Data.IORef (IORef, readIORef, newIORef, writeIORef) import Data.Typeable (Typeable) import Data.Aeson.Types import Data.Text (pack) import qualified Text.Parsec as P (parse) import Control.Monad.State (modify,get,execState,State) import Control.Lens import Control.Concurrent import Control.Monad (mplus, (>=>)) import Control.Monad.IO.Class (liftIO) import Carnap.Core.Unification.Unification (MonadVar,FirstOrder, applySub) import Carnap.Core.Unification.ACUI (ACUI) import Carnap.Core.Data.Types import Carnap.Core.Data.Classes import Carnap.Core.Data.Optics import Carnap.Languages.ClassicalSequent.Syntax import Carnap.Languages.ClassicalSequent.Parser import Carnap.Languages.PurePropositional.Syntax import Carnap.Languages.Util.LanguageClasses import Carnap.Calculi.Util import Carnap.Calculi.NaturalDeduction.Syntax import Carnap.Calculi.NaturalDeduction.Checker import Carnap.Calculi.Tableau.Data import Carnap.Languages.PurePropositional.Logic (ofPropTreeSys) import Carnap.Languages.PureFirstOrder.Logic (ofFOLTreeSys) import Carnap.GHCJS.Util.ProofJS import Carnap.GHCJS.SharedTypes import GHCJS.DOM.HTMLElement (getInnerText, castToHTMLElement) import GHCJS.DOM.Element (setInnerHTML, click, keyDown, input, setAttribute ) import GHCJS.DOM.Node (appendChild, removeChild, getParentNode, insertBefore, getParentElement) import GHCJS.DOM.Types (Element, Document, IsElement) import GHCJS.DOM.Document (createElement, getActiveElement) import GHCJS.DOM.KeyboardEvent import GHCJS.DOM.EventM import GHCJS.DOM import GHCJS.Types treeDeductionCheckAction :: IO () treeDeductionCheckAction = do initializeCallback "checkProofTreeInfo" njCheck initElements getCheckers activateChecker return () where njCheck = maybe (error "can't find PropNJ") id $ (\calc -> checkProofTree calc Nothing >=> return . fst) `ofPropTreeSys` "PropNJ" getCheckers :: IsElement self => Document -> self -> IO [Maybe (Element, Element, Map String String)] getCheckers w = genInOutElts w "div" "div" "treedeductionchecker" activateChecker :: Document -> Maybe (Element, Element, Map String String) -> IO () activateChecker _ Nothing = return () activateChecker w (Just (i, o, opts)) = case (setupWith `ofPropTreeSys` sys) `mplus` (setupWith `ofFOLTreeSys` sys) of Just io -> io Nothing -> error $ "couldn't parse tree system: " ++ sys where sys = case M.lookup "system" opts of Just s -> s Nothing -> "propNK" setupWith calc = do mgoal <- parseGoal calc let content = M.lookup "content" opts root <- case (content >>= decodeJSON, mgoal) of (Just val,_) -> let Just c = content in initRoot c o (_, Just seq) | "prepopulate" `inOpts` opts -> initRoot ("{\"label\": \"" ++ show (view rhs seq) ++ "\", \"rule\":\"\", \"forest\": []}") o _ -> initRoot "{\"label\": \"\", \"rule\":\"\", \"forest\": []}" o memo <- newIORef mempty threadRef <- newIORef (Nothing :: Maybe ThreadId) bw <- createButtonWrapper w o let submit = submitTree w memo opts calc root mgoal btStatus <- createSubmitButton w bw submit opts if "displayJSON" `inOpts` opts then do Just displayDiv <- createElement w (Just "div") setAttribute displayDiv "class" "jsonDisplay" setAttribute displayDiv "contenteditable" "true" val <- toCleanVal root setInnerHTML displayDiv . Just $ toJSONString val toggleDisplay <- newListener $ do kbe <- event isCtrl <- getCtrlKey kbe code <- liftIO $ keyString kbe liftIO $ print code if isCtrl && code == "?" then do preventDefault mparent <- getParentNode displayDiv case mparent of Just p -> removeChild o (Just displayDiv) _ -> appendChild o (Just displayDiv) return () else return () addListener o keyDown toggleDisplay False updateRoot <- newListener $ liftIO $ do Just json <- getInnerText (castToHTMLElement displayDiv) replaceRoot root json addListener displayDiv input updateRoot False root `onChange` (\_ -> do mfocus <- getActiveElement w --don't update when the display is --focussed, to avoid cursor jumping if Just displayDiv /= mfocus then do val <- toCleanVal root setInnerHTML displayDiv . Just $ toJSONString val else return ()) return () else return () initialCheck <- newListener $ liftIO $ do forkIO $ do threadDelay 500000 mr <- toCleanVal root case mr of Just r -> do (info,mseq) <- checkProofTree calc (Just memo) r decorate root info Just wrap <- getParentElement i updateInfo calc mgoal mseq wrap Nothing -> return () return () addListener i initialize initialCheck False --initial check in case we preload a tableau doOnce i mutate False $ liftIO $ btStatus Edited case M.lookup "init" opts of Just "now" -> dispatchCustom w i "initialize"; _ -> return () root `onChange` (\_ -> dispatchCustom w i "mutate") root `onChange` (\_ -> checkOnChange memo threadRef calc mgoal i root) parseGoal calc = do let seqParse = parseSeqOver $ tbParseForm calc case M.lookup "goal" opts of Just s -> case P.parse seqParse "" s of Left e -> do setInnerHTML i (Just $ "Couldn't Parse This Goal:" ++ s) error "couldn't parse goal" Right seq -> do setInnerHTML i (Just . tbNotation calc . show $ seq) return $ Just seq Nothing -> do setInnerHTML i (Just "Awaiting a proof") return Nothing updateInfo _ (Just goal) (Just seq) wrap | seq `seqSubsetUnify` goal = setAttribute wrap "class" "success" updateInfo _ (Just goal) (Just seq) wrap = setAttribute wrap "class" "failure" updateInfo calc Nothing (Just seq) wrap = setInnerHTML wrap (Just . tbNotation calc . show $ seq) updateInfo _ Nothing Nothing wrap = setInnerHTML wrap (Just "Awaiting a proof") updateInfo _ _ _ wrap = setAttribute wrap "class" "" submitTree w memo opts calc root (Just seq) l = do Just val <- liftIO $ toCleanVal root case parse parseTreeJSON val of Error s -> message $ "Something has gone wrong. Here's the error:" ++ s Success tree -> case toProofTree calc tree of Left _ | "exam" `inOpts` opts -> trySubmit w DeductionTree opts l (DeductionTreeData (pack (show seq)) tree (toList opts)) False Left _ -> message "Something is wrong with the proof... Try again?" Right prooftree -> do validation <- liftIO $ hoReduceProofTreeMemo memo (structuralRestriction prooftree) prooftree case validation of Right seq' | "exam" `inOpts` opts || (seq' `seqSubsetUnify` seq) -> trySubmit w DeductionTree opts l (DeductionTreeData (pack (show seq)) tree (toList opts)) (seq' `seqSubsetUnify` seq) _ -> message "Something is wrong with the proof... Try again?" checkOnChange :: ( ReLex lex , Sequentable lex , Inference rule lex sem , FirstOrder (ClassicalSequentOver lex) , ACUI (ClassicalSequentOver lex) , MonadVar (ClassicalSequentOver lex) (State Int) , StaticVar (ClassicalSequentOver lex) , Schematizable (lex (ClassicalSequentOver lex)) , CopulaSchema (ClassicalSequentOver lex) , Typeable sem , Show rule , PrismSubstitutionalVariable lex , FirstOrderLex (lex (ClassicalSequentOver lex)) , StructuralOverride rule (ProofTree rule lex sem) , StructuralInference rule lex (ProofTree rule lex sem) ) => ProofMemoRef lex sem rule -> IORef (Maybe ThreadId) -> TableauCalc lex sem rule -> Maybe (ClassicalSequentOver lex (Sequent sem)) -> Element -> JSVal -> IO () checkOnChange memo threadRef calc mgoal i root = do mt <- readIORef threadRef case mt of Just t -> killThread t Nothing -> return () t' <- forkIO $ do threadDelay 500000 Just changedVal <- toCleanVal root (theInfo, mseq) <- checkProofTree calc (Just memo) changedVal decorate root theInfo Just wrap <- getParentElement i updateInfo calc mgoal mseq wrap writeIORef threadRef (Just t') toProofTree :: ( Typeable sem , ReLex lex , Sequentable lex , StructuralOverride rule (ProofTree rule lex sem) , Inference rule lex sem ) => TableauCalc lex sem rule -> Tree (String,String) -> Either (TreeFeedback lex) (ProofTree rule lex sem) toProofTree calc (Node (l,r) f) | all isRight parsedForest && isRight newNode = handleOverride <$> (Node <$> newNode <*> sequence parsedForest) | isRight newNode = Left $ Node Waiting (map cleanTree parsedForest) | Left n <- newNode = Left n where parsedLabel = (SS . liftToSequent) <$> P.parse (tbParseForm calc) "" l parsedRules = P.parse (tbParseRule calc) "" r parsedForest = map (toProofTree calc) f cleanTree (Left fs) = fs cleanTree (Right fs) = fmap (const Waiting) fs newNode = case ProofLine 0 <$> parsedLabel <*> parsedRules of Right l -> Right l Left e -> Left (Node (ProofError $ NoParse e 0) (map cleanTree parsedForest)) handleOverride f@(Node l fs) = case structuralOverride f (head (rule l)) of Nothing -> f Just rs -> Node (l {rule = rs}) fs checkProofTree :: ( ReLex lex , Sequentable lex , Inference rule lex sem , FirstOrder (ClassicalSequentOver lex) , ACUI (ClassicalSequentOver lex) , MonadVar (ClassicalSequentOver lex) (State Int) , StaticVar (ClassicalSequentOver lex) , Schematizable (lex (ClassicalSequentOver lex)) , CopulaSchema (ClassicalSequentOver lex) , Typeable sem , Show rule , StructuralOverride rule (ProofTree rule lex sem) , StructuralInference rule lex (ProofTree rule lex sem) ) => TableauCalc lex sem rule -> Maybe (ProofMemoRef lex sem rule) -> Value -> IO (Value, Maybe (ClassicalSequentOver lex (Sequent sem))) checkProofTree calc mmemo v = case parse parseTreeJSON v of Success t -> case toProofTree calc t of Left feedback -> return (toInfo feedback, Nothing) Right tree -> do (val,mseq) <- validateProofTree calc mmemo tree return (toInfo val, mseq) Error s -> do print (show v) error s validateProofTree :: ( ReLex lex , Sequentable lex , Inference rule lex sem , FirstOrder (ClassicalSequentOver lex) , ACUI (ClassicalSequentOver lex) , MonadVar (ClassicalSequentOver lex) (State Int) , StaticVar (ClassicalSequentOver lex) , Schematizable (lex (ClassicalSequentOver lex)) , CopulaSchema (ClassicalSequentOver lex) , Typeable sem , Show rule , StructuralInference rule lex (ProofTree rule lex sem) ) => TableauCalc lex sem rule -> Maybe (ProofMemoRef lex sem rule) -> ProofTree rule lex sem -> IO (TreeFeedback lex, Maybe (ClassicalSequentOver lex (Sequent sem))) validateProofTree calc mmemo t@(Node _ fs) = do rslt <- case mmemo of Nothing -> return $ hoReduceProofTree (structuralRestriction t) t Just memo -> hoReduceProofTreeMemo memo (structuralRestriction t) t case rslt of Left msg -> (,) <$> (Node <$> pure (ProofError msg) <*> mapM (validateProofTree calc mmemo >=> return . fst) fs) <*> pure Nothing Right seq -> (,) <$> (Node <$> pure (ProofData (tbNotation calc . show $ seq)) <*> mapM (validateProofTree calc mmemo >=> return . fst) fs) <*> pure (Just seq)
Java
/* * Darmix-Core Copyright (C) 2013 Deremix * Integrated Files: CREDITS.md and LICENSE.md */ #ifndef BLIZZLIKE_OBJECTACCESSOR_H #define BLIZZLIKE_OBJECTACCESSOR_H #include "Platform/Define.h" #include "Policies/Singleton.h" #include <ace/Thread_Mutex.h> #include "Utilities/UnorderedMap.h" #include "Policies/ThreadingModel.h" #include "ByteBuffer.h" #include "UpdateData.h" #include "GridDefines.h" #include "Object.h" #include "Player.h" #include <set> class Creature; class Corpse; class Unit; class GameObject; class DynamicObject; class WorldObject; class Map; template <class T> class HashMapHolder { public: typedef UNORDERED_MAP<uint64, T*> MapType; typedef ACE_Thread_Mutex LockType; typedef BlizzLike::GeneralLock<LockType > Guard; static void Insert(T* o) { Guard guard(i_lock); m_objectMap[o->GetGUID()] = o; } static void Remove(T* o) { Guard guard(i_lock); m_objectMap.erase(o->GetGUID()); } static T* Find(uint64 guid) { Guard guard(i_lock); typename MapType::iterator itr = m_objectMap.find(guid); return (itr != m_objectMap.end()) ? itr->second : NULL; } static MapType& GetContainer() { return m_objectMap; } static LockType* GetLock() { return &i_lock; } private: //Non instanceable only static HashMapHolder() {} static LockType i_lock; static MapType m_objectMap; }; class ObjectAccessor : public BlizzLike::Singleton<ObjectAccessor, BlizzLike::ClassLevelLockable<ObjectAccessor, ACE_Thread_Mutex> > { friend class BlizzLike::OperatorNew<ObjectAccessor>; ObjectAccessor(); ~ObjectAccessor(); ObjectAccessor(const ObjectAccessor&); ObjectAccessor& operator=(const ObjectAccessor&); public: typedef UNORDERED_MAP<uint64, Corpse*> Player2CorpsesMapType; typedef UNORDERED_MAP<Player*, UpdateData>::value_type UpdateDataValueType; // returns object if is in world template<class T> static T* GetObjectInWorld(uint64 guid, T* /*typeSpecifier*/) { return HashMapHolder<T>::Find(guid); } // Player may be not in world while in ObjectAccessor static Player* GetObjectInWorld(uint64 guid, Player* /*typeSpecifier*/) { Player* player = HashMapHolder<Player>::Find(guid); if (player && player->IsInWorld()) return player; return NULL; } static Unit* GetObjectInWorld(uint64 guid, Unit* /*typeSpecifier*/) { if (IS_PLAYER_GUID(guid)) return (Unit*)GetObjectInWorld(guid, (Player*)NULL); if (IS_PET_GUID(guid)) return (Unit*)GetObjectInWorld(guid, (Pet*)NULL); return (Unit*)GetObjectInWorld(guid, (Creature*)NULL); } // returns object if is in map template<class T> static T* GetObjectInMap(uint64 guid, Map * map, T* /*typeSpecifier*/) { assert(map); if (T * obj = GetObjectInWorld(guid, (T*)NULL)) if (obj->GetMap() == map) return obj; return NULL; } template<class T> static T* GetObjectInWorld(uint32 mapid, float x, float y, uint64 guid, T* /*fake*/) { T* obj = HashMapHolder<T>::Find(guid); if (!obj || obj->GetMapId() != mapid) return NULL; CellPair p = BlizzLike::ComputeCellPair(x, y); if (p.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || p.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP) { sLog.outError("ObjectAccessor::GetObjectInWorld: invalid coordinates supplied X:%f Y:%f grid cell [%u:%u]", x, y, p.x_coord, p.y_coord); return NULL; } CellPair q = BlizzLike::ComputeCellPair(obj->GetPositionX(),obj->GetPositionY()); if (q.x_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP || q.y_coord >= TOTAL_NUMBER_OF_CELLS_PER_MAP) { sLog.outError("ObjectAccessor::GetObjecInWorld: object (GUID: %u TypeId: %u) has invalid coordinates X:%f Y:%f grid cell [%u:%u]", obj->GetGUIDLow(), obj->GetTypeId(), obj->GetPositionX(), obj->GetPositionY(), q.x_coord, q.y_coord); return NULL; } int32 dx = int32(p.x_coord) - int32(q.x_coord); int32 dy = int32(p.y_coord) - int32(q.y_coord); if (dx > -2 && dx < 2 && dy > -2 && dy < 2) return obj; else return NULL; } // these functions return objects only if in map of specified object static Object* GetObjectByTypeMask(WorldObject const&, uint64, uint32 typemask); static Corpse* GetCorpse(WorldObject const& u, uint64 guid); static GameObject* GetGameObject(WorldObject const& u, uint64 guid); static DynamicObject* GetDynamicObject(WorldObject const& u, uint64 guid); static Unit* GetUnit(WorldObject const&, uint64 guid); static Creature* GetCreature(WorldObject const& u, uint64 guid); static Pet* GetPet(WorldObject const&, uint64 guid); static Player* GetPlayer(WorldObject const&, uint64 guid); static Creature* GetCreatureOrPet(WorldObject const&, uint64); // these functions return objects if found in whole world // ACCESS LIKE THAT IS NOT THREAD SAFE static Pet* FindPet(uint64); static Player* FindPlayer(uint64); static Unit* FindUnit(uint64); Player* FindPlayerByName(const char* name); // when using this, you must use the hashmapholder's lock HashMapHolder<Player>::MapType& GetPlayers() { return HashMapHolder<Player>::GetContainer(); } template<class T> void AddObject(T* object) { HashMapHolder<T>::Insert(object); } template<class T> void RemoveObject(T* object) { HashMapHolder<T>::Remove(object); } void RemoveObject(Player* pl) { HashMapHolder<Player>::Remove(pl); RemoveUpdateObject((Object*)pl); } void SaveAllPlayers(); void AddUpdateObject(Object* obj) { Guard guard(i_updateGuard); i_objects.insert(obj); } void RemoveUpdateObject(Object* obj) { Guard guard(i_updateGuard); i_objects.erase(obj); } void Update(uint32 diff); Corpse* GetCorpseForPlayerGUID(uint64 guid); void RemoveCorpse(Corpse* corpse); void AddCorpse(Corpse* corpse); void AddCorpsesToGrid(GridPair const& gridpair, GridType& grid, Map* map); Corpse* ConvertCorpseForPlayer(uint64 player_guid, bool insignia = false); void RemoveOldCorpses(); typedef ACE_Thread_Mutex LockType; typedef BlizzLike::GeneralLock<LockType> Guard; private: Player2CorpsesMapType i_player2corpse; static void _buildChangeObjectForPlayer(WorldObject*, UpdateDataMapType&); static void _buildPacket(Player*, Object*, UpdateDataMapType&); void _update(); std::set<Object*> i_objects; LockType i_updateGuard; LockType i_corpseGuard; }; #endif
Java
#include "stdafx.h" #include <gtest/gtest.h> #include "MonsterHeadingCalculator.h" namespace PacMan { namespace Logic { namespace Tests { using namespace Logic; void test_calculate_sets_heading ( Row monster_row, Column monster_column, Row pacman_row, Column pacman_column, Heading expected ) { // Arrange MonsterHeadingCalculator sut{}; sut.monster_row = monster_row; sut.monster_column = monster_column; sut.pacman_row = pacman_row; sut.pacman_column = pacman_column; // Act sut.calculate(); // Assert Heading actual = sut.get_heading(); EXPECT_EQ(expected, actual); } TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_0_0_and_pac_man_1_1) { test_calculate_sets_heading( Row{0}, Column{0}, Row{1}, Column{1}, Heading_Down); } TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_0_1_and_pac_man_1_1) { test_calculate_sets_heading( Row{0}, Column{1}, Row{1}, Column{1}, Heading_Down); } TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_0_2_and_pac_man_1_1) { test_calculate_sets_heading( Row{0}, Column{2}, Row{1}, Column{1}, Heading_Down); } TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_1_0_and_pac_man_1_1) { test_calculate_sets_heading( Row{1}, Column{0}, Row{1}, Column{1}, Heading_Right); } TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_1_1_and_pac_man_1_1) { test_calculate_sets_heading( Row{1}, Column{1}, Row{1}, Column{1}, Heading_Unknown); } TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_1_2_and_pac_man_1_1) { test_calculate_sets_heading( Row{1}, Column{2}, Row{1}, Column{1}, Heading_Left); } TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_2_0_and_pac_man_1_1) { using namespace Logic; test_calculate_sets_heading( Row{2}, Column{0}, Row{1}, Column{1}, Heading_Up); } TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_2_1_and_pac_man_1_1) { test_calculate_sets_heading( Row{2}, Column{1}, Row{1}, Column{1}, Heading_Up); } TEST(MonsterHeadingCalculator, calculate_sets_heading_for_monster_2_2_and_pac_man_1_1) { test_calculate_sets_heading( Row{2}, Column{2}, Row{1}, Column{1}, Heading_Up); } }; }; };
Java
/** Author: Sharmin Akter **/ /** Created at: 4/30/2012 12:07:26 AM **/ #include<stdio.h> int main() { int i,j,k,p,m,n,t; while(scanf("%d",&t)==1) { for(i=1;i<=t;i++) { scanf("%d",&p); if(p==2||p==3||p==5||p==7||p==13||p==17) printf("Yes\n"); else printf("No\n"); getchar(); } } return 0; }
Java
""" Tests for closeness centrality. """ import pytest import networkx as nx from networkx.testing import almost_equal class TestClosenessCentrality: @classmethod def setup_class(cls): cls.K = nx.krackhardt_kite_graph() cls.P3 = nx.path_graph(3) cls.P4 = nx.path_graph(4) cls.K5 = nx.complete_graph(5) cls.C4 = nx.cycle_graph(4) cls.T = nx.balanced_tree(r=2, h=2) cls.Gb = nx.Graph() cls.Gb.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (4, 5), (3, 5)]) F = nx.florentine_families_graph() cls.F = F cls.LM = nx.les_miserables_graph() # Create random undirected, unweighted graph for testing incremental version cls.undirected_G = nx.fast_gnp_random_graph(n=100, p=0.6, seed=123) cls.undirected_G_cc = nx.closeness_centrality(cls.undirected_G) def test_wf_improved(self): G = nx.union(self.P4, nx.path_graph([4, 5, 6])) c = nx.closeness_centrality(G) cwf = nx.closeness_centrality(G, wf_improved=False) res = {0: 0.25, 1: 0.375, 2: 0.375, 3: 0.25, 4: 0.222, 5: 0.333, 6: 0.222} wf_res = {0: 0.5, 1: 0.75, 2: 0.75, 3: 0.5, 4: 0.667, 5: 1.0, 6: 0.667} for n in G: assert almost_equal(c[n], res[n], places=3) assert almost_equal(cwf[n], wf_res[n], places=3) def test_digraph(self): G = nx.path_graph(3, create_using=nx.DiGraph()) c = nx.closeness_centrality(G) cr = nx.closeness_centrality(G.reverse()) d = {0: 0.0, 1: 0.500, 2: 0.667} dr = {0: 0.667, 1: 0.500, 2: 0.0} for n in sorted(self.P3): assert almost_equal(c[n], d[n], places=3) assert almost_equal(cr[n], dr[n], places=3) def test_k5_closeness(self): c = nx.closeness_centrality(self.K5) d = {0: 1.000, 1: 1.000, 2: 1.000, 3: 1.000, 4: 1.000} for n in sorted(self.K5): assert almost_equal(c[n], d[n], places=3) def test_p3_closeness(self): c = nx.closeness_centrality(self.P3) d = {0: 0.667, 1: 1.000, 2: 0.667} for n in sorted(self.P3): assert almost_equal(c[n], d[n], places=3) def test_krackhardt_closeness(self): c = nx.closeness_centrality(self.K) d = { 0: 0.529, 1: 0.529, 2: 0.500, 3: 0.600, 4: 0.500, 5: 0.643, 6: 0.643, 7: 0.600, 8: 0.429, 9: 0.310, } for n in sorted(self.K): assert almost_equal(c[n], d[n], places=3) def test_florentine_families_closeness(self): c = nx.closeness_centrality(self.F) d = { "Acciaiuoli": 0.368, "Albizzi": 0.483, "Barbadori": 0.4375, "Bischeri": 0.400, "Castellani": 0.389, "Ginori": 0.333, "Guadagni": 0.467, "Lamberteschi": 0.326, "Medici": 0.560, "Pazzi": 0.286, "Peruzzi": 0.368, "Ridolfi": 0.500, "Salviati": 0.389, "Strozzi": 0.4375, "Tornabuoni": 0.483, } for n in sorted(self.F): assert almost_equal(c[n], d[n], places=3) def test_les_miserables_closeness(self): c = nx.closeness_centrality(self.LM) d = { "Napoleon": 0.302, "Myriel": 0.429, "MlleBaptistine": 0.413, "MmeMagloire": 0.413, "CountessDeLo": 0.302, "Geborand": 0.302, "Champtercier": 0.302, "Cravatte": 0.302, "Count": 0.302, "OldMan": 0.302, "Valjean": 0.644, "Labarre": 0.394, "Marguerite": 0.413, "MmeDeR": 0.394, "Isabeau": 0.394, "Gervais": 0.394, "Listolier": 0.341, "Tholomyes": 0.392, "Fameuil": 0.341, "Blacheville": 0.341, "Favourite": 0.341, "Dahlia": 0.341, "Zephine": 0.341, "Fantine": 0.461, "MmeThenardier": 0.461, "Thenardier": 0.517, "Cosette": 0.478, "Javert": 0.517, "Fauchelevent": 0.402, "Bamatabois": 0.427, "Perpetue": 0.318, "Simplice": 0.418, "Scaufflaire": 0.394, "Woman1": 0.396, "Judge": 0.404, "Champmathieu": 0.404, "Brevet": 0.404, "Chenildieu": 0.404, "Cochepaille": 0.404, "Pontmercy": 0.373, "Boulatruelle": 0.342, "Eponine": 0.396, "Anzelma": 0.352, "Woman2": 0.402, "MotherInnocent": 0.398, "Gribier": 0.288, "MmeBurgon": 0.344, "Jondrette": 0.257, "Gavroche": 0.514, "Gillenormand": 0.442, "Magnon": 0.335, "MlleGillenormand": 0.442, "MmePontmercy": 0.315, "MlleVaubois": 0.308, "LtGillenormand": 0.365, "Marius": 0.531, "BaronessT": 0.352, "Mabeuf": 0.396, "Enjolras": 0.481, "Combeferre": 0.392, "Prouvaire": 0.357, "Feuilly": 0.392, "Courfeyrac": 0.400, "Bahorel": 0.394, "Bossuet": 0.475, "Joly": 0.394, "Grantaire": 0.358, "MotherPlutarch": 0.285, "Gueulemer": 0.463, "Babet": 0.463, "Claquesous": 0.452, "Montparnasse": 0.458, "Toussaint": 0.402, "Child1": 0.342, "Child2": 0.342, "Brujon": 0.380, "MmeHucheloup": 0.353, } for n in sorted(self.LM): assert almost_equal(c[n], d[n], places=3) def test_weighted_closeness(self): edges = [ ("s", "u", 10), ("s", "x", 5), ("u", "v", 1), ("u", "x", 2), ("v", "y", 1), ("x", "u", 3), ("x", "v", 5), ("x", "y", 2), ("y", "s", 7), ("y", "v", 6), ] XG = nx.Graph() XG.add_weighted_edges_from(edges) c = nx.closeness_centrality(XG, distance="weight") d = {"y": 0.200, "x": 0.286, "s": 0.138, "u": 0.235, "v": 0.200} for n in sorted(XG): assert almost_equal(c[n], d[n], places=3) # # Tests for incremental closeness centrality. # @staticmethod def pick_add_edge(g): u = nx.utils.arbitrary_element(g) possible_nodes = set(g.nodes()) neighbors = list(g.neighbors(u)) + [u] possible_nodes.difference_update(neighbors) v = nx.utils.arbitrary_element(possible_nodes) return (u, v) @staticmethod def pick_remove_edge(g): u = nx.utils.arbitrary_element(g) possible_nodes = list(g.neighbors(u)) v = nx.utils.arbitrary_element(possible_nodes) return (u, v) def test_directed_raises(self): with pytest.raises(nx.NetworkXNotImplemented): dir_G = nx.gn_graph(n=5) prev_cc = None edge = self.pick_add_edge(dir_G) insert = True nx.incremental_closeness_centrality(dir_G, edge, prev_cc, insert) def test_wrong_size_prev_cc_raises(self): with pytest.raises(nx.NetworkXError): G = self.undirected_G.copy() edge = self.pick_add_edge(G) insert = True prev_cc = self.undirected_G_cc.copy() prev_cc.pop(0) nx.incremental_closeness_centrality(G, edge, prev_cc, insert) def test_wrong_nodes_prev_cc_raises(self): with pytest.raises(nx.NetworkXError): G = self.undirected_G.copy() edge = self.pick_add_edge(G) insert = True prev_cc = self.undirected_G_cc.copy() num_nodes = len(prev_cc) prev_cc.pop(0) prev_cc[num_nodes] = 0.5 nx.incremental_closeness_centrality(G, edge, prev_cc, insert) def test_zero_centrality(self): G = nx.path_graph(3) prev_cc = nx.closeness_centrality(G) edge = self.pick_remove_edge(G) test_cc = nx.incremental_closeness_centrality(G, edge, prev_cc, insertion=False) G.remove_edges_from([edge]) real_cc = nx.closeness_centrality(G) shared_items = set(test_cc.items()) & set(real_cc.items()) assert len(shared_items) == len(real_cc) assert 0 in test_cc.values() def test_incremental(self): # Check that incremental and regular give same output G = self.undirected_G.copy() prev_cc = None for i in range(5): if i % 2 == 0: # Remove an edge insert = False edge = self.pick_remove_edge(G) else: # Add an edge insert = True edge = self.pick_add_edge(G) # start = timeit.default_timer() test_cc = nx.incremental_closeness_centrality(G, edge, prev_cc, insert) # inc_elapsed = (timeit.default_timer() - start) # print(f"incremental time: {inc_elapsed}") if insert: G.add_edges_from([edge]) else: G.remove_edges_from([edge]) # start = timeit.default_timer() real_cc = nx.closeness_centrality(G) # reg_elapsed = (timeit.default_timer() - start) # print(f"regular time: {reg_elapsed}") # Example output: # incremental time: 0.208 # regular time: 0.276 # incremental time: 0.00683 # regular time: 0.260 # incremental time: 0.0224 # regular time: 0.278 # incremental time: 0.00804 # regular time: 0.208 # incremental time: 0.00947 # regular time: 0.188 assert set(test_cc.items()) == set(real_cc.items()) prev_cc = test_cc
Java
/** * This file is part of JsonFL. * * JsonFL 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. * * JsonFL 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 JsonFL. If not, see <http://www.gnu.org/licenses/>. */ package au.com.houliston.jsonfl; /** * Is thrown when the creation string for the JsonFL is invalid * * @author Trent Houliston * @version 1.0 */ public class InvalidJsonFLException extends Exception { /** * Creates a new InvalidJsonFLException with the passed message * * @param message The message to set */ public InvalidJsonFLException(String message) { super(message); } /** * Creates a new InvalidJsonFLException along with a message and a cause * * @param message The message to set * @param cause The root cause which made this exception */ public InvalidJsonFLException(String message, Throwable cause) { super(message, cause); } }
Java
package edu.kit.iti.formal.mandatsverteilung.generierer; import edu.kit.iti.formal.mandatsverteilung.datenhaltung.Bundestagswahl; /** * Modelliert eine Einschränkung an das Ergebnis des Generierers, dass der * Bundestag eine bestimmte Größe haben soll. * * @author Jan * */ public class SitzzahlEinschraenkung extends Einschraenkung { public SitzzahlEinschraenkung(int wert, int abweichung) { assert wert > 0; assert abweichung > 0; this.wert = wert; this.abweichung = abweichung; gewichtung = 1.0; } @Override int ueberpruefeErgebnis(Bundestagswahl b) { int tatsaechlicheSitzzahl = b.getSitzzahl(); int genauigkeit = RandomisierterGenerierer.getGenauigkeit(); double minD = (minDistance(genauigkeit * tatsaechlicheSitzzahl, genauigkeit * wert, genauigkeit * abweichung)); return (int) (gewichtung * minD); } }
Java
#include "definitions.h" CustomWeakForm::CustomWeakForm(std::vector<std::string> newton_boundaries, double heatcap, double rho, double tau, double lambda, double alpha, double temp_ext, MeshFunctionSharedPtr<double> sln_prev_time, bool JFNK) : WeakForm<double>(1, JFNK) { this->set_ext(sln_prev_time); // Jacobian forms - volumetric. add_matrix_form(new JacobianFormVol(0, 0, heatcap, rho, lambda, tau)); // Jacobian forms - surface. add_matrix_form_surf(new JacobianFormSurf(0, 0, newton_boundaries, alpha, lambda)); // Residual forms - volumetric. ResidualFormVol* res_form = new ResidualFormVol(0, heatcap, rho, lambda, tau); add_vector_form(res_form); // Residual forms - surface. add_vector_form_surf(new ResidualFormSurf(0, newton_boundaries, alpha, lambda, temp_ext)); } double CustomWeakForm::JacobianFormVol::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v, GeomVol<double> *e, Func<double> **ext) const { double result = 0; for (int i = 0; i < n; i++) result += wt[i] * (heatcap * rho * u->val[i] * v->val[i] / tau + lambda * (u->dx[i] * v->dx[i] + u->dy[i] * v->dy[i])); return result; } Ord CustomWeakForm::JacobianFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomVol<Ord> *e, Func<Ord> **ext) const { // Returning the sum of the degrees of the basis and test function plus two. return Ord(10); } MatrixFormVol<double>* CustomWeakForm::JacobianFormVol::clone() const { return new CustomWeakForm::JacobianFormVol(*this); } double CustomWeakForm::JacobianFormSurf::value(int n, double *wt, Func<double> *u_ext[], Func<double> *u, Func<double> *v, GeomSurf<double> *e, Func<double> **ext) const { double result = 0; for (int i = 0; i < n; i++) result += wt[i] * alpha * lambda * u->val[i] * v->val[i]; return result; } Ord CustomWeakForm::JacobianFormSurf::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *u, Func<Ord> *v, GeomSurf<Ord> *e, Func<Ord> **ext) const { // Returning the sum of the degrees of the basis and test function plus two. return Ord(10); } MatrixFormSurf<double>* CustomWeakForm::JacobianFormSurf::clone() const { return new CustomWeakForm::JacobianFormSurf(*this); } double CustomWeakForm::ResidualFormVol::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomVol<double> *e, Func<double> **ext) const { double result = 0; for (int i = 0; i < n; i++) result += wt[i] * (heatcap * rho * (u_ext[0]->val[i] - ext[0]->val[i]) * v->val[i] / tau + lambda * (u_ext[0]->dx[i] * v->dx[i] + u_ext[0]->dy[i] * v->dy[i])); return result; } Ord CustomWeakForm::ResidualFormVol::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomVol<Ord> *e, Func<Ord> **ext) const { // Returning the sum of the degrees of the test function and solution plus two. return Ord(10); } VectorFormVol<double>* CustomWeakForm::ResidualFormVol::clone() const { return new CustomWeakForm::ResidualFormVol(*this); } double CustomWeakForm::ResidualFormSurf::value(int n, double *wt, Func<double> *u_ext[], Func<double> *v, GeomSurf<double> *e, Func<double> **ext) const { double result = 0; for (int i = 0; i < n; i++) result += wt[i] * alpha * lambda * (u_ext[0]->val[i] - temp_ext) * v->val[i]; return result; } Ord CustomWeakForm::ResidualFormSurf::ord(int n, double *wt, Func<Ord> *u_ext[], Func<Ord> *v, GeomSurf<Ord> *e, Func<Ord> **ext) const { // Returning the sum of the degrees of the test function and solution plus two. return Ord(10); } VectorFormSurf<double>* CustomWeakForm::ResidualFormSurf::clone() const { return new CustomWeakForm::ResidualFormSurf(*this); }
Java
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding unique constraint on 'Vendeur', fields ['code_permanent'] db.create_unique(u'encefal_vendeur', ['code_permanent']) def backwards(self, orm): # Removing unique constraint on 'Vendeur', fields ['code_permanent'] db.delete_unique(u'encefal_vendeur', ['code_permanent']) models = { u'auth.group': { 'Meta': {'object_name': 'Group'}, u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, u'auth.permission': { 'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, u'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, u'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, u'encefal.exemplaire': { 'Meta': {'object_name': 'Exemplaire'}, 'actif': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'date_creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'date_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'etat': ('django.db.models.fields.CharField', [], {'default': "'VENT'", 'max_length': '4'}), 'facture': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'exemplaires'", 'null': 'True', 'db_column': "'facture'", 'to': u"orm['encefal.Facture']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'livre': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'exemplaires'", 'db_column': "'livre'", 'to': u"orm['encefal.Livre']"}), 'prix': ('django.db.models.fields.IntegerField', [], {}), 'vendeur': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'exemplaires'", 'db_column': "'vendeur'", 'to': u"orm['encefal.Vendeur']"}) }, u'encefal.facture': { 'Meta': {'object_name': 'Facture'}, 'actif': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'date_creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'date_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'employe': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'factures'", 'blank': 'True', 'db_column': "'employe'", 'to': u"orm['auth.User']"}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'session': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'factures'", 'blank': 'True', 'db_column': "'session'", 'to': u"orm['encefal.Session']"}) }, u'encefal.livre': { 'Meta': {'object_name': 'Livre'}, 'actif': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'auteur': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'date_creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'date_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'edition': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'isbn': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '13', 'blank': 'True'}), 'titre': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'vendeur': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'livres'", 'symmetrical': 'False', 'through': u"orm['encefal.Exemplaire']", 'db_column': "'vendeur'", 'to': u"orm['encefal.Vendeur']"}) }, u'encefal.session': { 'Meta': {'object_name': 'Session'}, 'actif': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'date_creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'date_debut': ('django.db.models.fields.DateField', [], {}), 'date_fin': ('django.db.models.fields.DateField', [], {}), 'date_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nom': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}) }, u'encefal.vendeur': { 'Meta': {'object_name': 'Vendeur'}, 'actif': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'code_permanent': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '12'}), 'date_creation': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}), 'date_modification': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '255'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'nom': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'prenom': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'telephone': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}) } } complete_apps = ['encefal']
Java
# $Id$ # Copyright 2013 Matthew Wall # See the file LICENSE.txt for your full rights. # # Thanks to Eddie De Pieri for the first Python implementation for WS-28xx. # Eddie did the difficult work of decompiling HeavyWeather then converting # and reverse engineering into a functional Python implementation. Eddie's # work was based on reverse engineering of HeavyWeather 2800 v 1.54 # # Thanks to Lucas Heijst for enumerating the console message types and for # debugging the transceiver/console communication timing issues. """Classes and functions for interfacing with WS-28xx weather stations. LaCrosse makes a number of stations in the 28xx series, including: WS-2810, WS-2810U-IT WS-2811, WS-2811SAL-IT, WS-2811BRN-IT, WS-2811OAK-IT WS-2812, WS-2812U-IT WS-2813 WS-2814, WS-2814U-IT WS-2815, WS-2815U-IT C86234 The station is also sold as the TFA Primus, TFA Opus, and TechnoLine. HeavyWeather is the software provided by LaCrosse. There are two versions of HeavyWeather for the WS-28xx series: 1.5.4 and 1.5.4b Apparently there is a difference between TX59UN-1-IT and TX59U-IT models (this identifier is printed on the thermo-hygro sensor). HeavyWeather Version Firmware Version Thermo-Hygro Model 1.54 333 or 332 TX59UN-1-IT 1.54b 288, 262, 222 TX59U-IT HeavyWeather provides the following weather station settings: time display: 12|24 hour temperature display: C|F air pressure display: inhg|hpa wind speed display: m/s|knots|bft|km/h|mph rain display: mm|inch recording interval: 1m keep weather station in hi-speed communication mode: true/false According to the HeavyWeatherPro User Manual (1.54, rev2), "Hi speed mode wears down batteries on your display much faster, and similarly consumes more power on the PC. We do not believe most users need to enable this setting. It was provided at the request of users who prefer ultra-frequent uploads." The HeavyWeatherPro 'CurrentWeather' view is updated as data arrive from the console. The console sends current weather data approximately every 13 seconds. Historical data are updated less frequently - every 2 hours in the default HeavyWeatherPro configuration. According to the User Manual, "The 2800 series weather station uses the 'original' wind chill calculation rather than the 2001 'North American' formula because the original formula is international." Apparently the station console determines when data will be sent, and, once paired, the transceiver is always listening. The station console sends a broadcast on the hour. If the transceiver responds, the station console may continue to broadcast data, depending on the transceiver response and the timing of the transceiver response. According to the C86234 Operations Manual (Revision 7): - Temperature and humidity data are sent to the console every 13 seconds. - Wind data are sent to the temperature/humidity sensor every 17 seconds. - Rain data are sent to the temperature/humidity sensor every 19 seconds. - Air pressure is measured every 15 seconds. Each tip of the rain bucket is 0.26 mm of rain. The following information was obtained by logging messages from the ws28xx.py driver in weewx and by capturing USB messages between Heavy Weather Pro for ws2800 and the TFA Primus Weather Station via windows program USB sniffer busdog64_v0.2.1. Pairing The transceiver must be paired with a console before it can receive data. Each frame sent by the console includes the device identifier of the transceiver with which it is paired. Synchronizing When the console and transceiver stop communicating, they can be synchronized by one of the following methods: - Push the SET button on the console - Wait till the next full hour when the console sends a clock message In each case a Request Time message is received by the transceiver from the console. The 'Send Time to WS' message should be sent within ms (10 ms typical). The transceiver should handle the 'Time SET' message then send a 'Time/Config written' message about 85 ms after the 'Send Time to WS' message. When complete, the console and transceiver will have been synchronized. Timing Current Weather messages, History messages, getConfig/setConfig messages, and setTime messages each have their own timing. Missed History messages - as a result of bad timing - result in console and transceiver becoming out of synch. Current Weather The console periodically sends Current Weather messages, each with the latest values from the sensors. The CommModeInterval determines how often the console will send Current Weather messages. History The console records data periodically at an interval defined by the HistoryInterval parameter. The factory default setting is 2 hours. Each history record contains a timestamp. Timestamps use the time from the console clock. The console can record up to 1797 history records. Reading 1795 history records took about 110 minutes on a raspberry pi, for an average of 3.6 seconds per history record. Reading 1795 history records took 65 minutes on a synology ds209+ii, for an average of 2.2 seconds per history record. Reading 1750 history records took 19 minutes using HeavyWeatherPro on a Windows 7 64-bit laptop. Message Types The first byte of a message determines the message type. ID Type Length 01 ? 0x0f (15) d0 SetRX 0x15 (21) d1 SetTX 0x15 (21) d5 SetFrame 0x111 (273) d6 GetFrame 0x111 (273) d7 SetState 0x15 (21) d8 SetPreamblePattern 0x15 (21) d9 Execute 0x0f (15) dc ReadConfigFlash< 0x15 (21) dd ReadConfigFlash> 0x15 (21) de GetState 0x0a (10) f0 WriteReg 0x05 (5) In the following sections, some messages are decomposed using the following structure: start position in message buffer hi-lo data starts on first (hi) or second (lo) nibble chars data length in characters (nibbles) rem remark name variable ------------------------------------------------------------------------------- 1. 01 message (15 bytes) 000: 01 15 00 0b 08 58 3f 53 00 00 00 00 ff 15 0b (detected via USB sniffer) 000: 01 15 00 57 01 92 3f 53 00 00 00 00 ff 15 0a (detected via USB sniffer) 00: messageID 02-15: ?? ------------------------------------------------------------------------------- 2. SetRX message (21 bytes) 000: d0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 020: 00 00: messageID 01-20: 00 ------------------------------------------------------------------------------- 3. SetTX message (21 bytes) 000: d1 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 020: 00 00: messageID 01-20: 00 ------------------------------------------------------------------------------- 4. SetFrame message (273 bytes) Action: 00: rtGetHistory - Ask for History message 01: rtSetTime - Ask for Send Time to weather station message 02: rtSetConfig - Ask for Send Config to weather station message 03: rtGetConfig - Ask for Config message 05: rtGetCurrent - Ask for Current Weather message c0: Send Time - Send Time to WS 40: Send Config - Send Config to WS 000: d5 00 09 DevID 00 CfgCS cIntThisAdr xx xx xx rtGetHistory 000: d5 00 09 DevID 01 CfgCS cIntThisAdr xx xx xx rtReqSetTime 000: d5 00 09 f0 f0 02 CfgCS cIntThisAdr xx xx xx rtReqFirstConfig 000: d5 00 09 DevID 02 CfgCS cIntThisAdr xx xx xx rtReqSetConfig 000: d5 00 09 DevID 03 CfgCS cIntThisAdr xx xx xx rtGetConfig 000: d5 00 09 DevID 05 CfgCS cIntThisAdr xx xx xx rtGetCurrent 000: d5 00 0c DevID c0 CfgCS [TimeData . .. .. .. Send Time 000: d5 00 30 DevID 40 CfgCS [ConfigData .. .. .. Send Config All SetFrame messages: 00: messageID 01: 00 02: Message Length (starting with next byte) 03-04: DeviceID [DevID] 05: Action 06-07: Config checksum [CfgCS] Additional bytes rtGetCurrent, rtGetHistory, rtSetTime messages: 08-09hi: ComInt [cINT] 1.5 bytes (high byte first) 09lo-11: ThisHistoryAddress [ThisAdr] 2.5 bytes (high byte first) Additional bytes Send Time message: 08: seconds 09: minutes 10: hours 11hi: DayOfWeek 11lo: day_lo (low byte) 12hi: month_lo (low byte) 12lo: day_hi (high byte) 13hi: (year-2000)_lo (low byte) 13lo: month_hi (high byte) 14lo: (year-2000)_hi (high byte) ------------------------------------------------------------------------------- 5. GetFrame message Response type: 20: WS SetTime / SetConfig - Data written 40: GetConfig 60: Current Weather 80: Actual / Outstanding History a1: Request First-Time Config a2: Request SetConfig a3: Request SetTime 000: 00 00 06 DevID 20 64 CfgCS xx xx xx xx xx xx xx xx xx Time/Config written 000: 00 00 30 DevID 40 64 [ConfigData .. .. .. .. .. .. .. GetConfig 000: 00 00 d7 DevID 60 64 CfgCS [CurData .. .. .. .. .. .. Current Weather 000: 00 00 1e DevID 80 64 CfgCS 0LateAdr 0ThisAdr [HisData Outstanding History 000: 00 00 1e DevID 80 64 CfgCS 0LateAdr 0ThisAdr [HisData Actual History 000: 00 00 06 DevID a1 64 CfgCS xx xx xx xx xx xx xx xx xx Request FirstConfig 000: 00 00 06 DevID a2 64 CfgCS xx xx xx xx xx xx xx xx xx Request SetConfig 000: 00 00 06 DevID a3 64 CfgCS xx xx xx xx xx xx xx xx xx Request SetTime ReadConfig example: 000: 01 2e 40 5f 36 53 02 00 00 00 00 81 00 04 10 00 82 00 04 20 020: 00 71 41 72 42 00 05 00 00 00 27 10 00 02 83 60 96 01 03 07 040: 21 04 01 00 00 00 CfgCS WriteConfig example: 000: 01 2e 40 64 36 53 02 00 00 00 00 00 10 04 00 81 00 20 04 00 020: 82 41 71 42 72 00 00 05 00 00 00 10 27 01 96 60 83 02 01 04 040: 21 07 03 10 00 00 CfgCS 00: messageID 01: 00 02: Message Length (starting with next byte) 03-04: DeviceID [devID] 05hi: responseType 06: Quality (in steps of 5) Additional byte GetFrame messages except Request SetConfig and Request SetTime: 05lo: BatteryStat 8=WS bat low; 4=TMP bat low; 2=RAIN bat low; 1=WIND bat low Additional byte Request SetConfig and Request SetTime: 05lo: RequestID Additional bytes all GetFrame messages except ReadConfig and WriteConfig 07-08: Config checksum [CfgCS] Additional bytes Outstanding History: 09lo-11: LatestHistoryAddress [LateAdr] 2.5 bytes (Latest to sent) 12lo-14: ThisHistoryAddress [ThisAdr] 2.5 bytes (Outstanding) Additional bytes Actual History: 09lo-11: LatestHistoryAddress [ThisAdr] 2.5 bytes (LatestHistoryAddress is the) 12lo-14: ThisHistoryAddress [ThisAdr] 2.5 bytes (same as ThisHistoryAddress) Additional bytes ReadConfig and WriteConfig 43-45: ResetMinMaxFlags (Output only; not included in checksum calculation) 46-47: Config checksum [CfgCS] (CheckSum = sum of bytes (00-42) + 7) ------------------------------------------------------------------------------- 6. SetState message 000: d7 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00: messageID 01-14: 00 ------------------------------------------------------------------------------- 7. SetPreamblePattern message 000: d8 aa 00 00 00 00 00 00 00 00 00 00 00 00 00 00: messageID 01: ?? 02-14: 00 ------------------------------------------------------------------------------- 8. Execute message 000: d9 05 00 00 00 00 00 00 00 00 00 00 00 00 00 00: messageID 01: ?? 02-14: 00 ------------------------------------------------------------------------------- 9. ReadConfigFlash in - receive data 000: dc 0a 01 f5 00 01 78 a0 01 02 0a 0c 0c 01 2e ff ff ff ff ff - freq correction 000: dc 0a 01 f9 01 02 0a 0c 0c 01 2e ff ff ff ff ff ff ff ff ff - transceiver data 00: messageID 01: length 02-03: address Additional bytes frequency correction 05lo-07hi: frequency correction Additional bytes transceiver data 05-10: serial number 09-10: DeviceID [devID] ------------------------------------------------------------------------------- 10. ReadConfigFlash out - ask for data 000: dd 0a 01 f5 cc cc cc cc cc cc cc cc cc cc cc - Ask for freq correction 000: dd 0a 01 f9 cc cc cc cc cc cc cc cc cc cc cc - Ask for transceiver data 00: messageID 01: length 02-03: address 04-14: cc ------------------------------------------------------------------------------- 11. GetState message 000: de 14 00 00 00 00 (between SetPreamblePattern and first de16 message) 000: de 15 00 00 00 00 Idle message 000: de 16 00 00 00 00 Normal message 000: de 0b 00 00 00 00 (detected via USB sniffer) 00: messageID 01: stateID 02-05: 00 ------------------------------------------------------------------------------- 12. Writereg message 000: f0 08 01 00 00 - AX5051RegisterNames.IFMODE 000: f0 10 01 41 00 - AX5051RegisterNames.MODULATION 000: f0 11 01 07 00 - AX5051RegisterNames.ENCODING ... 000: f0 7b 01 88 00 - AX5051RegisterNames.TXRATEMID 000: f0 7c 01 23 00 - AX5051RegisterNames.TXRATELO 000: f0 7d 01 35 00 - AX5051RegisterNames.TXDRIVER 00: messageID 01: register address 02: 01 03: AX5051RegisterName 04: 00 ------------------------------------------------------------------------------- 13. Current Weather message start hi-lo chars rem name 0 hi 4 DevID 2 hi 2 Action 3 hi 2 Quality 4 hi 4 DeviceCS 6 hi 4 6 _AlarmRingingFlags 8 hi 1 _WeatherTendency 8 lo 1 _WeatherState 9 hi 1 not used 9 lo 10 _TempIndoorMinMax._Max._Time 14 lo 10 _TempIndoorMinMax._Min._Time 19 lo 5 _TempIndoorMinMax._Max._Value 22 hi 5 _TempIndoorMinMax._Min._Value 24 lo 5 _TempIndoor (C) 27 lo 10 _TempOutdoorMinMax._Max._Time 32 lo 10 _TempOutdoorMinMax._Min._Time 37 lo 5 _TempOutdoorMinMax._Max._Value 40 hi 5 _TempOutdoorMinMax._Min._Value 42 lo 5 _TempOutdoor (C) 45 hi 1 not used 45 lo 10 1 _WindchillMinMax._Max._Time 50 lo 10 2 _WindchillMinMax._Min._Time 55 lo 5 1 _WindchillMinMax._Max._Value 57 hi 5 1 _WindchillMinMax._Min._Value 60 lo 6 _Windchill (C) 63 hi 1 not used 63 lo 10 _DewpointMinMax._Max._Time 68 lo 10 _DewpointMinMax._Min._Time 73 lo 5 _DewpointMinMax._Max._Value 76 hi 5 _DewpointMinMax._Min._Value 78 lo 5 _Dewpoint (C) 81 hi 10 _HumidityIndoorMinMax._Max._Time 86 hi 10 _HumidityIndoorMinMax._Min._Time 91 hi 2 _HumidityIndoorMinMax._Max._Value 92 hi 2 _HumidityIndoorMinMax._Min._Value 93 hi 2 _HumidityIndoor (%) 94 hi 10 _HumidityOutdoorMinMax._Max._Time 99 hi 10 _HumidityOutdoorMinMax._Min._Time 104 hi 2 _HumidityOutdoorMinMax._Max._Value 105 hi 2 _HumidityOutdoorMinMax._Min._Value 106 hi 2 _HumidityOutdoor (%) 107 hi 10 3 _RainLastMonthMax._Time 112 hi 6 3 _RainLastMonthMax._Max._Value 115 hi 6 _RainLastMonth (mm) 118 hi 10 3 _RainLastWeekMax._Time 123 hi 6 3 _RainLastWeekMax._Max._Value 126 hi 6 _RainLastWeek (mm) 129 hi 10 _Rain24HMax._Time 134 hi 6 _Rain24HMax._Max._Value 137 hi 6 _Rain24H (mm) 140 hi 10 _Rain24HMax._Time 145 hi 6 _Rain24HMax._Max._Value 148 hi 6 _Rain24H (mm) 151 hi 1 not used 152 lo 10 _LastRainReset 158 lo 7 _RainTotal (mm) 160 hi 1 _WindDirection5 160 lo 1 _WindDirection4 161 hi 1 _WindDirection3 161 lo 1 _WindDirection2 162 hi 1 _WindDirection1 162 lo 1 _WindDirection (0-15) 163 hi 18 unknown data 172 hi 6 _WindSpeed (km/h) 175 hi 1 _GustDirection5 175 lo 1 _GustDirection4 176 hi 1 _GustDirection3 176 lo 1 _GustDirection2 177 hi 1 _GustDirection1 177 lo 1 _GustDirection (0-15) 178 hi 2 not used 179 hi 10 _GustMax._Max._Time 184 hi 6 _GustMax._Max._Value 187 hi 6 _Gust (km/h) 190 hi 10 4 _PressureRelative_MinMax._Max/Min._Time 195 hi 5 5 _PressureRelative_inHgMinMax._Max._Value 197 lo 5 5 _PressureRelative_hPaMinMax._Max._Value 200 hi 5 _PressureRelative_inHgMinMax._Max._Value 202 lo 5 _PressureRelative_hPaMinMax._Max._Value 205 hi 5 _PressureRelative_inHgMinMax._Min._Value 207 lo 5 _PressureRelative_hPaMinMax._Min._Value 210 hi 5 _PressureRelative_inHg 212 lo 5 _PressureRelative_hPa 214 lo 430 end Remarks 1 since factory reset 2 since software reset 3 not used? 4 should be: _PressureRelative_MinMax._Max._Time 5 should be: _PressureRelative_MinMax._Min._Time 6 _AlarmRingingFlags (values in hex) 80 00 = Hi Al Gust 40 00 = Al WindDir 20 00 = One or more WindDirs set 10 00 = Hi Al Rain24H 08 00 = Hi Al Outdoor Humidity 04 00 = Lo Al Outdoor Humidity 02 00 = Hi Al Indoor Humidity 01 00 = Lo Al Indoor Humidity 00 80 = Hi Al Outdoor Temp 00 40 = Lo Al Outdoor Temp 00 20 = Hi Al Indoor Temp 00 10 = Lo Al Indoor Temp 00 08 = Hi Al Pressure 00 04 = Lo Al Pressure 00 02 = not used 00 01 = not used ------------------------------------------------------------------------------- 14. History Message start hi-lo chars rem name 0 hi 4 DevID 2 hi 2 Action 3 hi 2 Quality (%) 4 hi 4 DeviceCS 6 hi 6 LatestAddress 9 hi 6 ThisAddress 12 hi 1 not used 12 lo 3 Gust (m/s) 14 hi 1 WindDirection (0-15, also GustDirection) 14 lo 3 WindSpeed (m/s) 16 hi 3 RainCounterRaw (total in period in 0.1 inch) 17 lo 2 HumidityOutdoor (%) 18 lo 2 HumidityIndoor (%) 19 lo 5 PressureRelative (hPa) 22 hi 3 TempOutdoor (C) 23 lo 3 TempIndoor (C) 25 hi 10 Time 29 lo 60 end ------------------------------------------------------------------------------- 15. Set Config Message start hi-lo chars rem name 0 hi 4 DevID 2 hi 2 Action 3 hi 2 Quality 4 hi 1 1 _WindspeedFormat 4 lo 0,25 2 _RainFormat 4 lo 0,25 3 _PressureFormat 4 lo 0,25 4 _TemperatureFormat 4 lo 0,25 5 _ClockMode 5 hi 1 _WeatherThreshold 5 lo 1 _StormThreshold 6 hi 1 _LowBatFlags 6 lo 1 6 _LCDContrast 7 hi 4 7 _WindDirAlarmFlags (reverse group 1) 9 hi 4 8 _OtherAlarmFlags (reverse group 1) 11 hi 10 _TempIndoorMinMax._Min._Value (reverse group 2) _TempIndoorMinMax._Max._Value (reverse group 2) 16 hi 10 _TempOutdoorMinMax._Min._Value (reverse group 3) _TempOutdoorMinMax._Max._Value (reverse group 3) 21 hi 2 _HumidityIndoorMinMax._Min._Value 22 hi 2 _HumidityIndoorMinMax._Max._Value 23 hi 2 _HumidityOutdoorMinMax._Min._Value 24 hi 2 _HumidityOutdoorMinMax._Max._Value 25 hi 1 not used 25 lo 7 _Rain24HMax._Max._Value (reverse bytes) 29 hi 2 _HistoryInterval 30 hi 1 not used 30 lo 5 _GustMax._Max._Value (reverse bytes) 33 hi 10 _PressureRelative_hPaMinMax._Min._Value (rev grp4) _PressureRelative_inHgMinMax._Min._Value(rev grp4) 38 hi 10 _PressureRelative_hPaMinMax._Max._Value (rev grp5) _PressureRelative_inHgMinMax._Max._Value(rev grp5) 43 hi 6 9 _ResetMinMaxFlags 46 hi 4 10 _InBufCS 47 lo 96 end Remarks 1 0=m/s 1=knots 2=bft 3=km/h 4=mph 2 0=mm 1=inch 3 0=inHg 2=hPa 4 0=F 1=C 5 0=24h 1=12h 6 values 0-7 => LCD contrast 1-8 7 WindDir Alarms (not-reversed values in hex) 80 00 = NNW 40 00 = NW 20 00 = WNW 10 00 = W 08 00 = WSW 04 00 = SW 02 00 = SSW 01 00 = S 00 80 = SSE 00 40 = SE 00 20 = ESE 00 10 = E 00 08 = ENE 00 04 = NE 00 02 = NNE 00 01 = N 8 Other Alarms (not-reversed values in hex) 80 00 = Hi Al Gust 40 00 = Al WindDir 20 00 = One or more WindDirs set 10 00 = Hi Al Rain24H 08 00 = Hi Al Outdoor Humidity 04 00 = Lo Al Outdoor Humidity 02 00 = Hi Al Indoor Humidity 01 00 = Lo Al Indoor Humidity 00 80 = Hi Al Outdoor Temp 00 40 = Lo Al Outdoor Temp 00 20 = Hi Al Indoor Temp 00 10 = Lo Al Indoor Temp 00 08 = Hi Al Pressure 00 04 = Lo Al Pressure 00 02 = not used 00 01 = not used 9 ResetMinMaxFlags (not-reversed values in hex) "Output only; not included in checksum calc" 80 00 00 = Reset DewpointMax 40 00 00 = Reset DewpointMin 20 00 00 = not used 10 00 00 = Reset WindchillMin* "*Reset dateTime only; Min._Value is preserved" 08 00 00 = Reset TempOutMax 04 00 00 = Reset TempOutMin 02 00 00 = Reset TempInMax 01 00 00 = Reset TempInMin 00 80 00 = Reset Gust 00 40 00 = not used 00 20 00 = not used 00 10 00 = not used 00 08 00 = Reset HumOutMax 00 04 00 = Reset HumOutMin 00 02 00 = Reset HumInMax 00 01 00 = Reset HumInMin 00 00 80 = not used 00 00 40 = Reset Rain Total 00 00 20 = Reset last month? 00 00 10 = Reset lastweek? 00 00 08 = Reset Rain24H 00 00 04 = Reset Rain1H 00 00 02 = Reset PresRelMax 00 00 01 = Reset PresRelMin 10 Checksum = sum bytes (0-42) + 7 ------------------------------------------------------------------------------- 16. Get Config Message start hi-lo chars rem name 0 hi 4 DevID 2 hi 2 Action 3 hi 2 Quality 4 hi 1 1 _WindspeedFormat 4 lo 0,25 2 _RainFormat 4 lo 0,25 3 _PressureFormat 4 lo 0,25 4 _TemperatureFormat 4 lo 0,25 5 _ClockMode 5 hi 1 _WeatherThreshold 5 lo 1 _StormThreshold 6 hi 1 _LowBatFlags 6 lo 1 6 _LCDContrast 7 hi 4 7 _WindDirAlarmFlags 9 hi 4 8 _OtherAlarmFlags 11 hi 5 _TempIndoorMinMax._Min._Value 13 lo 5 _TempIndoorMinMax._Max._Value 16 hi 5 _TempOutdoorMinMax._Min._Value 18 lo 5 _TempOutdoorMinMax._Max._Value 21 hi 2 _HumidityIndoorMinMax._Max._Value 22 hi 2 _HumidityIndoorMinMax._Min._Value 23 hi 2 _HumidityOutdoorMinMax._Max._Value 24 hi 2 _HumidityOutdoorMinMax._Min._Value 25 hi 1 not used 25 lo 7 _Rain24HMax._Max._Value 29 hi 2 _HistoryInterval 30 hi 5 _GustMax._Max._Value 32 lo 1 not used 33 hi 5 _PressureRelative_hPaMinMax._Min._Value 35 lo 5 _PressureRelative_inHgMinMax._Min._Value 38 hi 5 _PressureRelative_hPaMinMax._Max._Value 40 lo 5 _PressureRelative_inHgMinMax._Max._Value 43 hi 6 9 _ResetMinMaxFlags 46 hi 4 10 _InBufCS 47 lo 96 end Remarks 1 0=m/s 1=knots 2=bft 3=km/h 4=mph 2 0=mm 1=inch 3 0=inHg 2=hPa 4 0=F 1=C 5 0=24h 1=12h 6 values 0-7 => LCD contrast 1-8 7 WindDir Alarms (values in hex) 80 00 = NNW 40 00 = NW 20 00 = WNW 10 00 = W 08 00 = WSW 04 00 = SW 02 00 = SSW 01 00 = S 00 80 = SSE 00 40 = SE 00 20 = ESE 00 10 = E 00 08 = ENE 00 04 = NE 00 02 = NNE 00 01 = N 8 Other Alarms (values in hex) 80 00 = Hi Al Gust 40 00 = Al WindDir 20 00 = One or more WindDirs set 10 00 = Hi Al Rain24H 08 00 = Hi Al Outdoor Humidity 04 00 = Lo Al Outdoor Humidity 02 00 = Hi Al Indoor Humidity 01 00 = Lo Al Indoor Humidity 00 80 = Hi Al Outdoor Temp 00 40 = Lo Al Outdoor Temp 00 20 = Hi Al Indoor Temp 00 10 = Lo Al Indoor Temp 00 08 = Hi Al Pressure 00 04 = Lo Al Pressure 00 02 = not used 00 01 = not used 9 ResetMinMaxFlags (values in hex) "Output only; input = 00 00 00" 10 Checksum = sum bytes (0-42) + 7 ------------------------------------------------------------------------------- Examples of messages readCurrentWeather Cur 000: 01 2e 60 5f 05 1b 00 00 12 01 30 62 21 54 41 30 62 40 75 36 Cur 020: 59 00 60 70 06 35 00 01 30 62 31 61 21 30 62 30 55 95 92 00 Cur 040: 53 10 05 37 00 01 30 62 01 90 81 30 62 40 90 66 38 00 49 00 Cur 060: 05 37 00 01 30 62 21 53 01 30 62 22 31 75 51 11 50 40 05 13 Cur 080: 80 13 06 22 21 40 13 06 23 19 37 67 52 59 13 06 23 06 09 13 Cur 100: 06 23 16 19 91 65 86 00 00 00 00 00 00 00 00 00 00 00 00 00 Cur 120: 00 00 00 00 00 00 00 00 00 13 06 23 09 59 00 06 19 00 00 51 Cur 140: 13 06 22 20 43 00 01 54 00 00 00 01 30 62 21 51 00 00 38 70 Cur 160: a7 cc 7b 50 09 01 01 00 00 00 00 00 00 fc 00 a7 cc 7b 14 13 Cur 180: 06 23 14 06 0e a0 00 01 b0 00 13 06 23 06 34 03 00 91 01 92 Cur 200: 03 00 91 01 92 02 97 41 00 74 03 00 91 01 92 WeatherState: Sunny(Good) WeatherTendency: Rising(Up) AlarmRingingFlags: 0000 TempIndoor 23.500 Min:20.700 2013-06-24 07:53 Max:25.900 2013-06-22 15:44 HumidityIndoor 59.000 Min:52.000 2013-06-23 19:37 Max:67.000 2013-06-22 21:40 TempOutdoor 13.700 Min:13.100 2013-06-23 05:59 Max:19.200 2013-06-23 16:12 HumidityOutdoor 86.000 Min:65.000 2013-06-23 16:19 Max:91.000 2013-06-23 06:09 Windchill 13.700 Min: 9.000 2013-06-24 09:06 Max:23.800 2013-06-20 19:08 Dewpoint 11.380 Min:10.400 2013-06-22 23:17 Max:15.111 2013-06-22 15:30 WindSpeed 2.520 Gust 4.320 Max:37.440 2013-06-23 14:06 WindDirection WSW GustDirection WSW WindDirection1 SSE GustDirection1 SSE WindDirection2 W GustDirection2 W WindDirection3 W GustDirection3 W WindDirection4 SSE GustDirection4 SSE WindDirection5 SW GustDirection5 SW RainLastMonth 0.000 Max: 0.000 1900-01-01 00:00 RainLastWeek 0.000 Max: 0.000 1900-01-01 00:00 Rain24H 0.510 Max: 6.190 2013-06-23 09:59 Rain1H 0.000 Max: 1.540 2013-06-22 20:43 RainTotal 3.870 LastRainReset 2013-06-22 15:10 PresRelhPa 1019.200 Min:1007.400 2013-06-23 06:34 Max:1019.200 2013-06-23 06:34 PresRel_inHg 30.090 Min: 29.740 2013-06-23 06:34 Max: 30.090 2013-06-23 06:34 Bytes with unknown meaning at 157-165: 50 09 01 01 00 00 00 00 00 ------------------------------------------------------------------------------- readHistory His 000: 01 2e 80 5f 05 1b 00 7b 32 00 7b 32 00 0c 70 0a 00 08 65 91 His 020: 01 92 53 76 35 13 06 24 09 10 Time 2013-06-24 09:10:00 TempIndoor= 23.5 HumidityIndoor= 59 TempOutdoor= 13.7 HumidityOutdoor= 86 PressureRelative= 1019.2 RainCounterRaw= 0.0 WindDirection= SSE WindSpeed= 1.0 Gust= 1.2 ------------------------------------------------------------------------------- readConfig In 000: 01 2e 40 5f 36 53 02 00 00 00 00 81 00 04 10 00 82 00 04 20 In 020: 00 71 41 72 42 00 05 00 00 00 27 10 00 02 83 60 96 01 03 07 In 040: 21 04 01 00 00 00 05 1b ------------------------------------------------------------------------------- writeConfig Out 000: 01 2e 40 64 36 53 02 00 00 00 00 00 10 04 00 81 00 20 04 00 Out 020: 82 41 71 42 72 00 00 05 00 00 00 10 27 01 96 60 83 02 01 04 Out 040: 21 07 03 10 00 00 05 1b OutBufCS= 051b ClockMode= 0 TemperatureFormat= 1 PressureFormat= 1 RainFormat= 0 WindspeedFormat= 3 WeatherThreshold= 3 StormThreshold= 5 LCDContrast= 2 LowBatFlags= 0 WindDirAlarmFlags= 0000 OtherAlarmFlags= 0000 HistoryInterval= 0 TempIndoor_Min= 1.0 TempIndoor_Max= 41.0 TempOutdoor_Min= 2.0 TempOutdoor_Max= 42.0 HumidityIndoor_Min= 41 HumidityIndoor_Max= 71 HumidityOutdoor_Min= 42 HumidityOutdoor_Max= 72 Rain24HMax= 50.0 GustMax= 100.0 PressureRel_hPa_Min= 960.1 PressureRel_inHg_Min= 28.36 PressureRel_hPa_Max= 1040.1 PressureRel_inHg_Max= 30.72 ResetMinMaxFlags= 100000 (Output only; Input always 00 00 00) ------------------------------------------------------------------------------- class EHistoryInterval: Constant Value Message received at hi01Min = 0 00:00, 00:01, 00:02, 00:03 ... 23:59 hi05Min = 1 00:00, 00:05, 00:10, 00:15 ... 23:55 hi10Min = 2 00:00, 00:10, 00:20, 00:30 ... 23:50 hi15Min = 3 00:00, 00:15, 00:30, 00:45 ... 23:45 hi20Min = 4 00:00, 00:20, 00:40, 01:00 ... 23:40 hi30Min = 5 00:00, 00:30, 01:00, 01:30 ... 23:30 hi60Min = 6 00:00, 01:00, 02:00, 03:00 ... 23:00 hi02Std = 7 00:00, 02:00, 04:00, 06:00 ... 22:00 hi04Std = 8 00:00, 04:00, 08:00, 12:00 ... 20:00 hi06Std = 9 00:00, 06:00, 12:00, 18:00 hi08Std = 0xA 00:00, 08:00, 16:00 hi12Std = 0xB 00:00, 12:00 hi24Std = 0xC 00:00 ------------------------------------------------------------------------------- WS SetTime - Send time to WS Time 000: 01 2e c0 05 1b 19 14 12 40 62 30 01 time sent: 2013-06-24 12:14:19 ------------------------------------------------------------------------------- ReadConfigFlash data Ask for frequency correction rcfo 000: dd 0a 01 f5 cc cc cc cc cc cc cc cc cc cc cc readConfigFlash frequency correction rcfi 000: dc 0a 01 f5 00 01 78 a0 01 02 0a 0c 0c 01 2e ff ff ff ff ff frequency correction: 96416 (0x178a0) adjusted frequency: 910574957 (3646456d) Ask for transceiver data rcfo 000: dd 0a 01 f9 cc cc cc cc cc cc cc cc cc cc cc readConfigFlash serial number and DevID rcfi 000: dc 0a 01 f9 01 02 0a 0c 0c 01 2e ff ff ff ff ff ff ff ff ff transceiver ID: 302 (0x012e) transceiver serial: 01021012120146 Program Logic The RF communication thread uses the following logic to communicate with the weather station console: Step 1. Perform in a while loop getState commands until state 0xde16 is received. Step 2. Perform a getFrame command to read the message data. Step 3. Handle the contents of the message. The type of message depends on the response type: Response type (hex): 20: WS SetTime / SetConfig - Data written confirmation the setTime/setConfig setFrame message has been received by the console 40: GetConfig save the contents of the configuration for later use (i.e. a setConfig message with one ore more parameters changed) 60: Current Weather handle the weather data of the current weather message 80: Actual / Outstanding History ignore the data of the actual history record when there is no data gap; handle the data of a (one) requested history record (note: in step 4 we can decide to request another history record). a1: Request First-Time Config prepare a setFrame first time message a2: Request SetConfig prepare a setFrame setConfig message a3: Request SetTime prepare a setFrame setTime message Step 4. When you didn't receive the message in step 3 you asked for (see step 5 how to request a certain type of message), decide if you want to ignore or handle the received message. Then go to step 5 to request for a certain type of message unless the received message has response type a1, a2 or a3, then prepare first the setFrame message the wireless console asked for. Step 5. Decide what kind of message you want to receive next time. The request is done via a setFrame message (see step 6). It is not guaranteed that you will receive that kind of message the next time but setting the proper timing parameters of firstSleep and nextSleep increase the chance you will get the requested type of message. Step 6. The action parameter in the setFrame message sets the type of the next to receive message. Action (hex): 00: rtGetHistory - Ask for History message setSleep(0.300,0.010) 01: rtSetTime - Ask for Send Time to weather station message setSleep(0.085,0.005) 02: rtSetConfig - Ask for Send Config to weather station message setSleep(0.300,0.010) 03: rtGetConfig - Ask for Config message setSleep(0.400,0.400) 05: rtGetCurrent - Ask for Current Weather message setSleep(0.300,0.010) c0: Send Time - Send Time to WS setSleep(0.085,0.005) 40: Send Config - Send Config to WS setSleep(0.085,0.005) Note: after the Request First-Time Config message (response type = 0xa1) perform a rtGetConfig with setSleep(0.085,0.005) Step 7. Perform a setTX command Step 8. Go to step 1 to wait for state 0xde16 again. """ # TODO: how often is currdat.lst modified with/without hi-speed mode? # TODO: thread locking around observation data # TODO: eliminate polling, make MainThread get data as soon as RFThread updates # TODO: get rid of Length/Buffer construct, replace with a Buffer class or obj # FIXME: the history retrieval assumes a constant archive interval across all # history records. this means anything that modifies the archive # interval should clear the history. from datetime import datetime import StringIO import sys import syslog import threading import time import traceback import usb import weewx.drivers import weewx.wxformulas import weeutil.weeutil DRIVER_NAME = 'WS28xx' DRIVER_VERSION = '0.33' def loader(config_dict, engine): return WS28xxDriver(**config_dict[DRIVER_NAME]) def configurator_loader(config_dict): return WS28xxConfigurator() def confeditor_loader(): return WS28xxConfEditor() # flags for enabling/disabling debug verbosity DEBUG_COMM = 0 DEBUG_CONFIG_DATA = 0 DEBUG_WEATHER_DATA = 0 DEBUG_HISTORY_DATA = 0 DEBUG_DUMP_FORMAT = 'auto' def logmsg(dst, msg): syslog.syslog(dst, 'ws28xx: %s: %s' % (threading.currentThread().getName(), msg)) def logdbg(msg): logmsg(syslog.LOG_DEBUG, msg) def loginf(msg): logmsg(syslog.LOG_INFO, msg) def logcrt(msg): logmsg(syslog.LOG_CRIT, msg) def logerr(msg): logmsg(syslog.LOG_ERR, msg) def log_traceback(dst=syslog.LOG_INFO, prefix='**** '): sfd = StringIO.StringIO() traceback.print_exc(file=sfd) sfd.seek(0) for line in sfd: logmsg(dst, prefix + line) del sfd def log_frame(n, buf): logdbg('frame length is %d' % n) strbuf = '' for i in xrange(0,n): strbuf += str('%02x ' % buf[i]) if (i + 1) % 16 == 0: logdbg(strbuf) strbuf = '' if strbuf: logdbg(strbuf) def get_datum_diff(v, np, ofl): if abs(np - v) < 0.001 or abs(ofl - v) < 0.001: return None return v def get_datum_match(v, np, ofl): if np == v or ofl == v: return None return v def calc_checksum(buf, start, end=None): if end is None: end = len(buf[0]) - start cs = 0 for i in xrange(0, end): cs += buf[0][i+start] return cs def get_next_index(idx): return get_index(idx + 1) def get_index(idx): if idx < 0: return idx + WS28xxDriver.max_records elif idx >= WS28xxDriver.max_records: return idx - WS28xxDriver.max_records return idx def tstr_to_ts(tstr): try: return int(time.mktime(time.strptime(tstr, "%Y-%m-%d %H:%M:%S"))) except (OverflowError, ValueError, TypeError): pass return None def bytes_to_addr(a, b, c): return ((((a & 0xF) << 8) | b) << 8) | c def addr_to_index(addr): return (addr - 416) / 18 def index_to_addr(idx): return 18 * idx + 416 def print_dict(data): for x in sorted(data.keys()): if x == 'dateTime': print '%s: %s' % (x, weeutil.weeutil.timestamp_to_string(data[x])) else: print '%s: %s' % (x, data[x]) class WS28xxConfEditor(weewx.drivers.AbstractConfEditor): @property def default_stanza(self): return """ [WS28xx] # This section is for the La Crosse WS-2800 series of weather stations. # Radio frequency to use between USB transceiver and console: US or EU # US uses 915 MHz, EU uses 868.3 MHz. Default is US. transceiver_frequency = US # The station model, e.g., 'LaCrosse C86234' or 'TFA Primus' model = LaCrosse WS28xx # The driver to use: driver = weewx.drivers.ws28xx """ def prompt_for_settings(self): print "Specify the frequency used between the station and the" print "transceiver, either 'US' (915 MHz) or 'EU' (868.3 MHz)." freq = self._prompt('frequency', 'US', ['US', 'EU']) return {'transceiver_frequency': freq} class WS28xxConfigurator(weewx.drivers.AbstractConfigurator): def add_options(self, parser): super(WS28xxConfigurator, self).add_options(parser) parser.add_option("--check-transceiver", dest="check", action="store_true", help="check USB transceiver") parser.add_option("--pair", dest="pair", action="store_true", help="pair the USB transceiver with station console") parser.add_option("--info", dest="info", action="store_true", help="display weather station configuration") parser.add_option("--set-interval", dest="interval", type=int, metavar="N", help="set logging interval to N minutes") parser.add_option("--current", dest="current", action="store_true", help="get the current weather conditions") parser.add_option("--history", dest="nrecords", type=int, metavar="N", help="display N history records") parser.add_option("--history-since", dest="recmin", type=int, metavar="N", help="display history records since N minutes ago") parser.add_option("--maxtries", dest="maxtries", type=int, help="maximum number of retries, 0 indicates no max") def do_options(self, options, parser, config_dict, prompt): maxtries = 3 if options.maxtries is None else int(options.maxtries) self.station = WS28xxDriver(**config_dict[DRIVER_NAME]) if options.check: self.check_transceiver(maxtries) elif options.pair: self.pair(maxtries) elif options.interval is not None: self.set_interval(maxtries, options.interval, prompt) elif options.current: self.show_current(maxtries) elif options.nrecords is not None: self.show_history(maxtries, count=options.nrecords) elif options.recmin is not None: ts = int(time.time()) - options.recmin * 60 self.show_history(maxtries, ts=ts) else: self.show_info(maxtries) self.station.closePort() def check_transceiver(self, maxtries): """See if the transceiver is installed and operational.""" print 'Checking for transceiver...' ntries = 0 while ntries < maxtries: ntries += 1 if self.station.transceiver_is_present(): print 'Transceiver is present' sn = self.station.get_transceiver_serial() print 'serial: %s' % sn tid = self.station.get_transceiver_id() print 'id: %d (0x%04x)' % (tid, tid) break print 'Not found (attempt %d of %d) ...' % (ntries, maxtries) time.sleep(5) else: print 'Transceiver not responding.' def pair(self, maxtries): """Pair the transceiver with the station console.""" print 'Pairing transceiver with console...' maxwait = 90 # how long to wait between button presses, in seconds ntries = 0 while ntries < maxtries or maxtries == 0: if self.station.transceiver_is_paired(): print 'Transceiver is paired to console' break ntries += 1 msg = 'Press and hold the [v] key until "PC" appears' if maxtries > 0: msg += ' (attempt %d of %d)' % (ntries, maxtries) else: msg += ' (attempt %d)' % ntries print msg now = start_ts = int(time.time()) while (now - start_ts < maxwait and not self.station.transceiver_is_paired()): time.sleep(5) now = int(time.time()) else: print 'Transceiver not paired to console.' def get_interval(self, maxtries): cfg = self.get_config(maxtries) if cfg is None: return None return getHistoryInterval(cfg['history_interval']) def get_config(self, maxtries): start_ts = None ntries = 0 while ntries < maxtries or maxtries == 0: cfg = self.station.get_config() if cfg is not None: return cfg ntries += 1 if start_ts is None: start_ts = int(time.time()) else: dur = int(time.time()) - start_ts print 'No data after %d seconds (press SET to sync)' % dur time.sleep(30) return None def set_interval(self, maxtries, interval, prompt): """Set the station archive interval""" print "This feature is not yet implemented" def show_info(self, maxtries): """Query the station then display the settings.""" print 'Querying the station for the configuration...' cfg = self.get_config(maxtries) if cfg is not None: print_dict(cfg) def show_current(self, maxtries): """Get current weather observation.""" print 'Querying the station for current weather data...' start_ts = None ntries = 0 while ntries < maxtries or maxtries == 0: packet = self.station.get_observation() if packet is not None: print_dict(packet) break ntries += 1 if start_ts is None: start_ts = int(time.time()) else: dur = int(time.time()) - start_ts print 'No data after %d seconds (press SET to sync)' % dur time.sleep(30) def show_history(self, maxtries, ts=0, count=0): """Display the indicated number of records or the records since the specified timestamp (local time, in seconds)""" print "Querying the station for historical records..." ntries = 0 last_n = nrem = None last_ts = int(time.time()) self.station.start_caching_history(since_ts=ts, num_rec=count) while nrem is None or nrem > 0: if ntries >= maxtries: print 'Giving up after %d tries' % ntries break time.sleep(30) ntries += 1 now = int(time.time()) n = self.station.get_num_history_scanned() if n == last_n: dur = now - last_ts print 'No data after %d seconds (press SET to sync)' % dur else: ntries = 0 last_ts = now last_n = n nrem = self.station.get_uncached_history_count() ni = self.station.get_next_history_index() li = self.station.get_latest_history_index() msg = " scanned %s records: current=%s latest=%s remaining=%s\r" % (n, ni, li, nrem) sys.stdout.write(msg) sys.stdout.flush() self.station.stop_caching_history() records = self.station.get_history_cache_records() self.station.clear_history_cache() print print 'Found %d records' % len(records) for r in records: print r class WS28xxDriver(weewx.drivers.AbstractDevice): """Driver for LaCrosse WS28xx stations.""" max_records = 1797 def __init__(self, **stn_dict) : """Initialize the station object. model: Which station model is this? [Optional. Default is 'LaCrosse WS28xx'] transceiver_frequency: Frequency for transceiver-to-console. Specify either US or EU. [Required. Default is US] polling_interval: How often to sample the USB interface for data. [Optional. Default is 30 seconds] comm_interval: Communications mode interval [Optional. Default is 3] device_id: The USB device ID for the transceiver. If there are multiple devices with the same vendor and product IDs on the bus, each will have a unique device identifier. Use this identifier to indicate which device should be used. [Optional. Default is None] serial: The transceiver serial number. If there are multiple devices with the same vendor and product IDs on the bus, each will have a unique serial number. Use the serial number to indicate which transceiver should be used. [Optional. Default is None] """ self.model = stn_dict.get('model', 'LaCrosse WS28xx') self.polling_interval = int(stn_dict.get('polling_interval', 30)) self.comm_interval = int(stn_dict.get('comm_interval', 3)) self.frequency = stn_dict.get('transceiver_frequency', 'US') self.device_id = stn_dict.get('device_id', None) self.serial = stn_dict.get('serial', None) self.vendor_id = 0x6666 self.product_id = 0x5555 now = int(time.time()) self._service = None self._last_rain = None self._last_obs_ts = None self._last_nodata_log_ts = now self._nodata_interval = 300 # how often to check for no data self._last_contact_log_ts = now self._nocontact_interval = 300 # how often to check for no contact self._log_interval = 600 # how often to log global DEBUG_COMM DEBUG_COMM = int(stn_dict.get('debug_comm', 0)) global DEBUG_CONFIG_DATA DEBUG_CONFIG_DATA = int(stn_dict.get('debug_config_data', 0)) global DEBUG_WEATHER_DATA DEBUG_WEATHER_DATA = int(stn_dict.get('debug_weather_data', 0)) global DEBUG_HISTORY_DATA DEBUG_HISTORY_DATA = int(stn_dict.get('debug_history_data', 0)) global DEBUG_DUMP_FORMAT DEBUG_DUMP_FORMAT = stn_dict.get('debug_dump_format', 'auto') loginf('driver version is %s' % DRIVER_VERSION) loginf('frequency is %s' % self.frequency) self.startUp() @property def hardware_name(self): return self.model # this is invoked by StdEngine as it shuts down def closePort(self): self.shutDown() def genLoopPackets(self): """Generator function that continuously returns decoded packets.""" while True: now = int(time.time()+0.5) packet = self.get_observation() if packet is not None: ts = packet['dateTime'] if self._last_obs_ts is None or self._last_obs_ts != ts: self._last_obs_ts = ts self._last_nodata_log_ts = now self._last_contact_log_ts = now else: packet = None # if no new weather data, return an empty packet if packet is None: packet = {'usUnits': weewx.METRIC, 'dateTime': now} # if no new weather data for awhile, log it if self._last_obs_ts is None or \ now - self._last_obs_ts > self._nodata_interval: if now - self._last_nodata_log_ts > self._log_interval: msg = 'no new weather data' if self._last_obs_ts is not None: msg += ' after %d seconds' % ( now - self._last_obs_ts) loginf(msg) self._last_nodata_log_ts = now # if no contact with console for awhile, log it ts = self.get_last_contact() if ts is None or now - ts > self._nocontact_interval: if now - self._last_contact_log_ts > self._log_interval: msg = 'no contact with console' if ts is not None: msg += ' after %d seconds' % (now - ts) msg += ': press [SET] to sync' loginf(msg) self._last_contact_log_ts = now yield packet time.sleep(self.polling_interval) def genStartupRecords(self, ts): loginf('Scanning historical records') maxtries = 65 ntries = 0 last_n = n = nrem = None last_ts = now = int(time.time()) self.start_caching_history(since_ts=ts) while nrem is None or nrem > 0: if ntries >= maxtries: logerr('No historical data after %d tries' % ntries) return time.sleep(60) ntries += 1 now = int(time.time()) n = self.get_num_history_scanned() if n == last_n: dur = now - last_ts loginf('No data after %d seconds (press SET to sync)' % dur) else: ntries = 0 last_ts = now last_n = n nrem = self.get_uncached_history_count() ni = self.get_next_history_index() li = self.get_latest_history_index() loginf("Scanned %s records: current=%s latest=%s remaining=%s" % (n, ni, li, nrem)) self.stop_caching_history() records = self.get_history_cache_records() self.clear_history_cache() loginf('Found %d historical records' % len(records)) last_ts = None for r in records: if last_ts is not None and r['dateTime'] is not None: r['usUnits'] = weewx.METRIC r['interval'] = (r['dateTime'] - last_ts) / 60 yield r last_ts = r['dateTime'] # FIXME: do not implement hardware record generation until we figure # out how to query the historical records faster. # def genArchiveRecords(self, since_ts): # pass # FIXME: implement retries for this so that rf thread has time to get # configuration data from the station # @property # def archive_interval(self): # cfg = self.get_config() # return getHistoryInterval(cfg['history_interval']) * 60 # FIXME: implement set/get time # def setTime(self): # pass # def getTime(self): # pass def startUp(self): if self._service is not None: return self._service = CCommunicationService() self._service.setup(self.frequency, self.vendor_id, self.product_id, self.device_id, self.serial, comm_interval=self.comm_interval) self._service.startRFThread() def shutDown(self): self._service.stopRFThread() self._service.teardown() self._service = None def transceiver_is_present(self): return self._service.DataStore.getTransceiverPresent() def transceiver_is_paired(self): return self._service.DataStore.getDeviceRegistered() def get_transceiver_serial(self): return self._service.DataStore.getTransceiverSerNo() def get_transceiver_id(self): return self._service.DataStore.getDeviceID() def get_last_contact(self): return self._service.getLastStat().last_seen_ts def get_observation(self): data = self._service.getWeatherData() ts = data._timestamp if ts is None: return None # add elements required for weewx LOOP packets packet = {} packet['usUnits'] = weewx.METRIC packet['dateTime'] = ts # data from the station sensors packet['inTemp'] = get_datum_diff(data._TempIndoor, CWeatherTraits.TemperatureNP(), CWeatherTraits.TemperatureOFL()) packet['inHumidity'] = get_datum_diff(data._HumidityIndoor, CWeatherTraits.HumidityNP(), CWeatherTraits.HumidityOFL()) packet['outTemp'] = get_datum_diff(data._TempOutdoor, CWeatherTraits.TemperatureNP(), CWeatherTraits.TemperatureOFL()) packet['outHumidity'] = get_datum_diff(data._HumidityOutdoor, CWeatherTraits.HumidityNP(), CWeatherTraits.HumidityOFL()) packet['pressure'] = get_datum_diff(data._PressureRelative_hPa, CWeatherTraits.PressureNP(), CWeatherTraits.PressureOFL()) packet['windSpeed'] = get_datum_diff(data._WindSpeed, CWeatherTraits.WindNP(), CWeatherTraits.WindOFL()) packet['windGust'] = get_datum_diff(data._Gust, CWeatherTraits.WindNP(), CWeatherTraits.WindOFL()) packet['windDir'] = getWindDir(data._WindDirection, packet['windSpeed']) packet['windGustDir'] = getWindDir(data._GustDirection, packet['windGust']) # calculated elements not directly reported by station packet['rainRate'] = get_datum_match(data._Rain1H, CWeatherTraits.RainNP(), CWeatherTraits.RainOFL()) if packet['rainRate'] is not None: packet['rainRate'] /= 10 # weewx wants cm/hr rain_total = get_datum_match(data._RainTotal, CWeatherTraits.RainNP(), CWeatherTraits.RainOFL()) delta = weewx.wxformulas.calculate_rain(rain_total, self._last_rain) self._last_rain = rain_total packet['rain'] = delta if packet['rain'] is not None: packet['rain'] /= 10 # weewx wants cm # track the signal strength and battery levels laststat = self._service.getLastStat() packet['rxCheckPercent'] = laststat.LastLinkQuality packet['windBatteryStatus'] = getBatteryStatus( laststat.LastBatteryStatus, 'wind') packet['rainBatteryStatus'] = getBatteryStatus( laststat.LastBatteryStatus, 'rain') packet['outTempBatteryStatus'] = getBatteryStatus( laststat.LastBatteryStatus, 'th') packet['inTempBatteryStatus'] = getBatteryStatus( laststat.LastBatteryStatus, 'console') return packet def get_config(self): logdbg('get station configuration') cfg = self._service.getConfigData().asDict() cs = cfg.get('checksum_out') if cs is None or cs == 0: return None return cfg def start_caching_history(self, since_ts=0, num_rec=0): self._service.startCachingHistory(since_ts, num_rec) def stop_caching_history(self): self._service.stopCachingHistory() def get_uncached_history_count(self): return self._service.getUncachedHistoryCount() def get_next_history_index(self): return self._service.getNextHistoryIndex() def get_latest_history_index(self): return self._service.getLatestHistoryIndex() def get_num_history_scanned(self): return self._service.getNumHistoryScanned() def get_history_cache_records(self): return self._service.getHistoryCacheRecords() def clear_history_cache(self): self._service.clearHistoryCache() def set_interval(self, interval): # FIXME: set the archive interval pass # The following classes and methods are adapted from the implementation by # eddie de pieri, which is in turn based on the HeavyWeather implementation. class BadResponse(Exception): """raised when unexpected data found in frame buffer""" pass class DataWritten(Exception): """raised when message 'data written' in frame buffer""" pass class BitHandling: # return a nonzero result, 2**offset, if the bit at 'offset' is one. @staticmethod def testBit(int_type, offset): mask = 1 << offset return int_type & mask # return an integer with the bit at 'offset' set to 1. @staticmethod def setBit(int_type, offset): mask = 1 << offset return int_type | mask # return an integer with the bit at 'offset' set to 1. @staticmethod def setBitVal(int_type, offset, val): mask = val << offset return int_type | mask # return an integer with the bit at 'offset' cleared. @staticmethod def clearBit(int_type, offset): mask = ~(1 << offset) return int_type & mask # return an integer with the bit at 'offset' inverted, 0->1 and 1->0. @staticmethod def toggleBit(int_type, offset): mask = 1 << offset return int_type ^ mask class EHistoryInterval: hi01Min = 0 hi05Min = 1 hi10Min = 2 hi15Min = 3 hi20Min = 4 hi30Min = 5 hi60Min = 6 hi02Std = 7 hi04Std = 8 hi06Std = 9 hi08Std = 0xA hi12Std = 0xB hi24Std = 0xC class EWindspeedFormat: wfMs = 0 wfKnots = 1 wfBFT = 2 wfKmh = 3 wfMph = 4 class ERainFormat: rfMm = 0 rfInch = 1 class EPressureFormat: pfinHg = 0 pfHPa = 1 class ETemperatureFormat: tfFahrenheit = 0 tfCelsius = 1 class EClockMode: ct24H = 0 ctAmPm = 1 class EWeatherTendency: TREND_NEUTRAL = 0 TREND_UP = 1 TREND_DOWN = 2 TREND_ERR = 3 class EWeatherState: WEATHER_BAD = 0 WEATHER_NEUTRAL = 1 WEATHER_GOOD = 2 WEATHER_ERR = 3 class EWindDirection: wdN = 0 wdNNE = 1 wdNE = 2 wdENE = 3 wdE = 4 wdESE = 5 wdSE = 6 wdSSE = 7 wdS = 8 wdSSW = 9 wdSW = 0x0A wdWSW = 0x0B wdW = 0x0C wdWNW = 0x0D wdNW = 0x0E wdNNW = 0x0F wdERR = 0x10 wdInvalid = 0x11 wdNone = 0x12 def getWindDir(wdir, wspeed): if wspeed is None or wspeed == 0: return None if wdir < 0 or wdir >= 16: return None return wdir * 360 / 16 class EResetMinMaxFlags: rmTempIndoorHi = 0 rmTempIndoorLo = 1 rmTempOutdoorHi = 2 rmTempOutdoorLo = 3 rmWindchillHi = 4 rmWindchillLo = 5 rmDewpointHi = 6 rmDewpointLo = 7 rmHumidityIndoorLo = 8 rmHumidityIndoorHi = 9 rmHumidityOutdoorLo = 0x0A rmHumidityOutdoorHi = 0x0B rmWindspeedHi = 0x0C rmWindspeedLo = 0x0D rmGustHi = 0x0E rmGustLo = 0x0F rmPressureLo = 0x10 rmPressureHi = 0x11 rmRain1hHi = 0x12 rmRain24hHi = 0x13 rmRainLastWeekHi = 0x14 rmRainLastMonthHi = 0x15 rmRainTotal = 0x16 rmInvalid = 0x17 class ERequestType: rtGetCurrent = 0 rtGetHistory = 1 rtGetConfig = 2 rtSetConfig = 3 rtSetTime = 4 rtFirstConfig = 5 rtINVALID = 6 class EAction: aGetHistory = 0 aReqSetTime = 1 aReqSetConfig = 2 aGetConfig = 3 aGetCurrent = 5 aSendTime = 0xc0 aSendConfig = 0x40 class ERequestState: rsQueued = 0 rsRunning = 1 rsFinished = 2 rsPreamble = 3 rsWaitDevice = 4 rsWaitConfig = 5 rsError = 6 rsChanged = 7 rsINVALID = 8 class EResponseType: rtDataWritten = 0x20 rtGetConfig = 0x40 rtGetCurrentWeather = 0x60 rtGetHistory = 0x80 rtRequest = 0xa0 rtReqFirstConfig = 0xa1 rtReqSetConfig = 0xa2 rtReqSetTime = 0xa3 # frequency standards and their associated transmission frequencies class EFrequency: fsUS = 'US' tfUS = 905000000 fsEU = 'EU' tfEU = 868300000 def getFrequency(standard): if standard == EFrequency.fsUS: return EFrequency.tfUS elif standard == EFrequency.fsEU: return EFrequency.tfEU logerr("unknown frequency standard '%s', using US" % standard) return EFrequency.tfUS def getFrequencyStandard(frequency): if frequency == EFrequency.tfUS: return EFrequency.fsUS elif frequency == EFrequency.tfEU: return EFrequency.fsEU logerr("unknown frequency '%s', using US" % frequency) return EFrequency.fsUS # HWPro presents battery flags as WS/TH/RAIN/WIND # 0 - wind # 1 - rain # 2 - thermo-hygro # 3 - console batterybits = {'wind':0, 'rain':1, 'th':2, 'console':3} def getBatteryStatus(status, flag): """Return 1 if bit is set, 0 otherwise""" bit = batterybits.get(flag) if bit is None: return None if BitHandling.testBit(status, bit): return 1 return 0 history_intervals = { EHistoryInterval.hi01Min: 1, EHistoryInterval.hi05Min: 5, EHistoryInterval.hi10Min: 10, EHistoryInterval.hi20Min: 20, EHistoryInterval.hi30Min: 30, EHistoryInterval.hi60Min: 60, EHistoryInterval.hi02Std: 120, EHistoryInterval.hi04Std: 240, EHistoryInterval.hi06Std: 360, EHistoryInterval.hi08Std: 480, EHistoryInterval.hi12Std: 720, EHistoryInterval.hi24Std: 1440, } def getHistoryInterval(i): return history_intervals.get(i) # NP - not present # OFL - outside factory limits class CWeatherTraits(object): windDirMap = { 0: "N", 1: "NNE", 2: "NE", 3: "ENE", 4: "E", 5: "ESE", 6: "SE", 7: "SSE", 8: "S", 9: "SSW", 10: "SW", 11: "WSW", 12: "W", 13: "WNW", 14: "NW", 15: "NWN", 16: "err", 17: "inv", 18: "None" } forecastMap = { 0: "Rainy(Bad)", 1: "Cloudy(Neutral)", 2: "Sunny(Good)", 3: "Error" } trendMap = { 0: "Stable(Neutral)", 1: "Rising(Up)", 2: "Falling(Down)", 3: "Error" } @staticmethod def TemperatureNP(): return 81.099998 @staticmethod def TemperatureOFL(): return 136.0 @staticmethod def PressureNP(): return 10101010.0 @staticmethod def PressureOFL(): return 16666.5 @staticmethod def HumidityNP(): return 110.0 @staticmethod def HumidityOFL(): return 121.0 @staticmethod def RainNP(): return -0.2 @staticmethod def RainOFL(): return 16666.664 @staticmethod def WindNP(): return 183.6 # km/h = 51.0 m/s @staticmethod def WindOFL(): return 183.96 # km/h = 51.099998 m/s @staticmethod def TemperatureOffset(): return 40.0 class CMeasurement: _Value = 0.0 _ResetFlag = 23 _IsError = 1 _IsOverflow = 1 _Time = None def Reset(self): self._Value = 0.0 self._ResetFlag = 23 self._IsError = 1 self._IsOverflow = 1 class CMinMaxMeasurement(object): def __init__(self): self._Min = CMeasurement() self._Max = CMeasurement() # firmware XXX has bogus date values for these fields _bad_labels = ['RainLastMonthMax','RainLastWeekMax','PressureRelativeMin'] class USBHardware(object): @staticmethod def isOFL2(buf, start, StartOnHiNibble): if StartOnHiNibble: result = (buf[0][start+0] >> 4) == 15 \ or (buf[0][start+0] & 0xF) == 15 else: result = (buf[0][start+0] & 0xF) == 15 \ or (buf[0][start+1] >> 4) == 15 return result @staticmethod def isOFL3(buf, start, StartOnHiNibble): if StartOnHiNibble: result = (buf[0][start+0] >> 4) == 15 \ or (buf[0][start+0] & 0xF) == 15 \ or (buf[0][start+1] >> 4) == 15 else: result = (buf[0][start+0] & 0xF) == 15 \ or (buf[0][start+1] >> 4) == 15 \ or (buf[0][start+1] & 0xF) == 15 return result @staticmethod def isOFL5(buf, start, StartOnHiNibble): if StartOnHiNibble: result = (buf[0][start+0] >> 4) == 15 \ or (buf[0][start+0] & 0xF) == 15 \ or (buf[0][start+1] >> 4) == 15 \ or (buf[0][start+1] & 0xF) == 15 \ or (buf[0][start+2] >> 4) == 15 else: result = (buf[0][start+0] & 0xF) == 15 \ or (buf[0][start+1] >> 4) == 15 \ or (buf[0][start+1] & 0xF) == 15 \ or (buf[0][start+2] >> 4) == 15 \ or (buf[0][start+2] & 0xF) == 15 return result @staticmethod def isErr2(buf, start, StartOnHiNibble): if StartOnHiNibble: result = (buf[0][start+0] >> 4) >= 10 \ and (buf[0][start+0] >> 4) != 15 \ or (buf[0][start+0] & 0xF) >= 10 \ and (buf[0][start+0] & 0xF) != 15 else: result = (buf[0][start+0] & 0xF) >= 10 \ and (buf[0][start+0] & 0xF) != 15 \ or (buf[0][start+1] >> 4) >= 10 \ and (buf[0][start+1] >> 4) != 15 return result @staticmethod def isErr3(buf, start, StartOnHiNibble): if StartOnHiNibble: result = (buf[0][start+0] >> 4) >= 10 \ and (buf[0][start+0] >> 4) != 15 \ or (buf[0][start+0] & 0xF) >= 10 \ and (buf[0][start+0] & 0xF) != 15 \ or (buf[0][start+1] >> 4) >= 10 \ and (buf[0][start+1] >> 4) != 15 else: result = (buf[0][start+0] & 0xF) >= 10 \ and (buf[0][start+0] & 0xF) != 15 \ or (buf[0][start+1] >> 4) >= 10 \ and (buf[0][start+1] >> 4) != 15 \ or (buf[0][start+1] & 0xF) >= 10 \ and (buf[0][start+1] & 0xF) != 15 return result @staticmethod def isErr5(buf, start, StartOnHiNibble): if StartOnHiNibble: result = (buf[0][start+0] >> 4) >= 10 \ and (buf[0][start+0] >> 4) != 15 \ or (buf[0][start+0] & 0xF) >= 10 \ and (buf[0][start+0] & 0xF) != 15 \ or (buf[0][start+1] >> 4) >= 10 \ and (buf[0][start+1] >> 4) != 15 \ or (buf[0][start+1] & 0xF) >= 10 \ and (buf[0][start+1] & 0xF) != 15 \ or (buf[0][start+2] >> 4) >= 10 \ and (buf[0][start+2] >> 4) != 15 else: result = (buf[0][start+0] & 0xF) >= 10 \ and (buf[0][start+0] & 0xF) != 15 \ or (buf[0][start+1] >> 4) >= 10 \ and (buf[0][start+1] >> 4) != 15 \ or (buf[0][start+1] & 0xF) >= 10 \ and (buf[0][start+1] & 0xF) != 15 \ or (buf[0][start+2] >> 4) >= 10 \ and (buf[0][start+2] >> 4) != 15 \ or (buf[0][start+2] & 0xF) >= 10 \ and (buf[0][start+2] & 0xF) != 15 return result @staticmethod def reverseByteOrder(buf, start, Count): nbuf=buf[0] for i in xrange(0, Count >> 1): tmp = nbuf[start + i] nbuf[start + i] = nbuf[start + Count - i - 1] nbuf[start + Count - i - 1 ] = tmp buf[0]=nbuf @staticmethod def readWindDirectionShared(buf, start): return (buf[0][0+start] & 0xF, buf[0][start] >> 4) @staticmethod def toInt_2(buf, start, StartOnHiNibble): """read 2 nibbles""" if StartOnHiNibble: rawpre = (buf[0][start+0] >> 4)* 10 \ + (buf[0][start+0] & 0xF)* 1 else: rawpre = (buf[0][start+0] & 0xF)* 10 \ + (buf[0][start+1] >> 4)* 1 return rawpre @staticmethod def toRain_7_3(buf, start, StartOnHiNibble): """read 7 nibbles, presentation with 3 decimals; units of mm""" if (USBHardware.isErr2(buf, start+0, StartOnHiNibble) or USBHardware.isErr5(buf, start+1, StartOnHiNibble)): result = CWeatherTraits.RainNP() elif (USBHardware.isOFL2(buf, start+0, StartOnHiNibble) or USBHardware.isOFL5(buf, start+1, StartOnHiNibble)): result = CWeatherTraits.RainOFL() elif StartOnHiNibble: result = (buf[0][start+0] >> 4)* 1000 \ + (buf[0][start+0] & 0xF)* 100 \ + (buf[0][start+1] >> 4)* 10 \ + (buf[0][start+1] & 0xF)* 1 \ + (buf[0][start+2] >> 4)* 0.1 \ + (buf[0][start+2] & 0xF)* 0.01 \ + (buf[0][start+3] >> 4)* 0.001 else: result = (buf[0][start+0] & 0xF)* 1000 \ + (buf[0][start+1] >> 4)* 100 \ + (buf[0][start+1] & 0xF)* 10 \ + (buf[0][start+2] >> 4)* 1 \ + (buf[0][start+2] & 0xF)* 0.1 \ + (buf[0][start+3] >> 4)* 0.01 \ + (buf[0][start+3] & 0xF)* 0.001 return result @staticmethod def toRain_6_2(buf, start, StartOnHiNibble): '''read 6 nibbles, presentation with 2 decimals; units of mm''' if (USBHardware.isErr2(buf, start+0, StartOnHiNibble) or USBHardware.isErr2(buf, start+1, StartOnHiNibble) or USBHardware.isErr2(buf, start+2, StartOnHiNibble) ): result = CWeatherTraits.RainNP() elif (USBHardware.isOFL2(buf, start+0, StartOnHiNibble) or USBHardware.isOFL2(buf, start+1, StartOnHiNibble) or USBHardware.isOFL2(buf, start+2, StartOnHiNibble)): result = CWeatherTraits.RainOFL() elif StartOnHiNibble: result = (buf[0][start+0] >> 4)* 1000 \ + (buf[0][start+0] & 0xF)* 100 \ + (buf[0][start+1] >> 4)* 10 \ + (buf[0][start+1] & 0xF)* 1 \ + (buf[0][start+2] >> 4)* 0.1 \ + (buf[0][start+2] & 0xF)* 0.01 else: result = (buf[0][start+0] & 0xF)* 1000 \ + (buf[0][start+1] >> 4)* 100 \ + (buf[0][start+1] & 0xF)* 10 \ + (buf[0][start+2] >> 4)* 1 \ + (buf[0][start+2] & 0xF)* 0.1 \ + (buf[0][start+3] >> 4)* 0.01 return result @staticmethod def toRain_3_1(buf, start, StartOnHiNibble): """read 3 nibbles, presentation with 1 decimal; units of 0.1 inch""" if StartOnHiNibble: hibyte = buf[0][start+0] lobyte = (buf[0][start+1] >> 4) & 0xF else: hibyte = 16*(buf[0][start+0] & 0xF) + ((buf[0][start+1] >> 4) & 0xF) lobyte = buf[0][start+1] & 0xF if hibyte == 0xFF and lobyte == 0xE : result = CWeatherTraits.RainNP() elif hibyte == 0xFF and lobyte == 0xF : result = CWeatherTraits.RainOFL() else: val = USBHardware.toFloat_3_1(buf, start, StartOnHiNibble) # 0.1 inch result = val * 2.54 # mm return result @staticmethod def toFloat_3_1(buf, start, StartOnHiNibble): """read 3 nibbles, presentation with 1 decimal""" if StartOnHiNibble: result = (buf[0][start+0] >> 4)*16**2 \ + (buf[0][start+0] & 0xF)* 16**1 \ + (buf[0][start+1] >> 4)* 16**0 else: result = (buf[0][start+0] & 0xF)*16**2 \ + (buf[0][start+1] >> 4)* 16**1 \ + (buf[0][start+1] & 0xF)* 16**0 result = result / 10.0 return result @staticmethod def toDateTime(buf, start, StartOnHiNibble, label): """read 10 nibbles, presentation as DateTime""" result = None if (USBHardware.isErr2(buf, start+0, StartOnHiNibble) or USBHardware.isErr2(buf, start+1, StartOnHiNibble) or USBHardware.isErr2(buf, start+2, StartOnHiNibble) or USBHardware.isErr2(buf, start+3, StartOnHiNibble) or USBHardware.isErr2(buf, start+4, StartOnHiNibble)): logerr('ToDateTime: bogus date for %s: error status in buffer' % label) else: year = USBHardware.toInt_2(buf, start+0, StartOnHiNibble) + 2000 month = USBHardware.toInt_2(buf, start+1, StartOnHiNibble) days = USBHardware.toInt_2(buf, start+2, StartOnHiNibble) hours = USBHardware.toInt_2(buf, start+3, StartOnHiNibble) minutes = USBHardware.toInt_2(buf, start+4, StartOnHiNibble) try: result = datetime(year, month, days, hours, minutes) except ValueError: if label not in _bad_labels: logerr(('ToDateTime: bogus date for %s:' ' bad date conversion from' ' %s %s %s %s %s') % (label, minutes, hours, days, month, year)) if result is None: # FIXME: use None instead of a really old date to indicate invalid result = datetime(1900, 01, 01, 00, 00) return result @staticmethod def toHumidity_2_0(buf, start, StartOnHiNibble): """read 2 nibbles, presentation with 0 decimal""" if USBHardware.isErr2(buf, start+0, StartOnHiNibble): result = CWeatherTraits.HumidityNP() elif USBHardware.isOFL2(buf, start+0, StartOnHiNibble): result = CWeatherTraits.HumidityOFL() else: result = USBHardware.toInt_2(buf, start, StartOnHiNibble) return result @staticmethod def toTemperature_5_3(buf, start, StartOnHiNibble): """read 5 nibbles, presentation with 3 decimals; units of degree C""" if USBHardware.isErr5(buf, start+0, StartOnHiNibble): result = CWeatherTraits.TemperatureNP() elif USBHardware.isOFL5(buf, start+0, StartOnHiNibble): result = CWeatherTraits.TemperatureOFL() else: if StartOnHiNibble: rawtemp = (buf[0][start+0] >> 4)* 10 \ + (buf[0][start+0] & 0xF)* 1 \ + (buf[0][start+1] >> 4)* 0.1 \ + (buf[0][start+1] & 0xF)* 0.01 \ + (buf[0][start+2] >> 4)* 0.001 else: rawtemp = (buf[0][start+0] & 0xF)* 10 \ + (buf[0][start+1] >> 4)* 1 \ + (buf[0][start+1] & 0xF)* 0.1 \ + (buf[0][start+2] >> 4)* 0.01 \ + (buf[0][start+2] & 0xF)* 0.001 result = rawtemp - CWeatherTraits.TemperatureOffset() return result @staticmethod def toTemperature_3_1(buf, start, StartOnHiNibble): """read 3 nibbles, presentation with 1 decimal; units of degree C""" if USBHardware.isErr3(buf, start+0, StartOnHiNibble): result = CWeatherTraits.TemperatureNP() elif USBHardware.isOFL3(buf, start+0, StartOnHiNibble): result = CWeatherTraits.TemperatureOFL() else: if StartOnHiNibble : rawtemp = (buf[0][start+0] >> 4)* 10 \ + (buf[0][start+0] & 0xF)* 1 \ + (buf[0][start+1] >> 4)* 0.1 else: rawtemp = (buf[0][start+0] & 0xF)* 10 \ + (buf[0][start+1] >> 4)* 1 \ + (buf[0][start+1] & 0xF)* 0.1 result = rawtemp - CWeatherTraits.TemperatureOffset() return result @staticmethod def toWindspeed_6_2(buf, start): """read 6 nibbles, presentation with 2 decimals; units of km/h""" result = (buf[0][start+0] >> 4)* 16**5 \ + (buf[0][start+0] & 0xF)* 16**4 \ + (buf[0][start+1] >> 4)* 16**3 \ + (buf[0][start+1] & 0xF)* 16**2 \ + (buf[0][start+2] >> 4)* 16**1 \ + (buf[0][start+2] & 0xF) result /= 256.0 result /= 100.0 # km/h return result @staticmethod def toWindspeed_3_1(buf, start, StartOnHiNibble): """read 3 nibbles, presentation with 1 decimal; units of m/s""" if StartOnHiNibble : hibyte = buf[0][start+0] lobyte = (buf[0][start+1] >> 4) & 0xF else: hibyte = 16*(buf[0][start+0] & 0xF) + ((buf[0][start+1] >> 4) & 0xF) lobyte = buf[0][start+1] & 0xF if hibyte == 0xFF and lobyte == 0xE: result = CWeatherTraits.WindNP() elif hibyte == 0xFF and lobyte == 0xF: result = CWeatherTraits.WindOFL() else: result = USBHardware.toFloat_3_1(buf, start, StartOnHiNibble) # m/s result *= 3.6 # km/h return result @staticmethod def readPressureShared(buf, start, StartOnHiNibble): return (USBHardware.toPressure_hPa_5_1(buf,start+2,1-StartOnHiNibble), USBHardware.toPressure_inHg_5_2(buf,start,StartOnHiNibble)) @staticmethod def toPressure_hPa_5_1(buf, start, StartOnHiNibble): """read 5 nibbles, presentation with 1 decimal; units of hPa (mbar)""" if USBHardware.isErr5(buf, start+0, StartOnHiNibble): result = CWeatherTraits.PressureNP() elif USBHardware.isOFL5(buf, start+0, StartOnHiNibble): result = CWeatherTraits.PressureOFL() elif StartOnHiNibble : result = (buf[0][start+0] >> 4)* 1000 \ + (buf[0][start+0] & 0xF)* 100 \ + (buf[0][start+1] >> 4)* 10 \ + (buf[0][start+1] & 0xF)* 1 \ + (buf[0][start+2] >> 4)* 0.1 else: result = (buf[0][start+0] & 0xF)* 1000 \ + (buf[0][start+1] >> 4)* 100 \ + (buf[0][start+1] & 0xF)* 10 \ + (buf[0][start+2] >> 4)* 1 \ + (buf[0][start+2] & 0xF)* 0.1 return result @staticmethod def toPressure_inHg_5_2(buf, start, StartOnHiNibble): """read 5 nibbles, presentation with 2 decimals; units of inHg""" if USBHardware.isErr5(buf, start+0, StartOnHiNibble): result = CWeatherTraits.PressureNP() elif USBHardware.isOFL5(buf, start+0, StartOnHiNibble): result = CWeatherTraits.PressureOFL() elif StartOnHiNibble : result = (buf[0][start+0] >> 4)* 100 \ + (buf[0][start+0] & 0xF)* 10 \ + (buf[0][start+1] >> 4)* 1 \ + (buf[0][start+1] & 0xF)* 0.1 \ + (buf[0][start+2] >> 4)* 0.01 else: result = (buf[0][start+0] & 0xF)* 100 \ + (buf[0][start+1] >> 4)* 10 \ + (buf[0][start+1] & 0xF)* 1 \ + (buf[0][start+2] >> 4)* 0.1 \ + (buf[0][start+2] & 0xF)* 0.01 return result class CCurrentWeatherData(object): def __init__(self): self._timestamp = None self._checksum = None self._PressureRelative_hPa = CWeatherTraits.PressureNP() self._PressureRelative_hPaMinMax = CMinMaxMeasurement() self._PressureRelative_inHg = CWeatherTraits.PressureNP() self._PressureRelative_inHgMinMax = CMinMaxMeasurement() self._WindSpeed = CWeatherTraits.WindNP() self._WindDirection = EWindDirection.wdNone self._WindDirection1 = EWindDirection.wdNone self._WindDirection2 = EWindDirection.wdNone self._WindDirection3 = EWindDirection.wdNone self._WindDirection4 = EWindDirection.wdNone self._WindDirection5 = EWindDirection.wdNone self._Gust = CWeatherTraits.WindNP() self._GustMax = CMinMaxMeasurement() self._GustDirection = EWindDirection.wdNone self._GustDirection1 = EWindDirection.wdNone self._GustDirection2 = EWindDirection.wdNone self._GustDirection3 = EWindDirection.wdNone self._GustDirection4 = EWindDirection.wdNone self._GustDirection5 = EWindDirection.wdNone self._Rain1H = CWeatherTraits.RainNP() self._Rain1HMax = CMinMaxMeasurement() self._Rain24H = CWeatherTraits.RainNP() self._Rain24HMax = CMinMaxMeasurement() self._RainLastWeek = CWeatherTraits.RainNP() self._RainLastWeekMax = CMinMaxMeasurement() self._RainLastMonth = CWeatherTraits.RainNP() self._RainLastMonthMax = CMinMaxMeasurement() self._RainTotal = CWeatherTraits.RainNP() self._LastRainReset = None self._TempIndoor = CWeatherTraits.TemperatureNP() self._TempIndoorMinMax = CMinMaxMeasurement() self._TempOutdoor = CWeatherTraits.TemperatureNP() self._TempOutdoorMinMax = CMinMaxMeasurement() self._HumidityIndoor = CWeatherTraits.HumidityNP() self._HumidityIndoorMinMax = CMinMaxMeasurement() self._HumidityOutdoor = CWeatherTraits.HumidityNP() self._HumidityOutdoorMinMax = CMinMaxMeasurement() self._Dewpoint = CWeatherTraits.TemperatureNP() self._DewpointMinMax = CMinMaxMeasurement() self._Windchill = CWeatherTraits.TemperatureNP() self._WindchillMinMax = CMinMaxMeasurement() self._WeatherState = EWeatherState.WEATHER_ERR self._WeatherTendency = EWeatherTendency.TREND_ERR self._AlarmRingingFlags = 0 self._AlarmMarkedFlags = 0 self._PresRel_hPa_Max = 0.0 self._PresRel_inHg_Max = 0.0 @staticmethod def calcChecksum(buf): return calc_checksum(buf, 6) def checksum(self): return self._checksum def read(self, buf): self._timestamp = int(time.time() + 0.5) self._checksum = CCurrentWeatherData.calcChecksum(buf) nbuf = [0] nbuf[0] = buf[0] self._StartBytes = nbuf[0][6]*0xF + nbuf[0][7] # FIXME: what is this? self._WeatherTendency = (nbuf[0][8] >> 4) & 0xF if self._WeatherTendency > 3: self._WeatherTendency = 3 self._WeatherState = nbuf[0][8] & 0xF if self._WeatherState > 3: self._WeatherState = 3 self._TempIndoorMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 19, 0) self._TempIndoorMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 22, 1) self._TempIndoor = USBHardware.toTemperature_5_3(nbuf, 24, 0) self._TempIndoorMinMax._Min._IsError = (self._TempIndoorMinMax._Min._Value == CWeatherTraits.TemperatureNP()) self._TempIndoorMinMax._Min._IsOverflow = (self._TempIndoorMinMax._Min._Value == CWeatherTraits.TemperatureOFL()) self._TempIndoorMinMax._Max._IsError = (self._TempIndoorMinMax._Max._Value == CWeatherTraits.TemperatureNP()) self._TempIndoorMinMax._Max._IsOverflow = (self._TempIndoorMinMax._Max._Value == CWeatherTraits.TemperatureOFL()) self._TempIndoorMinMax._Max._Time = None if self._TempIndoorMinMax._Max._IsError or self._TempIndoorMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 9, 0, 'TempIndoorMax') self._TempIndoorMinMax._Min._Time = None if self._TempIndoorMinMax._Min._IsError or self._TempIndoorMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 14, 0, 'TempIndoorMin') self._TempOutdoorMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 37, 0) self._TempOutdoorMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 40, 1) self._TempOutdoor = USBHardware.toTemperature_5_3(nbuf, 42, 0) self._TempOutdoorMinMax._Min._IsError = (self._TempOutdoorMinMax._Min._Value == CWeatherTraits.TemperatureNP()) self._TempOutdoorMinMax._Min._IsOverflow = (self._TempOutdoorMinMax._Min._Value == CWeatherTraits.TemperatureOFL()) self._TempOutdoorMinMax._Max._IsError = (self._TempOutdoorMinMax._Max._Value == CWeatherTraits.TemperatureNP()) self._TempOutdoorMinMax._Max._IsOverflow = (self._TempOutdoorMinMax._Max._Value == CWeatherTraits.TemperatureOFL()) self._TempOutdoorMinMax._Max._Time = None if self._TempOutdoorMinMax._Max._IsError or self._TempOutdoorMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 27, 0, 'TempOutdoorMax') self._TempOutdoorMinMax._Min._Time = None if self._TempOutdoorMinMax._Min._IsError or self._TempOutdoorMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 32, 0, 'TempOutdoorMin') self._WindchillMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 55, 0) self._WindchillMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 58, 1) self._Windchill = USBHardware.toTemperature_5_3(nbuf, 60, 0) self._WindchillMinMax._Min._IsError = (self._WindchillMinMax._Min._Value == CWeatherTraits.TemperatureNP()) self._WindchillMinMax._Min._IsOverflow = (self._WindchillMinMax._Min._Value == CWeatherTraits.TemperatureOFL()) self._WindchillMinMax._Max._IsError = (self._WindchillMinMax._Max._Value == CWeatherTraits.TemperatureNP()) self._WindchillMinMax._Max._IsOverflow = (self._WindchillMinMax._Max._Value == CWeatherTraits.TemperatureOFL()) self._WindchillMinMax._Max._Time = None if self._WindchillMinMax._Max._IsError or self._WindchillMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 45, 0, 'WindchillMax') self._WindchillMinMax._Min._Time = None if self._WindchillMinMax._Min._IsError or self._WindchillMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 50, 0, 'WindchillMin') self._DewpointMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 73, 0) self._DewpointMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 76, 1) self._Dewpoint = USBHardware.toTemperature_5_3(nbuf, 78, 0) self._DewpointMinMax._Min._IsError = (self._DewpointMinMax._Min._Value == CWeatherTraits.TemperatureNP()) self._DewpointMinMax._Min._IsOverflow = (self._DewpointMinMax._Min._Value == CWeatherTraits.TemperatureOFL()) self._DewpointMinMax._Max._IsError = (self._DewpointMinMax._Max._Value == CWeatherTraits.TemperatureNP()) self._DewpointMinMax._Max._IsOverflow = (self._DewpointMinMax._Max._Value == CWeatherTraits.TemperatureOFL()) self._DewpointMinMax._Min._Time = None if self._DewpointMinMax._Min._IsError or self._DewpointMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 68, 0, 'DewpointMin') self._DewpointMinMax._Max._Time = None if self._DewpointMinMax._Max._IsError or self._DewpointMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 63, 0, 'DewpointMax') self._HumidityIndoorMinMax._Max._Value = USBHardware.toHumidity_2_0(nbuf, 91, 1) self._HumidityIndoorMinMax._Min._Value = USBHardware.toHumidity_2_0(nbuf, 92, 1) self._HumidityIndoor = USBHardware.toHumidity_2_0(nbuf, 93, 1) self._HumidityIndoorMinMax._Min._IsError = (self._HumidityIndoorMinMax._Min._Value == CWeatherTraits.HumidityNP()) self._HumidityIndoorMinMax._Min._IsOverflow = (self._HumidityIndoorMinMax._Min._Value == CWeatherTraits.HumidityOFL()) self._HumidityIndoorMinMax._Max._IsError = (self._HumidityIndoorMinMax._Max._Value == CWeatherTraits.HumidityNP()) self._HumidityIndoorMinMax._Max._IsOverflow = (self._HumidityIndoorMinMax._Max._Value == CWeatherTraits.HumidityOFL()) self._HumidityIndoorMinMax._Max._Time = None if self._HumidityIndoorMinMax._Max._IsError or self._HumidityIndoorMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 81, 1, 'HumidityIndoorMax') self._HumidityIndoorMinMax._Min._Time = None if self._HumidityIndoorMinMax._Min._IsError or self._HumidityIndoorMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 86, 1, 'HumidityIndoorMin') self._HumidityOutdoorMinMax._Max._Value = USBHardware.toHumidity_2_0(nbuf, 104, 1) self._HumidityOutdoorMinMax._Min._Value = USBHardware.toHumidity_2_0(nbuf, 105, 1) self._HumidityOutdoor = USBHardware.toHumidity_2_0(nbuf, 106, 1) self._HumidityOutdoorMinMax._Min._IsError = (self._HumidityOutdoorMinMax._Min._Value == CWeatherTraits.HumidityNP()) self._HumidityOutdoorMinMax._Min._IsOverflow = (self._HumidityOutdoorMinMax._Min._Value == CWeatherTraits.HumidityOFL()) self._HumidityOutdoorMinMax._Max._IsError = (self._HumidityOutdoorMinMax._Max._Value == CWeatherTraits.HumidityNP()) self._HumidityOutdoorMinMax._Max._IsOverflow = (self._HumidityOutdoorMinMax._Max._Value == CWeatherTraits.HumidityOFL()) self._HumidityOutdoorMinMax._Max._Time = None if self._HumidityOutdoorMinMax._Max._IsError or self._HumidityOutdoorMinMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 94, 1, 'HumidityOutdoorMax') self._HumidityOutdoorMinMax._Min._Time = None if self._HumidityOutdoorMinMax._Min._IsError or self._HumidityOutdoorMinMax._Min._IsOverflow else USBHardware.toDateTime(nbuf, 99, 1, 'HumidityOutdoorMin') self._RainLastMonthMax._Max._Time = USBHardware.toDateTime(nbuf, 107, 1, 'RainLastMonthMax') self._RainLastMonthMax._Max._Value = USBHardware.toRain_6_2(nbuf, 112, 1) self._RainLastMonth = USBHardware.toRain_6_2(nbuf, 115, 1) self._RainLastWeekMax._Max._Time = USBHardware.toDateTime(nbuf, 118, 1, 'RainLastWeekMax') self._RainLastWeekMax._Max._Value = USBHardware.toRain_6_2(nbuf, 123, 1) self._RainLastWeek = USBHardware.toRain_6_2(nbuf, 126, 1) self._Rain24HMax._Max._Time = USBHardware.toDateTime(nbuf, 129, 1, 'Rain24HMax') self._Rain24HMax._Max._Value = USBHardware.toRain_6_2(nbuf, 134, 1) self._Rain24H = USBHardware.toRain_6_2(nbuf, 137, 1) self._Rain1HMax._Max._Time = USBHardware.toDateTime(nbuf, 140, 1, 'Rain1HMax') self._Rain1HMax._Max._Value = USBHardware.toRain_6_2(nbuf, 145, 1) self._Rain1H = USBHardware.toRain_6_2(nbuf, 148, 1) self._LastRainReset = USBHardware.toDateTime(nbuf, 151, 0, 'LastRainReset') self._RainTotal = USBHardware.toRain_7_3(nbuf, 156, 0) (w ,w1) = USBHardware.readWindDirectionShared(nbuf, 162) (w2,w3) = USBHardware.readWindDirectionShared(nbuf, 161) (w4,w5) = USBHardware.readWindDirectionShared(nbuf, 160) self._WindDirection = w self._WindDirection1 = w1 self._WindDirection2 = w2 self._WindDirection3 = w3 self._WindDirection4 = w4 self._WindDirection5 = w5 if DEBUG_WEATHER_DATA > 2: unknownbuf = [0]*9 for i in xrange(0,9): unknownbuf[i] = nbuf[163+i] strbuf = "" for i in unknownbuf: strbuf += str("%.2x " % i) logdbg('Bytes with unknown meaning at 157-165: %s' % strbuf) self._WindSpeed = USBHardware.toWindspeed_6_2(nbuf, 172) # FIXME: read the WindErrFlags (g ,g1) = USBHardware.readWindDirectionShared(nbuf, 177) (g2,g3) = USBHardware.readWindDirectionShared(nbuf, 176) (g4,g5) = USBHardware.readWindDirectionShared(nbuf, 175) self._GustDirection = g self._GustDirection1 = g1 self._GustDirection2 = g2 self._GustDirection3 = g3 self._GustDirection4 = g4 self._GustDirection5 = g5 self._GustMax._Max._Value = USBHardware.toWindspeed_6_2(nbuf, 184) self._GustMax._Max._IsError = (self._GustMax._Max._Value == CWeatherTraits.WindNP()) self._GustMax._Max._IsOverflow = (self._GustMax._Max._Value == CWeatherTraits.WindOFL()) self._GustMax._Max._Time = None if self._GustMax._Max._IsError or self._GustMax._Max._IsOverflow else USBHardware.toDateTime(nbuf, 179, 1, 'GustMax') self._Gust = USBHardware.toWindspeed_6_2(nbuf, 187) # Apparently the station returns only ONE date time for both hPa/inHg # Min Time Reset and Max Time Reset self._PressureRelative_hPaMinMax._Max._Time = USBHardware.toDateTime(nbuf, 190, 1, 'PressureRelative_hPaMax') self._PressureRelative_inHgMinMax._Max._Time = self._PressureRelative_hPaMinMax._Max._Time self._PressureRelative_hPaMinMax._Min._Time = self._PressureRelative_hPaMinMax._Max._Time # firmware bug, should be: USBHardware.toDateTime(nbuf, 195, 1) self._PressureRelative_inHgMinMax._Min._Time = self._PressureRelative_hPaMinMax._Min._Time (self._PresRel_hPa_Max, self._PresRel_inHg_Max) = USBHardware.readPressureShared(nbuf, 195, 1) # firmware bug, should be: self._PressureRelative_hPaMinMax._Min._Time (self._PressureRelative_hPaMinMax._Max._Value, self._PressureRelative_inHgMinMax._Max._Value) = USBHardware.readPressureShared(nbuf, 200, 1) (self._PressureRelative_hPaMinMax._Min._Value, self._PressureRelative_inHgMinMax._Min._Value) = USBHardware.readPressureShared(nbuf, 205, 1) (self._PressureRelative_hPa, self._PressureRelative_inHg) = USBHardware.readPressureShared(nbuf, 210, 1) def toLog(self): logdbg("_WeatherState=%s _WeatherTendency=%s _AlarmRingingFlags %04x" % (CWeatherTraits.forecastMap[self._WeatherState], CWeatherTraits.trendMap[self._WeatherTendency], self._AlarmRingingFlags)) logdbg("_TempIndoor= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._TempIndoor, self._TempIndoorMinMax._Min._Value, self._TempIndoorMinMax._Min._Time, self._TempIndoorMinMax._Max._Value, self._TempIndoorMinMax._Max._Time)) logdbg("_HumidityIndoor= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._HumidityIndoor, self._HumidityIndoorMinMax._Min._Value, self._HumidityIndoorMinMax._Min._Time, self._HumidityIndoorMinMax._Max._Value, self._HumidityIndoorMinMax._Max._Time)) logdbg("_TempOutdoor= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._TempOutdoor, self._TempOutdoorMinMax._Min._Value, self._TempOutdoorMinMax._Min._Time, self._TempOutdoorMinMax._Max._Value, self._TempOutdoorMinMax._Max._Time)) logdbg("_HumidityOutdoor=%8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._HumidityOutdoor, self._HumidityOutdoorMinMax._Min._Value, self._HumidityOutdoorMinMax._Min._Time, self._HumidityOutdoorMinMax._Max._Value, self._HumidityOutdoorMinMax._Max._Time)) logdbg("_Windchill= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._Windchill, self._WindchillMinMax._Min._Value, self._WindchillMinMax._Min._Time, self._WindchillMinMax._Max._Value, self._WindchillMinMax._Max._Time)) logdbg("_Dewpoint= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s)" % (self._Dewpoint, self._DewpointMinMax._Min._Value, self._DewpointMinMax._Min._Time, self._DewpointMinMax._Max._Value, self._DewpointMinMax._Max._Time)) logdbg("_WindSpeed= %8.3f" % self._WindSpeed) logdbg("_Gust= %8.3f _Max=%8.3f (%s)" % (self._Gust, self._GustMax._Max._Value, self._GustMax._Max._Time)) logdbg('_WindDirection= %3s _GustDirection= %3s' % (CWeatherTraits.windDirMap[self._WindDirection], CWeatherTraits.windDirMap[self._GustDirection])) logdbg('_WindDirection1= %3s _GustDirection1= %3s' % (CWeatherTraits.windDirMap[self._WindDirection1], CWeatherTraits.windDirMap[self._GustDirection1])) logdbg('_WindDirection2= %3s _GustDirection2= %3s' % (CWeatherTraits.windDirMap[self._WindDirection2], CWeatherTraits.windDirMap[self._GustDirection2])) logdbg('_WindDirection3= %3s _GustDirection3= %3s' % (CWeatherTraits.windDirMap[self._WindDirection3], CWeatherTraits.windDirMap[self._GustDirection3])) logdbg('_WindDirection4= %3s _GustDirection4= %3s' % (CWeatherTraits.windDirMap[self._WindDirection4], CWeatherTraits.windDirMap[self._GustDirection4])) logdbg('_WindDirection5= %3s _GustDirection5= %3s' % (CWeatherTraits.windDirMap[self._WindDirection5], CWeatherTraits.windDirMap[self._GustDirection5])) if (self._RainLastMonth > 0) or (self._RainLastWeek > 0): logdbg("_RainLastMonth= %8.3f _Max=%8.3f (%s)" % (self._RainLastMonth, self._RainLastMonthMax._Max._Value, self._RainLastMonthMax._Max._Time)) logdbg("_RainLastWeek= %8.3f _Max=%8.3f (%s)" % (self._RainLastWeek, self._RainLastWeekMax._Max._Value, self._RainLastWeekMax._Max._Time)) logdbg("_Rain24H= %8.3f _Max=%8.3f (%s)" % (self._Rain24H, self._Rain24HMax._Max._Value, self._Rain24HMax._Max._Time)) logdbg("_Rain1H= %8.3f _Max=%8.3f (%s)" % (self._Rain1H, self._Rain1HMax._Max._Value, self._Rain1HMax._Max._Time)) logdbg("_RainTotal= %8.3f _LastRainReset= (%s)" % (self._RainTotal, self._LastRainReset)) logdbg("PressureRel_hPa= %8.3f _Min=%8.3f (%s) _Max=%8.3f (%s) " % (self._PressureRelative_hPa, self._PressureRelative_hPaMinMax._Min._Value, self._PressureRelative_hPaMinMax._Min._Time, self._PressureRelative_hPaMinMax._Max._Value, self._PressureRelative_hPaMinMax._Max._Time)) logdbg("PressureRel_inHg=%8.3f _Min=%8.3f (%s) _Max=%8.3f (%s) " % (self._PressureRelative_inHg, self._PressureRelative_inHgMinMax._Min._Value, self._PressureRelative_inHgMinMax._Min._Time, self._PressureRelative_inHgMinMax._Max._Value, self._PressureRelative_inHgMinMax._Max._Time)) ###logdbg('(* Bug in Weather Station: PressureRelative._Min._Time is written to location of _PressureRelative._Max._Time') ###logdbg('Instead of PressureRelative._Min._Time we get: _PresRel_hPa_Max= %8.3f, _PresRel_inHg_max =%8.3f;' % (self._PresRel_hPa_Max, self._PresRel_inHg_Max)) class CWeatherStationConfig(object): def __init__(self): self._InBufCS = 0 # checksum of received config self._OutBufCS = 0 # calculated config checksum from outbuf config self._ClockMode = 0 self._TemperatureFormat = 0 self._PressureFormat = 0 self._RainFormat = 0 self._WindspeedFormat = 0 self._WeatherThreshold = 0 self._StormThreshold = 0 self._LCDContrast = 0 self._LowBatFlags = 0 self._WindDirAlarmFlags = 0 self._OtherAlarmFlags = 0 self._ResetMinMaxFlags = 0 # output only self._HistoryInterval = 0 self._TempIndoorMinMax = CMinMaxMeasurement() self._TempOutdoorMinMax = CMinMaxMeasurement() self._HumidityIndoorMinMax = CMinMaxMeasurement() self._HumidityOutdoorMinMax = CMinMaxMeasurement() self._Rain24HMax = CMinMaxMeasurement() self._GustMax = CMinMaxMeasurement() self._PressureRelative_hPaMinMax = CMinMaxMeasurement() self._PressureRelative_inHgMinMax = CMinMaxMeasurement() def setTemps(self,TempFormat,InTempLo,InTempHi,OutTempLo,OutTempHi): f1 = TempFormat t1 = InTempLo t2 = InTempHi t3 = OutTempLo t4 = OutTempHi if f1 not in [ETemperatureFormat.tfFahrenheit, ETemperatureFormat.tfCelsius]: logerr('setTemps: unknown temperature format %s' % TempFormat) return 0 if t1 < -40.0 or t1 > 59.9 or t2 < -40.0 or t2 > 59.9 or \ t3 < -40.0 or t3 > 59.9 or t4 < -40.0 or t4 > 59.9: logerr('setTemps: one or more values out of range') return 0 self._TemperatureFormat = f1 self._TempIndoorMinMax._Min._Value = t1 self._TempIndoorMinMax._Max._Value = t2 self._TempOutdoorMinMax._Min._Value = t3 self._TempOutdoorMinMax._Max._Value = t4 return 1 def setHums(self,InHumLo,InHumHi,OutHumLo,OutHumHi): h1 = InHumLo h2 = InHumHi h3 = OutHumLo h4 = OutHumHi if h1 < 1 or h1 > 99 or h2 < 1 or h2 > 99 or \ h3 < 1 or h3 > 99 or h4 < 1 or h4 > 99: logerr('setHums: one or more values out of range') return 0 self._HumidityIndoorMinMax._Min._Value = h1 self._HumidityIndoorMinMax._Max._Value = h2 self._HumidityOutdoorMinMax._Min._Value = h3 self._HumidityOutdoorMinMax._Max._Value = h4 return 1 def setRain24H(self,RainFormat,Rain24hHi): f1 = RainFormat r1 = Rain24hHi if f1 not in [ERainFormat.rfMm, ERainFormat.rfInch]: logerr('setRain24: unknown format %s' % RainFormat) return 0 if r1 < 0.0 or r1 > 9999.9: logerr('setRain24: value outside range') return 0 self._RainFormat = f1 self._Rain24HMax._Max._Value = r1 return 1 def setGust(self,WindSpeedFormat,GustHi): # When the units of a max gust alarm are changed in the weather # station itself, automatically the value is converted to the new # unit and rounded to a whole number. Weewx receives a value # converted to km/h. # # It is too much trouble to sort out what exactly the internal # conversion algoritms are for the other wind units. # # Setting a value in km/h units is tested and works, so this will # be the only option available. f1 = WindSpeedFormat g1 = GustHi if f1 < EWindspeedFormat.wfMs or f1 > EWindspeedFormat.wfMph: logerr('setGust: unknown format %s' % WindSpeedFormat) return 0 if f1 != EWindspeedFormat.wfKmh: logerr('setGust: only units of km/h are supported') return 0 if g1 < 0.0 or g1 > 180.0: logerr('setGust: value outside range') return 0 self._WindSpeedFormat = f1 self._GustMax._Max._Value = int(g1) # apparently gust value is always an integer return 1 def setPresRels(self,PressureFormat,PresRelhPaLo,PresRelhPaHi,PresRelinHgLo,PresRelinHgHi): f1 = PressureFormat p1 = PresRelhPaLo p2 = PresRelhPaHi p3 = PresRelinHgLo p4 = PresRelinHgHi if f1 not in [EPressureFormat.pfinHg, EPressureFormat.pfHPa]: logerr('setPresRel: unknown format %s' % PressureFormat) return 0 if p1 < 920.0 or p1 > 1080.0 or p2 < 920.0 or p2 > 1080.0 or \ p3 < 27.10 or p3 > 31.90 or p4 < 27.10 or p4 > 31.90: logerr('setPresRel: value outside range') return 0 self._RainFormat = f1 self._PressureRelative_hPaMinMax._Min._Value = p1 self._PressureRelative_hPaMinMax._Max._Value = p2 self._PressureRelative_inHgMinMax._Min._Value = p3 self._PressureRelative_inHgMinMax._Max._Value = p4 return 1 def getOutBufCS(self): return self._OutBufCS def getInBufCS(self): return self._InBufCS def setResetMinMaxFlags(self, resetMinMaxFlags): logdbg('setResetMinMaxFlags: %s' % resetMinMaxFlags) self._ResetMinMaxFlags = resetMinMaxFlags def parseRain_3(self, number, buf, start, StartOnHiNibble, numbytes): '''Parse 7-digit number with 3 decimals''' num = int(number*1000) parsebuf=[0]*7 for i in xrange(7-numbytes,7): parsebuf[i] = num%10 num = num//10 if StartOnHiNibble: buf[0][0+start] = parsebuf[6]*16 + parsebuf[5] buf[0][1+start] = parsebuf[4]*16 + parsebuf[3] buf[0][2+start] = parsebuf[2]*16 + parsebuf[1] buf[0][3+start] = parsebuf[0]*16 + (buf[0][3+start] & 0xF) else: buf[0][0+start] = (buf[0][0+start] & 0xF0) + parsebuf[6] buf[0][1+start] = parsebuf[5]*16 + parsebuf[4] buf[0][2+start] = parsebuf[3]*16 + parsebuf[2] buf[0][3+start] = parsebuf[1]*16 + parsebuf[0] def parseWind_6(self, number, buf, start): '''Parse float number to 6 bytes''' num = int(number*100*256) parsebuf=[0]*6 for i in xrange(0,6): parsebuf[i] = num%16 num = num//16 buf[0][0+start] = parsebuf[5]*16 + parsebuf[4] buf[0][1+start] = parsebuf[3]*16 + parsebuf[2] buf[0][2+start] = parsebuf[1]*16 + parsebuf[0] def parse_0(self, number, buf, start, StartOnHiNibble, numbytes): '''Parse 5-digit number with 0 decimals''' num = int(number) nbuf=[0]*5 for i in xrange(5-numbytes,5): nbuf[i] = num%10 num = num//10 if StartOnHiNibble: buf[0][0+start] = nbuf[4]*16 + nbuf[3] buf[0][1+start] = nbuf[2]*16 + nbuf[1] buf[0][2+start] = nbuf[0]*16 + (buf[0][2+start] & 0x0F) else: buf[0][0+start] = (buf[0][0+start] & 0xF0) + nbuf[4] buf[0][1+start] = nbuf[3]*16 + nbuf[2] buf[0][2+start] = nbuf[1]*16 + nbuf[0] def parse_1(self, number, buf, start, StartOnHiNibble, numbytes): '''Parse 5 digit number with 1 decimal''' self.parse_0(number*10.0, buf, start, StartOnHiNibble, numbytes) def parse_2(self, number, buf, start, StartOnHiNibble, numbytes): '''Parse 5 digit number with 2 decimals''' self.parse_0(number*100.0, buf, start, StartOnHiNibble, numbytes) def parse_3(self, number, buf, start, StartOnHiNibble, numbytes): '''Parse 5 digit number with 3 decimals''' self.parse_0(number*1000.0, buf, start, StartOnHiNibble, numbytes) def read(self,buf): nbuf=[0] nbuf[0]=buf[0] self._WindspeedFormat = (nbuf[0][4] >> 4) & 0xF self._RainFormat = (nbuf[0][4] >> 3) & 1 self._PressureFormat = (nbuf[0][4] >> 2) & 1 self._TemperatureFormat = (nbuf[0][4] >> 1) & 1 self._ClockMode = nbuf[0][4] & 1 self._StormThreshold = (nbuf[0][5] >> 4) & 0xF self._WeatherThreshold = nbuf[0][5] & 0xF self._LowBatFlags = (nbuf[0][6] >> 4) & 0xF self._LCDContrast = nbuf[0][6] & 0xF self._WindDirAlarmFlags = (nbuf[0][7] << 8) | nbuf[0][8] self._OtherAlarmFlags = (nbuf[0][9] << 8) | nbuf[0][10] self._TempIndoorMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 11, 1) self._TempIndoorMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 13, 0) self._TempOutdoorMinMax._Max._Value = USBHardware.toTemperature_5_3(nbuf, 16, 1) self._TempOutdoorMinMax._Min._Value = USBHardware.toTemperature_5_3(nbuf, 18, 0) self._HumidityIndoorMinMax._Max._Value = USBHardware.toHumidity_2_0(nbuf, 21, 1) self._HumidityIndoorMinMax._Min._Value = USBHardware.toHumidity_2_0(nbuf, 22, 1) self._HumidityOutdoorMinMax._Max._Value = USBHardware.toHumidity_2_0(nbuf, 23, 1) self._HumidityOutdoorMinMax._Min._Value = USBHardware.toHumidity_2_0(nbuf, 24, 1) self._Rain24HMax._Max._Value = USBHardware.toRain_7_3(nbuf, 25, 0) self._HistoryInterval = nbuf[0][29] self._GustMax._Max._Value = USBHardware.toWindspeed_6_2(nbuf, 30) (self._PressureRelative_hPaMinMax._Min._Value, self._PressureRelative_inHgMinMax._Min._Value) = USBHardware.readPressureShared(nbuf, 33, 1) (self._PressureRelative_hPaMinMax._Max._Value, self._PressureRelative_inHgMinMax._Max._Value) = USBHardware.readPressureShared(nbuf, 38, 1) self._ResetMinMaxFlags = (nbuf[0][43]) <<16 | (nbuf[0][44] << 8) | (nbuf[0][45]) self._InBufCS = (nbuf[0][46] << 8) | nbuf[0][47] self._OutBufCS = calc_checksum(buf, 4, end=39) + 7 """ Reset DewpointMax 80 00 00 Reset DewpointMin 40 00 00 not used 20 00 00 Reset WindchillMin* 10 00 00 *dateTime only; Min._Value is preserved Reset TempOutMax 08 00 00 Reset TempOutMin 04 00 00 Reset TempInMax 02 00 00 Reset TempInMin 01 00 00 Reset Gust 00 80 00 not used 00 40 00 not used 00 20 00 not used 00 10 00 Reset HumOutMax 00 08 00 Reset HumOutMin 00 04 00 Reset HumInMax 00 02 00 Reset HumInMin 00 01 00 not used 00 00 80 Reset Rain Total 00 00 40 Reset last month? 00 00 20 Reset last week? 00 00 10 Reset Rain24H 00 00 08 Reset Rain1H 00 00 04 Reset PresRelMax 00 00 02 Reset PresRelMin 00 00 01 """ #self._ResetMinMaxFlags = 0x000000 #logdbg('set _ResetMinMaxFlags to %06x' % self._ResetMinMaxFlags) """ setTemps(self,TempFormat,InTempLo,InTempHi,OutTempLo,OutTempHi) setHums(self,InHumLo,InHumHi,OutHumLo,OutHumHi) setPresRels(self,PressureFormat,PresRelhPaLo,PresRelhPaHi,PresRelinHgLo,PresRelinHgHi) setGust(self,WindSpeedFormat,GustHi) setRain24H(self,RainFormat,Rain24hHi) """ # Examples: #self.setTemps(ETemperatureFormat.tfCelsius,1.0,41.0,2.0,42.0) #self.setHums(41,71,42,72) #self.setPresRels(EPressureFormat.pfHPa,960.1,1040.1,28.36,30.72) #self.setGust(EWindspeedFormat.wfKmh,040.0) #self.setRain24H(ERainFormat.rfMm,50.0) # Set historyInterval to 5 minutes (default: 2 hours) self._HistoryInterval = EHistoryInterval.hi05Min # Clear all alarm flags, otherwise the datastream from the weather # station will pause during an alarm and connection will be lost. self._WindDirAlarmFlags = 0x0000 self._OtherAlarmFlags = 0x0000 def testConfigChanged(self,buf): nbuf = [0] nbuf[0] = buf[0] nbuf[0][0] = 16*(self._WindspeedFormat & 0xF) + 8*(self._RainFormat & 1) + 4*(self._PressureFormat & 1) + 2*(self._TemperatureFormat & 1) + (self._ClockMode & 1) nbuf[0][1] = self._WeatherThreshold & 0xF | 16 * self._StormThreshold & 0xF0 nbuf[0][2] = self._LCDContrast & 0xF | 16 * self._LowBatFlags & 0xF0 nbuf[0][3] = (self._OtherAlarmFlags >> 0) & 0xFF nbuf[0][4] = (self._OtherAlarmFlags >> 8) & 0xFF nbuf[0][5] = (self._WindDirAlarmFlags >> 0) & 0xFF nbuf[0][6] = (self._WindDirAlarmFlags >> 8) & 0xFF # reverse buf from here self.parse_2(self._PressureRelative_inHgMinMax._Max._Value, nbuf, 7, 1, 5) self.parse_1(self._PressureRelative_hPaMinMax._Max._Value, nbuf, 9, 0, 5) self.parse_2(self._PressureRelative_inHgMinMax._Min._Value, nbuf, 12, 1, 5) self.parse_1(self._PressureRelative_hPaMinMax._Min._Value, nbuf, 14, 0, 5) self.parseWind_6(self._GustMax._Max._Value, nbuf, 17) nbuf[0][20] = self._HistoryInterval & 0xF self.parseRain_3(self._Rain24HMax._Max._Value, nbuf, 21, 0, 7) self.parse_0(self._HumidityOutdoorMinMax._Max._Value, nbuf, 25, 1, 2) self.parse_0(self._HumidityOutdoorMinMax._Min._Value, nbuf, 26, 1, 2) self.parse_0(self._HumidityIndoorMinMax._Max._Value, nbuf, 27, 1, 2) self.parse_0(self._HumidityIndoorMinMax._Min._Value, nbuf, 28, 1, 2) self.parse_3(self._TempOutdoorMinMax._Max._Value + CWeatherTraits.TemperatureOffset(), nbuf, 29, 1, 5) self.parse_3(self._TempOutdoorMinMax._Min._Value + CWeatherTraits.TemperatureOffset(), nbuf, 31, 0, 5) self.parse_3(self._TempIndoorMinMax._Max._Value + CWeatherTraits.TemperatureOffset(), nbuf, 34, 1, 5) self.parse_3(self._TempIndoorMinMax._Min._Value + CWeatherTraits.TemperatureOffset(), nbuf, 36, 0, 5) # reverse buf to here USBHardware.reverseByteOrder(nbuf, 7, 32) # do not include the ResetMinMaxFlags bytes when calculating checksum nbuf[0][39] = (self._ResetMinMaxFlags >> 16) & 0xFF nbuf[0][40] = (self._ResetMinMaxFlags >> 8) & 0xFF nbuf[0][41] = (self._ResetMinMaxFlags >> 0) & 0xFF self._OutBufCS = calc_checksum(nbuf, 0, end=39) + 7 nbuf[0][42] = (self._OutBufCS >> 8) & 0xFF nbuf[0][43] = (self._OutBufCS >> 0) & 0xFF buf[0] = nbuf[0] if self._OutBufCS == self._InBufCS and self._ResetMinMaxFlags == 0: if DEBUG_CONFIG_DATA > 2: logdbg('testConfigChanged: checksum not changed: OutBufCS=%04x' % self._OutBufCS) changed = 0 else: if DEBUG_CONFIG_DATA > 0: logdbg('testConfigChanged: checksum or resetMinMaxFlags changed: OutBufCS=%04x InBufCS=%04x _ResetMinMaxFlags=%06x' % (self._OutBufCS, self._InBufCS, self._ResetMinMaxFlags)) if DEBUG_CONFIG_DATA > 1: self.toLog() changed = 1 return changed def toLog(self): logdbg('OutBufCS= %04x' % self._OutBufCS) logdbg('InBufCS= %04x' % self._InBufCS) logdbg('ClockMode= %s' % self._ClockMode) logdbg('TemperatureFormat= %s' % self._TemperatureFormat) logdbg('PressureFormat= %s' % self._PressureFormat) logdbg('RainFormat= %s' % self._RainFormat) logdbg('WindspeedFormat= %s' % self._WindspeedFormat) logdbg('WeatherThreshold= %s' % self._WeatherThreshold) logdbg('StormThreshold= %s' % self._StormThreshold) logdbg('LCDContrast= %s' % self._LCDContrast) logdbg('LowBatFlags= %01x' % self._LowBatFlags) logdbg('WindDirAlarmFlags= %04x' % self._WindDirAlarmFlags) logdbg('OtherAlarmFlags= %04x' % self._OtherAlarmFlags) logdbg('HistoryInterval= %s' % self._HistoryInterval) logdbg('TempIndoor_Min= %s' % self._TempIndoorMinMax._Min._Value) logdbg('TempIndoor_Max= %s' % self._TempIndoorMinMax._Max._Value) logdbg('TempOutdoor_Min= %s' % self._TempOutdoorMinMax._Min._Value) logdbg('TempOutdoor_Max= %s' % self._TempOutdoorMinMax._Max._Value) logdbg('HumidityIndoor_Min= %s' % self._HumidityIndoorMinMax._Min._Value) logdbg('HumidityIndoor_Max= %s' % self._HumidityIndoorMinMax._Max._Value) logdbg('HumidityOutdoor_Min= %s' % self._HumidityOutdoorMinMax._Min._Value) logdbg('HumidityOutdoor_Max= %s' % self._HumidityOutdoorMinMax._Max._Value) logdbg('Rain24HMax= %s' % self._Rain24HMax._Max._Value) logdbg('GustMax= %s' % self._GustMax._Max._Value) logdbg('PressureRel_hPa_Min= %s' % self._PressureRelative_hPaMinMax._Min._Value) logdbg('PressureRel_inHg_Min= %s' % self._PressureRelative_inHgMinMax._Min._Value) logdbg('PressureRel_hPa_Max= %s' % self._PressureRelative_hPaMinMax._Max._Value) logdbg('PressureRel_inHg_Max= %s' % self._PressureRelative_inHgMinMax._Max._Value) logdbg('ResetMinMaxFlags= %06x (Output only)' % self._ResetMinMaxFlags) def asDict(self): return { 'checksum_in': self._InBufCS, 'checksum_out': self._OutBufCS, 'format_clock': self._ClockMode, 'format_temperature': self._TemperatureFormat, 'format_pressure': self._PressureFormat, 'format_rain': self._RainFormat, 'format_windspeed': self._WindspeedFormat, 'threshold_weather': self._WeatherThreshold, 'threshold_storm': self._StormThreshold, 'lcd_contrast': self._LCDContrast, 'low_battery_flags': self._LowBatFlags, 'alarm_flags_wind_dir': self._WindDirAlarmFlags, 'alarm_flags_other': self._OtherAlarmFlags, # 'reset_minmax_flags': self._ResetMinMaxFlags, 'history_interval': self._HistoryInterval, 'indoor_temp_min': self._TempIndoorMinMax._Min._Value, 'indoor_temp_min_time': self._TempIndoorMinMax._Min._Time, 'indoor_temp_max': self._TempIndoorMinMax._Max._Value, 'indoor_temp_max_time': self._TempIndoorMinMax._Max._Time, 'indoor_humidity_min': self._HumidityIndoorMinMax._Min._Value, 'indoor_humidity_min_time': self._HumidityIndoorMinMax._Min._Time, 'indoor_humidity_max': self._HumidityIndoorMinMax._Max._Value, 'indoor_humidity_max_time': self._HumidityIndoorMinMax._Max._Time, 'outdoor_temp_min': self._TempOutdoorMinMax._Min._Value, 'outdoor_temp_min_time': self._TempOutdoorMinMax._Min._Time, 'outdoor_temp_max': self._TempOutdoorMinMax._Max._Value, 'outdoor_temp_max_time': self._TempOutdoorMinMax._Max._Time, 'outdoor_humidity_min': self._HumidityOutdoorMinMax._Min._Value, 'outdoor_humidity_min_time':self._HumidityOutdoorMinMax._Min._Time, 'outdoor_humidity_max': self._HumidityOutdoorMinMax._Max._Value, 'outdoor_humidity_max_time':self._HumidityOutdoorMinMax._Max._Time, 'rain_24h_max': self._Rain24HMax._Max._Value, 'rain_24h_max_time': self._Rain24HMax._Max._Time, 'wind_gust_max': self._GustMax._Max._Value, 'wind_gust_max_time': self._GustMax._Max._Time, 'pressure_min': self._PressureRelative_hPaMinMax._Min._Value, 'pressure_min_time': self._PressureRelative_hPaMinMax._Min._Time, 'pressure_max': self._PressureRelative_hPaMinMax._Max._Value, 'pressure_max_time': self._PressureRelative_hPaMinMax._Max._Time # do not bother with pressure inHg } class CHistoryData(object): def __init__(self): self.Time = None self.TempIndoor = CWeatherTraits.TemperatureNP() self.HumidityIndoor = CWeatherTraits.HumidityNP() self.TempOutdoor = CWeatherTraits.TemperatureNP() self.HumidityOutdoor = CWeatherTraits.HumidityNP() self.PressureRelative = None self.RainCounterRaw = 0 self.WindSpeed = CWeatherTraits.WindNP() self.WindDirection = EWindDirection.wdNone self.Gust = CWeatherTraits.WindNP() self.GustDirection = EWindDirection.wdNone def read(self, buf): nbuf = [0] nbuf[0] = buf[0] self.Gust = USBHardware.toWindspeed_3_1(nbuf, 12, 0) self.GustDirection = (nbuf[0][14] >> 4) & 0xF self.WindSpeed = USBHardware.toWindspeed_3_1(nbuf, 14, 0) self.WindDirection = (nbuf[0][14] >> 4) & 0xF self.RainCounterRaw = USBHardware.toRain_3_1(nbuf, 16, 1) self.HumidityOutdoor = USBHardware.toHumidity_2_0(nbuf, 17, 0) self.HumidityIndoor = USBHardware.toHumidity_2_0(nbuf, 18, 0) self.PressureRelative = USBHardware.toPressure_hPa_5_1(nbuf, 19, 0) self.TempIndoor = USBHardware.toTemperature_3_1(nbuf, 23, 0) self.TempOutdoor = USBHardware.toTemperature_3_1(nbuf, 22, 1) self.Time = USBHardware.toDateTime(nbuf, 25, 1, 'HistoryData') def toLog(self): """emit raw historical data""" logdbg("Time %s" % self.Time) logdbg("TempIndoor= %7.1f" % self.TempIndoor) logdbg("HumidityIndoor= %7.0f" % self.HumidityIndoor) logdbg("TempOutdoor= %7.1f" % self.TempOutdoor) logdbg("HumidityOutdoor= %7.0f" % self.HumidityOutdoor) logdbg("PressureRelative= %7.1f" % self.PressureRelative) logdbg("RainCounterRaw= %7.3f" % self.RainCounterRaw) logdbg("WindSpeed= %7.3f" % self.WindSpeed) logdbg("WindDirection= % 3s" % CWeatherTraits.windDirMap[self.WindDirection]) logdbg("Gust= %7.3f" % self.Gust) logdbg("GustDirection= % 3s" % CWeatherTraits.windDirMap[self.GustDirection]) def asDict(self): """emit historical data as a dict with weewx conventions""" return { 'dateTime': tstr_to_ts(str(self.Time)), 'inTemp': self.TempIndoor, 'inHumidity': self.HumidityIndoor, 'outTemp': self.TempOutdoor, 'outHumidity': self.HumidityOutdoor, 'pressure': self.PressureRelative, 'rain': self.RainCounterRaw / 10, # weewx wants cm 'windSpeed': self.WindSpeed, 'windDir': getWindDir(self.WindDirection, self.WindSpeed), 'windGust': self.Gust, 'windGustDir': getWindDir(self.GustDirection, self.Gust), } class HistoryCache: def __init__(self): self.clear_records() def clear_records(self): self.since_ts = 0 self.num_rec = 0 self.start_index = None self.next_index = None self.records = [] self.num_outstanding_records = None self.num_scanned = 0 self.last_ts = 0 class CDataStore(object): class TTransceiverSettings(object): def __init__(self): self.VendorId = 0x6666 self.ProductId = 0x5555 self.VersionNo = 1 self.manufacturer = "LA CROSSE TECHNOLOGY" self.product = "Weather Direct Light Wireless Device" self.FrequencyStandard = EFrequency.fsUS self.Frequency = getFrequency(self.FrequencyStandard) self.SerialNumber = None self.DeviceID = None class TLastStat(object): def __init__(self): self.LastBatteryStatus = None self.LastLinkQuality = None self.LastHistoryIndex = None self.LatestHistoryIndex = None self.last_seen_ts = None self.last_weather_ts = 0 self.last_history_ts = 0 self.last_config_ts = 0 def __init__(self): self.transceiverPresent = False self.commModeInterval = 3 self.registeredDeviceID = None self.LastStat = CDataStore.TLastStat() self.TransceiverSettings = CDataStore.TTransceiverSettings() self.StationConfig = CWeatherStationConfig() self.CurrentWeather = CCurrentWeatherData() def getFrequencyStandard(self): return self.TransceiverSettings.FrequencyStandard def setFrequencyStandard(self, val): logdbg('setFrequency: %s' % val) self.TransceiverSettings.FrequencyStandard = val self.TransceiverSettings.Frequency = getFrequency(val) def getDeviceID(self): return self.TransceiverSettings.DeviceID def setDeviceID(self,val): logdbg("setDeviceID: %04x" % val) self.TransceiverSettings.DeviceID = val def getRegisteredDeviceID(self): return self.registeredDeviceID def setRegisteredDeviceID(self, val): if val != self.registeredDeviceID: loginf("console is paired to device with ID %04x" % val) self.registeredDeviceID = val def getTransceiverPresent(self): return self.transceiverPresent def setTransceiverPresent(self, val): self.transceiverPresent = val def setLastStatCache(self, seen_ts=None, quality=None, battery=None, weather_ts=None, history_ts=None, config_ts=None): if DEBUG_COMM > 1: logdbg('setLastStatCache: seen=%s quality=%s battery=%s weather=%s history=%s config=%s' % (seen_ts, quality, battery, weather_ts, history_ts, config_ts)) if seen_ts is not None: self.LastStat.last_seen_ts = seen_ts if quality is not None: self.LastStat.LastLinkQuality = quality if battery is not None: self.LastStat.LastBatteryStatus = battery if weather_ts is not None: self.LastStat.last_weather_ts = weather_ts if history_ts is not None: self.LastStat.last_history_ts = history_ts if config_ts is not None: self.LastStat.last_config_ts = config_ts def setLastHistoryIndex(self,val): self.LastStat.LastHistoryIndex = val def getLastHistoryIndex(self): return self.LastStat.LastHistoryIndex def setLatestHistoryIndex(self,val): self.LastStat.LatestHistoryIndex = val def getLatestHistoryIndex(self): return self.LastStat.LatestHistoryIndex def setCurrentWeather(self, data): self.CurrentWeather = data def getDeviceRegistered(self): if ( self.registeredDeviceID is None or self.TransceiverSettings.DeviceID is None or self.registeredDeviceID != self.TransceiverSettings.DeviceID ): return False return True def getCommModeInterval(self): return self.commModeInterval def setCommModeInterval(self,val): logdbg("setCommModeInterval to %x" % val) self.commModeInterval = val def setTransceiverSerNo(self,val): logdbg("setTransceiverSerialNumber to %s" % val) self.TransceiverSettings.SerialNumber = val def getTransceiverSerNo(self): return self.TransceiverSettings.SerialNumber class sHID(object): """USB driver abstraction""" def __init__(self): self.devh = None self.timeout = 1000 self.last_dump = None def open(self, vid, pid, did, serial): device = self._find_device(vid, pid, did, serial) if device is None: logcrt('Cannot find USB device with Vendor=0x%04x ProdID=0x%04x Device=%s Serial=%s' % (vid, pid, did, serial)) raise weewx.WeeWxIOError('Unable to find transceiver on USB') self._open_device(device) def close(self): self._close_device() def _find_device(self, vid, pid, did, serial): for bus in usb.busses(): for dev in bus.devices: if dev.idVendor == vid and dev.idProduct == pid: if did is None or dev.filename == did: if serial is None: loginf('found transceiver at bus=%s device=%s' % (bus.dirname, dev.filename)) return dev else: handle = dev.open() try: buf = self.readCfg(handle, 0x1F9, 7) sn = str("%02d" % (buf[0])) sn += str("%02d" % (buf[1])) sn += str("%02d" % (buf[2])) sn += str("%02d" % (buf[3])) sn += str("%02d" % (buf[4])) sn += str("%02d" % (buf[5])) sn += str("%02d" % (buf[6])) if str(serial) == sn: loginf('found transceiver at bus=%s device=%s serial=%s' % (bus.dirname, dev.filename, sn)) return dev else: loginf('skipping transceiver with serial %s (looking for %s)' % (sn, serial)) finally: del handle return None def _open_device(self, dev, interface=0): self.devh = dev.open() if not self.devh: raise weewx.WeeWxIOError('Open USB device failed') loginf('manufacturer: %s' % self.devh.getString(dev.iManufacturer,30)) loginf('product: %s' % self.devh.getString(dev.iProduct,30)) loginf('interface: %d' % interface) # be sure kernel does not claim the interface try: self.devh.detachKernelDriver(interface) except Exception: pass # attempt to claim the interface try: logdbg('claiming USB interface %d' % interface) self.devh.claimInterface(interface) self.devh.setAltInterface(interface) except usb.USBError, e: self._close_device() logcrt('Unable to claim USB interface %s: %s' % (interface, e)) raise weewx.WeeWxIOError(e) # FIXME: this seems to be specific to ws28xx? # FIXME: check return values usbWait = 0.05 self.devh.getDescriptor(0x1, 0, 0x12) time.sleep(usbWait) self.devh.getDescriptor(0x2, 0, 0x9) time.sleep(usbWait) self.devh.getDescriptor(0x2, 0, 0x22) time.sleep(usbWait) self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, 0xa, [], 0x0, 0x0, 1000) time.sleep(usbWait) self.devh.getDescriptor(0x22, 0, 0x2a9) time.sleep(usbWait) def _close_device(self): try: logdbg('releasing USB interface') self.devh.releaseInterface() except Exception: pass self.devh = None def setTX(self): buf = [0]*0x15 buf[0] = 0xD1 if DEBUG_COMM > 1: self.dump('setTX', buf, fmt=DEBUG_DUMP_FORMAT) self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, request=0x0000009, buffer=buf, value=0x00003d1, index=0x0000000, timeout=self.timeout) def setRX(self): buf = [0]*0x15 buf[0] = 0xD0 if DEBUG_COMM > 1: self.dump('setRX', buf, fmt=DEBUG_DUMP_FORMAT) self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, request=0x0000009, buffer=buf, value=0x00003d0, index=0x0000000, timeout=self.timeout) def getState(self,StateBuffer): buf = self.devh.controlMsg(requestType=usb.TYPE_CLASS | usb.RECIP_INTERFACE | usb.ENDPOINT_IN, request=usb.REQ_CLEAR_FEATURE, buffer=0x0a, value=0x00003de, index=0x0000000, timeout=self.timeout) if DEBUG_COMM > 1: self.dump('getState', buf, fmt=DEBUG_DUMP_FORMAT) StateBuffer[0]=[0]*0x2 StateBuffer[0][0]=buf[1] StateBuffer[0][1]=buf[2] def readConfigFlash(self, addr, numBytes, data): if numBytes > 512: raise Exception('bad number of bytes') while numBytes: buf=[0xcc]*0x0f #0x15 buf[0] = 0xdd buf[1] = 0x0a buf[2] = (addr >>8) & 0xFF buf[3] = (addr >>0) & 0xFF if DEBUG_COMM > 1: self.dump('readCfgFlash>', buf, fmt=DEBUG_DUMP_FORMAT) self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, request=0x0000009, buffer=buf, value=0x00003dd, index=0x0000000, timeout=self.timeout) buf = self.devh.controlMsg(requestType=usb.TYPE_CLASS | usb.RECIP_INTERFACE | usb.ENDPOINT_IN, request=usb.REQ_CLEAR_FEATURE, buffer=0x15, value=0x00003dc, index=0x0000000, timeout=self.timeout) new_data=[0]*0x15 if numBytes < 16: for i in xrange(0, numBytes): new_data[i] = buf[i+4] numBytes = 0 else: for i in xrange(0, 16): new_data[i] = buf[i+4] numBytes -= 16 addr += 16 if DEBUG_COMM > 1: self.dump('readCfgFlash<', buf, fmt=DEBUG_DUMP_FORMAT) data[0] = new_data # FIXME: new_data might be unset def setState(self,state): buf = [0]*0x15 buf[0] = 0xd7 buf[1] = state if DEBUG_COMM > 1: self.dump('setState', buf, fmt=DEBUG_DUMP_FORMAT) self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, request=0x0000009, buffer=buf, value=0x00003d7, index=0x0000000, timeout=self.timeout) def setFrame(self,data,numBytes): buf = [0]*0x111 buf[0] = 0xd5 buf[1] = numBytes >> 8 buf[2] = numBytes for i in xrange(0, numBytes): buf[i+3] = data[i] if DEBUG_COMM == 1: self.dump('setFrame', buf, 'short') elif DEBUG_COMM > 1: self.dump('setFrame', buf, fmt=DEBUG_DUMP_FORMAT) self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, request=0x0000009, buffer=buf, value=0x00003d5, index=0x0000000, timeout=self.timeout) def getFrame(self,data,numBytes): buf = self.devh.controlMsg(requestType=usb.TYPE_CLASS | usb.RECIP_INTERFACE | usb.ENDPOINT_IN, request=usb.REQ_CLEAR_FEATURE, buffer=0x111, value=0x00003d6, index=0x0000000, timeout=self.timeout) new_data=[0]*0x131 new_numBytes=(buf[1] << 8 | buf[2])& 0x1ff for i in xrange(0, new_numBytes): new_data[i] = buf[i+3] if DEBUG_COMM == 1: self.dump('getFrame', buf, 'short') elif DEBUG_COMM > 1: self.dump('getFrame', buf, fmt=DEBUG_DUMP_FORMAT) data[0] = new_data numBytes[0] = new_numBytes def writeReg(self,regAddr,data): buf = [0]*0x05 buf[0] = 0xf0 buf[1] = regAddr & 0x7F buf[2] = 0x01 buf[3] = data buf[4] = 0x00 if DEBUG_COMM > 1: self.dump('writeReg', buf, fmt=DEBUG_DUMP_FORMAT) self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, request=0x0000009, buffer=buf, value=0x00003f0, index=0x0000000, timeout=self.timeout) def execute(self, command): buf = [0]*0x0f #*0x15 buf[0] = 0xd9 buf[1] = command if DEBUG_COMM > 1: self.dump('execute', buf, fmt=DEBUG_DUMP_FORMAT) self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, request=0x0000009, buffer=buf, value=0x00003d9, index=0x0000000, timeout=self.timeout) def setPreamblePattern(self,pattern): buf = [0]*0x15 buf[0] = 0xd8 buf[1] = pattern if DEBUG_COMM > 1: self.dump('setPreamble', buf, fmt=DEBUG_DUMP_FORMAT) self.devh.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, request=0x0000009, buffer=buf, value=0x00003d8, index=0x0000000, timeout=self.timeout) # three formats, long, short, auto. short shows only the first 16 bytes. # long shows the full length of the buffer. auto shows the message length # as indicated by the length in the message itself for setFrame and # getFrame, or the first 16 bytes for any other message. def dump(self, cmd, buf, fmt='auto'): strbuf = '' msglen = None if fmt == 'auto': if buf[0] in [0xd5, 0x00]: msglen = buf[2] + 3 # use msg length for set/get frame else: msglen = 16 # otherwise do same as short format elif fmt == 'short': msglen = 16 for i,x in enumerate(buf): strbuf += str('%02x ' % x) if (i+1) % 16 == 0: self.dumpstr(cmd, strbuf) strbuf = '' if msglen is not None and i+1 >= msglen: break if strbuf: self.dumpstr(cmd, strbuf) # filter output that we do not care about, pad the command string. def dumpstr(self, cmd, strbuf): pad = ' ' * (15-len(cmd)) # de15 is idle, de14 is intermediate if strbuf in ['de 15 00 00 00 00 ','de 14 00 00 00 00 ']: if strbuf != self.last_dump or DEBUG_COMM > 2: logdbg('%s: %s%s' % (cmd, pad, strbuf)) self.last_dump = strbuf else: logdbg('%s: %s%s' % (cmd, pad, strbuf)) self.last_dump = None def readCfg(self, handle, addr, numBytes): while numBytes: buf=[0xcc]*0x0f #0x15 buf[0] = 0xdd buf[1] = 0x0a buf[2] = (addr >>8) & 0xFF buf[3] = (addr >>0) & 0xFF handle.controlMsg(usb.TYPE_CLASS + usb.RECIP_INTERFACE, request=0x0000009, buffer=buf, value=0x00003dd, index=0x0000000, timeout=1000) buf = handle.controlMsg(requestType=usb.TYPE_CLASS | usb.RECIP_INTERFACE | usb.ENDPOINT_IN, request=usb.REQ_CLEAR_FEATURE, buffer=0x15, value=0x00003dc, index=0x0000000, timeout=1000) new_data=[0]*0x15 if numBytes < 16: for i in xrange(0, numBytes): new_data[i] = buf[i+4] numBytes = 0 else: for i in xrange(0, 16): new_data[i] = buf[i+4] numBytes -= 16 addr += 16 return new_data class CCommunicationService(object): reg_names = dict() class AX5051RegisterNames: REVISION = 0x0 SCRATCH = 0x1 POWERMODE = 0x2 XTALOSC = 0x3 FIFOCTRL = 0x4 FIFODATA = 0x5 IRQMASK = 0x6 IFMODE = 0x8 PINCFG1 = 0x0C PINCFG2 = 0x0D MODULATION = 0x10 ENCODING = 0x11 FRAMING = 0x12 CRCINIT3 = 0x14 CRCINIT2 = 0x15 CRCINIT1 = 0x16 CRCINIT0 = 0x17 FREQ3 = 0x20 FREQ2 = 0x21 FREQ1 = 0x22 FREQ0 = 0x23 FSKDEV2 = 0x25 FSKDEV1 = 0x26 FSKDEV0 = 0x27 IFFREQHI = 0x28 IFFREQLO = 0x29 PLLLOOP = 0x2C PLLRANGING = 0x2D PLLRNGCLK = 0x2E TXPWR = 0x30 TXRATEHI = 0x31 TXRATEMID = 0x32 TXRATELO = 0x33 MODMISC = 0x34 FIFOCONTROL2 = 0x37 ADCMISC = 0x38 AGCTARGET = 0x39 AGCATTACK = 0x3A AGCDECAY = 0x3B AGCCOUNTER = 0x3C CICDEC = 0x3F DATARATEHI = 0x40 DATARATELO = 0x41 TMGGAINHI = 0x42 TMGGAINLO = 0x43 PHASEGAIN = 0x44 FREQGAIN = 0x45 FREQGAIN2 = 0x46 AMPLGAIN = 0x47 TRKFREQHI = 0x4C TRKFREQLO = 0x4D XTALCAP = 0x4F SPAREOUT = 0x60 TESTOBS = 0x68 APEOVER = 0x70 TMMUX = 0x71 PLLVCOI = 0x72 PLLCPEN = 0x73 PLLRNGMISC = 0x74 AGCMANUAL = 0x78 ADCDCLEVEL = 0x79 RFMISC = 0x7A TXDRIVER = 0x7B REF = 0x7C RXMISC = 0x7D def __init__(self): logdbg('CCommunicationService.init') self.shid = sHID() self.DataStore = CDataStore() self.firstSleep = 1 self.nextSleep = 1 self.pollCount = 0 self.running = False self.child = None self.thread_wait = 60.0 # seconds self.command = None self.history_cache = HistoryCache() # do not set time when offset to whole hour is <= _a3_offset self._a3_offset = 3 def buildFirstConfigFrame(self, Buffer, cs): logdbg('buildFirstConfigFrame: cs=%04x' % cs) newBuffer = [0] newBuffer[0] = [0]*9 comInt = self.DataStore.getCommModeInterval() historyAddress = 0xFFFFFF newBuffer[0][0] = 0xf0 newBuffer[0][1] = 0xf0 newBuffer[0][2] = EAction.aGetConfig newBuffer[0][3] = (cs >> 8) & 0xff newBuffer[0][4] = (cs >> 0) & 0xff newBuffer[0][5] = (comInt >> 4) & 0xff newBuffer[0][6] = (historyAddress >> 16) & 0x0f | 16 * (comInt & 0xf) newBuffer[0][7] = (historyAddress >> 8 ) & 0xff newBuffer[0][8] = (historyAddress >> 0 ) & 0xff Buffer[0] = newBuffer[0] Length = 0x09 return Length def buildConfigFrame(self, Buffer): logdbg("buildConfigFrame") newBuffer = [0] newBuffer[0] = [0]*48 cfgBuffer = [0] cfgBuffer[0] = [0]*44 changed = self.DataStore.StationConfig.testConfigChanged(cfgBuffer) if changed: self.shid.dump('OutBuf', cfgBuffer[0], fmt='long') newBuffer[0][0] = Buffer[0][0] newBuffer[0][1] = Buffer[0][1] newBuffer[0][2] = EAction.aSendConfig # 0x40 # change this value if we won't store config newBuffer[0][3] = Buffer[0][3] for i in xrange(0,44): newBuffer[0][i+4] = cfgBuffer[0][i] Buffer[0] = newBuffer[0] Length = 48 # 0x30 else: # current config not up to date; do not write yet Length = 0 return Length def buildTimeFrame(self, Buffer, cs): logdbg("buildTimeFrame: cs=%04x" % cs) now = time.time() tm = time.localtime(now) newBuffer=[0] newBuffer[0]=Buffer[0] #00000000: d5 00 0c 00 32 c0 00 8f 45 25 15 91 31 20 01 00 #00000000: d5 00 0c 00 32 c0 06 c1 47 25 15 91 31 20 01 00 # 3 4 5 6 7 8 9 10 11 newBuffer[0][2] = EAction.aSendTime # 0xc0 newBuffer[0][3] = (cs >> 8) & 0xFF newBuffer[0][4] = (cs >> 0) & 0xFF newBuffer[0][5] = (tm[5] % 10) + 0x10 * (tm[5] // 10) #sec newBuffer[0][6] = (tm[4] % 10) + 0x10 * (tm[4] // 10) #min newBuffer[0][7] = (tm[3] % 10) + 0x10 * (tm[3] // 10) #hour #DayOfWeek = tm[6] - 1; #ole from 1 - 7 - 1=Sun... 0-6 0=Sun DayOfWeek = tm[6] #py from 0 - 6 - 0=Mon newBuffer[0][8] = DayOfWeek % 10 + 0x10 * (tm[2] % 10) #DoW + Day newBuffer[0][9] = (tm[2] // 10) + 0x10 * (tm[1] % 10) #day + month newBuffer[0][10] = (tm[1] // 10) + 0x10 * ((tm[0] - 2000) % 10) #month + year newBuffer[0][11] = (tm[0] - 2000) // 10 #year Buffer[0]=newBuffer[0] Length = 0x0c return Length def buildACKFrame(self, Buffer, action, cs, hidx=None): if DEBUG_COMM > 1: logdbg("buildACKFrame: action=%x cs=%04x historyIndex=%s" % (action, cs, hidx)) newBuffer = [0] newBuffer[0] = [0]*9 for i in xrange(0,2): newBuffer[0][i] = Buffer[0][i] comInt = self.DataStore.getCommModeInterval() # When last weather is stale, change action to get current weather # This is only needed during long periods of history data catchup if self.command == EAction.aGetHistory: now = int(time.time()) age = now - self.DataStore.LastStat.last_weather_ts # Morphing action only with GetHistory requests, # and stale data after a period of twice the CommModeInterval, # but not with init GetHistory requests (0xF0) if action == EAction.aGetHistory and age >= (comInt +1) * 2 and newBuffer[0][1] != 0xF0: if DEBUG_COMM > 0: logdbg('buildACKFrame: morphing action from %d to 5 (age=%s)' % (action, age)) action = EAction.aGetCurrent if hidx is None: if self.command == EAction.aGetHistory: hidx = self.history_cache.next_index elif self.DataStore.getLastHistoryIndex() is not None: hidx = self.DataStore.getLastHistoryIndex() if hidx is None or hidx < 0 or hidx >= WS28xxDriver.max_records: haddr = 0xffffff else: haddr = index_to_addr(hidx) if DEBUG_COMM > 1: logdbg('buildACKFrame: idx: %s addr: 0x%04x' % (hidx, haddr)) newBuffer[0][2] = action & 0xF newBuffer[0][3] = (cs >> 8) & 0xFF newBuffer[0][4] = (cs >> 0) & 0xFF newBuffer[0][5] = (comInt >> 4) & 0xFF newBuffer[0][6] = (haddr >> 16) & 0x0F | 16 * (comInt & 0xF) newBuffer[0][7] = (haddr >> 8 ) & 0xFF newBuffer[0][8] = (haddr >> 0 ) & 0xFF #d5 00 09 f0 f0 03 00 32 00 3f ff ff Buffer[0]=newBuffer[0] return 9 def handleWsAck(self,Buffer,Length): logdbg('handleWsAck') self.DataStore.setLastStatCache(seen_ts=int(time.time()), quality=(Buffer[0][3] & 0x7f), battery=(Buffer[0][2] & 0xf)) def handleConfig(self,Buffer,Length): logdbg('handleConfig: %s' % self.timing()) if DEBUG_CONFIG_DATA > 2: self.shid.dump('InBuf', Buffer[0], fmt='long') newBuffer=[0] newBuffer[0] = Buffer[0] newLength = [0] now = int(time.time()) self.DataStore.StationConfig.read(newBuffer) if DEBUG_CONFIG_DATA > 1: self.DataStore.StationConfig.toLog() self.DataStore.setLastStatCache(seen_ts=now, quality=(Buffer[0][3] & 0x7f), battery=(Buffer[0][2] & 0xf), config_ts=now) cs = newBuffer[0][47] | (newBuffer[0][46] << 8) self.setSleep(0.300,0.010) newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetHistory, cs) Buffer[0] = newBuffer[0] Length[0] = newLength[0] def handleCurrentData(self,Buffer,Length): if DEBUG_WEATHER_DATA > 0: logdbg('handleCurrentData: %s' % self.timing()) now = int(time.time()) # update the weather data cache if changed or stale chksum = CCurrentWeatherData.calcChecksum(Buffer) age = now - self.DataStore.LastStat.last_weather_ts if age >= 10 or chksum != self.DataStore.CurrentWeather.checksum(): if DEBUG_WEATHER_DATA > 2: self.shid.dump('CurWea', Buffer[0], fmt='long') data = CCurrentWeatherData() data.read(Buffer) self.DataStore.setCurrentWeather(data) if DEBUG_WEATHER_DATA > 1: data.toLog() # update the connection cache self.DataStore.setLastStatCache(seen_ts=now, quality=(Buffer[0][3] & 0x7f), battery=(Buffer[0][2] & 0xf), weather_ts=now) newBuffer = [0] newBuffer[0] = Buffer[0] newLength = [0] cs = newBuffer[0][5] | (newBuffer[0][4] << 8) cfgBuffer = [0] cfgBuffer[0] = [0]*44 changed = self.DataStore.StationConfig.testConfigChanged(cfgBuffer) inBufCS = self.DataStore.StationConfig.getInBufCS() if inBufCS == 0 or inBufCS != cs: # request for a get config logdbg('handleCurrentData: inBufCS of station does not match') self.setSleep(0.300,0.010) newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetConfig, cs) elif changed: # Request for a set config logdbg('handleCurrentData: outBufCS of station changed') self.setSleep(0.300,0.010) newLength[0] = self.buildACKFrame(newBuffer, EAction.aReqSetConfig, cs) else: # Request for either a history message or a current weather message # In general we don't use EAction.aGetCurrent to ask for a current # weather message; they also come when requested for # EAction.aGetHistory. This we learned from the Heavy Weather Pro # messages (via USB sniffer). self.setSleep(0.300,0.010) newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetHistory, cs) Length[0] = newLength[0] Buffer[0] = newBuffer[0] def handleHistoryData(self, buf, buflen): if DEBUG_HISTORY_DATA > 0: logdbg('handleHistoryData: %s' % self.timing()) now = int(time.time()) self.DataStore.setLastStatCache(seen_ts=now, quality=(buf[0][3] & 0x7f), battery=(buf[0][2] & 0xf), history_ts=now) newbuf = [0] newbuf[0] = buf[0] newlen = [0] data = CHistoryData() data.read(newbuf) if DEBUG_HISTORY_DATA > 1: data.toLog() cs = newbuf[0][5] | (newbuf[0][4] << 8) latestAddr = bytes_to_addr(buf[0][6], buf[0][7], buf[0][8]) thisAddr = bytes_to_addr(buf[0][9], buf[0][10], buf[0][11]) latestIndex = addr_to_index(latestAddr) thisIndex = addr_to_index(thisAddr) ts = tstr_to_ts(str(data.Time)) nrec = get_index(latestIndex - thisIndex) logdbg('handleHistoryData: time=%s' ' this=%d (0x%04x) latest=%d (0x%04x) nrec=%d' % (data.Time, thisIndex, thisAddr, latestIndex, latestAddr, nrec)) # track the latest history index self.DataStore.setLastHistoryIndex(thisIndex) self.DataStore.setLatestHistoryIndex(latestIndex) nextIndex = None if self.command == EAction.aGetHistory: if self.history_cache.start_index is None: nreq = 0 if self.history_cache.num_rec > 0: loginf('handleHistoryData: request for %s records' % self.history_cache.num_rec) nreq = self.history_cache.num_rec else: loginf('handleHistoryData: request records since %s' % weeutil.weeutil.timestamp_to_string(self.history_cache.since_ts)) span = int(time.time()) - self.history_cache.since_ts # FIXME: what if we do not have config data yet? cfg = self.getConfigData().asDict() arcint = 60 * getHistoryInterval(cfg['history_interval']) # FIXME: this assumes a constant archive interval for all # records in the station history nreq = int(span / arcint) + 5 # FIXME: punt 5 if nreq > nrec: loginf('handleHistoryData: too many records requested (%d)' ', clipping to number stored (%d)' % (nreq, nrec)) nreq = nrec idx = get_index(latestIndex - nreq) self.history_cache.start_index = idx self.history_cache.next_index = idx self.DataStore.setLastHistoryIndex(idx) self.history_cache.num_outstanding_records = nreq logdbg('handleHistoryData: start_index=%s' ' num_outstanding_records=%s' % (idx, nreq)) nextIndex = idx elif self.history_cache.next_index is not None: # thisIndex should be the next record after next_index thisIndexTst = get_next_index(self.history_cache.next_index) if thisIndexTst == thisIndex: self.history_cache.num_scanned += 1 # get the next history record if ts is not None and self.history_cache.since_ts <= ts: # Check if two records in a row with the same ts if self.history_cache.last_ts == ts: logdbg('handleHistoryData: remove previous record' ' with duplicate timestamp: %s' % weeutil.weeutil.timestamp_to_string(ts)) self.history_cache.records.pop() self.history_cache.last_ts = ts # append to the history logdbg('handleHistoryData: appending history record' ' %s: %s' % (thisIndex, data.asDict())) self.history_cache.records.append(data.asDict()) self.history_cache.num_outstanding_records = nrec elif ts is None: logerr('handleHistoryData: skip record: this_ts=None') else: logdbg('handleHistoryData: skip record: since_ts=%s this_ts=%s' % (weeutil.weeutil.timestamp_to_string(self.history_cache.since_ts), weeutil.weeutil.timestamp_to_string(ts))) self.history_cache.next_index = thisIndex else: loginf('handleHistoryData: index mismatch: %s != %s' % (thisIndexTst, thisIndex)) nextIndex = self.history_cache.next_index logdbg('handleHistoryData: next=%s' % nextIndex) self.setSleep(0.300,0.010) newlen[0] = self.buildACKFrame(newbuf, EAction.aGetHistory, cs, nextIndex) buflen[0] = newlen[0] buf[0] = newbuf[0] def handleNextAction(self,Buffer,Length): newBuffer = [0] newBuffer[0] = Buffer[0] newLength = [0] newLength[0] = Length[0] self.DataStore.setLastStatCache(seen_ts=int(time.time()), quality=(Buffer[0][3] & 0x7f)) cs = newBuffer[0][5] | (newBuffer[0][4] << 8) if (Buffer[0][2] & 0xEF) == EResponseType.rtReqFirstConfig: logdbg('handleNextAction: a1 (first-time config)') self.setSleep(0.085,0.005) newLength[0] = self.buildFirstConfigFrame(newBuffer, cs) elif (Buffer[0][2] & 0xEF) == EResponseType.rtReqSetConfig: logdbg('handleNextAction: a2 (set config data)') self.setSleep(0.085,0.005) newLength[0] = self.buildConfigFrame(newBuffer) elif (Buffer[0][2] & 0xEF) == EResponseType.rtReqSetTime: logdbg('handleNextAction: a3 (set time data)') now = int(time.time()) age = now - self.DataStore.LastStat.last_weather_ts if age >= (self.DataStore.getCommModeInterval() +1) * 2: # always set time if init or stale communication self.setSleep(0.085,0.005) newLength[0] = self.buildTimeFrame(newBuffer, cs) else: # When time is set at the whole hour we may get an extra # historical record with time stamp a history period ahead # We will skip settime if offset to whole hour is too small # (time difference between WS and server < self._a3_offset) m, s = divmod(now, 60) h, m = divmod(m, 60) logdbg('Time: hh:%02d:%02d' % (m,s)) if (m == 59 and s >= (60 - self._a3_offset)) or (m == 0 and s <= self._a3_offset): logdbg('Skip settime; time difference <= %s s' % int(self._a3_offset)) self.setSleep(0.300,0.010) newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetHistory, cs) else: # set time self.setSleep(0.085,0.005) newLength[0] = self.buildTimeFrame(newBuffer, cs) else: logdbg('handleNextAction: %02x' % (Buffer[0][2] & 0xEF)) self.setSleep(0.300,0.010) newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetHistory, cs) Length[0] = newLength[0] Buffer[0] = newBuffer[0] def generateResponse(self, Buffer, Length): if DEBUG_COMM > 1: logdbg('generateResponse: %s' % self.timing()) newBuffer = [0] newBuffer[0] = Buffer[0] newLength = [0] newLength[0] = Length[0] if Length[0] == 0: raise BadResponse('zero length buffer') bufferID = (Buffer[0][0] <<8) | Buffer[0][1] respType = (Buffer[0][2] & 0xE0) if DEBUG_COMM > 1: logdbg("generateResponse: id=%04x resp=%x length=%x" % (bufferID, respType, Length[0])) deviceID = self.DataStore.getDeviceID() if bufferID != 0xF0F0: self.DataStore.setRegisteredDeviceID(bufferID) if bufferID == 0xF0F0: loginf('generateResponse: console not paired, attempting to pair to 0x%04x' % deviceID) newLength[0] = self.buildACKFrame(newBuffer, EAction.aGetConfig, deviceID, 0xFFFF) elif bufferID == deviceID: if respType == EResponseType.rtDataWritten: # 00000000: 00 00 06 00 32 20 if Length[0] == 0x06: self.DataStore.StationConfig.setResetMinMaxFlags(0) self.shid.setRX() raise DataWritten() else: raise BadResponse('len=%x resp=%x' % (Length[0], respType)) elif respType == EResponseType.rtGetConfig: # 00000000: 00 00 30 00 32 40 if Length[0] == 0x30: self.handleConfig(newBuffer, newLength) else: raise BadResponse('len=%x resp=%x' % (Length[0], respType)) elif respType == EResponseType.rtGetCurrentWeather: # 00000000: 00 00 d7 00 32 60 if Length[0] == 0xd7: #215 self.handleCurrentData(newBuffer, newLength) else: raise BadResponse('len=%x resp=%x' % (Length[0], respType)) elif respType == EResponseType.rtGetHistory: # 00000000: 00 00 1e 00 32 80 if Length[0] == 0x1e: self.handleHistoryData(newBuffer, newLength) else: raise BadResponse('len=%x resp=%x' % (Length[0], respType)) elif respType == EResponseType.rtRequest: # 00000000: 00 00 06 f0 f0 a1 # 00000000: 00 00 06 00 32 a3 # 00000000: 00 00 06 00 32 a2 if Length[0] == 0x06: self.handleNextAction(newBuffer, newLength) else: raise BadResponse('len=%x resp=%x' % (Length[0], respType)) else: raise BadResponse('unexpected response type %x' % respType) elif respType not in [0x20,0x40,0x60,0x80,0xa1,0xa2,0xa3]: # message is probably corrupt raise BadResponse('unknown response type %x' % respType) else: msg = 'message from console contains unknown device ID (id=%04x resp=%x)' % (bufferID, respType) logdbg(msg) log_frame(Length[0],Buffer[0]) raise BadResponse(msg) Buffer[0] = newBuffer[0] Length[0] = newLength[0] def configureRegisterNames(self): self.reg_names[self.AX5051RegisterNames.IFMODE] =0x00 self.reg_names[self.AX5051RegisterNames.MODULATION]=0x41 #fsk self.reg_names[self.AX5051RegisterNames.ENCODING] =0x07 self.reg_names[self.AX5051RegisterNames.FRAMING] =0x84 #1000:0100 ##?hdlc? |1000 010 0 self.reg_names[self.AX5051RegisterNames.CRCINIT3] =0xff self.reg_names[self.AX5051RegisterNames.CRCINIT2] =0xff self.reg_names[self.AX5051RegisterNames.CRCINIT1] =0xff self.reg_names[self.AX5051RegisterNames.CRCINIT0] =0xff self.reg_names[self.AX5051RegisterNames.FREQ3] =0x38 self.reg_names[self.AX5051RegisterNames.FREQ2] =0x90 self.reg_names[self.AX5051RegisterNames.FREQ1] =0x00 self.reg_names[self.AX5051RegisterNames.FREQ0] =0x01 self.reg_names[self.AX5051RegisterNames.PLLLOOP] =0x1d self.reg_names[self.AX5051RegisterNames.PLLRANGING]=0x08 self.reg_names[self.AX5051RegisterNames.PLLRNGCLK] =0x03 self.reg_names[self.AX5051RegisterNames.MODMISC] =0x03 self.reg_names[self.AX5051RegisterNames.SPAREOUT] =0x00 self.reg_names[self.AX5051RegisterNames.TESTOBS] =0x00 self.reg_names[self.AX5051RegisterNames.APEOVER] =0x00 self.reg_names[self.AX5051RegisterNames.TMMUX] =0x00 self.reg_names[self.AX5051RegisterNames.PLLVCOI] =0x01 self.reg_names[self.AX5051RegisterNames.PLLCPEN] =0x01 self.reg_names[self.AX5051RegisterNames.RFMISC] =0xb0 self.reg_names[self.AX5051RegisterNames.REF] =0x23 self.reg_names[self.AX5051RegisterNames.IFFREQHI] =0x20 self.reg_names[self.AX5051RegisterNames.IFFREQLO] =0x00 self.reg_names[self.AX5051RegisterNames.ADCMISC] =0x01 self.reg_names[self.AX5051RegisterNames.AGCTARGET] =0x0e self.reg_names[self.AX5051RegisterNames.AGCATTACK] =0x11 self.reg_names[self.AX5051RegisterNames.AGCDECAY] =0x0e self.reg_names[self.AX5051RegisterNames.CICDEC] =0x3f self.reg_names[self.AX5051RegisterNames.DATARATEHI]=0x19 self.reg_names[self.AX5051RegisterNames.DATARATELO]=0x66 self.reg_names[self.AX5051RegisterNames.TMGGAINHI] =0x01 self.reg_names[self.AX5051RegisterNames.TMGGAINLO] =0x96 self.reg_names[self.AX5051RegisterNames.PHASEGAIN] =0x03 self.reg_names[self.AX5051RegisterNames.FREQGAIN] =0x04 self.reg_names[self.AX5051RegisterNames.FREQGAIN2] =0x0a self.reg_names[self.AX5051RegisterNames.AMPLGAIN] =0x06 self.reg_names[self.AX5051RegisterNames.AGCMANUAL] =0x00 self.reg_names[self.AX5051RegisterNames.ADCDCLEVEL]=0x10 self.reg_names[self.AX5051RegisterNames.RXMISC] =0x35 self.reg_names[self.AX5051RegisterNames.FSKDEV2] =0x00 self.reg_names[self.AX5051RegisterNames.FSKDEV1] =0x31 self.reg_names[self.AX5051RegisterNames.FSKDEV0] =0x27 self.reg_names[self.AX5051RegisterNames.TXPWR] =0x03 self.reg_names[self.AX5051RegisterNames.TXRATEHI] =0x00 self.reg_names[self.AX5051RegisterNames.TXRATEMID] =0x51 self.reg_names[self.AX5051RegisterNames.TXRATELO] =0xec self.reg_names[self.AX5051RegisterNames.TXDRIVER] =0x88 def initTransceiver(self, frequency_standard): logdbg('initTransceiver: frequency_standard=%s' % frequency_standard) self.DataStore.setFrequencyStandard(frequency_standard) self.configureRegisterNames() # calculate the frequency then set frequency registers freq = self.DataStore.TransceiverSettings.Frequency loginf('base frequency: %d' % freq) freqVal = long(freq / 16000000.0 * 16777216.0) corVec = [None] self.shid.readConfigFlash(0x1F5, 4, corVec) corVal = corVec[0][0] << 8 corVal |= corVec[0][1] corVal <<= 8 corVal |= corVec[0][2] corVal <<= 8 corVal |= corVec[0][3] loginf('frequency correction: %d (0x%x)' % (corVal,corVal)) freqVal += corVal if not (freqVal % 2): freqVal += 1 loginf('adjusted frequency: %d (0x%x)' % (freqVal,freqVal)) self.reg_names[self.AX5051RegisterNames.FREQ3] = (freqVal >>24) & 0xFF self.reg_names[self.AX5051RegisterNames.FREQ2] = (freqVal >>16) & 0xFF self.reg_names[self.AX5051RegisterNames.FREQ1] = (freqVal >>8) & 0xFF self.reg_names[self.AX5051RegisterNames.FREQ0] = (freqVal >>0) & 0xFF logdbg('frequency registers: %x %x %x %x' % ( self.reg_names[self.AX5051RegisterNames.FREQ3], self.reg_names[self.AX5051RegisterNames.FREQ2], self.reg_names[self.AX5051RegisterNames.FREQ1], self.reg_names[self.AX5051RegisterNames.FREQ0])) # figure out the transceiver id buf = [None] self.shid.readConfigFlash(0x1F9, 7, buf) tid = buf[0][5] << 8 tid += buf[0][6] loginf('transceiver identifier: %d (0x%04x)' % (tid,tid)) self.DataStore.setDeviceID(tid) # figure out the transceiver serial number sn = str("%02d"%(buf[0][0])) sn += str("%02d"%(buf[0][1])) sn += str("%02d"%(buf[0][2])) sn += str("%02d"%(buf[0][3])) sn += str("%02d"%(buf[0][4])) sn += str("%02d"%(buf[0][5])) sn += str("%02d"%(buf[0][6])) loginf('transceiver serial: %s' % sn) self.DataStore.setTransceiverSerNo(sn) for r in self.reg_names: self.shid.writeReg(r, self.reg_names[r]) def setup(self, frequency_standard, vendor_id, product_id, device_id, serial, comm_interval=3): self.DataStore.setCommModeInterval(comm_interval) self.shid.open(vendor_id, product_id, device_id, serial) self.initTransceiver(frequency_standard) self.DataStore.setTransceiverPresent(True) def teardown(self): self.shid.close() # FIXME: make this thread-safe def getWeatherData(self): return self.DataStore.CurrentWeather # FIXME: make this thread-safe def getLastStat(self): return self.DataStore.LastStat # FIXME: make this thread-safe def getConfigData(self): return self.DataStore.StationConfig def startCachingHistory(self, since_ts=0, num_rec=0): self.history_cache.clear_records() if since_ts is None: since_ts = 0 self.history_cache.since_ts = since_ts if num_rec > WS28xxDriver.max_records - 2: num_rec = WS28xxDriver.max_records - 2 self.history_cache.num_rec = num_rec self.command = EAction.aGetHistory def stopCachingHistory(self): self.command = None def getUncachedHistoryCount(self): return self.history_cache.num_outstanding_records def getNextHistoryIndex(self): return self.history_cache.next_index def getNumHistoryScanned(self): return self.history_cache.num_scanned def getLatestHistoryIndex(self): return self.DataStore.LastStat.LatestHistoryIndex def getHistoryCacheRecords(self): return self.history_cache.records def clearHistoryCache(self): self.history_cache.clear_records() def startRFThread(self): if self.child is not None: return logdbg('startRFThread: spawning RF thread') self.running = True self.child = threading.Thread(target=self.doRF) self.child.setName('RFComm') self.child.setDaemon(True) self.child.start() def stopRFThread(self): self.running = False logdbg('stopRFThread: waiting for RF thread to terminate') self.child.join(self.thread_wait) if self.child.isAlive(): logerr('unable to terminate RF thread after %d seconds' % self.thread_wait) else: self.child = None def isRunning(self): return self.running def doRF(self): try: logdbg('setting up rf communication') self.doRFSetup() logdbg('starting rf communication') while self.running: self.doRFCommunication() except Exception, e: logerr('exception in doRF: %s' % e) if weewx.debug: log_traceback(dst=syslog.LOG_DEBUG) self.running = False raise finally: logdbg('stopping rf communication') # it is probably not necessary to have two setPreamblePattern invocations. # however, HeavyWeatherPro seems to do it this way on a first time config. # doing it this way makes configuration easier during a factory reset and # when re-establishing communication with the station sensors. def doRFSetup(self): self.shid.execute(5) self.shid.setPreamblePattern(0xaa) self.shid.setState(0) time.sleep(1) self.shid.setRX() self.shid.setPreamblePattern(0xaa) self.shid.setState(0x1e) time.sleep(1) self.shid.setRX() self.setSleep(0.085,0.005) def doRFCommunication(self): time.sleep(self.firstSleep) self.pollCount = 0 while self.running: StateBuffer = [None] self.shid.getState(StateBuffer) self.pollCount += 1 if StateBuffer[0][0] == 0x16: break time.sleep(self.nextSleep) else: return DataLength = [0] DataLength[0] = 0 FrameBuffer=[0] FrameBuffer[0]=[0]*0x03 self.shid.getFrame(FrameBuffer, DataLength) try: self.generateResponse(FrameBuffer, DataLength) self.shid.setFrame(FrameBuffer[0], DataLength[0]) except BadResponse, e: logerr('generateResponse failed: %s' % e) except DataWritten, e: logdbg('SetTime/SetConfig data written') self.shid.setTX() # these are for diagnostics and debugging def setSleep(self, firstsleep, nextsleep): self.firstSleep = firstsleep self.nextSleep = nextsleep def timing(self): s = self.firstSleep + self.nextSleep * (self.pollCount - 1) return 'sleep=%s first=%s next=%s count=%s' % ( s, self.firstSleep, self.nextSleep, self.pollCount)
Java
# frozen_string_literal: true RSpec.shared_examples 'vcs: having remote' do describe '#remote' do it 'sets @remote' do object.remote = 'some-value' expect(object.instance_variable_get(:@remote)).to eq 'some-value' end end describe '#remote' do subject(:remote) { object.remote } let(:remote_class) { object.send(:remote_class) } before do allow(object).to receive(:remote_file_id).and_return 'remote-id' allow(remote_class).to receive(:new).and_return 'new-instance' hook if defined?(hook) object.remote end it 'returns an instance of remote class' do expect(remote_class).to have_received(:new).with('remote-id') end it 'sets @remote to new instance' do expect(object.instance_variable_get(:@remote)).to eq 'new-instance' end context 'when @remote is already set' do let(:hook) { object.instance_variable_set(:@remote, 'existing-value') } it { is_expected.to eq 'existing-value' } end end describe '#reload' do before do allow(object).to receive(:reset_remote) allow(object.class).to receive(:find) object.reload end it { expect(object).to have_received(:reset_remote) } it 'reloads the object from database' do expect(object.class).to have_received(:find) end end describe '#reset_remote' do subject(:reset_remote) { object.send(:reset_remote) } before do object.instance_variable_set(:@remote, 'some-value') end it 'resets @remote to nil' do reset_remote expect(object.instance_variable_get(:@remote)).to eq nil end end describe '#remote_class' do subject { object.send(:remote_class) } it { is_expected.to eq Providers::GoogleDrive::FileSync } end end
Java
// NOTE: nbApp is defined in app.js nbApp.directive("languageContainerDirective", function() { return { restrict : 'E', templateUrl : 'js/templates/language-container.html', scope: { color: "@", language: "@", reading: "@", writing: "@", listening: "@", speaking: "@", flag: "@", }, link: function(scope, element, attrs) { scope.color = attrs.color; scope.language = attrs.language; scope.reading = attrs.reading; scope.writing = attrs.writing; scope.listening = attrs.listening; scope.speaking = attrs.speaking; scope.flag = attrs.flag; scope.$watch('language', function(nV, oV) { if(nV){ RadarChart.defaultConfig.color = function() {}; RadarChart.defaultConfig.radius = 3; RadarChart.defaultConfig.w = 250; RadarChart.defaultConfig.h = 250; /* * 0 - No Practical Proficiency * 1 - Elementary Proficiency * 2 - Limited Working Proficiency * 3 - Minimum Professional Proficiency * 4 - Full Professional Proficiency * 5 - Native or Bilingual Proficiency Read: the ability to read and understand texts written in the language Write: the ability to formulate written texts in the language Listen: the ability to follow and understand speech in the language Speak: the ability to produce speech in the language and be understood by its speakers. */ var data = [ { className: attrs.language, // optional can be used for styling axes: [ {axis: "Reading", value: attrs.reading}, {axis: "Writing", value: attrs.writing}, {axis: "Listening", value: attrs.listening}, {axis: "Speaking", value: attrs.speaking}, ] }, ]; function mapData() { return data.map(function(d) { return { className: d.className, axes: d.axes.map(function(axis) { return {axis: axis.axis, value: axis.value}; }) }; }); } // chart.config.w; // chart.config.h; // chart.config.axisText = true; // chart.config.levels = 5; // chart.config.maxValue = 5; // chart.config.circles = true; // chart.config.actorLegend = 1; var chart = RadarChart.chart(); var cfg = chart.config(); // retrieve default config cfg = chart.config({axisText: true, levels: 5, maxValue: 5, circles: true}); // retrieve default config var svg = d3.select('.' + attrs.language).append('svg') .attr('width', 250) .attr('height', 270); svg.append('g').classed('single', 1).datum(mapData()).call(chart); console.log('Rendering new language Radar Viz! --> ' + attrs.language); } }) } }; });
Java
//============================================================================= /*! return transposed _dsymatrix */ inline _dsymatrix t(const _dsymatrix& mat) {CPPL_VERBOSE_REPORT; #ifdef CPPL_DEBUG WARNING_REPORT; std::cerr << "This function call has no effect since the matrix is symmetric." << std::endl; #endif//CPPL_DEBUG return mat; } //============================================================================= /*! return its inverse matrix */ inline _dsymatrix i(const _dsymatrix& mat) {CPPL_VERBOSE_REPORT; dsymatrix mat_cp(mat); dsymatrix mat_inv(mat_cp.n); mat_inv.identity(); char UPLO('l'); CPPL_INT NRHS(mat.n), LDA(mat.n), *IPIV(new CPPL_INT[mat.n]), LDB(mat.n), LWORK(-1), INFO(1); double *WORK( new double[1] ); dsysv_(&UPLO, &mat_cp.n, &NRHS, mat_cp.array, &LDA, IPIV, mat_inv.array, &LDB, WORK, &LWORK, &INFO); LWORK = CPPL_INT(WORK[0]); delete [] WORK; WORK = new double[LWORK]; dsysv_(&UPLO, &mat_cp.n, &NRHS, mat_cp.array, &LDA, IPIV, mat_inv.array, &LDB, WORK, &LWORK, &INFO); delete [] WORK; delete [] IPIV; if(INFO!=0){ WARNING_REPORT; std::cerr << "Serious trouble happend. INFO = " << INFO << "." << std::endl; } return _(mat_inv); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// //============================================================================= /*! search the index of element having the largest absolute value in 0-based numbering system */ inline void idamax(CPPL_INT& i, CPPL_INT& j, const _dsymatrix& mat) {CPPL_VERBOSE_REPORT; dsymatrix newmat =mat; idamax(i, j, newmat); } //============================================================================= /*! return its largest absolute value */ inline double damax(const _dsymatrix& mat) {CPPL_VERBOSE_REPORT; dsymatrix newmat =mat; return damax(newmat); }
Java
package name.parsak.controller; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import name.parsak.api.Tcpip; import name.parsak.dto.UsrDptRole; import name.parsak.model.Department; import name.parsak.model.Menu; import name.parsak.model.Role; import name.parsak.model.User; import name.parsak.service.UserDBService; @Controller public class WebController { final private String project_name = "JWC"; final private String user_cookie_name = "user"; final private String blank = ""; final private int max_login_time = 7200; private UserDBService userDBService; @Autowired(required=true) @Qualifier(value="UserDBService") public void setUserDBService(UserDBService us){ this.userDBService = us; } // Create Admin User, if it doesn't exist @RequestMapping(value="setup") public String setup() { this.userDBService.setup(); return "redirect:/"; } // Default page @RequestMapping({"/", "index"}) public String index( Model model, @CookieValue(value = user_cookie_name, defaultValue = blank) String userid, @ModelAttribute(project_name)Menu menu) { if (! userid.equals(blank)) { int id = Integer.parseInt(userid); User user = this.userDBService.getUserById(id); if (user != null) { model.addAttribute("id", userid); model.addAttribute("name", user.getName()); model.addAttribute("lastname", user.getLastname()); model.addAttribute("email", user.getEmail()); if (this.userDBService.isUserAdmin(user)) { model.addAttribute("admin", "true"); } try { String name = menu.getName(); if (name != null) { this.userDBService.AddMenu(menu); } } catch (NullPointerException e) {} // menu.id is used to browse long menuid = menu.getId(); model.addAttribute("menu", this.userDBService.getMenuDtoById(menuid)); model.addAttribute("parent", menuid); model.addAttribute("menulist", this.userDBService.getMenuByParent(menuid)); } } return "index"; } // Login User @RequestMapping(value="login") public String login( Model model, @ModelAttribute(project_name)User u, HttpServletResponse response) { Long userid = u.getId(); // In case user enters /login without submitting a login form if (userid != 0) { User user = this.userDBService.getUser(u.getId(), u.getPassword()); if (user != null) { Cookie cookie = new Cookie(user_cookie_name, String.valueOf(user.getId())); cookie.setMaxAge(max_login_time); response.addCookie(cookie); } } return "redirect:/"; } // Logout User @RequestMapping(value="logout") public String logout( HttpServletResponse response) { Cookie cookie = new Cookie(user_cookie_name,blank); cookie.setMaxAge(0); response.addCookie(cookie); return "redirect:/"; } // Display All Users @RequestMapping(value="users") public String users( Model model, @CookieValue(value = user_cookie_name, defaultValue = blank) String userid) { if (! userid.equals(blank)) { int adminid = Integer.parseInt(userid); User admin = this.userDBService.getUserById(adminid); if (admin != null) { if (this.userDBService.isUserAdmin(admin)) { model.addAttribute("id", userid); model.addAttribute("admin", "true"); model.addAttribute("userslist", this.userDBService.listUsers()); return "users"; } } } return "redirect:/"; } // Display All Departments @RequestMapping(value="departments") public String departments( Model model, @CookieValue(value = user_cookie_name, defaultValue = blank) String userid) { if (! userid.equals(blank)) { int adminid = Integer.parseInt(userid); User admin = this.userDBService.getUserById(adminid); if (admin != null) { if (this.userDBService.isUserAdmin(admin)) { model.addAttribute("id", userid); model.addAttribute("admin", "true"); model.addAttribute("deptlist", this.userDBService.listDepartments()); model.addAttribute("rolelist", this.userDBService.listRoles()); return "departments"; } } } return "redirect:/"; } @RequestMapping(value="department") public String department( Model model, @CookieValue(value = user_cookie_name, defaultValue = blank) String userid, @ModelAttribute(project_name)UsrDptRole usrdptrole){ if (! userid.equals(blank)) { int adminid = Integer.parseInt(userid); User admin = this.userDBService.getUserById(adminid); if (admin != null) { if (this.userDBService.isUserAdmin(admin)) { model.addAttribute("id", userid); model.addAttribute("admin", "true"); String DeptName = usrdptrole.getDeptname(); System.out.println(">> Displaying "+DeptName); Department department = this.userDBService.getDepartmentByName(DeptName); model.addAttribute("department", department.getDepartment_name()); // model.addAttribute("deptrolelist", this.userDBService.getDepartmentUsers(department)); return "department"; } } } return "redirect:/"; } @RequestMapping(value="add_user") public String add_user( Model model, @ModelAttribute(project_name)User user, HttpServletResponse response) { String user_name = null; String user_lastname = null; String user_email = null; String user_password = null; try { user_name = user.getName(); user_lastname = user.getLastname(); user_email = user.getEmail(); user_password = user.getPassword(); } catch (NullPointerException e) {} if (user_name != null && user_lastname != null && user_email != null && user_password != null) { this.userDBService.addUser(user); } return "redirect:/users"; } @RequestMapping(value="update_user") public String update_user( Model model, @ModelAttribute(project_name)User user, HttpServletResponse response) { String user_name = null; String user_lastname = null; String user_email = null; String user_password = null; try { user_name = user.getName(); user_lastname = user.getLastname(); user_email = user.getEmail(); user_password = user.getPassword(); } catch (NullPointerException e) {} if (user_name != null && user_lastname != null && user_email != null && user_password != null) { this.userDBService.updateUser(user); } return "redirect:/user"+user.getId(); } // Assign UserRole to a user @RequestMapping(value="add_user_role") public String AddUserRole(@ModelAttribute(project_name)UsrDptRole usrdptrole) { String deptname = usrdptrole.getDeptname(); String rolename = usrdptrole.getRolename(); long userid = usrdptrole.getUserid(); if (userid != 0 && !deptname.equals(blank) && !rolename.equals(blank)) { User user = this.userDBService.getUserById((int) userid); Department department = this.userDBService.getDepartmentByName(deptname); Role role = this.userDBService.getRoleByName(rolename); this.userDBService.AddUserRole(user, department, role); } return "redirect:/user"+userid; } @RequestMapping(value="remove_userrole") public String RemoveUserRole(@ModelAttribute(project_name) UsrDptRole deptrole) { this.userDBService.removeUserRoleById(deptrole.getId()); return "redirect:/user"+deptrole.getUserid(); } // Display User{id} @RequestMapping(value="/user{id}") public String user( Model model, @CookieValue(value = user_cookie_name, defaultValue = blank) String userid, @PathVariable("id") int id) { if (! userid.equals(blank)) { int adminid = Integer.parseInt(userid); User admin = this.userDBService.getUserById(adminid); if (admin != null) { if (this.userDBService.isUserAdmin(admin)) { model.addAttribute("id", userid); model.addAttribute("admin", "true"); User user = this.userDBService.getUserById(id); model.addAttribute("userid",user.getId()); model.addAttribute("name",user.getName()); model.addAttribute("lastname",user.getLastname()); model.addAttribute("email",user.getEmail()); model.addAttribute("User", user); // To populate Edit Form model.addAttribute("deptrolelist",this.userDBService.getUsrDptRoles(user)); model.addAttribute("deptlist", this.userDBService.listDepartments()); model.addAttribute("rolelist", this.userDBService.listRoles()); return "user"; } } } return "redirect:/"; } // Remove User{id} @RequestMapping(value="/removeuser{id}") public String removeuser( Model model, @CookieValue(value = user_cookie_name, defaultValue = blank) String userid, @PathVariable("id") int id) { if (! userid.equals(blank)) { int adminid = Integer.parseInt(userid); User admin = this.userDBService.getUserById(adminid); if (admin != null) { if (this.userDBService.isUserAdmin(admin)) { model.addAttribute("id", userid); model.addAttribute("admin", "true"); User user = this.userDBService.getUserById(id); this.userDBService.RemoveUserRoleByUser(user); this.userDBService.removeUser(user); return "redirect:/users"; } } } return "redirect:/"; } @RequestMapping(value="/add_department") public String addNewDepartment(@ModelAttribute(project_name) UsrDptRole deptrole) { this.userDBService.AddDepartment(deptrole.getDeptname()); return "redirect:/departments"; } @RequestMapping(value="/add_role") public String addNewRole(@ModelAttribute(project_name) UsrDptRole deptrole) { this.userDBService.AddRole(deptrole.getRolename()); return "redirect:/departments"; } @RequestMapping(value="/api_test") public String test_api(Model model) { Tcpip tcpip = new Tcpip(); String response = tcpip.get("http://www.google.com"); model.addAttribute("response", response); return "api_test"; } }
Java
#pragma once // // njhseq - A library for analyzing sequence data // Copyright (C) 2012-2018 Nicholas Hathaway <nicholas.hathaway@umassmed.edu>, // // This file is part of njhseq. // // njhseq 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. // // njhseq 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 njhseq. If not, see <http://www.gnu.org/licenses/>. // // // alnInfoHolder.hpp // // Created by Nicholas Hathaway on 1/13/14. // #include "njhseq/alignment/alnCache/alnInfoHolderBase.hpp" #if __APPLE__ == 1 && __cpp_lib_shared_timed_mutex < 201402L && __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ <= 101106 #include <sharedMutex.h> #else #include <shared_mutex> #endif namespace njhseq { class alnInfoMasterHolder { public: // constructors alnInfoMasterHolder(); alnInfoMasterHolder(const gapScoringParameters & gapPars, const substituteMatrix & scoringArray); alnInfoMasterHolder(const std::string &masterDirName, const gapScoringParameters & gapPars, const substituteMatrix & scoringArray, bool verbose = false); // members std::unordered_map<std::string, alnInfoHolderBase<alnInfoLocal>> localHolder_; std::unordered_map<std::string, alnInfoHolderBase<alnInfoGlobal>> globalHolder_; std::hash<std::string> strH_; void clearHolders(); void addHolder(const gapScoringParameters & gapPars, const substituteMatrix & scoringArray); // reading void read(const std::string &masterDirName, bool verbose = false); // writing void write(const std::string &masterDirName, bool verbose = false); void mergeOtherHolder(const alnInfoMasterHolder & otherHolder); }; namespace alignment { static std::mutex alnCacheDirSearchLock; static std::unordered_map<std::string, std::unique_ptr<std::shared_timed_mutex>> alnCacheDirLocks; } // namespace alignment } // namespace njhseq
Java
#include "common_header.h" namespace { using ArrayType = std::vector<int>; /** Given a sorted array and a number x, find the pair in array whose sum is closest to x * * @reference https://www.geeksforgeeks.org/given-sorted-array-number-x-find-pair-array-whose-sum-closest-x/ * * Given a sorted array and a number x, find a pair in array whose sum is closest to x. * * @reference 2 Sum Closest * https://aaronice.gitbook.io/lintcode/high_frequency/2sum_closest * * Given an array nums of n integers, find two integers in nums such that the sum is * closest to a given number, target. Return the difference between the sum of the two * integers and the target. * * @reference Two elements whose sum is closest to zero * https://www.geeksforgeeks.org/two-elements-whose-sum-is-closest-to-zero/ */ auto ClosestSumPair_Sorted_TwoPointer(const ArrayType &elements, const ArrayType::value_type x) { assert(std::is_sorted(elements.cbegin(), elements.cend())); auto diff = std::numeric_limits<ArrayType::value_type>::max(); std::pair<ArrayType::value_type, ArrayType::value_type> output; if (not elements.empty()) { auto left = elements.cbegin(); auto right = std::prev(elements.cend()); while (left != right and diff) { const auto sum = *left + *right; const auto new_diff = std::abs(sum - x); if (new_diff < diff) { diff = new_diff; output = std::pair(*left, *right); } if (sum < x) { ++left; } else { --right; } } } return output; } inline auto ClosestSumPair_Sort(ArrayType elements, const ArrayType::value_type x) { std::sort(elements.begin(), elements.end()); return ClosestSumPair_Sorted_TwoPointer(elements, x); } /** * @reference 3Sum Closest * https://leetcode.com/problems/3sum-closest/ * * Given an array nums of n integers and an integer target, find three integers in nums * such that the sum is closest to target. Return the sum of the three integers. You may * assume that each input would have exactly one solution. */ auto ThreeSum(ArrayType nums, const int target) { std::sort(nums.begin(), nums.end()); int min_diff = INT_MAX; int result = 0; for (std::size_t i = 0; i < nums.size() and min_diff; ++i) { int left = i + 1; int right = nums.size() - 1; while (left < right) { const int sum = nums[i] + nums[left] + nums[right]; if (std::abs(target - sum) < min_diff) { min_diff = std::abs(target - sum); result = sum; } if (sum < target) { ++left; } else { --right; } } } return result; } /** * @reference Two Sum Less Than K * https://wentao-shao.gitbook.io/leetcode/two-pointers/1099.two-sum-less-than-k * * Given an array A of integers and integer K, return the maximum S such that there * exists i < j with A[i] + A[j] = S and S < K. If no i, j exist satisfying this * equation, return -1. */ auto TwoSumLessThan(ArrayType nums, const int K) { std::sort(nums.begin(), nums.end()); int left = 0; int right = nums.size() - 1; int result = -1; while (left < right) { const auto sum = nums[left] + nums[right]; if (sum >= K) { --right; } else { result = std::max(result, sum); ++left; } } return result; } }//namespace const ArrayType SAMPLE1 = {10, 22, 28, 29, 30, 40}; const ArrayType SAMPLE2 = {1, 3, 4, 7, 10}; const ArrayType SAMPLE3 = {1, 60, -10, 70, -80, 85}; THE_BENCHMARK(ClosestSumPair_Sorted_TwoPointer, SAMPLE1, 54); SIMPLE_TEST(ClosestSumPair_Sorted_TwoPointer, TestSample1, std::pair(22, 30), SAMPLE1, 54); SIMPLE_TEST(ClosestSumPair_Sorted_TwoPointer, TestSample2, std::pair(4, 10), SAMPLE2, 15); SIMPLE_TEST(ClosestSumPair_Sort, TestSample3, std::pair(-80, 85), SAMPLE3, 0); const ArrayType SAMPLE4 = {-1, 2, 1, -4}; THE_BENCHMARK(ThreeSum, SAMPLE4, 1); SIMPLE_TEST(ThreeSum, TestSample4, 2, SAMPLE4, 1); const ArrayType SAMPLE1L = {34, 23, 1, 24, 75, 33, 54, 8}; const ArrayType SAMPLE2L = {10, 20, 30}; THE_BENCHMARK(TwoSumLessThan, SAMPLE1L, 60); SIMPLE_TEST(TwoSumLessThan, TestSample1, 58, SAMPLE1L, 60); SIMPLE_TEST(TwoSumLessThan, TestSample2, -1, SAMPLE2L, 15);
Java
<!DOCTYPE html> <html lang="en" prefix="og: http://ogp.me/ns# fb: https://www.facebook.com/2008/fbml" > <head> <title>misc - jm33_ng</title> <!-- Using the latest rendering mode for IE --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://jm33.me/img/icon.png" rel="icon"> <meta name="author" content="jm33" /> <meta name="keywords" content="misc" /> <!-- Open Graph tags --> <meta property="og:site_name" content="jm33_ng" /> <meta property="og:type" content="website" /> <meta property="og:title" content="jm33_ng" /> <meta property="og:url" content="https://jm33.me" /> <meta property="og:description" content="jm33_ng" /> <!-- Bootstrap --> <link rel="stylesheet" href="https://jm33.me/theme/css/bootstrap.sandstone.min.css" type="text/css" /> <link href="https://jm33.me/theme/css/font-awesome.min.css" rel="stylesheet"> <link href="https://jm33.me/theme/css/pygments/monokai.css" rel="stylesheet"> <link rel="stylesheet" href="https://jm33.me/theme/css/style.css" type="text/css" /> <!-- FontAwesome --> <!-- --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <!-- Noto Sans SC font --> <!-- --> <link href="https://fonts.googleapis.com/css?family=Noto+Sans+SC&display=swap" rel="stylesheet"> <!-- Source Code Pro --> <link href="https://fonts.googleapis.com/css?family=Source+Code+Pro&display=swap" rel="stylesheet"> <!-- asciinema css --> <link rel="stylesheet" type="text/css" href="https://jm33.me/theme/css/asciinema-player.css" /> </head> <body> <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="https://jm33.me/" class="navbar-brand"> jm33_ng </a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav"> <li > <a href="https://jm33.me/category/cryptography.html">Cryptography</a> </li> <li > <a href="https://jm33.me/category/ctf.html">Ctf</a> </li> <li class="active" > <a href="https://jm33.me/category/misc.html">Misc</a> </li> <li > <a href="https://jm33.me/category/pentest.html">Pentest</a> </li> <li > <a href="https://jm33.me/category/programming.html">Programming</a> </li> <li > <a href="https://jm33.me/category/tools.html">Tools</a> </li> <li > <a href="https://jm33.me/category/vulnerabilities.html">Vulnerabilities</a> </li> </ul> <ul class="nav navbar-nav navbar-right"> </ul> </div> <!-- /.navbar-collapse --> </div> </div> <!-- /.navbar --> <!-- Banner --> <style> #banner { background-image:url("https://jm33.me/img/banner.webp"); } </style> <div id="banner"> <div class="container"> <div class="copy" style="border-radius: 4px"> <h1>jm33_ng</h1> <br> <p class="intro">an <s>infosec</s> newbie's <s>tech</s> blog</p> </div> </div> </div> <!-- End Banner --> <!-- Content Container --> <div class="container"> <div class="row"> <div class="col-sm-9"> <article> <h2><a href="https://jm33.me/sh4d0ws0cks-over-obfsproxy-scramblesuit.html">Sh4d0ws0cks Over Obfsproxy (Scramblesuit)</a></h2> <div class="well well-sm"> <footer class="post-info"> <span class="label label-default">Date</span> <span class="published"> <i class="fa fa-calendar"></i><time datetime="2016-05-16T00:00:00+08:00"> Mon 16 May 2016</time> </span> <span class="label label-default">Tags</span> <a href="https://jm33.me/tag/greatwall.html">Greatwall</a> / <a href="https://jm33.me/tag/obfsproxy.html">obfsproxy</a> / <a href="https://jm33.me/tag/scramblesuit.html">scramblesuit</a> / <a href="https://jm33.me/tag/dpi.html">DPI</a> / <a href="https://jm33.me/tag/censorship.html">censorship</a> / <a href="https://jm33.me/tag/openwrt.html">openwrt</a> / <a href="https://jm33.me/tag/pi.html">pi</a> </footer><!-- /.post-info --> </div> <div class="summary"><blockquote> <p>如果您看不懂英文,请点击<a href="/shi-yong-obfsproxy-scramblesuit-hun-yao-sh4d0ws0cksliu-liang.html">这里</a>以查看简体中文版本</p> </blockquote> <h2 id="get-obfsproxy-for-your-server">Get <em>obfsproxy</em> for your server</h2> <h3 id="tor-official-debianubuntu-repo"><em>TOR</em> official Debian/Ubuntu repo</h3> <ul> <li> <p>You can find your repo <a href="https://www.torproject.org/docs/debian.html.en" title="Get your repo">here</a></p> </li> <li> <p>For Debian Jessie users like me, simply add the following to your <code>/etc/apt/sources.list</code></p> </li> </ul> <div class="highlight"><pre><span></span>deb http://deb.torproject.org/torproject.org jessie main deb-src http://deb.torproject.org …</pre></div> <p><small><a href="https://jm33.me/sh4d0ws0cks-over-obfsproxy-scramblesuit.html#disqus_thread" >View comments</a>.</small></p> <a class="btn btn-default btn-xs" href="https://jm33.me/sh4d0ws0cks-over-obfsproxy-scramblesuit.html">more ...</a> </div> </article> <hr/> <article> <h2><a href="https://jm33.me/glowing-bear.html">Glowing Bear</a></h2> <div class="well well-sm"> <footer class="post-info"> <span class="label label-default">Date</span> <span class="published"> <i class="fa fa-calendar"></i><time datetime="2016-05-09T00:00:00+08:00"> Mon 09 May 2016</time> </span> <span class="label label-default">Tags</span> <a href="https://jm33.me/tag/misc.html">Misc</a> / <a href="https://jm33.me/tag/glowing-bear.html">Glowing Bear</a> / <a href="https://jm33.me/tag/irc.html">IRC</a> / <a href="https://jm33.me/tag/weechat.html">weechat</a> / <a href="https://jm33.me/tag/ssl.html">SSL</a> </footer><!-- /.post-info --> </div> <div class="summary"><h2 id="get-certs-ready">Get certs ready</h2> <ul> <li> <p>Get Letsencrypt with <code>git clone https://github.com/letsencrypt/letsencrypt</code></p> </li> <li> <p>Enter git directory, and <code>./letsencrypt-auto certonly -d &lt;your domain&gt;</code></p> </li> <li> <p>Find your certs in <code>cd /etc/letsencrypt/live/&lt;your domain&gt;</code>, you will see the following</p> </li> </ul> <p><img alt="certs" src="/img/certs.png"></p> <ul> <li>You will need to combine <code>privkey.pem</code> and <code>fullchain.pem</code>, fire up the …</li></ul> <p><small><a href="https://jm33.me/glowing-bear.html#disqus_thread" >View comments</a>.</small></p> <a class="btn btn-default btn-xs" href="https://jm33.me/glowing-bear.html">more ...</a> </div> </article> <hr/> <ul class="pagination"> <li class="prev"><a href="https://jm33.me/category/misc12.html">&laquo;</a> </li> <li class=""><a href="https://jm33.me/category/misc.html">1</a></li> <li class=""><a href="https://jm33.me/category/misc2.html">2</a></li> <li class=""><a href="https://jm33.me/category/misc3.html">3</a></li> <li class=""><a href="https://jm33.me/category/misc4.html">4</a></li> <li class=""><a href="https://jm33.me/category/misc5.html">5</a></li> <li class=""><a href="https://jm33.me/category/misc6.html">6</a></li> <li class=""><a href="https://jm33.me/category/misc7.html">7</a></li> <li class=""><a href="https://jm33.me/category/misc8.html">8</a></li> <li class=""><a href="https://jm33.me/category/misc9.html">9</a></li> <li class=""><a href="https://jm33.me/category/misc10.html">10</a></li> <li class=""><a href="https://jm33.me/category/misc11.html">11</a></li> <li class=""><a href="https://jm33.me/category/misc12.html">12</a></li> <li class="active"><a href="https://jm33.me/category/misc13.html">13</a></li> <li class=""><a href="https://jm33.me/category/misc14.html">14</a></li> <li class="next"><a href="https://jm33.me/category/misc14.html">&raquo;</a></li> </ul> </div> <div class="col-sm-3" id="sidebar"> <aside> <div id="aboutme"> <p> <img width="100%" class="img-thumbnail" src="https://jm33.me//img/profile.webp"/> </p> <p> <strong>About jm33</strong><br/> <h3>Who</h3> <ul> <li><strong><em>weaponizer / linux user / vimer / pythonist / gopher / gray hat / male / siscon / freak</em></strong></li> </ul> <h3>Contact</h3> <ul> <li> <p><strong><a href="/pages/jm33-ngs-cv.html" target="_blank" title="Check my CV">Online CV</a></strong></p> </li> <li> <p><strong><a href="/jm33@jm33.me.asc" target="_blank" title="My GPG public key">3A5DBF07</a></strong></p> </li> <li> <p><strong><a href="https://jm33.me/pages/got-something-to-say.html" target="_blank">Leave a message</a></strong></p> </li> </ul> </p> </div><!-- Sidebar --> <section class="well well-sm"> <ul class="list-group list-group-flush"> <!-- Sidebar/Social --> <li class="list-group-item"> <h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Social</span></h4> <ul class="list-group" id="social"> <li class="list-group-item"><a href="https://twitter.com/jm33_m0"><i class="fa fa-twitter-square fa-lg"></i> Twitter</a></li> <li class="list-group-item"><a href="https://cn.linkedin.com/in/jim-mee-80ba7a111"><i class="fa fa-linkedin-square fa-lg"></i> LinkedIn</a></li> <li class="list-group-item"><a href="https://stackoverflow.com/users/5230333/jm33-m0"><i class="fa fa-stack-overflow fa-lg"></i> StackOverflow</a></li> <li class="list-group-item"><a href="https://github.com/jm33-m0"><i class="fa fa-github-square fa-lg"></i> Github</a></li> </ul> </li> <!-- End Sidebar/Social --> <!-- Sidebar/Recent Posts --> <li class="list-group-item"> <h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Recent Posts</span></h4> <ul class="list-group" id="recentposts"> <li class="list-group-item"><a href="https://jm33.me/digging-into-a-macos-kernel-panic.html">Digging Into A macOS Kernel Panic</a></li> <li class="list-group-item"><a href="https://jm33.me/killer-wireless-kills-my-network.html">Killer Wireless Kills My Network</a></li> <li class="list-group-item"><a href="https://jm33.me/fa-da-cai.html">发大财</a></li> <li class="list-group-item"><a href="https://jm33.me/tan-tan-career.html">谈谈career</a></li> <li class="list-group-item"><a href="https://jm33.me/enabling-new-pgp-key.html">Enabling New PGP Key</a></li> </ul> </li> <!-- End Sidebar/Recent Posts --> <!-- Sidebar/Tag Cloud --> <li class="list-group-item"> <a href="https://jm33.me/tags.html"><h4><i class="fa fa-tags fa-lg"></i><span class="icon-label">Tags</span></h4></a> <ul class="list-group list-inline tagcloud" id="tags"> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/443.html">443</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/active-directory.html">active directory</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/ad.html">ad</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/announcement.html">announcement</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/anonymity.html">anonymity</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/antivirus.html">antivirus</a> </li> <li class="list-group-item tag-2"> <a href="https://jm33.me/tag/anyconnect.html">anyconnect</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/apache.html">apache</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/assembly.html">assembly</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/baidu.html">baidu</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/blackhat.html">blackhat</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/buffer-overflow.html">buffer overflow</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/c.html">C#</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/career.html">career</a> </li> <li class="list-group-item tag-2"> <a href="https://jm33.me/tag/censorship.html">censorship</a> </li> <li class="list-group-item tag-2"> <a href="https://jm33.me/tag/change.html">change</a> </li> <li class="list-group-item tag-2"> <a href="https://jm33.me/tag/cisco.html">cisco</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/code-maintainance.html">code maintainance</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/compton.html">compton</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/coursera.html">Coursera</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/crypto.html">crypto</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/cryptography.html">cryptography</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/ctf.html">ctf</a> </li> <li class="list-group-item tag-2"> <a href="https://jm33.me/tag/cve.html">CVE</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/cve-2018-18955.html">CVE-2018-18955</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/cve-2018-7750.html">CVE-2018-7750</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/dairy.html">dairy</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/diary.html">Diary</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/dnswu-ran.html">DNS污染</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/dpi.html">DPI</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/email.html">email</a> </li> <li class="list-group-item tag-2"> <a href="https://jm33.me/tag/emp3r0r.html">emp3r0r</a> </li> <li class="list-group-item tag-2"> <a href="https://jm33.me/tag/exploit.html">exploit</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/file-transfer.html">file transfer</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/gf.html">gf</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/gfw.html">gfw</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/github.html">github</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/glowing-bear.html">Glowing Bear</a> </li> <li class="list-group-item tag-2"> <a href="https://jm33.me/tag/golang.html">golang</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/google-hacking.html">google hacking</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/great-wall.html">great wall</a> </li> <li class="list-group-item tag-1"> <a href="https://jm33.me/tag/greatwall.html">greatwall</a> </li> <li class="list-group-item tag-2"> <a href="https://jm33.me/tag/hacking.html">hacking</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/hacking-tool.html">hacking tool</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/hiwifi.html">HiWiFi</a> </li> <li class="list-group-item tag-2"> <a href="https://jm33.me/tag/http2.html">HTTP2</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/https.html">https</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/injection.html">injection</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/irc.html">IRC</a> </li> <li class="list-group-item tag-2"> <a href="https://jm33.me/tag/ji-lu-you.html">极路由</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/joomla.html">Joomla</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/kcp.html">KCP</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/kcptun.html">kcptun</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/kernel.html">kernel</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/killer.html">killer</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/lede.html">lede</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/life.html">life</a> </li> <li class="list-group-item tag-1"> <a href="https://jm33.me/tag/linux.html">linux</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/linux-kernel.html">linux kernel</a> </li> <li class="list-group-item tag-1"> <a href="https://jm33.me/tag/lkm.html">lkm</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/local-privilege-escalation.html">local privilege escalation</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/log-cleaner.html">log cleaner</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/login-bypass.html">login bypass</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/lpe.html">LPE</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/macos.html">macos</a> </li> <li class="list-group-item tag-2"> <a href="https://jm33.me/tag/mass-exploit.html">mass exploit</a> </li> <li class="list-group-item tag-2"> <a href="https://jm33.me/tag/mec.html">mec</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/memory-layout.html">memory layout</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/mentohust.html">mentohust</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/misc.html">Misc</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/multi-threaded-crawler.html">multi-threaded crawler</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/mysql.html">mysql</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/namespace.html">namespace</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/netcat.html">netcat</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/network.html">network</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/nic.html">nic</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/nikto.html">nikto</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/nmap.html">nmap</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/obfs4.html">obfs4</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/obfsproxy.html">obfsproxy</a> </li> <li class="list-group-item tag-2"> <a href="https://jm33.me/tag/ocserv.html">ocserv</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/openwrt.html">openwrt</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/osin.html">OSIN</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/paramiko.html">paramiko</a> </li> <li class="list-group-item tag-1"> <a href="https://jm33.me/tag/pentest.html">pentest</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/pep8.html">pep8</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/pgp.html">PGP</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/php.html">php</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/pi.html">pi</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/plan.html">plan</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/port-forwarding.html">port-forwarding</a> </li> <li class="list-group-item tag-1"> <a href="https://jm33.me/tag/post-exploitation.html">post-exploitation</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/privilege-escalation.html">privilege escalation</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/programming.html">programming</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/project.html">project</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/proxy.html">proxy</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/ptrace.html">ptrace</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/ptrace_traceme.html">PTRACE_TRACEME</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/pythonic.html">pythonic</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/quote.html">quote</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/rce.html">RCE</a> </li> <li class="list-group-item tag-2"> <a href="https://jm33.me/tag/reverse-shell.html">reverse shell</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/reversing.html">reversing</a> </li> <li class="list-group-item tag-1"> <a href="https://jm33.me/tag/rootkit.html">rootkit</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/router.html">router</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/s2-045.html">s2-045</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/scanner.html">scanner</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/scramblesuit.html">scramblesuit</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/seed-lab.html">SEED lab</a> </li> <li class="list-group-item tag-2"> <a href="https://jm33.me/tag/shadowsocks.html">shadowsocks</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/shadowsocks-plus.html">shadowsocks-plus</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/skydog.html">skydog</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/smartphone.html">smartphone</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/socket.html">socket</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/sqli.html">sqli</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/sqlmap.html">sqlmap</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/ss.html">SS</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/sshd.html">sshd</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/ssl.html">SSL</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/stanford.html">Stanford</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/sudo.html">sudo</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/systemd.html">systemd</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/thomas-jefferson.html">Thomas Jefferson</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/tmux.html">TMUX</a> </li> <li class="list-group-item tag-2"> <a href="https://jm33.me/tag/tools.html">tools</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/tor.html">Tor</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/trasparent-proxy.html">trasparent proxy</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/vim.html">vim</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/virtualbox.html">virtualbox</a> </li> <li class="list-group-item tag-2"> <a href="https://jm33.me/tag/vpn.html">vpn</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/wayland.html">wayland</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/web.html">web</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/weechat.html">weechat</a> </li> <li class="list-group-item tag-3"> <a href="https://jm33.me/tag/windows.html">windows</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/windows-domain.html">windows domain</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/windows-server.html">windows server</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/xfce4.html">xfce4</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/xfwm.html">xfwm</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/xhost.html">xhost</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/xml.html">xml</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/xmpp.html">xmpp</a> </li> <li class="list-group-item tag-4"> <a href="https://jm33.me/tag/zoomeye.html">zoomeye</a> </li> </ul> </li> <!-- End Sidebar/Tag Cloud --> </ul> </section> <!-- End Sidebar --> </aside> </div> </div> </div> <!-- End Content Container --> <footer> <div class="container"> <hr> <div class="row"> <div class="col-xs-10">&copy; 2020 jm33-ng - <a href="/pages/about.html" target="_blank" title="about this site"> About this site</a> <p><small> <a rel="license" href="https://creativecommons.org/licenses/by-nc/4.0/deed.en"><img alt="Creative Commons License" style="border-width:0" src="//i.creativecommons.org/l/by-nc/4.0/80x15.png" /></a> Content licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-nc/4.0/deed.en">Creative Commons Attribution-NonCommercial 4.0 International License</a>, except where indicated otherwise. </small></p> <p><small>Images hosted on this site are either my own or from Google Image Search</small></p> </div> </div> </div> </footer> <script src="https://jm33.me/theme/js/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="https://jm33.me/theme/js/bootstrap.min.js"></script> <!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) --> <script src="https://jm33.me/theme/js/respond.min.js"></script> <script src="https://jm33.me/theme/js/bodypadding.js"></script> <!-- Disqus --> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = 'jm33-m0'; // required: replace example with your forum shortname /* * * DON'T EDIT BELOW THIS LINE * * */ (function () { var s = document.createElement('script'); s.async = true; s.type = 'text/javascript'; s.src = '//' + disqus_shortname + '.disqus.com/count.js'; (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s); }()); </script> <!-- End Disqus Code --> <!-- custom part --> <!-- asciinema js --> <script src="https://jm33.me/theme/js/asciinema-player.js" async></script> <!-- back-to-top starts --> <style> #topBtn { display: none; position: fixed; bottom: 20px; right: 30px; z-index: 99; border: none; outline: none; background-color: rgba(62, 63, 58, 0.9); color: white; cursor: pointer; padding: 10px; border-radius: 200px; font-size: 40px; line-height: 40px; } #topBtn:hover { background-color: #3e3f3a; } </style> <button onclick="topFunction()" id="topBtn" title="Go to top"><i class="fa fa-arrow-up" aria-hidden="true"></i></button> <script> // When the user scrolls down 20px from the top of the document, show the button window.onscroll = function() { scrollFunction() }; function scrollFunction() { if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) { document.getElementById("topBtn").style.display = "block"; } else { document.getElementById("topBtn").style.display = "none"; } } // When the user clicks on the button, scroll to the top of the document function topFunction() { document.body.scrollTop = 0; document.documentElement.scrollTop = 0; } </script> <!-- back-to-top ends--> </body> </html>
Java
module XmlResolution # Most named exceptions in the XmlResolution service we subclass here # to one of the HTTP classes. Libraries are designed specifically # to be unaware of this mapping: they only use their specific low level # exceptions classes. # # In general, if we catch an HttpError at our top level app, we can # blindly return the error message to the client as a diagnostic, # and log it. The fact that we're naming these exceptions means # we're being careful not to leak information, and still be helpful # to the Client. They are very specific messages; tracebacks will # not be required. # # When we get an un-named exception, however, the appropriate thing # to do is to just supply a very terse message to the client (e.g., # we wouldn't like to expose errors from an ORM that said something # like "password 'topsecret' failed in mysql open"). We *will* want # to log the full error message, and probably a backtrace to boot. class HttpError < StandardError; def client_message "#{status_code} #{status_text} - #{message.chomp('.')}." end end # Most of the following comments are pretty darn obvious - they # are included for easy navigation in the generated rdoc html files. # Http400Error's group named exceptions as something the client did # wrong. It is subclassed from the HttpError exception. class Http400Error < HttpError; end # Http400 exception: 400 Bad Request - it is subclassed from Http400Error. class Http400 < Http400Error def status_code; 400; end def status_text; "Bad Request"; end end # Http401 exception: 401 Unauthorized - it is subclassed from Http400Error. class Http401 < Http400Error def status_code; 401; end def status_text; "Unauthorized"; end end # Http403 exception: 403 Forbidden - it is subclassed from Http400Error. class Http403 < Http400Error def status_code; 403; end def status_text; "Forbidden"; end end # Http404 exception: 404 Not Found - it is subclassed from Http400Error. class Http404 < Http400Error def status_code; 404; end def status_text; "Not Found"; end end # Http405 exception: 405 Method Not Allowed - it is subclassed from Http400Error. class Http405 < Http400Error def status_code; 405; end def status_text; "Method Not Allowed"; end end # Http406 exception: 406 Not Acceptable - it is subclassed from Http400Error. class Http406 < Http400Error def status_code; 406; end def status_text; "Not Acceptable"; end end # Http408 exception: 408 Request Timeout - it is subclassed from Http400Error. class Http408 < Http400Error def status_code; 408; end def status_text; "Request Timeout"; end end # Http409 exception: 409 Conflict - it is subclassed from Http400Error. class Http409 < Http400Error def status_code; 409; end def status_text; "Conflict"; end end # Http410 exception: 410 Gone - it is subclassed from Http400Error. class Http410 < Http400Error def status_code; 410; end def status_text; "Gone"; end end # Http411 exception: 411 Length Required - it is subclassed from Http400Error. class Http411 < Http400Error def status_code; 411; end def status_text; "Length Required"; end end # Http412 exception: 412 Precondition Failed - it is subclassed from Http400Error. class Http412 < Http400Error def status_code; 412; end def status_text; "Precondition Failed"; end end # Http413 exception: 413 Request Entity Too Large - it is subclassed from Http400Error. class Http413 < Http400Error def status_code; 413; end def status_text; "Request Entity Too Large"; end end # Http414 exception: 414 Request-URI Too Long - it is subclassed from Http400Error. class Http414 < Http400Error def status_code; 414; end def status_text; "Request-URI Too Long"; end end # Http415 exception: 415 Unsupported Media Type - it is subclassed from Http400Error. class Http415 < Http400Error def status_code; 415; end def status_text; "Unsupported Media Type"; end end # Http500Error's group errors that are the server's fault. # It is subclassed from the HttpError exception. class Http500Error < HttpError; end # Http500 exception: 500 Internal Service Error - it is subclassed from Http500Error. class Http500 < Http500Error def status_code; 500; end def status_text; "Internal Service Error"; end end # Http501 exception: 501 Not Implemented - it is subclassed from Http500Error. class Http501 < Http500Error def status_code; 501; end def status_text; "Not Implemented"; end end # Http503 exception: 503 Service Unavailable - it is subclassed from Http500Error. class Http503 < Http500Error def status_code; 503; end def status_text; "Service Unavailable"; end end # Http505 exception: 505 HTTP Version Not Supported - it is subclassed from Http500Error. class Http505 < Http500Error def status_code; 505; end def status_text; "HTTP Version Not Supported"; end end # BadXmlDocument exception, client's fault (subclasses Http400): Instance document could not be parsed.. class BadXmlDocument < Http415; end # BadBadXmlDocument exception, client's fault (subclasses BadXmlDocument): ..it *really* could not be parsed class BadBadXmlDocument < BadXmlDocument; end # InadequateDataError exception, client's fault (subclasses Http400): Problem with uploaded data (e.g. length 0) class InadequateDataError < Http400; end # BadCollectionID exception, client's fault (subclasses Http400): PUT of a Collection ID wasn't suitable class BadCollectionID < Http400; end # BadXmlVersion exception, client's fault (subclasses Http415): Unsupported XML version (only 1.0) class BadXmlVersion < Http415; end # TooManyDarnSchemas exception, client's fault (subclasses Http400): Possible denial of service - infinite train of schemas class TooManyDarnSchemas < Http400; end # LockError exception, server's fault (subclasses Http500): Timed out trying to get a locked file class LockError < Http500; end # ConfigurationError exception, server's fault (subclasses Http500): Something wasn't set up correctly class ConfigurationError < Http500; end # ResolverError exception, server's fault (subclasses Http500): Result of a programming error class ResolverError < Http500; end # The LocationError is caught internally, and is used to indicate that # the fetch of a Schema could not be performed because the location # URL scheme was not supported. This results in reporting broken # link, and is normally not very important: there are many other # schemas to report on. # # However, if this exception was raised to the top level, we do # not want to pass the information to the user. That's why it is not # assigned to an HttpError subclass - we *want* a logged backtrace in # that case. class LocationError < StandardError; end end # of module
Java
/*************************************************************************** * Copyright © 2010-2011 Jonathan Thomas <echidnaman@kubuntu.org> * * Heavily inspired by Synaptic library code ;-) * * * * 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) version 3 or any later version * * accepted by the membership of KDE e.V. (or its successor approved * * by the membership of KDE e.V.), which shall act as a proxy * * defined in Section 14 of version 3 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, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ //krazy:excludeall=qclasses // Qt-only library, so things like QUrl *should* be used #include "package.h" // Qt includes #include <QtCore/QFile> #include <QtCore/QStringBuilder> #include <QtCore/QStringList> #include <QtCore/QTemporaryFile> #include <QtCore/QTextStream> #include <QDebug> // Apt includes #include <apt-pkg/algorithms.h> #include <apt-pkg/debversion.h> #include <apt-pkg/depcache.h> #include <apt-pkg/indexfile.h> #include <apt-pkg/init.h> #include <apt-pkg/pkgrecords.h> #include <apt-pkg/sourcelist.h> #include <apt-pkg/strutl.h> #include <apt-pkg/tagfile.h> #include <apt-pkg/versionmatch.h> #include <algorithm> // Own includes #include "backend.h" #include "cache.h" #include "config.h" // krazy:exclude=includes #include "markingerrorinfo.h" namespace QApt { class PackagePrivate { public: PackagePrivate(pkgCache::PkgIterator iter, Backend *back) : packageIter(iter) , backend(back) , state(0) , staticStateCalculated(false) , foreignArchCalculated(false) { } ~PackagePrivate() { } pkgCache::PkgIterator packageIter; QApt::Backend *backend; int state; bool staticStateCalculated; bool isForeignArch; bool foreignArchCalculated; pkgCache::PkgFileIterator searchPkgFileIter(QLatin1String label, const QString &release) const; QString getReleaseFileForOrigin(QLatin1String label, const QString &release) const; // Calculate state flags that cannot change void initStaticState(const pkgCache::VerIterator &ver, pkgDepCache::StateCache &stateCache); }; pkgCache::PkgFileIterator PackagePrivate::searchPkgFileIter(QLatin1String label, const QString &release) const { pkgCache::VerIterator verIter = packageIter.VersionList(); pkgCache::VerFileIterator verFileIter; pkgCache::PkgFileIterator found; while (!verIter.end()) { for (verFileIter = verIter.FileList(); !verFileIter.end(); ++verFileIter) { for(found = verFileIter.File(); !found.end(); ++found) { const char *verLabel = found.Label(); const char *verOrigin = found.Origin(); const char *verArchive = found.Archive(); if (verLabel && verOrigin && verArchive) { if(verLabel == label && verOrigin == label && QLatin1String(verArchive) == release) { return found; } } } } ++verIter; } found = pkgCache::PkgFileIterator(*packageIter.Cache()); return found; } QString PackagePrivate::getReleaseFileForOrigin(QLatin1String label, const QString &release) const { pkgCache::PkgFileIterator pkg = searchPkgFileIter(label, release); // Return empty if no package matches the given label and release if (pkg.end()) return QString(); // Search for the matching meta-index pkgSourceList *list = backend->packageSourceList(); pkgIndexFile *index; // Return empty if the source list doesn't contain an index for the package if (!list->FindIndex(pkg, index)) return QString(); for (auto I = list->begin(); I != list->end(); ++I) { vector<pkgIndexFile *> *ifv = (*I)->GetIndexFiles(); if (find(ifv->begin(), ifv->end(), index) == ifv->end()) continue; // Construct release file path QString uri = backend->config()->findDirectory("Dir::State::lists") % QString::fromStdString(URItoFileName((*I)->GetURI())) % QLatin1String("dists_") % QString::fromStdString((*I)->GetDist()) % QLatin1String("_Release"); return uri; } return QString(); } void PackagePrivate::initStaticState(const pkgCache::VerIterator &ver, pkgDepCache::StateCache &stateCache) { int packageState = 0; if (!ver.end()) { // Set flags exclusive to installed packages packageState |= QApt::Package::Installed; if (stateCache.CandidateVer && stateCache.Upgradable()) { packageState |= QApt::Package::Upgradeable; if (stateCache.Keep()) packageState |= QApt::Package::Held; } } else packageState |= QApt::Package::NotInstalled; // Broken/garbage statuses are constant until a cache reload if (stateCache.NowBroken()) { packageState |= QApt::Package::NowBroken; } if (stateCache.InstBroken()) { packageState |= QApt::Package::InstallBroken; } if (stateCache.Garbage) { packageState |= QApt::Package::IsGarbage; } if (stateCache.NowPolicyBroken()) { packageState |= QApt::Package::NowPolicyBroken; } if (stateCache.InstPolicyBroken()) { packageState |= QApt::Package::InstallPolicyBroken; } // Essential/important status can only be changed by cache reload if (packageIter->Flags & (pkgCache::Flag::Important | pkgCache::Flag::Essential)) { packageState |= QApt::Package::IsImportant; } if (packageIter->CurrentState == pkgCache::State::ConfigFiles) { packageState |= QApt::Package::ResidualConfig; } // Packages will stay undownloadable until a sources file is refreshed // and the cache is reloaded. bool downloadable = true; if (!stateCache.CandidateVer || stateCache.CandidateVerIter(*backend->cache()->depCache()).Downloadable()) downloadable = false; if (!downloadable) packageState |= QApt::Package::NotDownloadable; state |= packageState; staticStateCalculated = true; } Package::Package(QApt::Backend* backend, pkgCache::PkgIterator &packageIter) : d(new PackagePrivate(packageIter, backend)) { } Package::~Package() { delete d; } const pkgCache::PkgIterator &Package::packageIterator() const { return d->packageIter; } QLatin1String Package::name() const { return QLatin1String(d->packageIter.Name()); } int Package::id() const { return d->packageIter->ID; } QLatin1String Package::section() const { return QLatin1String(d->packageIter.Section()); } QString Package::sourcePackage() const { QString sourcePackage; // In the APT package record format, the only time when a "Source:" field // is present is when the binary package name doesn't match the source // name const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (!ver.end()) { pkgRecords::Parser &rec = d->backend->records()->Lookup(ver.FileList()); sourcePackage = QString::fromStdString(rec.SourcePkg()); } // If the package record didn't have a "Source:" field, then this package's // name must be the source package's name. (Or there isn't a record for this package) if (sourcePackage.isEmpty()) { sourcePackage = name(); } return sourcePackage; } QString Package::shortDescription() const { QString shortDescription; const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (!ver.end()) { pkgCache::DescIterator Desc = ver.TranslatedDescription(); pkgRecords::Parser & parser = d->backend->records()->Lookup(Desc.FileList()); shortDescription = QString::fromUtf8(parser.ShortDesc().data()); return shortDescription; } return shortDescription; } QString Package::longDescription() const { const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (!ver.end()) { QString rawDescription; pkgCache::DescIterator Desc = ver.TranslatedDescription(); pkgRecords::Parser & parser = d->backend->records()->Lookup(Desc.FileList()); rawDescription = QString::fromUtf8(parser.LongDesc().data()); // Apt acutally returns the whole description, we just want the // extended part. rawDescription.remove(shortDescription() % '\n'); // *Now* we're really raw. Sort of. ;) QString parsedDescription; // Split at double newline, by "section" QStringList sections = rawDescription.split(QLatin1String("\n .")); for (int i = 0; i < sections.count(); ++i) { sections[i].replace(QRegExp(QLatin1String("\n( |\t)+(-|\\*)")), QLatin1Literal("\n\r ") % QString::fromUtf8("\xE2\x80\xA2")); // There should be no new lines within a section. sections[i].remove(QLatin1Char('\n')); // Hack to get the lists working again. sections[i].replace(QLatin1Char('\r'), QLatin1Char('\n')); // Merge multiple whitespace chars into one sections[i].replace(QRegExp(QLatin1String("\\ \\ +")), QChar::fromLatin1(' ')); // Remove the initial whitespace sections[i].remove(0, 1); // Append to parsedDescription if (sections[i].startsWith(QLatin1String("\n ") % QString::fromUtf8("\xE2\x80\xA2 ")) || !i) { parsedDescription += sections[i]; } else { parsedDescription += QLatin1Literal("\n\n") % sections[i]; } } return parsedDescription; } return QString(); } QString Package::maintainer() const { QString maintainer; const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (!ver.end()) { pkgRecords::Parser &parser = d->backend->records()->Lookup(ver.FileList()); maintainer = QString::fromUtf8(parser.Maintainer().data()); // This replacement prevents frontends from interpreting '<' as // an HTML tag opening maintainer.replace(QLatin1Char('<'), QLatin1String("&lt;")); } return maintainer; } QString Package::homepage() const { QString homepage; const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (!ver.end()) { pkgRecords::Parser &parser = d->backend->records()->Lookup(ver.FileList()); homepage = QString::fromUtf8(parser.Homepage().data()); } return homepage; } QString Package::version() const { if (!d->packageIter->CurrentVer) { pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter]; if (!State.CandidateVer) { return QString(); } else { return QLatin1String(State.CandidateVerIter(*d->backend->cache()->depCache()).VerStr()); } } else { return QLatin1String(d->packageIter.CurrentVer().VerStr()); } } QString Package::upstreamVersion() const { const char *ver; if (!d->packageIter->CurrentVer) { pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter]; if (!State.CandidateVer) { return QString(); } else { ver = State.CandidateVerIter(*d->backend->cache()->depCache()).VerStr(); } } else { ver = d->packageIter.CurrentVer().VerStr(); } return QString::fromStdString(_system->VS->UpstreamVersion(ver)); } QString Package::upstreamVersion(const QString &version) { QByteArray ver = version.toLatin1(); return QString::fromStdString(_system->VS->UpstreamVersion(ver.constData())); } QString Package::architecture() const { pkgDepCache *depCache = d->backend->cache()->depCache(); pkgCache::VerIterator ver = (*depCache)[d->packageIter].InstVerIter(*depCache); // the arch:all property is part of the version if (ver && ver.Arch()) return QLatin1String(ver.Arch()); return QLatin1String(d->packageIter.Arch()); } QStringList Package::availableVersions() const { QStringList versions; // Get available Versions. for (auto Ver = d->packageIter.VersionList(); !Ver.end(); ++Ver) { // We always take the first available version. pkgCache::VerFileIterator VF = Ver.FileList(); if (VF.end()) continue; pkgCache::PkgFileIterator File = VF.File(); // Files without an archive will have a site QString archive = (File->Archive) ? QLatin1String(File.Archive()) : QLatin1String(File.Site()); versions.append(QLatin1String(Ver.VerStr()) % QLatin1String(" (") % archive % ')'); } return versions; } QString Package::installedVersion() const { if (!d->packageIter->CurrentVer) { return QString(); } return QLatin1String(d->packageIter.CurrentVer().VerStr()); } QString Package::availableVersion() const { pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter]; if (!State.CandidateVer) { return QString(); } return QLatin1String(State.CandidateVerIter(*d->backend->cache()->depCache()).VerStr()); } QString Package::priority() const { const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (ver.end()) return QString(); return QLatin1String(ver.PriorityType()); } QStringList Package::installedFilesList() const { QStringList installedFilesList; QString path = QLatin1String("/var/lib/dpkg/info/") % name() % QLatin1String(".list"); // Fallback for multiarch packages if (!QFile::exists(path)) { path = QLatin1String("/var/lib/dpkg/info/") % name() % ':' % architecture() % QLatin1String(".list"); } QFile infoFile(path); if (infoFile.open(QFile::ReadOnly)) { QTextStream stream(&infoFile); QString line; do { line = stream.readLine(); installedFilesList << line; } while (!line.isNull()); // The first item won't be a file installedFilesList.removeFirst(); // Remove non-file directory listings for (int i = 0; i < installedFilesList.size() - 1; ++i) { if (installedFilesList.at(i+1).contains(installedFilesList.at(i) + '/')) { installedFilesList[i] = QString(QLatin1Char(' ')); } } installedFilesList.removeAll(QChar::fromLatin1(' ')); // Last line is empty for some reason... if (!installedFilesList.isEmpty()) { installedFilesList.removeLast(); } } return installedFilesList; } QString Package::origin() const { const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if(Ver.end()) return QString(); pkgCache::VerFileIterator VF = Ver.FileList(); return QLatin1String(VF.File().Origin()); } QStringList Package::archives() const { const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if(Ver.end()) return QStringList(); QStringList archiveList; for (auto VF = Ver.FileList(); !VF.end(); ++VF) archiveList << QLatin1String(VF.File().Archive()); return archiveList; } QString Package::component() const { QString sect = section(); if(sect.isEmpty()) return QString(); QStringList split = sect.split('/'); if (split.count() > 1) return split.first(); return QString("main"); } QByteArray Package::md5Sum() const { const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if(ver.end()) return QByteArray(); pkgRecords::Parser &rec = d->backend->records()->Lookup(ver.FileList()); return rec.MD5Hash().c_str(); } QUrl Package::changelogUrl() const { const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (ver.end()) return QUrl(); pkgRecords::Parser &rec = d->backend->records()->Lookup(ver.FileList()); // Find the latest version for the latest changelog QString versionString; if (!availableVersion().isEmpty()) versionString = availableVersion(); // Epochs in versions are ignored on changelog servers if (versionString.contains(QLatin1Char(':'))) { QStringList epochVersion = versionString.split(QLatin1Char(':')); // If the version has an epoch, take the stuff after the epoch versionString = epochVersion.at(1); } // Create URL in form using the correct server, file path, and file suffix Config *config = d->backend->config(); QString server = config->readEntry(QLatin1String("Apt::Changelogs::Server"), QLatin1String("http://packages.debian.org/changelogs")); QString path = QLatin1String(rec.FileName().c_str()); path = path.left(path.lastIndexOf(QLatin1Char('/')) + 1); path += sourcePackage() % '_' % versionString % '/'; bool fromDebian = server.contains(QLatin1String("debian")); QString suffix = fromDebian ? QLatin1String("changelog.txt") : QLatin1String("changelog"); return QUrl(server % '/' % path % suffix); } QUrl Package::screenshotUrl(QApt::ScreenshotType type) const { QUrl url; switch (type) { case QApt::Thumbnail: url = QUrl(controlField(QLatin1String("Thumbnail-Url"))); if(url.isEmpty()) url = QUrl("http://screenshots.debian.net/thumbnail/" % name()); break; case QApt::Screenshot: url = QUrl(controlField(QLatin1String("Screenshot-Url"))); if(url.isEmpty()) url = QUrl("http://screenshots.debian.net/screenshot/" % name()); break; default: qDebug() << "I do not know how to handle the screenshot type given to me: " << QString::number(type); } return url; } QDateTime Package::supportedUntil() const { if (!isSupported()) { return QDateTime(); } QFile lsb_release(QLatin1String("/etc/lsb-release")); if (!lsb_release.open(QFile::ReadOnly)) { // Though really, your system is screwed if this happens... return QDateTime(); } pkgTagSection sec; time_t releaseDate = -1; QString release; QTextStream stream(&lsb_release); QString line; do { line = stream.readLine(); QStringList split = line.split(QLatin1Char('=')); if (split.size() != 2) { continue; } if (split.at(0) == QLatin1String("DISTRIB_CODENAME")) { release = split.at(1); } } while (!line.isNull()); // Canonical only provides support for Ubuntu, but we don't have to worry // about Debian systems as long as we assume that this function can fail. QString releaseFile = d->getReleaseFileForOrigin(QLatin1String("Ubuntu"), release); if(!FileExists(releaseFile.toStdString())) { // happens e.g. when there is no release file and is harmless return QDateTime(); } // read the relase file FileFd fd(releaseFile.toStdString(), FileFd::ReadOnly); pkgTagFile tag(&fd); tag.Step(sec); if(!RFC1123StrToTime(sec.FindS("Date").data(), releaseDate)) { return QDateTime(); } // Default to 18m in case the package has no "supported" field QString supportTimeString = QLatin1String("18m"); QString supportTimeField = controlField(QLatin1String("Supported")); if (!supportTimeField.isEmpty()) { supportTimeString = supportTimeField; } QChar unit = supportTimeString.at(supportTimeString.length() - 1); supportTimeString.chop(1); // Remove the letter signifying months/years const int supportTime = supportTimeString.toInt(); QDateTime supportEnd; if (unit == QLatin1Char('m')) { supportEnd = QDateTime::fromTime_t(releaseDate).addMonths(supportTime); } else if (unit == QLatin1Char('y')) { supportEnd = QDateTime::fromTime_t(releaseDate).addYears(supportTime); } return supportEnd; } QString Package::controlField(QLatin1String name) const { const pkgCache::VerIterator &ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (ver.end()) { return QString(); } pkgRecords::Parser &rec = d->backend->records()->Lookup(ver.FileList()); return QString::fromStdString(rec.RecordField(name.latin1())); } QString Package::controlField(const QString &name) const { return controlField(QLatin1String(name.toLatin1())); } qint64 Package::currentInstalledSize() const { const pkgCache::VerIterator &ver = d->packageIter.CurrentVer(); if (!ver.end()) { return qint64(ver->InstalledSize); } else { return qint64(-1); } } qint64 Package::availableInstalledSize() const { pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter]; if (!State.CandidateVer) { return qint64(-1); } return qint64(State.CandidateVerIter(*d->backend->cache()->depCache())->InstalledSize); } qint64 Package::downloadSize() const { pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter]; if (!State.CandidateVer) { return qint64(-1); } return qint64(State.CandidateVerIter(*d->backend->cache()->depCache())->Size); } int Package::state() const { int packageState = 0; const pkgCache::VerIterator &ver = d->packageIter.CurrentVer(); pkgDepCache::StateCache &stateCache = (*d->backend->cache()->depCache())[d->packageIter]; if (!d->staticStateCalculated) { d->initStaticState(ver, stateCache); } if (stateCache.Install()) { packageState |= ToInstall; } if (stateCache.Flags & pkgCache::Flag::Auto) { packageState |= QApt::Package::IsAuto; } if (stateCache.iFlags & pkgDepCache::ReInstall) { packageState |= ToReInstall; } else if (stateCache.NewInstall()) { // Order matters here. packageState |= NewInstall; } else if (stateCache.Upgrade()) { packageState |= ToUpgrade; } else if (stateCache.Downgrade()) { packageState |= ToDowngrade; } else if (stateCache.Delete()) { packageState |= ToRemove; if (stateCache.iFlags & pkgDepCache::Purge) { packageState |= ToPurge; } } else if (stateCache.Keep()) { packageState |= ToKeep; } return packageState | d->state; } int Package::staticState() const { if (!d->staticStateCalculated) { const pkgCache::VerIterator &ver = d->packageIter.CurrentVer(); pkgDepCache::StateCache &stateCache = (*d->backend->cache()->depCache())[d->packageIter]; d->initStaticState(ver, stateCache); } return d->state; } int Package::compareVersion(const QString &v1, const QString &v2) { // Make deep copies of toStdString(), since otherwise they would // go out of scope when we call c_str() string s1 = v1.toStdString(); string s2 = v2.toStdString(); const char *a = s1.c_str(); const char *b = s2.c_str(); int lenA = strlen(a); int lenB = strlen(b); return _system->VS->DoCmpVersion(a, a+lenA, b, b+lenB); } bool Package::isInstalled() const { return !d->packageIter.CurrentVer().end(); } bool Package::isSupported() const { if (origin() == QLatin1String("Ubuntu")) { QString componentString = component(); if ((componentString == QLatin1String("main") || componentString == QLatin1String("restricted")) && isTrusted()) { return true; } } return false; } bool Package::isMultiArchDuplicate() const { // Excludes installed packages, which are always "interesting" if (isInstalled()) return false; // Otherwise, check if the pkgIterator is the "best" from its group return (d->packageIter.Group().FindPkg() != d->packageIter); } QString Package::multiArchTypeString() const { return controlField(QLatin1String("Multi-Arch")); } MultiArchType Package::multiArchType() const { QString typeString = multiArchTypeString(); MultiArchType archType = InvalidMultiArchType; if (typeString == QLatin1String("same")) archType = MultiArchSame; else if (typeString == QLatin1String("foreign")) archType = MultiArchForeign; else if (typeString == QLatin1String("allowed")) archType = MultiArchAllowed; return archType; } bool Package::isForeignArch() const { if (!d->foreignArchCalculated) { QString arch = architecture(); d->isForeignArch = (d->backend->nativeArchitecture() != arch) & (arch != QLatin1String("all")); d->foreignArchCalculated = true; } return d->isForeignArch; } QList<DependencyItem> Package::depends() const { return DependencyInfo::parseDepends(controlField("Depends"), Depends); } QList<DependencyItem> Package::preDepends() const { return DependencyInfo::parseDepends(controlField("Pre-Depends"), PreDepends); } QList<DependencyItem> Package::suggests() const { return DependencyInfo::parseDepends(controlField("Suggests"), Suggests); } QList<DependencyItem> Package::recommends() const { return DependencyInfo::parseDepends(controlField("Recommends"), Recommends); } QList<DependencyItem> Package::conflicts() const { return DependencyInfo::parseDepends(controlField("Conflicts"), Conflicts); } QList<DependencyItem> Package::replaces() const { return DependencyInfo::parseDepends(controlField("Replaces"), Replaces); } QList<DependencyItem> Package::obsoletes() const { return DependencyInfo::parseDepends(controlField("Obsoletes"), Obsoletes); } QList<DependencyItem> Package::breaks() const { return DependencyInfo::parseDepends(controlField("Breaks"), Breaks); } QList<DependencyItem> Package::enhances() const { return DependencyInfo::parseDepends(controlField("Enhance"), Enhances); } QStringList Package::dependencyList(bool useCandidateVersion) const { QStringList dependsList; pkgCache::VerIterator current; pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter]; if(!useCandidateVersion) { current = State.InstVerIter(*d->backend->cache()->depCache()); } if(useCandidateVersion || current.end()) { current = State.CandidateVerIter(*d->backend->cache()->depCache()); } // no information found if(current.end()) { return dependsList; } for(pkgCache::DepIterator D = current.DependsList(); D.end() != true; ++D) { QString type; bool isOr = false; bool isVirtual = false; QString name; QString version; QString versionCompare; QString finalString; // check target and or-depends status pkgCache::PkgIterator Trg = D.TargetPkg(); if ((D->CompareOp & pkgCache::Dep::Or) == pkgCache::Dep::Or) { isOr=true; } // common information type = QString::fromUtf8(D.DepType()); name = QLatin1String(Trg.Name()); if (!Trg->VersionList) { isVirtual = true; } else { version = QLatin1String(D.TargetVer()); versionCompare = QLatin1String(D.CompType()); } finalString = QLatin1Literal("<b>") % type % QLatin1Literal(":</b> "); if (isVirtual) { finalString += QLatin1Literal("<i>") % name % QLatin1Literal("</i>"); } else { finalString += name; } // Escape the compare operator so it won't be seen as HTML if (!version.isEmpty()) { QString compMarkup(versionCompare); compMarkup.replace(QLatin1Char('<'), QLatin1String("&lt;")); finalString += QLatin1String(" (") % compMarkup % QLatin1Char(' ') % version % QLatin1Char(')'); } if (isOr) { finalString += QLatin1String(" |"); } dependsList.append(finalString); } return dependsList; } QStringList Package::requiredByList() const { QStringList reverseDependsList; for(pkgCache::DepIterator it = d->packageIter.RevDependsList(); !it.end(); ++it) { reverseDependsList << QLatin1String(it.ParentPkg().Name()); } return reverseDependsList; } QStringList Package::providesList() const { pkgDepCache::StateCache &State = (*d->backend->cache()->depCache())[d->packageIter]; if (!State.CandidateVer) { return QStringList(); } QStringList provides; for (pkgCache::PrvIterator Prv = State.CandidateVerIter(*d->backend->cache()->depCache()).ProvidesList(); !Prv.end(); ++Prv) { provides.append(QLatin1String(Prv.Name())); } return provides; } QStringList Package::recommendsList() const { QStringList recommends; const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (Ver.end()) { return recommends; } for(pkgCache::DepIterator it = Ver.DependsList(); !it.end(); ++it) { pkgCache::PkgIterator pkg = it.TargetPkg(); // Skip purely virtual packages if (!pkg->VersionList) { continue; } pkgDepCache::StateCache &rState = (*d->backend->cache()->depCache())[pkg]; if (it->Type == pkgCache::Dep::Recommends && (rState.CandidateVer != 0 )) { recommends << QLatin1String(it.TargetPkg().Name()); } } return recommends; } QStringList Package::suggestsList() const { QStringList suggests; const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (Ver.end()) { return suggests; } for(pkgCache::DepIterator it = Ver.DependsList(); !it.end(); ++it) { pkgCache::PkgIterator pkg = it.TargetPkg(); // Skip purely virtual packages if (!pkg->VersionList) { continue; } pkgDepCache::StateCache &sState = (*d->backend->cache()->depCache())[pkg]; if (it->Type == pkgCache::Dep::Suggests && (sState.CandidateVer != 0 )) { suggests << QLatin1String(it.TargetPkg().Name()); } } return suggests; } QStringList Package::enhancesList() const { QStringList enhances; const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (Ver.end()) { return enhances; } for(pkgCache::DepIterator it = Ver.DependsList(); !it.end(); ++it) { pkgCache::PkgIterator pkg = it.TargetPkg(); // Skip purely virtual packages if (!pkg->VersionList) { continue; } pkgDepCache::StateCache &eState = (*d->backend->cache()->depCache())[pkg]; if (it->Type == pkgCache::Dep::Enhances && (eState.CandidateVer != 0 )) { enhances << QLatin1String(it.TargetPkg().Name()); } } return enhances; } QStringList Package::enhancedByList() const { QStringList enhancedByList; Q_FOREACH (QApt::Package *package, d->backend->availablePackages()) { if (package->enhancesList().contains(name())) { enhancedByList << package->name(); } } return enhancedByList; } QList<QApt::MarkingErrorInfo> Package::brokenReason() const { const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); QList<MarkingErrorInfo> reasons; // check if there is actually something to install if (!Ver) { QApt::DependencyInfo info(name(), QString(), NoOperand, InvalidType); QApt::MarkingErrorInfo error(QApt::ParentNotInstallable, info); reasons.append(error); return reasons; } for (pkgCache::DepIterator D = Ver.DependsList(); !D.end();) { // Compute a single dependency element (glob or) pkgCache::DepIterator Start; pkgCache::DepIterator End; D.GlobOr(Start, End); pkgCache::PkgIterator Targ = Start.TargetPkg(); if (!d->backend->cache()->depCache()->IsImportantDep(End)) { continue; } if (((*d->backend->cache()->depCache())[End] & pkgDepCache::DepGInstall) == pkgDepCache::DepGInstall) { continue; } if (!Targ->ProvidesList) { // Ok, not a virtual package since no provides pkgCache::VerIterator Ver = (*d->backend->cache()->depCache())[Targ].InstVerIter(*d->backend->cache()->depCache()); QString requiredVersion; if(Start.TargetVer() != 0) { requiredVersion = '(' % QLatin1String(Start.CompType()) % QLatin1String(Start.TargetVer()) % ')'; } if (!Ver.end()) { // Happens when a package needs an upgraded dep, but the dep won't // upgrade. Example: // "apt 0.5.4 but 0.5.3 is to be installed" QString targetName = QLatin1String(Start.TargetPkg().Name()); QApt::DependencyType relation = (QApt::DependencyType)End->Type; QApt::DependencyInfo errorInfo(targetName, requiredVersion, NoOperand, relation); QApt::MarkingErrorInfo error(QApt::WrongCandidateVersion, errorInfo); reasons.append(error); } else { // We have the package, but for some reason it won't be installed // In this case, the required version does not exist at all QString targetName = QLatin1String(Start.TargetPkg().Name()); QApt::DependencyType relation = (QApt::DependencyType)End->Type; QApt::DependencyInfo errorInfo(targetName, requiredVersion, NoOperand, relation); QApt::MarkingErrorInfo error(QApt::DepNotInstallable, errorInfo); reasons.append(error); } } else { // Ok, candidate has provides. We're a virtual package QString targetName = QLatin1String(Start.TargetPkg().Name()); QApt::DependencyType relation = (QApt::DependencyType)End->Type; QApt::DependencyInfo errorInfo(targetName, QString(), NoOperand, relation); QApt::MarkingErrorInfo error(QApt::VirtualPackage, errorInfo); reasons.append(error); } } return reasons; } bool Package::isTrusted() const { const pkgCache::VerIterator &Ver = (*d->backend->cache()->depCache()).GetCandidateVer(d->packageIter); if (!Ver) return false; pkgSourceList *Sources = d->backend->packageSourceList(); QHash<pkgCache::PkgFileIterator, pkgIndexFile*> *trustCache = d->backend->cache()->trustCache(); for (pkgCache::VerFileIterator i = Ver.FileList(); !i.end(); ++i) { pkgIndexFile *Index; //FIXME: Should be done in apt auto trustIter = trustCache->constBegin(); while (trustIter != trustCache->constEnd()) { if (trustIter.key() == i.File()) break; // Found it trustIter++; } // Find the index of the package file from the package sources if (trustIter == trustCache->constEnd()) { // Not found if (!Sources->FindIndex(i.File(), Index)) continue; } else Index = trustIter.value(); if (Index->IsTrusted()) return true; } return false; } bool Package::wouldBreak() const { int pkgState = state(); if ((pkgState & ToRemove) || (!(pkgState & Installed) && (pkgState & ToKeep))) { return false; } return pkgState & InstallBroken; } void Package::setAuto(bool flag) { d->backend->cache()->depCache()->MarkAuto(d->packageIter, flag); } void Package::setKeep() { d->backend->cache()->depCache()->MarkKeep(d->packageIter, false); if (d->backend->cache()->depCache()->BrokenCount() > 0) { pkgProblemResolver Fix(d->backend->cache()->depCache()); Fix.ResolveByKeep(); } d->state |= IsManuallyHeld; if (!d->backend->areEventsCompressed()) { d->backend->emitPackageChanged(); } } void Package::setInstall() { d->backend->cache()->depCache()->MarkInstall(d->packageIter, true); d->state &= ~IsManuallyHeld; // FIXME: can't we get rid of it here? // if there is something wrong, try to fix it if (!state() & ToInstall || d->backend->cache()->depCache()->BrokenCount() > 0) { pkgProblemResolver Fix(d->backend->cache()->depCache()); Fix.Clear(d->packageIter); Fix.Protect(d->packageIter); Fix.Resolve(true); } if (!d->backend->areEventsCompressed()) { d->backend->emitPackageChanged(); } } void Package::setReInstall() { d->backend->cache()->depCache()->SetReInstall(d->packageIter, true); d->state &= ~IsManuallyHeld; if (!d->backend->areEventsCompressed()) { d->backend->emitPackageChanged(); } } void Package::setRemove() { pkgProblemResolver Fix(d->backend->cache()->depCache()); Fix.Clear(d->packageIter); Fix.Protect(d->packageIter); Fix.Remove(d->packageIter); Fix.Resolve(true); d->backend->cache()->depCache()->SetReInstall(d->packageIter, false); d->backend->cache()->depCache()->MarkDelete(d->packageIter, false); d->state &= ~IsManuallyHeld; if (!d->backend->areEventsCompressed()) { d->backend->emitPackageChanged(); } } void Package::setPurge() { pkgProblemResolver Fix(d->backend->cache()->depCache()); Fix.Clear(d->packageIter); Fix.Protect(d->packageIter); Fix.Remove(d->packageIter); Fix.Resolve(true); d->backend->cache()->depCache()->SetReInstall(d->packageIter, false); d->backend->cache()->depCache()->MarkDelete(d->packageIter, true); d->state &= ~IsManuallyHeld; if (!d->backend->areEventsCompressed()) { d->backend->emitPackageChanged(); } } bool Package::setVersion(const QString &version) { pkgDepCache::StateCache &state = (*d->backend->cache()->depCache())[d->packageIter]; QLatin1String defaultCandVer(state.CandVersion); bool isDefault = (version == defaultCandVer); pkgVersionMatch Match(version.toLatin1().constData(), pkgVersionMatch::Version); const pkgCache::VerIterator &Ver = Match.Find(d->packageIter); if (Ver.end()) return false; d->backend->cache()->depCache()->SetCandidateVersion(Ver); for (auto VF = Ver.FileList(); !VF.end(); ++VF) { if (!VF.File() || !VF.File().Archive()) continue; d->backend->cache()->depCache()->SetCandidateRelease(Ver, VF.File().Archive()); break; } if (isDefault) d->state &= ~OverrideVersion; else d->state |= OverrideVersion; return true; } void Package::setPinned(bool pin) { pin ? d->state |= IsPinned : d->state &= ~IsPinned; } }
Java
extern crate rand; use std::io; use rand::Rng; use std::cmp::Ordering; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); loop { println!("Please input your guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) .expect("Failed to read line"); println!("You guessed {}", guess); let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(_) => continue, }; match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); break; } } } }
Java
<?php namespace App; use Illuminate\Database\Eloquent\Model; final class Contact extends Model { const PHONE = 'phone'; const ADDRESS = 'address'; const ADDRESS_COMPLEMENT = 'address_complement'; const POSTAL_CODE = 'postal_code'; const CITY = 'city'; const REGION = 'region'; const COUNTRY = 'country'; const CONTACTABLE_ID = 'contactable_id'; const CONTACTABLE_TYPE = 'contactable_type'; protected $fillable = [ self::PHONE, self::ADDRESS, self::ADDRESS_COMPLEMENT, self::POSTAL_CODE, self::CITY, self::REGION, self::COUNTRY, ]; protected $hidden = [ self::CONTACTABLE_ID, self::CONTACTABLE_TYPE, ]; }
Java
# # logutil.py # A module containing means of interacting with log files. # import logging import logging.handlers import os import time from data_structures import enum from config import get_config_value LoggingSection = enum( 'CLIENT', 'CRAWLER', 'DATA', 'FRONTIER', 'TEST', 'UTILITIES', ) #region Setup logging.basicConfig(level=logging.INFO, format='[%(asctime)s %(levelname)s] %(name)s::%(funcName)s - %(message)s', datefmt='%x %X %Z') module_dir = os.path.dirname(__file__) logfile = os.path.join(module_dir, get_config_value('LOG', 'path')) logdir = os.path.join(module_dir, get_config_value('LOG', 'dir')) if not os.path.exists(logdir): os.mkdir(logdir) handler = logging.handlers.RotatingFileHandler(logfile, maxBytes=8192, backupCount=10, ) formatter = logging.Formatter('[%(asctime)s %(levelname)s] %(name)s::%(funcName)s - %(message)s') formatter.datefmt = '%x %X %Z' formatter.converter = time.gmtime handler.setFormatter(formatter) #endregion def get_logger(section, name): """ Fetches a logger. Arguments: section (string): The section the logger is attributed to. name (string): The name of the logger. Returns: The logger corresponding to the section and name provided. """ section_name = LoggingSection.reverse_mapping[section].lower() logger = logging.getLogger('htresearch.{0}.{1}'.format(section_name, name)) logger.addHandler(handler) logger.setLevel(logging.INFO) return logger
Java
{% extends "geostitcher/views/templates/base.html" %} {% block content %} <div class="gallery"> <div id="error"></div> <script src="{{context}}/js/gallery.js" type="text/javascript"></script> <div> {% for pic in pictures %} <div class="thumbnail"> <a class={{pic.name}} href="{{context}}/img/{{pic.userid}}/{{pic.name}}"> <img src="{{context}}/img/{{pic.userid}}/{{thumb-prefix}}{{pic.name}}"/> {% ifequal username page-owner %} <input id="{{pic.name}}" name="{{pic.name}}" type="checkbox" value="true" /> {% endifequal %} </a> </div> {% endfor %} {% ifequal user page-owner %} <input id="delete" type="submit" value="delete images" /> {% endifequal %} </div> </div> <form action="{{context}}/upload/{{dataset_id}}" enctype="multipart/form-data" method="POST"> <input id="file" name="file" type="file" /> <input type="submit" value="Upload" /> </form> </div> {% endblock %}
Java
/* -*- c++ -*- * Copyright (C) 2007-2016 Hypertable, Inc. * * This file is part of Hypertable. * * Hypertable is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 3 * of the License, or any later version. * * Hypertable 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 /// Definitions for UpdatePipeline. /// This file contains type definitions for UpdatePipeline, a three-staged, /// multithreaded update pipeline. #include <Common/Compat.h> #include "UpdatePipeline.h" #include <Hypertable/RangeServer/Global.h> #include <Hypertable/RangeServer/Response/Callback/Update.h> #include <Hypertable/RangeServer/UpdateContext.h> #include <Hypertable/RangeServer/UpdateRecRange.h> #include <Hypertable/RangeServer/UpdateRecTable.h> #include <Hypertable/Lib/ClusterId.h> #include <Hypertable/Lib/RangeServer/Protocol.h> #include <Common/DynamicBuffer.h> #include <Common/FailureInducer.h> #include <Common/Logger.h> #include <Common/Serialization.h> #include <chrono> #include <set> #include <thread> using namespace Hypertable; using namespace Hypertable::RangeServer; using namespace std; UpdatePipeline::UpdatePipeline(ContextPtr &context, QueryCachePtr &query_cache, TimerHandlerPtr &timer_handler, CommitLogPtr &log, Filesystem::Flags flags) : m_context(context), m_query_cache(query_cache), m_timer_handler(timer_handler), m_log(log), m_flags(flags) { m_update_coalesce_limit = m_context->props->get_i64("Hypertable.RangeServer.UpdateCoalesceLimit"); m_maintenance_pause_interval = m_context->props->get_i32("Hypertable.RangeServer.Testing.MaintenanceNeeded.PauseInterval"); m_update_delay = m_context->props->get_i32("Hypertable.RangeServer.UpdateDelay", 0); m_max_clock_skew = m_context->props->get_i32("Hypertable.RangeServer.ClockSkew.Max"); m_threads.reserve(3); m_threads.push_back( thread(&UpdatePipeline::qualify_and_transform, this) ); m_threads.push_back( thread(&UpdatePipeline::commit, this) ); m_threads.push_back( thread(&UpdatePipeline::add_and_respond, this) ); } void UpdatePipeline::add(UpdateContext *uc) { lock_guard<mutex> lock(m_qualify_queue_mutex); m_qualify_queue.push_back(uc); m_qualify_queue_cond.notify_all(); } void UpdatePipeline::shutdown() { m_shutdown = true; m_qualify_queue_cond.notify_all(); m_commit_queue_cond.notify_all(); m_response_queue_cond.notify_all(); for (std::thread &t : m_threads) t.join(); } void UpdatePipeline::qualify_and_transform() { UpdateContext *uc; SerializedKey key; const uint8_t *mod, *mod_end; const char *row; String start_row, end_row; UpdateRecRangeList *rulist; int error = Error::OK; int64_t latest_range_revision; RangeTransferInfo transfer_info; bool transfer_pending; DynamicBuffer *cur_bufp; DynamicBuffer *transfer_bufp; uint32_t go_buf_reset_offset; uint32_t root_buf_reset_offset; CommitLogPtr transfer_log; UpdateRecRange range_update; RangePtr range; std::mutex &mutex = m_qualify_queue_mutex; condition_variable &cond = m_qualify_queue_cond; std::list<UpdateContext *> &queue = m_qualify_queue; while (true) { { unique_lock<std::mutex> lock(mutex); cond.wait(lock, [this, &queue](){ return !queue.empty() || m_shutdown; }); if (m_shutdown) return; uc = queue.front(); queue.pop_front(); } rulist = 0; transfer_bufp = 0; go_buf_reset_offset = 0; root_buf_reset_offset = 0; // This probably shouldn't happen for group commit, but since // it's only for testing purposes, we'll leave it here if (m_update_delay) this_thread::sleep_for(chrono::milliseconds(m_update_delay)); // Global commit log is only available after local recovery uc->auto_revision = Hypertable::get_ts64(); // TODO: Sanity check mod data (checksum validation) // hack to workaround xen timestamp issue if (uc->auto_revision < m_last_revision) uc->auto_revision = m_last_revision; for (UpdateRecTable *table_update : uc->updates) { HT_DEBUG_OUT <<"Update: "<< table_update->id << HT_END; if (!table_update->id.is_system() && m_context->server_state->readonly()) { table_update->error = Error::RANGESERVER_SERVER_IN_READONLY_MODE; continue; } try { if (!m_context->live_map->lookup(table_update->id.id, table_update->table_info)) { table_update->error = Error::TABLE_NOT_FOUND; table_update->error_msg = table_update->id.id; continue; } } catch (Exception &e) { table_update->error = e.code(); table_update->error_msg = e.what(); continue; } // verify schema if (table_update->table_info->get_schema()->get_generation() != table_update->id.generation) { table_update->error = Error::RANGESERVER_GENERATION_MISMATCH; table_update->error_msg = format("Update schema generation mismatch for table %s (received %lld != %lld)", table_update->id.id, (Lld)table_update->id.generation, (Lld)table_update->table_info->get_schema()->get_generation()); continue; } // Pre-allocate the go_buf - each key could expand by 8 or 9 bytes, // if auto-assigned (8 for the ts or rev and maybe 1 for possible // increase in vint length) table_update->go_buf.reserve(table_update->id.encoded_length() + table_update->total_buffer_size + (table_update->total_count * 9)); table_update->id.encode(&table_update->go_buf.ptr); table_update->go_buf.set_mark(); for (UpdateRequest *request : table_update->requests) { uc->total_updates++; mod_end = request->buffer.base + request->buffer.size; mod = request->buffer.base; go_buf_reset_offset = table_update->go_buf.fill(); root_buf_reset_offset = uc->root_buf.fill(); memset(&uc->send_back, 0, sizeof(uc->send_back)); while (mod < mod_end) { key.ptr = mod; row = key.row(); // error inducer for tests/integration/fail-index-mutator if (HT_FAILURE_SIGNALLED("fail-index-mutator-0")) { if (!strcmp(row, "1,+/JzamFvB6rqPqP5yNgI5nreCtZHkT\t\t01501")) { uc->send_back.count++; uc->send_back.error = Error::INDUCED_FAILURE; uc->send_back.offset = mod - request->buffer.base; uc->send_back.len = strlen(row); request->send_back_vector.push_back(uc->send_back); memset(&uc->send_back, 0, sizeof(uc->send_back)); key.next(); // skip key key.next(); // skip value; mod = key.ptr; continue; } } // If the row key starts with '\0' then the buffer is probably // corrupt, so mark the remaing key/value pairs as bad if (*row == 0) { uc->send_back.error = Error::BAD_KEY; uc->send_back.count = request->count; // fix me !!!! uc->send_back.offset = mod - request->buffer.base; uc->send_back.len = mod_end - mod; request->send_back_vector.push_back(uc->send_back); memset(&uc->send_back, 0, sizeof(uc->send_back)); mod = mod_end; continue; } // Look for containing range, add to stop mods if not found if (!table_update->table_info->find_containing_range(row, range, start_row, end_row) || range->get_relinquish()) { if (uc->send_back.error != Error::RANGESERVER_OUT_OF_RANGE && uc->send_back.count > 0) { uc->send_back.len = (mod - request->buffer.base) - uc->send_back.offset; request->send_back_vector.push_back(uc->send_back); memset(&uc->send_back, 0, sizeof(uc->send_back)); } if (uc->send_back.count == 0) { uc->send_back.error = Error::RANGESERVER_OUT_OF_RANGE; uc->send_back.offset = mod - request->buffer.base; } key.next(); // skip key key.next(); // skip value; mod = key.ptr; uc->send_back.count++; continue; } if ((rulist = table_update->range_map[range.get()]) == 0) { rulist = new UpdateRecRangeList(); rulist->range = range; table_update->range_map[range.get()] = rulist; } // See if range has some other error preventing it from receiving updates if ((error = rulist->range->get_error()) != Error::OK) { if (uc->send_back.error != error && uc->send_back.count > 0) { uc->send_back.len = (mod - request->buffer.base) - uc->send_back.offset; request->send_back_vector.push_back(uc->send_back); memset(&uc->send_back, 0, sizeof(uc->send_back)); } if (uc->send_back.count == 0) { uc->send_back.error = error; uc->send_back.offset = mod - request->buffer.base; } key.next(); // skip key key.next(); // skip value; mod = key.ptr; uc->send_back.count++; continue; } if (uc->send_back.count > 0) { uc->send_back.len = (mod - request->buffer.base) - uc->send_back.offset; request->send_back_vector.push_back(uc->send_back); memset(&uc->send_back, 0, sizeof(uc->send_back)); } /* * Increment update count on range * (block if maintenance in progress) */ if (!rulist->range_blocked) { if (!rulist->range->increment_update_counter()) { uc->send_back.error = Error::RANGESERVER_RANGE_NOT_FOUND; uc->send_back.offset = mod - request->buffer.base; uc->send_back.count++; key.next(); // skip key key.next(); // skip value; mod = key.ptr; continue; } rulist->range_blocked = true; } String range_start_row, range_end_row; rulist->range->get_boundary_rows(range_start_row, range_end_row); // Make sure range didn't just shrink if (range_start_row != start_row || range_end_row != end_row) { rulist->range->decrement_update_counter(); table_update->range_map.erase(rulist->range.get()); delete rulist; continue; } /** Fetch range transfer information **/ { bool wait_for_maintenance; transfer_pending = rulist->range->get_transfer_info(transfer_info, transfer_log, &latest_range_revision, wait_for_maintenance); } if (rulist->transfer_log.get() == 0) rulist->transfer_log = transfer_log; HT_ASSERT(rulist->transfer_log.get() == transfer_log.get()); bool in_transferring_region = false; // Check for clock skew { ByteString tmp_key; const uint8_t *tmp; int64_t difference, tmp_timestamp; tmp_key.ptr = key.ptr; tmp_key.decode_length(&tmp); if ((*tmp & Key::HAVE_REVISION) == 0) { if (latest_range_revision > TIMESTAMP_MIN && uc->auto_revision < latest_range_revision) { tmp_timestamp = Hypertable::get_ts64(); if (tmp_timestamp > uc->auto_revision) uc->auto_revision = tmp_timestamp; if (uc->auto_revision < latest_range_revision) { difference = (int32_t)((latest_range_revision - uc->auto_revision) / 1000LL); if (difference > m_max_clock_skew && !Global::ignore_clock_skew_errors) { request->error = Error::RANGESERVER_CLOCK_SKEW; HT_ERRORF("Clock skew of %lld microseconds exceeds maximum " "(%lld) range=%s", (Lld)difference, (Lld)m_max_clock_skew, rulist->range->get_name().c_str()); uc->send_back.count = 0; request->send_back_vector.clear(); break; } } } } } if (transfer_pending) { transfer_bufp = &rulist->transfer_buf; if (transfer_bufp->empty()) { transfer_bufp->reserve(table_update->id.encoded_length()); table_update->id.encode(&transfer_bufp->ptr); transfer_bufp->set_mark(); } rulist->transfer_buf_reset_offset = rulist->transfer_buf.fill(); } else { transfer_bufp = 0; rulist->transfer_buf_reset_offset = 0; } if (rulist->range->is_root()) { if (uc->root_buf.empty()) { uc->root_buf.reserve(table_update->id.encoded_length()); table_update->id.encode(&uc->root_buf.ptr); uc->root_buf.set_mark(); root_buf_reset_offset = uc->root_buf.fill(); } cur_bufp = &uc->root_buf; } else cur_bufp = &table_update->go_buf; rulist->last_request = request; range_update.bufp = cur_bufp; range_update.offset = cur_bufp->fill(); while (mod < mod_end && (end_row == "" || (strcmp(row, end_row.c_str()) <= 0))) { if (transfer_pending) { if (transfer_info.transferring(row)) { if (!in_transferring_region) { range_update.len = cur_bufp->fill() - range_update.offset; rulist->add_update(request, range_update); cur_bufp = transfer_bufp; range_update.bufp = cur_bufp; range_update.offset = cur_bufp->fill(); in_transferring_region = true; } table_update->transfer_count++; } else { if (in_transferring_region) { range_update.len = cur_bufp->fill() - range_update.offset; rulist->add_update(request, range_update); cur_bufp = &table_update->go_buf; range_update.bufp = cur_bufp; range_update.offset = cur_bufp->fill(); in_transferring_region = false; } } } try { SchemaPtr schema = table_update->table_info->get_schema(); uint8_t family=*(key.ptr+1+strlen((const char *)key.ptr+1)+1); ColumnFamilySpec *cf_spec = schema->get_column_family(family); // reset auto_revision if it's gotten behind if (uc->auto_revision < latest_range_revision) { uc->auto_revision = Hypertable::get_ts64(); if (uc->auto_revision < latest_range_revision) { HT_THROWF(Error::RANGESERVER_REVISION_ORDER_ERROR, "Auto revision (%lld) is less than latest range " "revision (%lld) for range %s", (Lld)uc->auto_revision, (Lld)latest_range_revision, rulist->range->get_name().c_str()); } } // This will transform keys that need to be assigned a // timestamp and/or revision number by re-writing the key // with the added timestamp and/or revision tacked on to the end transform_key(key, cur_bufp, ++uc->auto_revision,&m_last_revision, cf_spec ? cf_spec->get_option_time_order_desc() : false); // Validate revision number if (m_last_revision < latest_range_revision) { if (m_last_revision != uc->auto_revision) { HT_THROWF(Error::RANGESERVER_REVISION_ORDER_ERROR, "Supplied revision (%lld) is less than most recently " "seen revision (%lld) for range %s", (Lld)m_last_revision, (Lld)latest_range_revision, rulist->range->get_name().c_str()); } } } catch (Exception &e) { HT_ERRORF("%s - %s", e.what(), Error::get_text(e.code())); request->error = e.code(); break; } // Now copy the value (with sanity check) mod = key.ptr; key.next(); // skip value HT_ASSERT(key.ptr <= mod_end); cur_bufp->add(mod, key.ptr-mod); mod = key.ptr; table_update->total_added++; if (mod < mod_end) row = key.row(); } if (request->error == Error::OK) { range_update.len = cur_bufp->fill() - range_update.offset; rulist->add_update(request, range_update); // if there were transferring updates, record the latest revision if (transfer_pending && rulist->transfer_buf_reset_offset < rulist->transfer_buf.fill()) { if (rulist->latest_transfer_revision < m_last_revision) rulist->latest_transfer_revision = m_last_revision; } } else { /* * If we drop into here, this means that the request is * being aborted, so reset all of the UpdateRecRangeLists, * reset the go_buf and the root_buf */ for (auto iter = table_update->range_map.begin(); iter != table_update->range_map.end(); ++iter) (*iter).second->reset_updates(request); table_update->go_buf.ptr = table_update->go_buf.base + go_buf_reset_offset; if (root_buf_reset_offset) uc->root_buf.ptr = uc->root_buf.base + root_buf_reset_offset; uc->send_back.count = 0; mod = mod_end; } range_update.bufp = 0; } transfer_log = 0; if (uc->send_back.count > 0) { uc->send_back.len = (mod - request->buffer.base) - uc->send_back.offset; request->send_back_vector.push_back(uc->send_back); memset(&uc->send_back, 0, sizeof(uc->send_back)); } } HT_DEBUGF("Added %d (%d transferring) updates to '%s'", table_update->total_added, table_update->transfer_count, table_update->id.id); if (!table_update->id.is_metadata()) uc->total_added += table_update->total_added; } uc->last_revision = m_last_revision; // Enqueue update { lock_guard<std::mutex> lock(m_commit_queue_mutex); m_commit_queue.push_back(uc); m_commit_queue_cond.notify_all(); m_commit_queue_count++; } } } void UpdatePipeline::commit() { UpdateContext *uc; SerializedKey key; std::list<UpdateContext *> coalesce_queue; uint64_t coalesce_amount = 0; int error = Error::OK; uint32_t committed_transfer_data; bool log_needs_syncing {}; while (true) { // Dequeue next update { unique_lock<std::mutex> lock(m_commit_queue_mutex); m_commit_queue_cond.wait(lock, [this](){ return !m_commit_queue.empty() || m_shutdown; }); if (m_shutdown) return; uc = m_commit_queue.front(); m_commit_queue.pop_front(); m_commit_queue_count--; } committed_transfer_data = 0; log_needs_syncing = false; // Commit ROOT mutations if (uc->root_buf.ptr > uc->root_buf.mark) { if ((error = Global::root_log->write(ClusterId::get(), uc->root_buf, uc->last_revision, Filesystem::Flags::SYNC)) != Error::OK) { HT_FATALF("Problem writing %d bytes to ROOT commit log - %s", (int)uc->root_buf.fill(), Error::get_text(error)); } } for (UpdateRecTable *table_update : uc->updates) { coalesce_amount += table_update->total_buffer_size; // Iterate through all of the ranges, committing any transferring updates for (auto iter = table_update->range_map.begin(); iter != table_update->range_map.end(); ++iter) { if ((*iter).second->transfer_buf.ptr > (*iter).second->transfer_buf.mark) { committed_transfer_data += (*iter).second->transfer_buf.ptr - (*iter).second->transfer_buf.mark; if ((error = (*iter).second->transfer_log->write(ClusterId::get(), (*iter).second->transfer_buf, (*iter).second->latest_transfer_revision, m_flags)) != Error::OK) { table_update->error = error; table_update->error_msg = format("Problem writing %d bytes to transfer log", (int)(*iter).second->transfer_buf.fill()); HT_ERRORF("%s - %s", table_update->error_msg.c_str(), Error::get_text(error)); break; } } } if (table_update->error != Error::OK) continue; constexpr uint32_t NO_LOG_SYNC_FLAGS = Lib::RangeServer::Protocol::UPDATE_FLAG_NO_LOG_SYNC | Lib::RangeServer::Protocol::UPDATE_FLAG_NO_LOG; if ((table_update->flags & NO_LOG_SYNC_FLAGS) == 0) log_needs_syncing = true; // Commit valid (go) mutations if ((table_update->flags & Lib::RangeServer::Protocol::UPDATE_FLAG_NO_LOG) == 0 && table_update->go_buf.ptr > table_update->go_buf.mark) { if ((error = m_log->write(ClusterId::get(), table_update->go_buf, uc->last_revision, Filesystem::Flags::NONE)) != Error::OK) { table_update->error_msg = format("Problem writing %d bytes to commit log (%s) - %s", (int)table_update->go_buf.fill(), m_log->get_log_dir().c_str(), Error::get_text(error)); HT_ERRORF("%s", table_update->error_msg.c_str()); table_update->error = error; continue; } } } bool do_sync = false; if (log_needs_syncing) { if (m_commit_queue_count > 0 && coalesce_amount < m_update_coalesce_limit) { coalesce_queue.push_back(uc); continue; } do_sync = true; } else if (!coalesce_queue.empty()) do_sync = true; // Now sync the commit log if needed if (do_sync) { size_t retry_count {}; uc->total_syncs++; while (true) { if (m_flags == Filesystem::Flags::FLUSH) error = m_log->flush(); else if (m_flags == Filesystem::Flags::SYNC) error = m_log->sync(); else error = Error::OK; if (error != Error::OK) { HT_ERRORF("Problem %sing log fragment (%s) - %s", (m_flags == Filesystem::Flags::FLUSH ? "flush" : "sync"), m_log->get_current_fragment_file().c_str(), Error::get_text(error)); if (++retry_count == 6) break; this_thread::sleep_for(chrono::milliseconds(10000)); } else break; } } // Enqueue update { lock_guard<std::mutex> lock(m_response_queue_mutex); coalesce_queue.push_back(uc); while (!coalesce_queue.empty()) { uc = coalesce_queue.front(); coalesce_queue.pop_front(); m_response_queue.push_back(uc); } coalesce_amount = 0; m_response_queue_cond.notify_all(); } } } void UpdatePipeline::add_and_respond() { UpdateContext *uc; SerializedKey key; int error = Error::OK; while (true) { // Dequeue next update { unique_lock<std::mutex> lock(m_response_queue_mutex); m_response_queue_cond.wait(lock, [this](){ return !m_response_queue.empty() || m_shutdown; }); if (m_shutdown) return; uc = m_response_queue.front(); m_response_queue.pop_front(); } /** * Insert updates into Ranges */ for (UpdateRecTable *table_update : uc->updates) { // Iterate through all of the ranges, inserting updates for (auto iter = table_update->range_map.begin(); iter != table_update->range_map.end(); ++iter) { ByteString value; Key key_comps; for (UpdateRecRange &update : (*iter).second->updates) { Range *rangep = (*iter).first; lock_guard<Range> lock(*rangep); uint8_t *ptr = update.bufp->base + update.offset; uint8_t *end = ptr + update.len; if (!table_update->id.is_metadata()) uc->total_bytes_added += update.len; rangep->add_bytes_written( update.len ); std::set<uint8_t> columns; bool invalidate {}; const char *current_row {}; uint64_t count = 0; while (ptr < end) { key.ptr = ptr; key_comps.load(key); if (current_row == nullptr) current_row = key_comps.row; count++; ptr += key_comps.length; value.ptr = ptr; ptr += value.length(); if (key_comps.column_family_code == 0 && key_comps.flag != FLAG_DELETE_ROW) { HT_ERRORF("Skipping bad key - column family not specified in " "non-delete row update on %s row=%s", table_update->id.id, key_comps.row); continue; } rangep->add(key_comps, value); // invalidate if (m_query_cache) { if (strcmp(current_row, key_comps.row)) { if (invalidate) columns.clear(); m_query_cache->invalidate(table_update->id.id, current_row, columns); columns.clear(); invalidate = false; current_row = key_comps.row; } if (key_comps.flag == FLAG_DELETE_ROW) invalidate = true; else columns.insert(key_comps.column_family_code); } } if (m_query_cache && current_row) { if (invalidate) columns.clear(); m_query_cache->invalidate(table_update->id.id, current_row, columns); } rangep->add_cells_written(count); } } } // Decrement usage counters for all referenced ranges for (UpdateRecTable *table_update : uc->updates) { for (auto iter = table_update->range_map.begin(); iter != table_update->range_map.end(); ++iter) { if ((*iter).second->range_blocked) (*iter).first->decrement_update_counter(); } } /** * wait for these ranges to complete maintenance */ bool maintenance_needed = false; for (UpdateRecTable *table_update : uc->updates) { /* * If any of the newly updated ranges needs maintenance, * schedule immediately */ for (auto iter = table_update->range_map.begin(); iter != table_update->range_map.end(); ++iter) { if ((*iter).first->need_maintenance() && !Global::maintenance_queue->contains((*iter).first)) { maintenance_needed = true; HT_MAYBE_FAIL_X("metadata-update-and-respond", (*iter).first->is_metadata()); if (m_timer_handler) m_timer_handler->schedule_immediate_maintenance(); break; } } for (UpdateRequest *request : table_update->requests) { Response::Callback::Update cb(m_context->comm, request->event); if (table_update->error != Error::OK) { if ((error = cb.error(table_update->error, table_update->error_msg)) != Error::OK) HT_ERRORF("Problem sending error response - %s", Error::get_text(error)); continue; } if (request->error == Error::OK) { /** * Send back response */ if (!request->send_back_vector.empty()) { StaticBuffer ext(new uint8_t [request->send_back_vector.size() * 16], request->send_back_vector.size() * 16); uint8_t *ptr = ext.base; for (size_t i=0; i<request->send_back_vector.size(); i++) { Serialization::encode_i32(&ptr, request->send_back_vector[i].error); Serialization::encode_i32(&ptr, request->send_back_vector[i].count); Serialization::encode_i32(&ptr, request->send_back_vector[i].offset); Serialization::encode_i32(&ptr, request->send_back_vector[i].len); /* HT_INFOF("Sending back error %x, count %d, offset %d, len %d, table id %s", request->send_back_vector[i].error, request->send_back_vector[i].count, request->send_back_vector[i].offset, request->send_back_vector[i].len, table_update->id.id); */ } if ((error = cb.response(ext)) != Error::OK) HT_ERRORF("Problem sending OK response - %s", Error::get_text(error)); } else { if ((error = cb.response_ok()) != Error::OK) HT_ERRORF("Problem sending OK response - %s", Error::get_text(error)); } } else { if ((error = cb.error(request->error, "")) != Error::OK) HT_ERRORF("Problem sending error response - %s", Error::get_text(error)); } } } { lock_guard<LoadStatistics> lock(*Global::load_statistics); Global::load_statistics->add_update_data(uc->total_updates, uc->total_added, uc->total_bytes_added, uc->total_syncs); } delete uc; // For testing if (m_maintenance_pause_interval > 0 && maintenance_needed) this_thread::sleep_for(chrono::milliseconds(m_maintenance_pause_interval)); } } void UpdatePipeline::transform_key(ByteString &bskey, DynamicBuffer *dest_bufp, int64_t auto_revision, int64_t *revisionp, bool timeorder_desc) { size_t len; const uint8_t *ptr; len = bskey.decode_length(&ptr); HT_ASSERT(*ptr == Key::AUTO_TIMESTAMP || *ptr == Key::HAVE_TIMESTAMP); // if TIME_ORDER DESC was set for this column then we store the timestamps // NOT in 1-complements! if (timeorder_desc) { // if the timestamp was specified by the user: unpack it and pack it // again w/o 1-complement if (*ptr == Key::HAVE_TIMESTAMP) { uint8_t *p=(uint8_t *)ptr+len-8; int64_t ts=Key::decode_ts64((const uint8_t **)&p); p=(uint8_t *)ptr+len-8; Key::encode_ts64((uint8_t **)&p, ts, false); } } dest_bufp->ensure((ptr-bskey.ptr) + len + 9); Serialization::encode_vi32(&dest_bufp->ptr, len+8); memcpy(dest_bufp->ptr, ptr, len); if (*ptr == Key::AUTO_TIMESTAMP) *dest_bufp->ptr = Key::HAVE_REVISION | Key::HAVE_TIMESTAMP | Key::REV_IS_TS; else *dest_bufp->ptr = Key::HAVE_REVISION | Key::HAVE_TIMESTAMP; // if TIME_ORDER DESC then store a flag in the key if (timeorder_desc) *dest_bufp->ptr |= Key::TS_CHRONOLOGICAL; dest_bufp->ptr += len; Key::encode_ts64(&dest_bufp->ptr, auto_revision, timeorder_desc ? false : true); *revisionp = auto_revision; bskey.ptr = ptr + len; }
Java
#!/usr/bin/env python ''' Purpose: This script, using default values, determines and plots the CpG islands in relation to a given feature "type" (e.g. "gene" or "mRNA") from a GFF file which corresponds to the user-provided fasta file. Note: CpG Islands are determined by ObEx = (Observed CpG) / (Expected CpG) , default threshold > 1. Where Expected CpG = (count(C) * count(G)) / WindowSize Usage: python cpg_gene.py FastaFile Gff_File OutFile.png Default optional parameters: -s, Step Size, default = 50 -w, Window Size, default = 200 -oe, Minimum Observed Expected CpG, default = 1 -gc, Minimum GC, default = .5 -r Range from ATG, or provided feature, default = 5000 -f, GFF Feature, default = "gene" -i, Gene ID from GFF, default = "" ''' import sys import os import argparse from collections import Counter from Bio import SeqIO import cpgmod import gffutils import pandas as pd import numpy as np from ggplot import * # Capture command line args, with or without defaults if __name__ == '__main__': # Parse the arguments LineArgs = cpgmod.parseArguments() # Populate vars with args FastaFile = LineArgs.FastaFile GffFile = LineArgs.GffFile OutFile = LineArgs.FileOut Step = LineArgs.s WinSize = LineArgs.w ObExthresh = LineArgs.oe GCthresh = LineArgs.gc StartRange = LineArgs.r FeatGFF = LineArgs.f ID_Feat = LineArgs.i # Gather all possible CpG islands MergedRecs = [] print "Parsing sequences...\n" for SeqRecord in SeqIO.parse(FastaFile, "fasta"): print SeqRecord.id # Determine if sequences and args are acceptable cpgmod.arg_seqcheck(SeqRecord, WinSize, Step) # Pre-determine number of islands NumOfChunks = cpgmod.chunks(SeqRecord, WinSize, Step) # Return array of SeqRec class (potential CpG island) instances SeqRecList = cpgmod.compute(SeqRecord, Step, NumOfChunks, WinSize) MergedRecs = MergedRecs + SeqRecList # Create GFF DB GffDb = gffutils.create_db(GffFile, dbfn='GFF.db', force=True, keep_order=True, merge_strategy='merge', sort_attribute_values=True, disable_infer_transcripts=True, disable_infer_genes=True) print "\nGFF Database Created...\n" # Filter out SeqRec below threshold DistArr = [] for Rec in MergedRecs: Cond1 = Rec.expect() > 0 if Cond1 == True: ObEx = (Rec.observ() / Rec.expect()) Cond2 = ObEx > ObExthresh Cond3 = Rec.gc_cont() > GCthresh if Cond2 and Cond3: # Query GFF DB for closest gene feature *or provided feature* Arr = cpgmod.get_closest(Rec, GffDb, StartRange, FeatGFF, ID_Feat) if Arr <> False: Arr.append(ObEx) DistArr.append(Arr) print "CpG Islands predicted...\n" print "Generating Figure...\n" # Releasing SeqRecs MergedRecs = None SeqRecList = None # Pre-check DistArr Results if len(DistArr) < 2: print "WARNING, "+ str(len(DistArr)) + " sites were found." print "Consider changing parameters.\n" # Generate Figure: ObExRes = pd.DataFrame({ 'gene' : [], 'xval': [], 'yval': []}) try: Cnt = 0 for Dist in DistArr: Cnt += 1 print "PROGRESS: "+str(Cnt) +" of "+ str(len(DistArr)) ObExdf = pd.DataFrame({ 'gene': [Dist[2]], 'xval': [Dist[1]], 'yval': [Dist[3]]}) ObExFram = [ObExRes, ObExdf] ObExRes = pd.concat(ObExFram, ignore_index=True) p = ggplot(aes(x='xval', y='yval'), data=ObExRes) \ + geom_point() \ + ylab("Observed/Expected CpG") \ + xlab("Position (bp) Relative to (ATG = 0)") \ + ggtitle("Predicted CpG Island Position Relative to ATG") p.save(OutFile) except IndexError as e: print 'Error: '+ str(e) sys.exit('Exiting script...') print p # Remove GFF DB os.remove('GFF.db')
Java
#ifndef GLOBALS_H #define GLOBALS_H #include <stdio.h> #include <allegro.h> #include "resource.h" //#define LOG_COMMS // Uncomment this line to enable serial comm logging // system_of_measurements #define METRIC 0 #define IMPERIAL 1 // Display mode flags #define FULL_SCREEN_MODE 0 #define WINDOWED_MODE 1 #define FULLSCREEN_MODE_SUPPORTED 2 #define WINDOWED_MODE_SUPPORTED 4 #define WINDOWED_MODE_SET 8 // Password for Datafiles (Tr. Code Definitions and Resources) #define PASSWORD NULL // Colors in the main palette #define C_TRANSP -1 #define C_BLACK 0 #define C_WHITE 1 #define C_RED 255 #define C_BLUE 254 #define C_GREEN 99 #define C_DARK_YELLOW 54 #define C_PURPLE 9 #define C_DARK_GRAY 126 #define C_GRAY 50 #define C_LIGHT_GRAY 55 // int is_not_genuine_scan_tool; // Options int system_of_measurements; int display_mode; // File names char options_file_name[20]; char data_file_name[20]; char code_defs_file_name[20]; char log_file_name[20]; #ifdef LOG_COMMS char comm_log_file_name[20]; #endif void write_log(const char *log_string); #ifdef LOG_COMMS void write_comm_log(const char *marker, const char *data); #endif DATAFILE *datafile; #endif
Java