code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
from JumpScale import j import JumpScale.baselib.watchdog.manager import JumpScale.baselib.redis import JumpScale.lib.rogerthat descr = """ critical alert """ organization = "jumpscale" enable = True REDIS_PORT = 9999 # API_KEY = j.application.config.get('rogerthat.apikey') redis_client = j.clients.credis.getRedisClient('127.0.0.1', REDIS_PORT) # rogerthat_client = j.clients.rogerthat.get(API_KEY) # ANSWERS = [{'id': 'yes', 'caption': 'Take', 'action': '', 'type': 'button'},] # def _send_message(message, contacts, answers=ANSWERS, alert_flags=6): # result = rogerthat_client.send_message(message, contacts, answers=answers, alert_flags=alert_flags) # if result: # if result['error']: # j.logger.log('Could not send rogerthat message') # return # else: # message_id = result['result'] # return message_id def escalateL1(watchdogevent): if not j.tools.watchdog.manager.inAlert(watchdogevent): watchdogevent.escalationstate = 'L1' # contact1 = redis_client.hget('contacts', '1') message = str(watchdogevent) # message_id = _send_message(message, [contact1,]) # watchdogevent.message_id = message_id j.tools.watchdog.manager.setAlert(watchdogevent) print "Escalate:%s"%message def escalateL2(watchdogevent): if watchdogevent.escalationstate == 'L1': watchdogevent.escalationstate = 'L2' contacts = redis_client.hgetall('contacts') message = str(watchdogevent) message_id = _send_message(message, [contacts['2'], contacts['3']]) watchdogevent.message_id = message_id j.tools.watchdog.manager.setAlert(watchdogevent) def escalateL3(watchdogevent): if watchdogevent.escalationstate == 'L2': watchdogevent.escalationstate = 'L3' contacts = redis_client.hgetall('contacts')['all'].split(',') message = str(watchdogevent) message_id = _send_message(message, contacts) watchdogevent.message_id = message_id j.tools.watchdog.manager.setAlert(watchdogevent)
Jumpscale/jumpscale6_core
apps/watchdogmanager/alerttypes/critical.py
Python
bsd-2-clause
2,105
'use strict'; /** * Karma unit tests. */ describe('<%= componentName %>Service', function(){ var <%= componentName %>service; beforeEach(module('<%= appName %>.<%= moduleName %>')); beforeEach(inject(function($injector) { service = $injector.get('<%= componentName %>'); })); });
urecio/generator-angular-scalable
generators/service/templates/services/%component-name%.service.spec.js
JavaScript
bsd-2-clause
299
using WampSharp.V2.Core.Contracts; namespace WampSharp.V2.PubSub { internal interface IWampRawTopic<TMessage> : ISubscriptionNotifier { bool HasSubscribers { get; } long SubscriptionId { get; } string TopicUri { get; } void Subscribe(ISubscribeRequest<TMessage> request, SubscribeOptions options); void Unsubscribe(IUnsubscribeRequest<TMessage> request); } }
jmptrader/WampSharp
src/net45/WampSharp/WAMP2/V2/PubSub/Interfaces/IWampRawTopic.cs
C#
bsd-2-clause
414
class Nss < Formula desc "Libraries for security-enabled client and server applications" homepage "https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS" url "https://ftp.mozilla.org/pub/security/nss/releases/NSS_3_66_RTM/src/nss-3.66.tar.gz" sha256 "89a79e3a756cf0ac9ba645f4d4c0fc58d4133134401fb0b6c8a74c420bb4cdc9" license "MPL-2.0" livecheck do url "https://ftp.mozilla.org/pub/security/nss/releases/" regex(%r{href=.*?NSS[._-]v?(\d+(?:[._]\d+)+)[._-]RTM/?["' >]}i) end bottle do sha256 cellar: :any, arm64_big_sur: "79464553ec050fedccda7f3e7e3afab391c2aa716e93f9274d67c8f59fd20bf3" sha256 cellar: :any, big_sur: "e61fee35c34b082fc20af4ca89b65f8f5caac4bae8f460cc247e611f7785ee8c" sha256 cellar: :any, catalina: "45332c67dbc4f5414a1c40dc8ba59910de8d9881a6a730b8dfd88e1e3816c7e5" sha256 cellar: :any, mojave: "6a8b60bf3391c2ad8de030e7a2d43fd2458e9f93d6395c3573a81afb04ff7cb2" end depends_on "nspr" uses_from_macos "sqlite" uses_from_macos "zlib" conflicts_with "resty", because: "both install `pp` binaries" conflicts_with "googletest", because: "both install `libgtest.a`" def install ENV.deparallelize cd "nss" args = %W[ BUILD_OPT=1 NSS_ALLOW_SSLKEYLOGFILE=1 NSS_USE_SYSTEM_SQLITE=1 NSPR_INCLUDE_DIR=#{Formula["nspr"].opt_include}/nspr NSPR_LIB_DIR=#{Formula["nspr"].opt_lib} USE_64=1 ] # Remove the broken (for anyone but Firefox) install_name inreplace "coreconf/Darwin.mk", "-install_name @executable_path", "-install_name #{lib}" inreplace "lib/freebl/config.mk", "@executable_path", lib system "make", "all", *args # We need to use cp here because all files get cross-linked into the dist # hierarchy, and Homebrew's Pathname.install moves the symlink into the keg # rather than copying the referenced file. cd "../dist" bin.mkpath Dir.glob("Darwin*/bin/*") do |file| cp file, bin unless file.include? ".dylib" end include_target = include + "nss" include_target.mkpath Dir.glob("public/{dbm,nss}/*") { |file| cp file, include_target } lib.mkpath libexec.mkpath Dir.glob("Darwin*/lib/*") do |file| if file.include? ".chk" cp file, libexec else cp file, lib end end # resolves conflict with openssl, see #28258 rm lib/"libssl.a" (bin/"nss-config").write config_file (lib/"pkgconfig/nss.pc").write pc_file end test do # See: https://developer.mozilla.org/docs/Mozilla/Projects/NSS/tools/NSS_Tools_certutil (testpath/"passwd").write("It's a secret to everyone.") system "#{bin}/certutil", "-N", "-d", pwd, "-f", "passwd" system "#{bin}/certutil", "-L", "-d", pwd end # A very minimal nss-config for configuring firefox etc. with this nss, # see https://bugzil.la/530672 for the progress of upstream inclusion. def config_file <<~EOS #!/bin/sh for opt; do :; done case "$opt" in --version) opt="--modversion";; --cflags|--libs) ;; *) exit 1;; esac pkg-config "$opt" nss EOS end def pc_file <<~EOS prefix=#{prefix} exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include/nss Name: NSS Description: Mozilla Network Security Services Version: #{version} Requires: nspr >= 4.12 Libs: -L${libdir} -lnss3 -lnssutil3 -lsmime3 -lssl3 Cflags: -I${includedir} EOS end end
JCount/homebrew-core
Formula/nss.rb
Ruby
bsd-2-clause
3,529
#---------------------------------------------------------------- # Generated CMake target import file for configuration "MinSizeRel". #---------------------------------------------------------------- # Commands may need to know the format version. set(CMAKE_IMPORT_FILE_VERSION 1) # Import target "dart-collision-bullet" for configuration "MinSizeRel" set_property(TARGET dart-collision-bullet APPEND PROPERTY IMPORTED_CONFIGURATIONS MINSIZEREL) set_target_properties(dart-collision-bullet PROPERTIES IMPORTED_LOCATION_MINSIZEREL "${_IMPORT_PREFIX}/lib/libdart-collision-bullet.6.1.1.dylib" IMPORTED_SONAME_MINSIZEREL "@rpath/libdart-collision-bullet.6.1.dylib" ) list(APPEND _IMPORT_CHECK_TARGETS dart-collision-bullet ) list(APPEND _IMPORT_CHECK_FILES_FOR_dart-collision-bullet "${_IMPORT_PREFIX}/lib/libdart-collision-bullet.6.1.1.dylib" ) # Commands beyond this point should not need to know the version. set(CMAKE_IMPORT_FILE_VERSION)
axeisghost/DART6motionBlur
Xcode/dart/collision/bullet/CMakeFiles/Export/share/dart/cmake/dart_collision-bulletTargets-minsizerel.cmake
CMake
bsd-2-clause
951
{% load staticfiles %} <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" /> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %}
olszak94/django-polls
polls/templates/polls/index.html
HTML
bsd-2-clause
386
#pragma once #include "afxwin.h" // CRegisterInsterface ¶Ô»°¿ò class CRegisterInsterface : public CDialogEx { DECLARE_DYNAMIC(CRegisterInsterface) public: CRegisterInsterface(CWnd* pParent = NULL); // ±ê×¼¹¹Ô캯Êý virtual ~CRegisterInsterface(); // ¶Ô»°¿òÊý¾Ý enum { IDD = IDD_DIALOG_REGISTER }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV Ö§³Ö DECLARE_MESSAGE_MAP() private: CEdit editusername; CEdit editkey; CEdit editrekey; public: afx_msg void OnBnClickedButton2(); };
theDarkForce/chat
chat/chat/chat/RegisterInsterface.h
C
bsd-2-clause
524
/* * Copyright (c) 2015, Archarithms Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. */ package io.bigio.core; /** * A generic class for objects wishing to receive gossip messages. * * @author Andy Trimble */ public interface GossipListener { /** * Receive a gossip message. * * @param message a gossip message. */ public void accept(GossipMessage message); }
Archarithms/bigio
core/src/main/java/io/bigio/core/GossipListener.java
Java
bsd-2-clause
1,899
import tornado.web import json from tornado_cors import CorsMixin from common import ParameterFormat, EnumEncoder class DefaultRequestHandler(CorsMixin, tornado.web.RequestHandler): CORS_ORIGIN = '*' def initialize(self): self.default_format = self.get_argument("format", "json", True) self.show_about = self.get_argument("show_about", True, True) self.pg_version = self.get_argument("pg_version", 9.6, True) self.version = "2.0 beta" def write_about_stuff(self, format_type="alter_system"): default_comment = "--" if format_type == "conf": default_comment = "#" self.write("{} Generated by PGConfig {}\n".format(default_comment, self.version)) self.write("{} http://pgconfig.org\n\n".format(default_comment * 2)) def write_comment(self, format_type, comment): default_comment = "--" if format_type == "conf": default_comment = "#" if comment != "NONE": self.write("\n{} {}\n".format(default_comment, comment)) def write_config(self, output_data): if self.show_about is True: self.write_about_stuff("conf") for category in output_data: self.write("# {}\n".format(category["description"])) for parameter in category["parameters"]: config_value = parameter.get("config_value", "NI") value_format = parameter.get("format", ParameterFormat.NONE) if value_format in (ParameterFormat.String, ParameterFormat.Time): config_value = "'{}'".format(config_value) parameter_comment = parameter.get("comment", "NONE") if parameter_comment != "NONE": self.write_comment("conf", parameter_comment) self.write("{} = {}\n".format(parameter["name"], config_value)) self.write("\n") def write_alter_system(self, output_data): if float(self.pg_version) <= 9.3: self.write("-- ALTER SYSTEM format it's only supported on version 9.4 and higher. Use 'conf' format instead.") else: if self.show_about is True: self.write_about_stuff() for category in output_data: self.write("-- {}\n".format(category["description"])) for parameter in category["parameters"]: config_value = parameter.get("config_value", "NI") parameter_comment = parameter.get("comment", "NONE") self.write_comment("alter_system", parameter_comment) self.write("ALTER SYSTEM SET {} TO '{}';\n".format(parameter[ "name"], config_value)) self.write("\n") def write_plain(self, message=list()): if len(message) == 1: self.write(message[0]) else: for line in message: self.write(line + '\n') def write_bash(self, message=list()): bash_script = """ #!/bin/bash """ self.write(bash_script) if len(message) == 1: self.write('SQL_QUERY="{}"\n'.format(message[0])) self.write('psql -c "${SQL_QUERY}"\n') else: for line in message: self.write('SQL_QUERY="{}"\n'.format(line)) self.write('psql -c "${SQL_QUERY}"\n\n') def write_json_api(self, message): self.set_header('Content-Type', 'application/vnd.api+json') _document = {} _document["data"] = message _meta = {} _meta["copyright"] = "PGConfig API" _meta["version"] = self.version _meta["arguments"] = self.request.arguments _document["meta"] = _meta _document["jsonapi"] = {"version": "1.0"} full_url = self.request.protocol + "://" + self.request.host + self.request.uri _document["links"] = {"self": full_url} self.write( json.dumps( _document, sort_keys=True, separators=(',', ': '), cls=EnumEncoder)) def write_json(self, message=list()): self.set_header('Content-Type', 'application/json') if len(message) == 1: self.write("{ \"output\": \"" + message[0] + "\"}") else: new_output = "{ \"output\": [" first_line = True for line in message: if not first_line: new_output += "," else: first_line = False new_output += "\"{}\"".format(line) new_output += "] } " self.write(new_output) def return_output(self, message=list()): # default_format=self.get_argument("format", "json", True) # converting string input into a list (for solve issue with multiline strings) process_data = [] if not isinstance(message, list): process_data.insert(0, message) else: process_data = message if self.default_format == "json": self.write_json_api(message) elif self.default_format == "bash": self.write_bash(message) elif self.default_format == "conf": self.write_config(message) elif self.default_format == "alter_system": self.write_alter_system(message) else: self.write_plain(message) class GeneratorRequestHandler(DefaultRequestHandler): pass
sebastianwebber/pgconfig-api
common/util.py
Python
bsd-2-clause
5,642
<html> <head> <!-- <link rel="stylesheet" type="text/css" href="epoch_style.css" /> --> <link rel="stylesheet" type="text/css" href="css/bootstrap/bootstrap.css" /> <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="css/bootstrap/bootstrap-responsive.min.css" rel="stylesheet" type="text/css" /> <link href="css/suprtheme/jquery.ui.supr.css" rel="stylesheet" type="text/css"/> <title>Senarai Perolehan Secara Rundingan Terus</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <script type="text/javascript" src="epoch_classes.js"></script> <script type="text/javascript" src="scripts/bootstrap/bootstrap.js"></script> </head> <body> <table width="100%" border="0" cellspacing="0" cellpadding="5"> <tr valign="top"> <td width="100%"> <!-- Temporary Disable --> <!-- <form name="form1" method="get" action="/templates/theme427/rttender.php"> <table width="100%" border="0" cellspacing="1" cellpadding="2"> <tr> <td colspan="2" valign="top"><font size="2" face="Arial, Helvetica, sans-serif"><strong>Senarai Perolehan Secara Rundingan Terus Terkini</strong></font></td> <td width="15%" valign="top">&nbsp;</td> <td width="35%" align="right" valign="top"><font size="2"><font face="Arial, Helvetica, sans-serif"> <a href="keputusantender_arkib.php">Arkib Perolehan Secara Rundingan Terus Kerajaan</a></font></font> </td> </tr> <tr> <td width="15%" valign="top">&nbsp;</td> <td width="35%" valign="top">&nbsp;</td> <td valign="top">&nbsp;</td> <td valign="top">&nbsp;</td> </tr> <tr> <td valign="top"><font size="1"><font face="Arial, Helvetica, sans-serif">Tajuk Tender:</font></font></td> <td valign="top"><font size="1"><font face="Arial, Helvetica, sans-serif"> <input name="cari_tender_title" type="text" id="cari_tender_title" value="" size="30"> </font></font></td> <td valign="top"><font size="1"><font face="Arial, Helvetica, sans-serif">Kategori Perolehan:</font></font></td> <td valign="top"><font size="1"><font face="Arial, Helvetica, sans-serif"> </font><font size="1"><font face="Arial, Helvetica, sans-serif"> <select name="cari_tender_cat" id="cari_tender_cat"> <option selected value="">Semua Kategori</option> <option >KERJA</option> <option >BEKALAN</option> <option >PERKHIDMATAN BUKAN PERUNDING</option> <option >BEKALAN & PERKHIDMATAN BUKAN PERUNDING</option> </select> </font></font><font face="Arial, Helvetica, sans-serif"> </font></font></td> </tr> <tr> <td valign="top"><font size="1"><font face="Arial, Helvetica, sans-serif">Kementerian:</font></font></td> <td valign="top"><font size="1"><font face="Arial, Helvetica, sans-serif"> </font><font size="1"><font face="Arial, Helvetica, sans-serif"> <select name="cari_min_id" id="cari_min_id"> <option selected value="">Semua Kementerian</option> <option selected value="">JABATAN PERDANA MENTERI</option> <option selected value="">KEMENTERIAN BELIA DAN SUKAN</option> <option selected value="">KEMENTERIAN DALAM NEGERI</option> <option selected value="">KEMENTERIAN KEMAJUAN LUAR BANDAR DAN WILAYAH</option> <option selected value="">KEMENTERIAN KERJA RAYA</option> <option selected value="">KEMENTERIAN KESEJAHTERAAN BANDAR, PERUMAHAN DAN KERAJAAN TEMPATAN</option> <option selected value="">KEMENTERIAN KESIHATAN</option> <option selected value="">KEMENTERIAN KEWANGAN</option> <option selected value="">KEMENTERIAN KOMUNIKASI DAN MULTIMEDIA</option> <option selected value="">KEMENTERIAN LUAR NEGERI</option> <option selected value="">KEMENTERIAN PELANCONGAN DAN KEBUDAYAAN MALAYSIA</option> <option selected value="">KEMENTERIAN PEMBANGUNAN WANITA, KELUARGA DAN MASYARAKAT</option> <option selected value="">KEMENTERIAN PENDIDIKAN</option> <option selected value="">KEMENTERIAN PENGAJIAN TINGGI</option> <option selected value="">KEMENTERIAN PENGANGKUTAN</option> <option selected value="">KEMENTERIAN PERDAGANGAN ANTARABANGSA DAN INDUSTRI</option> <option selected value="">KEMENTERIAN PERDAGANGAN DALAM NEGERI, KOPERASI DAN KEPENGGUNAAN</option> <option selected value="">KEMENTERIAN PERTAHANAN</option> <option selected value="">KEMENTERIAN PERTANIAN DAN INDUSTRI ASAS TANI</option> <option selected value="">KEMENTERIAN SAINS, TEKNOLOGI DAN INOVASI</option> <option selected value="">KEMENTERIAN SUMBER ASLI DAN ALAM SEKITAR</option> <option selected value="">KEMENTERIAN SUMBER MANUSIA</option> <option selected value="">KEMENTERIAN TENAGA, TEKNOLOGI HIJAU DAN AIR</option> <option selected value="">PENTADBIRAN KERAJAAN NEGERI PERLIS</option> </select> </font> </font> <font face="Arial, Helvetica, sans-serif"> </font></font></td> </tr> <tr> <td valign="top"><font size="1"><font face="Arial, Helvetica, sans-serif">Kriteria :</font></font></td> <td valign="top"><font size="1"><font face="Arial, Helvetica, sans-serif"> <input name="cari_tender_criteria" type="text" id="cari_tender_criteria" value="" size="30"> </font></font></td> </tr> <tr> <td valign="top"><font size="1" face="Arial, Helvetica, sans-serif">Nilai Perolehan:</font></td> <td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr valign="top"> <td width="80%"><font size="1" face="Arial, Helvetica, sans-serif"> RM <input name="cari_tender_price_start" type="text" id="cari_tender_price_start" value="" size="10"> </font> <div class="row-fluid"> <label class="form-label span4" for="normal">Nilai Perolehan:</label> <input class="span8 mask" id="mask-eyeScript" type="text" /> </div> </td> </tr> </table></td> <td valign="top">&nbsp;</td> <td valign="middle"><font size="1"><font face="Arial, Helvetica, sans-serif"> <input name="Submit" type="submit" id="Submit" value=" Cari "> </font><font size="1"><font face="Arial, Helvetica, sans-serif"><font size="1"><font face="Arial, Helvetica, sans-serif"><font size="1"><font face="Arial, Helvetica, sans-serif"><font size="2"> <input name="semula" type="button" id="semula" value=" Semula " onClick="location.href='/templates/theme427/rttender.php'"> </font><font size="1"><font face="Arial, Helvetica, sans-serif"><font size="1"> <font face="Arial, Helvetica, sans-serif"><font size="1"><font face="Arial, Helvetica, sans-serif"><font size="2"> </font></font></font><font size="2"> </font></font></font><font size="2"> <input type="hidden" name="sort" value=""> <input type="hidden" name="by" value=""> </font></font></font></font></font></font></font></font></font><font face="Arial, Helvetica, sans-serif"></font></font></td> </tr> </table> </form> --> <!-- SORTING BY FIELD NAME --> <div align="right"> <!-- Temporary Disable --> <div align="center"> <a style="text-transform: uppercase; font-family: Arial; color: #FF0000;"><b>Senarai Perolehan Secara Rundingan Terus </b></a><br/> <a style="color: #FF0000;"><i>Penafian Tuntutan </a>: Sebarang Maklumat Mengenai Perolehan Secara Rundingan Terus Hendaklah Dirujuk Terus ke Kementerian/Agensi Yang Berkenaan.</i> </div> <font size="2" face="Arial, Helvetica, sans-serif">Sebanyak <strong>150</strong> rekod ditemui</font> </div> <table width="100%" border="1" cellpadding="3" cellspacing="0" bordercolor="#000000"> <tr align="center" bgcolor="#CCCCCC"> <td width="2%"><font size="2" face="Arial, Helvetica, sans-serif"><strong>BIL.</strong></font></td> <td width="27%"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center"><font size="2" face="Arial, Helvetica, sans-serif"><strong>TAJUK PEROLEHAN / PROJEK</strong></font></td> <td align="right"><font size="2" face="Arial, Helvetica, sans-serif"><strong><a href="/templates/theme427/rttender.php?sort=ASC&by=rttender_title"> <img src="images/asc.gif" width="9" height="11" border="0"></a><br> <a href="/templates/theme427/rttender.php?sort=DESC&by=rttender_title"> <img src="images/desc.gif" width="9" height="11" border="0"></a></strong></font></td> </tr> </table> <font size="2" face="Arial, Helvetica, sans-serif">&nbsp;</font> </td> <td width="8%"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center"><font size="2" face="Arial, Helvetica, sans-serif"><strong>KATEGORI PEROLEHAN</strong></font></td> <td align="right"><font size="2" face="Arial, Helvetica, sans-serif"><strong><a href="/templates/theme427/rttender.php?sort=ASC&by=rttender_cat"> <img src="images/asc.gif" width="9" height="11" border="0"></a><br> <a href="/templates/theme427/rttender.php?sort=DESC&by=rttender_cat"> <img src="images/desc.gif" width="9" height="11" border="0"></a></strong></font></td> </tr> </table> </td> <td width="16%"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center"><font size="2" face="Arial, Helvetica, sans-serif"><strong>KEMENTERIAN</strong></font></td> <td align="right"><font size="2" face="Arial, Helvetica, sans-serif"><strong><a href="/templates/theme427/rttender.php?sort=ASC&by=rtmin_name"> <img src="images/asc.gif" width="9" height="11" border="0"></a><br> <a href="/templates/theme427/rttender.php?sort=DESC&by=rtmin_name"> <img src="images/desc.gif" width="9" height="11" border="0"></a></strong></font></td> </tr> </table> <font size="2" face="Arial, Helvetica, sans-serif">&nbsp;</font></td> <td width="12%"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center"><font size="2" face="Arial, Helvetica, sans-serif"><strong>NAMA SYARIKAT</strong></font></td> <td align="right"><font size="2" face="Arial, Helvetica, sans-serif"><strong><a href="/templates/theme427/rttender.php?sort=ASC&by=rttender_com_name"> <img src="images/asc.gif" width="9" height="11" border="0"></a><br> <a href="/templates/theme427/rttender.php?sort=DESC&by=rttender_com_name"> <img src="images/desc.gif" width="9" height="11" border="0"></a></strong></font></td> </tr> </table> </td> <td width="8%"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center"><font size="2" face="Arial, Helvetica, sans-serif"><strong>NILAI PEROLEHAN (RM)</strong></font></td> <td align="right"><font size="2" face="Arial, Helvetica, sans-serif"><strong><a href="/templates/theme427/rttender.php?sort=ASC&by=rttender_price"> <img src="images/asc.gif" width="9" height="11" border="0"></a><br> <a href="/templates/theme427/rttender.php?sort=DESC&by=rttender_price"> <img src="images/desc.gif" width="9" height="11" border="0"></a></strong></font></td> </tr> </table> </td> <td width="9%"> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center"><font size="2" face="Arial, Helvetica, sans-serif"><strong>KRITERIA RUNDINGAN TERUS </strong></font></td> <td align="right"><font size="2" face="Arial, Helvetica, sans-serif"><strong><a href="/templates/theme427/rttender.php?sort=ASC&by=rttender_criteria"> <img src="images/asc.gif" width="9" height="11" border="0"></a><br> <a href="/templates/theme427/rttender.php?sort=DESC&by=rttender_criteria"> <img src="images/desc.gif" width="9" height="11" border="0"></a></strong></font></td> </tr> </table> </td> </tr> <tr valign="top"> <td bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">21.</font></td> <td bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif"> PERMOHONAN UNTUK MELAKSANAKAN PERKHIDMATAN MENYEDIAKAN IKLAN DI BADAN BAS SHUTTLE KLIA2, BAS METRO DAN BAS RAPID KL SECARA RUNDINGAN TERUS DENGAN SYARIKAT MESRA INDAH JAYA SDN. BHD SEMPENA MAHA 2014 PADA 20 HINGGA 30 NOVEMBER 2014 </font></td> <td align="center" bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">PERKHIDMATAN BUKAN PERUNDING</font></td> <td bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">KEMENTERIAN PERTANIAN DAN INDUSTRI ASAS TANI</font></td> <td align="center" bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">MESRA INDAH JAYA AUTOPART SERVICES & TRADING SDN. BHD.</font></td> <td align="center" bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">128,000.00</font></td> <td align="center" bgcolor="#FFFFFF" style="text-transform: uppercase;"><font size="1" face="Arial, Helvetica, sans-serif">Satu Punca Bekalan/ Perkhidmatan (Pembuat/ Pemegang Frachais), Penyeragaman</font></td> </tr> <tr valign="top"> <td bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">22.</font></td> <td bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif"> PERMOHONAN UNTUK MELAKSANAKAN PEROLEHAN MEMBEKAL TIGA (3) UNIT MESIN MENANAM PADI JENIS MENUNGGANG DAN MENANAM BERBARIS 6 KE BAHAGIAN KEJURUTERAAN PERTANIAN, JABATAN PERTANIAN, JABATAN PERTANIAN SERDANG SECARA RUNDINGAN TERUS </font></td> <td align="center" bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">BEKALAN</font></td> <td bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">KEMENTERIAN PERTANIAN DAN INDUSTRI ASAS TANI</font></td> <td align="center" bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">MINDA AGRIMACHINERY SDN BHD</font></td> <td align="center" bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">144,000.00</font></td> <td align="center" bgcolor="#FFFFCC" style="text-transform: uppercase;"><font size="1" face="Arial, Helvetica, sans-serif">Satu Punca Bekalan/ Perkhidmatan (Pembuat/ Pemegang Frachais)</font></td> </tr> <tr valign="top"> <td bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">23.</font></td> <td bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif"> PELANJUTAN KONTRAK SYARIKAT ALAM TEKNOKRAT SDN BHD BAGI PERKHIDMATAN PEMBANGUNAN LAMAN WEB LEMBAGA PERINDUSTRIAN NANAS MALAYSIA (LPNM) TAHUN 2015 UNTUK TEMPOH SATU (1) TAHUN </font></td> <td align="center" bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">PERKHIDMATAN BUKAN PERUNDING</font></td> <td bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">KEMENTERIAN PERTANIAN DAN INDUSTRI ASAS TANI</font></td> <td align="center" bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">ALAM TEKNOKRAT SDN. BHD.</font></td> <td align="center" bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">151,200.00</font></td> <td align="center" bgcolor="#FFFFFF" style="text-transform: uppercase;"><font size="1" face="Arial, Helvetica, sans-serif">Penyeragaman, Kepakaran</font></td> </tr> <tr valign="top"> <td bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">24.</font></td> <td bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif"> PELANTIKAN PUTRAJAYA INTERNATIONAL CONVENTION CENTRE SDN BHD (PICC) UNTUK MAJLIS KONVOKESYEN SEKTOR PERTANIAN 2014 ANJURAN MAJLIS LATIHAN PERTANIAN KEBANGSAAN (NATC) DENGAN KERJASAMA JABATAN PERTANIAN MALAYSIA DAN JABATAN PERKHIDMATAN VETERINAR MALAYSIA PADA 29 DAN 30 OKTOBER 2014 </font></td> <td align="center" bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">PERKHIDMATAN BUKAN PERUNDING</font></td> <td bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">KEMENTERIAN PERTANIAN DAN INDUSTRI ASAS TANI</font></td> <td align="center" bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">PUTRAJAYA INTERNATIONAL CONVENTION CENTRE SDN BHD</font></td> <td align="center" bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">157,780.00</font></td> <td align="center" bgcolor="#FFFFCC" style="text-transform: uppercase;"><font size="1" face="Arial, Helvetica, sans-serif">Satu Punca Bekalan/ Perkhidmatan (Pembuat/ Pemegang Frachais)</font></td> </tr> <tr valign="top"> <td bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">25.</font></td> <td bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif"> PERMOHONAN UNTUK MELAKSANAKAN PERKHIDMATAN PENYELENGGARAAN PERALATAN LIQUID CHROMATOGRAPH TRIPLE QUADRUPOLE MASS SPECTOMETER (LCMSMS) SELAMA DUA (2) TAHUN SECARA RUNDINGAN TERUS OLEH BAHAGIAN KAWALAN RACUN PEROSAK, JABATAN PERTANIAN SELAMA DUA (2) TAHUN </font></td> <td align="center" bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">PERKHIDMATAN BUKAN PERUNDING</font></td> <td bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">KEMENTERIAN PERTANIAN DAN INDUSTRI ASAS TANI</font></td> <td align="center" bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">ANALISA RESOURCES (M) SDN. BHD.</font></td> <td align="center" bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">180,000.00</font></td> <td align="center" bgcolor="#FFFFFF" style="text-transform: uppercase;"><font size="1" face="Arial, Helvetica, sans-serif">Satu Punca Bekalan/ Perkhidmatan (Pembuat/ Pemegang Frachais)</font></td> </tr> <tr valign="top"> <td bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">26.</font></td> <td bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif"> RUNDINGAN TERUS BAGI MEMBEKAL, MENGHANTAR, MEMASANG DAN MENGUJIGUNA SATU (1) UNIT MASS SELECTIVE DETECTOR KE PUSAT PENYELIDIKAN PADI & TANAMAN INDUSTRI, IBU PEJABAT MARDI SERDANG (ONE-OFF BAGI TAHUN 2014) </font></td> <td align="center" bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">BEKALAN</font></td> <td bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">KEMENTERIAN PERTANIAN DAN INDUSTRI ASAS TANI</font></td> <td align="center" bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">AGILENT TECHNOLOGIES SALES (MALAYSIA) SDN. BHD.</font></td> <td align="center" bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">205,000.00</font></td> <td align="center" bgcolor="#FFFFCC" style="text-transform: uppercase;"><font size="1" face="Arial, Helvetica, sans-serif">Satu Punca Bekalan/ Perkhidmatan (Pembuat/ Pemegang Frachais), Penyeragaman</font></td> </tr> <tr valign="top"> <td bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">27.</font></td> <td bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif"> RUNDINGAN TERUS BAGI KONTRAK PERKHIDMATAN SOKONGAN DAN PENYELENGGARAAN SISTEM PENGURUSAN MAKMAL [LABORATORY INFORMATION MANAGEMENT SYSTEM (LIMS)] DI PUSAT PENYELIDIKAN BIOTEKNOLOGI, IBU PEJABAT MARDI SERDANG, SELANGOR UNTUK TEMPOH SATU (1) TAHUN MULAI 1/11/2014 HINGGA 31/10/2015 </font></td> <td align="center" bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">PERKHIDMATAN BUKAN PERUNDING</font></td> <td bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">KEMENTERIAN PERTANIAN DAN INDUSTRI ASAS TANI</font></td> <td align="center" bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">EFFECTIVE SHIELD SDN. BHD.</font></td> <td align="center" bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">220,800.00</font></td> <td align="center" bgcolor="#FFFFFF" style="text-transform: uppercase;"><font size="1" face="Arial, Helvetica, sans-serif">Satu Punca Bekalan/ Perkhidmatan (Pembuat/ Pemegang Frachais), Penyeragaman</font></td> </tr> <tr valign="top"> <td bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">28.</font></td> <td bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif"> RUNDINGAN TERUS BAGI CADANGAN MENGUBAHSUAI DUA UNIT (2) BILIK SEJUK SEDIA ADA MENJADI AIRTIGHT CA ROOM DAN KERJA-KERJA BERKAITAN DI KOMPLEKS LEPAS TUAI, PUSAT PENYELIDIKAN HORTIKULTUR, IBU PEJABAT MARDI SERDANG, SELANGOR (TEMPOH SIAP 6 BULAN) </font></td> <td align="center" bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">KERJA</font></td> <td bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">KEMENTERIAN PERTANIAN DAN INDUSTRI ASAS TANI</font></td> <td align="center" bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">ETD MAKMUR (M) SDN.BHD.</font></td> <td align="center" bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">265,500.00</font></td> <td align="center" bgcolor="#FFFFCC" style="text-transform: uppercase;"><font size="1" face="Arial, Helvetica, sans-serif">Penyeragaman, Satu Punca Bekalan/ Perkhidmatan (Pembuat/ Pemegang Frachais), Kepakaran</font></td> </tr> <tr valign="top"> <td bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">29.</font></td> <td bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif"> PERMOHONAN PEMBELIAN 11 UNIT KIT UJIAN ELISA KIT FOR FMD ANTIBODY DETECTION (LIQUID PHASE BLOCKING IMMUNOASSAY) DAN 1 UNIT KIT ELISA KIT FOR FMD ANTIGEN DETECTION DARIPADA BIOLOGICAL DIAGNOSTIC SUPPLIES LIMITED SECARA RUNDINGAN TERUS( TAHUN 2014) </font></td> <td align="center" bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">BEKALAN</font></td> <td bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">KEMENTERIAN PERTANIAN DAN INDUSTRI ASAS TANI</font></td> <td align="center" bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">BIOLOGICAL DIAGNOSTIC SUPPLIES LIMITED</font></td> <td align="center" bgcolor="#FFFFFF"><font size="1" face="Arial, Helvetica, sans-serif">276,779.02</font></td> <td align="center" bgcolor="#FFFFFF" style="text-transform: uppercase;"><font size="1" face="Arial, Helvetica, sans-serif">Satu Punca Bekalan/ Perkhidmatan (Pembuat/ Pemegang Frachais)</font></td> </tr> <tr valign="top"> <td bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">30.</font></td> <td bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif"> PERMOHONAN KELULUSAN PEROLEHAN SECARA RUNDINGAN TERUS BAGI MELAKSANAKAN KERJA-KERJA PENAMBAHBAIKAN APLIKASI SISTEM PORTAL E-NELAYAN SELARAS DENGAN PENINGKATAN PERISIAN-PERISIAN SERVER DARI TEKNOLOGI 32BIT KEPADA 64BIT DENGAN EBI RESOURCES SDN BHD. </font></td> <td align="center" bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">PERKHIDMATAN BUKAN PERUNDING</font></td> <td bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">KEMENTERIAN PERTANIAN DAN INDUSTRI ASAS TANI</font></td> <td align="center" bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">EBI RESOURCES SDN. BHD.</font></td> <td align="center" bgcolor="#FFFFCC"><font size="1" face="Arial, Helvetica, sans-serif">300,000.00</font></td> <td align="center" bgcolor="#FFFFCC" style="text-transform: uppercase;"><font size="1" face="Arial, Helvetica, sans-serif">Penyeragaman</font></td> </tr> </table> <br> <table border="0" align="center" cellpadding="5" cellspacing="0"> <tr align="center" valign="middle"> <td><font size="1" face="Arial, Helvetica, sans-serif"> <a href="/templates/theme427/rttender.php?sort=&by=&page=1"> <img src="images/arrow_first.gif" width="27" height="20" border="0"><br> Mula </a> </font></td> <td><font size="1" face="Arial, Helvetica, sans-serif"> <a href="/templates/theme427/rttender.php?sort=&by=&page=2"> <img src="images/arrow_previous.gif" width="11" height="20" border="0"><br> Sebelum </a> </font></td> <td><font size="3" face="Arial, Helvetica, sans-serif"> <a href="/templates/theme427/rttender.php?sort=&by=&page=1">1</a> <a href="/templates/theme427/rttender.php?sort=&by=&page=2">2</a> <strong>3</strong> <a href="/templates/theme427/rttender.php?sort=&by=&page=4">4</a> <a href="/templates/theme427/rttender.php?sort=&by=&page=5">5</a> ... </font></td> <td><font size="1" face="Arial, Helvetica, sans-serif"> <a href="/templates/theme427/rttender.php?sort=&by=&page=4"> <img src="images/arrow_next.gif" width="11" height="20" border="0"><br> Selepas </a> </font></td> <td><font size="1" face="Arial, Helvetica, sans-serif"> <a href="/templates/theme427/rttender.php?sort=&by=&page=15"> <img src="images/arrow_last.gif" width="27" height="20" border="0"><br> Akhir </a> </font></td> </tr> </table> </td> </tr> </table> <div align="center"> <a style="color: #FF0000;"><i>Penafian Tuntutan </a>: Sebarang Maklumat Mengenai Perolehan Secara Rundingan Terus Hendaklah Dirujuk Terus ke Kementerian/Agensi Yang Berkenaan.</i> </div> </body> </html> <!-- Module: Iklan & Keputusan Tender with RSS Feeder Author: Mohd Saffuan bin Suntong Position: Penolong Setiausaha (Operasi) Dept: Bahagian Pengurusan Teknologi Maklumat Section: Infrastruktur, Keselamatan dan Logistik -->
klrkdekira/durian-runtuh
downloads/3.html
HTML
bsd-2-clause
27,644
/*++ Copyright (C) 2018 3MF Consortium All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. Abstract: NMR_ModelReaderNode100_Components.h defines the Model Components Reader Node Class. --*/ #ifndef __NMR_MODELREADERNODE100_COMPONENTS #define __NMR_MODELREADERNODE100_COMPONENTS #include "Model/Reader/NMR_ModelReaderNode.h" #include "Model/Classes/NMR_ModelComponentsObject.h" namespace NMR { class CModelReaderNode093_Components : public CModelReaderNode { private: protected: CModelComponentsObject * m_pComponentsObject; virtual void OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue); virtual void OnNSChildElement(_In_z_ const nfChar * pChildName, _In_z_ const nfChar * pNameSpace, _In_ CXmlReader * pXMLReader); public: CModelReaderNode093_Components() = delete; CModelReaderNode093_Components(_In_ CModelComponentsObject * pComponentsObject, _In_ PModelWarnings pWarnings); virtual void parseXML(_In_ CXmlReader * pXMLReader); }; } #endif // __NMR_MODELREADERNODE093_COMPONENTS
3MFConsortium/lib3mf
Include/Model/Reader/v093/NMR_ModelReaderNode093_Components.h
C
bsd-2-clause
2,258
#pragma once #include <iosfwd> #include <map> #include "../datastructs/var_degree_map.h" #include "../semirings/free-semiring.h" #include "commutative_polynomial.h" template <typename SR> class NonCommutativePolynomialBase; template <typename SR> class NonCommutativeMonomial; enum elemType {Variable, SemiringType}; template <typename SR> class NonCommutativeMonomialBase { protected: friend class NonCommutativeMonomial<SR>; friend class NonCommutativePolynomialBase<SR>; template <typename S> friend class NonCommutativeMonomialBase; /* a monomial is represented by three vectors * idx_ holds pairs of (type, index), type is either variable or sr * the index gives absolute position inside the chosen type vector * variables_ holds all variables * srs_ holds all semiring elements */ std::vector<std::pair<elemType,int>> idx_; std::vector<VarId> variables_; std::vector<SR> srs_; /* Private constructor to not leak the internal data structure. */ NonCommutativeMonomialBase(std::vector<std::pair<elemType,int>> &idx, std::vector<VarId> &variables, std::vector<SR> &srs) : idx_(idx), variables_(variables), srs_(srs) {} NonCommutativeMonomialBase(std::vector<std::pair<elemType,int>> &&idx, std::vector<VarId> &&variables, std::vector<SR> &&srs) : idx_(std::move(idx)), variables_(std::move(variables)), srs_(std::move(srs)) {} /* * evaluate all variables except the one at the exceptional position * returns a monomial of the form aXb where a,b are in SR. * TODO: check, that all variables are present in the valuation! */ NonCommutativeMonomialBase<SR> eval_all_except(const int except_pos, const ValuationMap<SR>& valuation) const { SR a = SR::one(); SR b = SR::one(); assert((unsigned int)except_pos < this->variables_.size()); /* * go through the idx_-vector, * - evaluate all variables encountered as long as its position is less than except_pos * - on the way: multiply everything (evaluated vars and sr-elems) onto a * - after except_pos has been found: multiply everything encountered onto b */ SR* prod = &a; for(auto p : this->idx_) { if(p.first == elemType::Variable && except_pos == p.second) { prod = &b; continue; } if(p.first == elemType::Variable) (*prod) *= valuation.at(this->variables_.at(p.second)); else (*prod) *= this->srs_.at(p.second); } std::vector<std::pair<elemType,int> > info{std::make_pair(elemType::SemiringType,0), std::make_pair(elemType::Variable,0), std::make_pair(elemType::SemiringType,1),}; std::vector<VarId> vars{this->variables_.at(except_pos)}; std::vector<SR> sr{a,b}; return NonCommutativeMonomialBase(info, vars, sr); } public: /* Since we don't manage any resources, we can simply use the default * constructors and assignment operators. */ NonCommutativeMonomialBase() = default; NonCommutativeMonomialBase(const NonCommutativeMonomialBase &m) = default; NonCommutativeMonomialBase(NonCommutativeMonomialBase &&m) = default; NonCommutativeMonomialBase(std::initializer_list<std::pair<elemType,int>> idx, std::initializer_list<VarId> variables, std::initializer_list<SR> srs) : idx_(idx), variables_(variables), srs_(srs_) {} NonCommutativeMonomialBase& operator=(const NonCommutativeMonomialBase &m) = default; NonCommutativeMonomialBase& operator=(NonCommutativeMonomialBase &&m) = default; /* Multiply two monomials and return a result in normalform if both monomials * already are in normal form */ NonCommutativeMonomialBase operator*(const NonCommutativeMonomialBase &monomial) const { auto tmp_idx = this->idx_; auto tmp_variables = this->variables_; auto tmp_srs = this->srs_; bool normalform = true; unsigned int offset_variables = tmp_variables.size(); unsigned int offset_srs = tmp_srs.size(); // assume both monomials are in normal form // then the only position where this assumption might // be violated is where both are concatenated if(tmp_idx.back().first == SemiringType && monomial.idx_.front().first == SemiringType) { tmp_idx.pop_back(); offset_srs--; normalform = false; } for (auto &p : monomial.idx_) { if(p.first == Variable) tmp_idx.push_back({Variable, p.second + offset_variables}); else if (p.first == SemiringType) tmp_idx.push_back({SemiringType, p.second + offset_srs}); } for (auto v : monomial.variables_) tmp_variables.push_back(v); //for (auto s : monomial.srs_) for(auto s = monomial.srs_.begin(); s != monomial.srs_.end(); s++) if(!normalform && s == monomial.srs_.begin()) { auto elem = tmp_srs.back(); tmp_srs.pop_back(); tmp_srs.push_back(elem * (*s)); normalform = true; } else { tmp_srs.push_back(*s); } //return NonCommutativeMonomialBase(std::move(tmp_idx), std::move(tmp_variables), std::move(tmp_srs)); return NonCommutativeMonomialBase(tmp_idx, tmp_variables, tmp_srs); } /* Multiply a monomial with a variable. */ NonCommutativeMonomialBase operator*(const VarId &var) const { auto tmp_idx = this->idx_; auto tmp_variables = this->variables_; auto tmp_srs = this->srs_; tmp_idx.push_back(std::pair<elemType, int>(Variable, tmp_variables.size())); tmp_variables.push_back(var); return NonCommutativeMonomialBase(tmp_idx, tmp_variables, tmp_srs); } /* Multiply a monomial with a semiring element and return it in normal form. */ NonCommutativeMonomialBase operator*(const SR &sr) const { auto tmp_idx = this->idx_; auto tmp_variables = this->variables_; auto tmp_srs = this->srs_; // assume the monomial is in normal form if(tmp_idx.back().first() == SemiringType) { auto elem = tmp_srs.back(); tmp_srs.pop_back(); tmp_srs.push_back(elem * sr); } else { tmp_idx.push_back(std::pair<elemType, int>(SemiringType, tmp_srs.size())); tmp_srs.push_back(sr); } return NonCommutativeMonomialBase(tmp_idx, tmp_variables, tmp_srs); } /* convert this monomial into an commutative one * return a Polynomial, because the semiring element is not saved * in the commutative version of the monomial but in the polynomial */ CommutativePolynomial<SR> make_commutative() const { CommutativePolynomial<SR> result_polynomial = CommutativePolynomial<SR>::one(); for(auto const &sr : this->srs_) { result_polynomial *= sr; } for(auto const &var : this->variables_) { result_polynomial *= var; } return result_polynomial; } /* derivative function which is used in the polynomial derivative function. * for the variables for the d-1-th iteration we use the given map 'substitution' */ NonCommutativePolynomialBase<SR> derivative(const SubstitutionMap &substitution) const { NonCommutativePolynomialBase<SR> result; // empty polynomial auto subst_monomial = this->subst(substitution); // substitute all variables for(unsigned int position = 0; position < this->variables_.size(); position++) { // the variable at the position is the variable which should not be touched auto tmp = subst_monomial; tmp.variables_.at(position) = this->variables_.at(position); // therefore restore this one... result += tmp; } return result; } /* * compute the linearization of the polynomial at the given point "valuation" * to this end, we linearize every monomial and sum them up */ NonCommutativePolynomialBase<SR> differential_at(const ValuationMap<SR> &valuation) const { NonCommutativePolynomialBase<SR> result; // empty polynomial = 0 (constant monomials have differential f(x)=0) for(unsigned int position = 0; position < this->variables_.size(); position++) { // the variable at the position is the variable which should not be touched, all others will be evaluated result += this->eval_all_except(position, valuation); } return result; } SR calculate_delta_helper( const std::vector<bool> &permutation, const ValuationMap<SR> &de2, // [d-2], true const ValuationMap<SR> &dl1 // (d-1), false ) const { SR tmp = SR::one(); for(auto const &p : this->idx_) { if(p.first == Variable) { if(permutation.at(p.second) == true) { // use [d-2] auto value_iter = de2.find(this->variables_.at(p.second)); assert(value_iter != de2.end()); tmp *= value_iter->second; } else { // if (permutation.at(p.second) == false) // use (d-1) auto value_iter = dl1.find(this->variables_.at(p.second)); assert(value_iter != dl1.end()); tmp *= value_iter->second; } } else if (p.first == SemiringType) tmp *= this->srs_.at(p.second); } return tmp; } SR calculate_delta( const ValuationMap<SR> &de2, // [d-2], true const ValuationMap<SR> &dl1 // (d-1), false ) const { SR result = SR::null(); /* outer loop handles the different cases (trees with exactly n-times dim == d-1 ) * start with n = 2, which means, exactly 2 children have dimensions exactly d-1 */ for(unsigned int n = 2; n <= this->variables_.size(); n++) { /* order of a vector of bools is [false, true] < [true, false] */ std::vector<bool> permutation(n, false); // these are the (d-1) elements std::vector<bool> permutation2(this->variables_.size()-n, true); // these are the [d-2] elements permutation.insert(permutation.end(), permutation2.begin(), permutation2.end()); do { result += calculate_delta_helper(permutation, de2, dl1); } while(std::next_permutation(permutation.begin(), permutation.end())); } return result; } /* Evaluate the monomial given the map from variables to values. */ SR eval(const ValuationMap<SR> &values) const { auto result = SR::one(); for (const auto &p : this->idx_) { if (p.first == Variable) { auto value_iter = values.find(this->variables_.at(p.second)); /* All variables should be in the values map. */ assert(value_iter != values.end()); result *= value_iter->second; } else if (p.first == SemiringType) result *= this->srs_.at(p.second); } return result; } /* Partially evaluate the monomial. */ NonCommutativeMonomialBase partial_eval( const ValuationMap<SR> &values) const { NonCommutativeMonomialBase result_monomial; for(auto p : this->idx_) { if (p.first == Variable) { auto value_iter = values.find(this->variables_.at(p.second)); if (value_iter == values.end()) { /* Variable not found in the mapping, so keep it. */ result_monomial.idx_.push_back(std::pair<elemType, int>(Variable, result_monomial.variables_.size())); result_monomial.variables_.push_back(this->variables_.at(p.second)); } else { /* Variable found, use it for evaluation */ if(result_monomial.idx_.size() > 0 && result_monomial.idx_.back().first == SemiringType) { // multiplying sr-elements to achieve normal form auto elem = result_monomial.srs_.back(); result_monomial.srs_.pop_back(); result_monomial.srs_.push_back(elem * value_iter->second); } else { result_monomial.idx_.push_back(std::pair<elemType, int>(SemiringType, result_monomial.srs_.size())); result_monomial.srs_.push_back(value_iter->second); } } } else if (p.first == SemiringType) { if(result_monomial.idx_.size() > 0 && result_monomial.idx_.back().first == SemiringType) { // multiplying sr-elements to achieve normal form auto elem = result_monomial.srs_.back(); result_monomial.srs_.pop_back(); result_monomial.srs_.push_back(elem * this->srs_.at(p.second)); } else { result_monomial.idx_.push_back(std::pair<elemType, int>(SemiringType, result_monomial.srs_.size())); result_monomial.srs_.push_back(this->srs_.at(p.second)); } } } return result_monomial; } /* Variable substitution. */ NonCommutativeMonomialBase subst(const SubstitutionMap &mapping) const { VarDegreeMap tmp_variables; auto result_monomial = *this; // copy it to work with it for(auto p : result_monomial.idx_) { if(p.first == Variable) { auto old_new_iter = mapping.find(this->variables_.at(p.second)); if(old_new_iter != mapping.end()) { // substitute result_monomial.variables_.at(p.second) = old_new_iter->second; } else { // do nothing continue; } } else { // do nothing continue; } } return result_monomial; } /* Convert this monomial to an element of the free semiring. */ FreeSemiring make_free(std::unordered_map<SR, VarId, SR> *valuation) const { FreeSemiring result = FreeSemiring::one(); for (auto p : this->idx_) { if (p.first == Variable) { result *= FreeSemiring(this->variables_.at(p.second)); } else if (p.first == SemiringType) { { auto tmp_sr = this->srs_.at(p.second); if(tmp_sr == SR::null()) { assert(false); //coefficients in the monomial are always != 0.. so this should not happen :) } else if (tmp_sr == SR::one()) { // does not do anything } else { auto value_iter = valuation->find(tmp_sr); if (value_iter == valuation->end()) { /* Use a fresh constant - the constructor of Var::getVar() will take * care of this. */ VarId tmp_var = Var::GetVarId(); FreeSemiring tmp_var_free{tmp_var}; valuation->emplace(tmp_sr, tmp_var); result *= tmp_var_free; } else { // there is already a variable for this element, use it result *= value_iter->second; } } } } } return result; } bool operator<(const NonCommutativeMonomialBase &rhs) const { // lexicographic ordering if(this->idx_ != rhs.idx_) return this->idx_ < rhs.idx_; if(this->variables_ != rhs.variables_) return this->variables_ < rhs.variables_; if(this->srs_ != rhs.srs_) return this->srs_ < rhs.srs_; // they are equal return false; } bool operator==(const NonCommutativeMonomialBase &rhs) const { return this->idx_ == rhs.idx_ && this->variables_ == rhs.variables_ && this->srs_ == rhs.srs_; } Degree get_degree() const { return this->variables_.size(); } // FIXME: modify or remove std::set<VarId> get_variables() const { std::set<VarId> set; for (auto var : this->variables_) { set.insert(var); } return set; } /* * If the monomial has form xYz where x is an element of the semiring, * Y is a monomial over the semiring, and z is an element of the semiring, * this method gives back x wrapped in a monomial. */ SR getLeadingSR() const { SR leadingSR = SR::one(); // give me a copy of the semiring factor on the leading side of the monomial for(unsigned int i = 0; i < this->idx_.size(); i++) { // multiply as long as there was no variable encountered if(this->idx_.at(i).first == SemiringType) { leadingSR = leadingSR * this->srs_.at(this->idx_.at(i).second); } else { break; // break on the first variable } } return leadingSR; } /* * If the monomial has form xYz where x is an element of the semiring, * Y is a monomial over the semiring, and z is an element of the semiring, * this method gives back z wrapped in a monomial. */ SR getTrailingSR() const { SR trailingSR = SR::one(); // give me a copy of the semiring factor on the trailing side of the monomial for(int i = this->idx_.size() - 1; i >= 0; i--) { // multiply as long as there was no variable encountered if(this->idx_.at(i).first == SemiringType) { trailingSR = this->srs_.at(this->idx_.at(i).second) * trailingSR; } else { break; // break on the first variable } } return trailingSR; } /* * Quick check to see whether this monomial is just an epsilon. */ bool isEpsilonMonomial() const { return (get_degree() == 0) && (getLeadingSR() == SR::one()); } std::string string() const { std::stringstream ss; for(auto p = this->idx_.begin(); p != this->idx_.end(); p++) { if(p != this->idx_.begin()) ss << " * "; if(p->first == Variable) ss << this->variables_.at(p->second); else ss << this->srs_.at(p->second); } return std::move(ss.str()); } template <typename F> auto Map(F fun) const -> NonCommutativeMonomialBase<typename std::result_of<F(SR)>::type> { typedef typename std::result_of<F(SR)>::type SR2; // Variables and types of elements do not change -- just copy them std::vector<VarId> result_vars = variables_; auto result_idx = idx_; std::vector<SR2> result_srs; std::transform( srs_.begin(), srs_.end(), std::inserter(result_srs, result_srs.begin()), [&fun](const SR& s) { return fun(s); }); return NonCommutativeMonomialBase<SR2>(std::move(result_idx), std::move(result_vars), std::move(result_srs)); } }; template <typename SR> std::ostream& operator<<(std::ostream &out, const NonCommutativeMonomialBase<SR> &monomial) { return out << monomial.string(); } template <typename SR> class NonCommutativeMonomial : public NonCommutativeMonomialBase<SR> { public: using NonCommutativeMonomialBase<SR>::NonCommutativeMonomialBase; // constructor for implicit conversions NonCommutativeMonomial(const NonCommutativeMonomialBase<SR>& p) { this->idx_ = p.idx_; this->srs_ = p.srs_; this->variables_ = p.variables_; } };
mschlund/FPsolve
c/src/polynomials/non_commutative_monomial.h
C
bsd-2-clause
18,264
from ._stub import * from ._fluent import * from ._matchers import *
manahl/mockextras
mockextras/__init__.py
Python
bsd-2-clause
69
package edu.ucsf.lava.core.spring; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.FactoryBean; public class ListMerger implements FactoryBean { private List list = new ArrayList(); public ListMerger(List<List> items) { for (List item : items) { if (item != null) { list.addAll(item); } } } public Object getObject() throws Exception { return list; } public Class getObjectType() { return list.getClass(); } public boolean isSingleton() { return true; } }
UCSFMemoryAndAging/lava
lava-core/src/edu/ucsf/lava/core/spring/ListMerger.java
Java
bsd-2-clause
643
#! /usr/bin/env perl # # Grep Crawl vault files for some string and output the match preceded by # vault name. Don't search things like SUBST lines or the MAP. # use File::Find; my $myname = $0; $myname =~ s,.*/,,; $myname =~ s/(.)\..*$/$1/; # probably pointless extensibility... my @path = ($ENV{HOME} . '/Sources/crawl/crawl-ref/source/dat/des'); my @sfx = ('des'); my %sel = (monster => [qr/^MONS:/, qr/^KMONS:/] ,item => [qr/^ITEM:/, qr/^KITEM:/] ,feature => [qr/^FEAT:/, qr/^KFEAT:/] ); my %extra = (property => [qr/^PROP:/, qr/^KPROP:/, qr/^TAGS:/, qr/^LTAGS:/] ,branch => [qr/^PLACE:/] ); my (%which, %also); my $err = 0; my $and = 1; while (@ARGV) { my $arg = shift @ARGV; if ($arg eq '--all') { %which = map {$_ => 1} keys %sel; } elsif ($arg =~ /^--(\w+)$/ and exists $sel{$1}) { $which{$1} = 1; } elsif ($arg =~ /^--no-(\w+)$/ and exists $sel{$1}) { if (!keys %which) { %which = map {$_ => 1} keys %sel; } delete $which{$1}; } elsif ($arg =~ /^--(\w+)$/ and exists $extra{$1}) { push @{$also{$1}}, shift @ARGV; } elsif ($arg =~ /^--(\w+)=(.*)$/ and exists $extra{$1}) { push @{$also{$1}}, $2; } # @@@ should perhaps accept --any|--all, except see above... elsif ($arg eq '--and' or $arg eq '-a') { $and = 1; } elsif ($arg eq '--or' or $arg eq '-o') { $and = 0; } elsif ($arg eq '--help' or $arg eq '-h') { $err = 1; last; } # @@@ do this via mapping somehow instead of breaking abstraction :/ elsif ($arg =~ /^-b(.*)$/) { push @{$also{branch}}, $1; } elsif ($arg eq '-b') { push @{$also{branch}}, shift @ARGV; } elsif ($arg eq '-m') { $which{monster} = 1; } elsif ($arg eq '-i') { $which{item} = 1; } elsif ($arg eq '-f') { $which{feature} = 1; } elsif ($arg eq '--') { last; } elsif ($arg =~ /^-/) { print STDERR "$myname: unknown switch $arg\n"; $err = 1; } else { unshift @ARGV, $arg; last; } } if ($err or !@ARGV) { print STDERR "usage: $myname [--and|--or] [--all"; for (keys %sel) { print STDERR "|--[no-]$_"; } print STDERR "] ["; $err = 0; for (keys %extra) { $err and print STDERR '|'; print STDERR "--$_=pattern"; $err = 1; } print STDERR "] pattern...\n"; exit 1; } keys %which or %which = map {$_ => 1} keys %sel; find(sub {vgrep(clean($File::Find::dir, @path), $_)} ,@path ); ############################################################################### sub clean { my ($dir, @pfx) = @_; # @@@ after allowing for multiple paths, we make it useless... for my $pfx (@pfx) { $dir =~ s,^$pfx($|/),, and return $dir; } return $dir; } sub vgrep { my ($dir, $name) = @_; -f $_ or return; my $ok = 0; for my $sfx (@sfx) { if (/\.$sfx$/i) { $ok = 1; last; } } $ok or return; # it's presumably a .des file; munch it open($f, $_) or return; my $ln; my $map = 0; my $lua = 0; my $cur = undef; my $lno = 0; my $doing = -1; my $dd = undef; my $ldd = undef; while (defined ($ln = <$f>)) { $lno++; chomp $ln; $ln =~ /^\s*($|#)/ and next; while ($ln =~ s/\\$//) { my $l2 = <$f>; unless (defined $l2) { print STDERR "$dir/$_:$lno: warning: end of file in continued line\n"; $l2 = ''; } $lno++; chomp $l2; $l2 =~ s/^\s+//; $ln .= $l2; } if (defined $cur and !$map and !$lua and $ln =~ /^MAP$/) { $map = 1; next; } elsif (!$map and !$lua and $ln =~ /^:/) { # one-liner lua next; } elsif (!$map and !$lua and $ln =~ /^(?:lua\s*)?\{\{$/) { $lua = 1; next; } elsif ($lua and $ln =~ /^\}\}$/) { $lua = 0; next; } elsif ($map and $ln =~ /^ENDMAP$/) { $cur = undef; $map = 0; next; } elsif ($map or $lua) { next; } elsif ($ln =~ /^NAME:\s*(\S+)\s*$/) { # @@@ serial vaults don't have maps in the main vaults # @@@ check default depth vs. branch here to set $doing! # @@@@ except that's wrong if it sets DEPTH: # if (defined $cur) { # print STDERR "$dir/$_:$lno: warning: already in $cur: $ln\n"; # } $cur = $1; $doing = -1; $ldd = undef; next; } # this is allowed outside of any definition elsif (!defined $cur and $ln =~ /^default-depth:\s*(.*)$/) { $dd = $1; next; } elsif (!defined $cur) { print STDERR "$dir/$_:$lno: warning: not in a definition: $ln\n"; next; } elsif ($ln =~ /^DEPTH:\s*(.*)$/) { $ldd = $1; } else { # look for extras matches $ok = 0; my $rok = 0; for my $extra (keys %also) { next if $extra eq 'branch'; # @@@@@@@@@@ # does this line match a selector? for my $kw (@{$extra{$extra}}) { if ($ln =~ $kw) { $rok = 1; for my $pat (@{$also{$extra}}) { if ($ln =~ /$pat/) { $ok = 1; last; } } $ok or $doing = 0; last; } } } # if we matched any extra keyword then it can't be a section keyword $rok and next; # is section enabled? for my $sect (keys %which) { # does the line match a selector? for my $kw (@{$sel{$sect}}) { if ($ln =~ $kw) { $ok = 1; last; } } $ok or next; # figure out if we are in a selected branch # @@@ and pray DEPTH: doesn't occur *after* MONS etc. if ($doing == -1) { if (!exists $also{branch}) { $doing = 1; } elsif (defined $dd or defined $ldd) { defined $ldd or $ldd = $dd; $doing = 0; for my $pat (map {split(',', $_)} @{$also{branch}}) { if ($ldd =~ /(?:^|,\s*)$pat(?:,|:|$)/i) { $doing = 1; } } } } $doing or next; # try matching against all the patterns. # @@@ AND / OR expressions? # @@@ for that matter, and/or sections... right now always OR $ok = $and ? @ARGV : 0; for my $pat (@ARGV) { # @@@ might want to delete prefixes for those keywords that have them if ($ln =~ /$pat/) { if ($and) { $ok--; } else { $ok = 1; } } } if (($and and !$ok) or (!$and and $ok)) { print "$dir/$_:${lno}: [$cur] $ln\n"; } } } } }
geekosaur/vaultgrep
vaultgrep.pl
Perl
bsd-2-clause
6,218
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.math; import static com.google.common.base.Preconditions.checkState; import static com.google.common.primitives.Doubles.isFinite; import static java.lang.Double.NaN; import static java.lang.Double.isNaN; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtIncompatible; /** * A mutable object which accumulates paired double values (e.g. points on a plane) and tracks some * basic statistics over all the values added so far. This class is not thread safe. * * @author Pete Gillin * @since 20.0 */ @Beta @GwtIncompatible public final class PairedStatsAccumulator { // These fields must satisfy the requirements of PairedStats' constructor as well as those of the // stat methods of this class. private final StatsAccumulator xStats = new StatsAccumulator(); private final StatsAccumulator yStats = new StatsAccumulator(); private double sumOfProductsOfDeltas = 0.0; /** * Adds the given pair of values to the dataset. */ public void add(double x, double y) { // We extend the recursive expression for the one-variable case at Art of Computer Programming // vol. 2, Knuth, 4.2.2, (16) to the two-variable case. We have two value series x_i and y_i. // We define the arithmetic means X_n = 1/n \sum_{i=1}^n x_i, and Y_n = 1/n \sum_{i=1}^n y_i. // We also define the sum of the products of the differences from the means // C_n = \sum_{i=1}^n x_i y_i - n X_n Y_n // for all n >= 1. Then for all n > 1: // C_{n-1} = \sum_{i=1}^{n-1} x_i y_i - (n-1) X_{n-1} Y_{n-1} // C_n - C_{n-1} = x_n y_n - n X_n Y_n + (n-1) X_{n-1} Y_{n-1} // = x_n y_n - X_n [ y_n + (n-1) Y_{n-1} ] + [ n X_n - x_n ] Y_{n-1} // = x_n y_n - X_n y_n - x_n Y_{n-1} + X_n Y_{n-1} // = (x_n - X_n) (y_n - Y_{n-1}) xStats.add(x); if (isFinite(x) && isFinite(y)) { if (xStats.count() > 1) { sumOfProductsOfDeltas += (x - xStats.mean()) * (y - yStats.mean()); } } else { sumOfProductsOfDeltas = NaN; } yStats.add(y); } /** * Adds the given statistics to the dataset, as if the individual values used to compute the * statistics had been added directly. */ public void addAll(PairedStats values) { if (values.count() == 0) { return; } xStats.addAll(values.xStats()); if (yStats.count() == 0) { sumOfProductsOfDeltas = values.sumOfProductsOfDeltas(); } else { // This is a generalized version of the calculation in add(double, double) above. Note that // non-finite inputs will have sumOfProductsOfDeltas = NaN, so non-finite values will result // in NaN naturally. sumOfProductsOfDeltas += values.sumOfProductsOfDeltas() + (values.xStats().mean() - xStats.mean()) * (values.yStats().mean() - yStats.mean()) * values.count(); } yStats.addAll(values.yStats()); } /** * Returns an immutable snapshot of the current statistics. */ public PairedStats snapshot() { return new PairedStats(xStats.snapshot(), yStats.snapshot(), sumOfProductsOfDeltas); } /** * Returns the number of pairs in the dataset. */ public long count() { return xStats.count(); } /** * Returns an immutable snapshot of the statistics on the {@code x} values alone. */ public Stats xStats() { return xStats.snapshot(); } /** * Returns an immutable snapshot of the statistics on the {@code y} values alone. */ public Stats yStats() { return yStats.snapshot(); } /** * Returns the population covariance of the values. The count must be non-zero. * * <p>This is guaranteed to return zero if the dataset contains a single pair of finite values. It * is not guaranteed to return zero when the dataset consists of the same pair of values multiple * times, due to numerical errors. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, * {@link Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}. * * @throws IllegalStateException if the dataset is empty */ public double populationCovariance() { checkState(count() != 0); return sumOfProductsOfDeltas / count(); } /** * Returns the sample covariance of the values. The count must be greater than one. * * <p>This is not guaranteed to return zero when the dataset consists of the same pair of values * multiple times, due to numerical errors. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, * {@link Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}. * * @throws IllegalStateException if the dataset is empty or contains a single pair of values */ public final double sampleCovariance() { checkState(count() > 1); return sumOfProductsOfDeltas / (count() - 1); } /** * Returns the <a href="http://mathworld.wolfram.com/CorrelationCoefficient.html">Pearson's or * product-moment correlation coefficient</a> of the values. The count must greater than one, and * the {@code x} and {@code y} values must both have non-zero population variance (i.e. * {@code xStats().populationVariance() > 0.0 && yStats().populationVariance() > 0.0}). The result * is not guaranteed to be exactly +/-1 even when the data are perfectly (anti-)correlated, due to * numerical errors. However, it is guaranteed to be in the inclusive range [-1, +1]. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, * {@link Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}. * * @throws IllegalStateException if the dataset is empty or contains a single pair of values, or * either the {@code x} and {@code y} dataset has zero population variance */ public final double pearsonsCorrelationCoefficient() { checkState(count() > 1); if (isNaN(sumOfProductsOfDeltas)) { return NaN; } double xSumOfSquaresOfDeltas = xStats.sumOfSquaresOfDeltas(); double ySumOfSquaresOfDeltas = yStats.sumOfSquaresOfDeltas(); checkState(xSumOfSquaresOfDeltas > 0.0); checkState(ySumOfSquaresOfDeltas > 0.0); // The product of two positive numbers can be zero if the multiplication underflowed. We // force a positive value by effectively rounding up to MIN_VALUE. double productOfSumsOfSquaresOfDeltas = ensurePositive(xSumOfSquaresOfDeltas * ySumOfSquaresOfDeltas); return ensureInUnitRange(sumOfProductsOfDeltas / Math.sqrt(productOfSumsOfSquaresOfDeltas)); } /** * Returns a linear transformation giving the best fit to the data according to * <a href="http://mathworld.wolfram.com/LeastSquaresFitting.html">Ordinary Least Squares linear * regression</a> of {@code y} as a function of {@code x}. The count must be greater than one, and * either the {@code x} or {@code y} data must have a non-zero population variance (i.e. * {@code xStats().populationVariance() > 0.0 || yStats().populationVariance() > 0.0}). The result * is guaranteed to be horizontal if there is variance in the {@code x} data but not the {@code y} * data, and vertical if there is variance in the {@code y} data but not the {@code x} data. * * <p>This fit minimizes the root-mean-square error in {@code y} as a function of {@code x}. This * error is defined as the square root of the mean of the squares of the differences between the * actual {@code y} values of the data and the values predicted by the fit for the {@code x} * values (i.e. it is the square root of the mean of the squares of the vertical distances between * the data points and the best fit line). For this fit, this error is a fraction * {@code sqrt(1 - R*R)} of the population standard deviation of {@code y}, where {@code R} is the * Pearson's correlation coefficient (as given by {@link #pearsonsCorrelationCoefficient()}). * * <p>The corresponding root-mean-square error in {@code x} as a function of {@code y} is a * fraction {@code sqrt(1/(R*R) - 1)} of the population standard deviation of {@code x}. This fit * does not normally minimize that error: to do that, you should swap the roles of {@code x} and * {@code y}. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, * {@link Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is * {@link LinearTransformation#forNaN()}. * * @throws IllegalStateException if the dataset is empty or contains a single pair of values, or * both the {@code x} and {@code y} dataset have zero population variance */ public final LinearTransformation leastSquaresFit() { checkState(count() > 1); if (isNaN(sumOfProductsOfDeltas)) { return LinearTransformation.forNaN(); } double xSumOfSquaresOfDeltas = xStats.sumOfSquaresOfDeltas(); if (xSumOfSquaresOfDeltas > 0.0) { if (yStats.sumOfSquaresOfDeltas() > 0.0) { return LinearTransformation.mapping(xStats.mean(), yStats.mean()).withSlope(sumOfProductsOfDeltas / xSumOfSquaresOfDeltas); } else { return LinearTransformation.horizontal(yStats.mean()); } } else { checkState(yStats.sumOfSquaresOfDeltas() > 0.0); return LinearTransformation.vertical(xStats.mean()); } } private double ensurePositive(double value) { if (value > 0.0) { return value; } else { return Double.MIN_VALUE; } } private static double ensureInUnitRange(double value) { if (value >= 1.0) { return 1.0; } if (value <= -1.0) { return -1.0; } return value; } }
antlr/codebuff
output/java_guava/1.4.19/PairedStatsAccumulator.java
Java
bsd-2-clause
10,613
cask 'beaker-electron' do version '1.4.2-0-ge55c059' sha256 '32d6ecf6a1ebfc32c3e1b2dfc1edb33eaeab6f83d3f9d74dd9b64e08bd24e3e6' # cloudfront.net is the official download host per the vendor homepage url "https://d299yghl10frh5.cloudfront.net/beaker-notebook-#{version}-electron-mac.dmg" name 'Beaker Electron' homepage 'http://beakernotebook.com/' license :apache app 'Beaker.app' end
coeligena/homebrew-verscustomized
Casks/beaker-electron.rb
Ruby
bsd-2-clause
402
/** * BSD 2-Clause License * * Copyright (c) 2016-2017, Jochen Seeber * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package me.seeber.gradle.project.base; import org.eclipse.jdt.annotation.Nullable; import org.gradle.model.Managed; /** * Issue tracker configuration */ @Managed public interface IssueTracker { /** * Get the ID of the tracker * * @return ID of the tracker */ public @Nullable String getId(); /** * Set the ID of the tracker * * @param id ID of the tracker */ public void setId(@Nullable String id); /** * Get the URL of the tracker * * @return URL of the tracker */ public @Nullable String getWebsiteUrl(); /** * Set the URL of the tracker * * @param websiteUrl Get the URL of the tracker */ public void setWebsiteUrl(@Nullable String websiteUrl); }
jochenseeber/gradle-project-config
src/main/java/me/seeber/gradle/project/base/IssueTracker.java
Java
bsd-2-clause
2,170
<blockquote class="blockquote-reverse"> Ranking - klasyfikacja wartościująca wg ustalonych kryteriów </blockquote> <p> Ranking powstał na bazie zdobytych przez zawodnika <abbr title="Punkty Klasyfikacyjne">PKL</abbr>, wykorzystując ich różnorodność w bazie <abbr title="Centralna Ewidencja Zawodników i Rozgrywek">CEZaR</abbr> – PKL regionalne, PKL ogólnopolskie, PKL międzynarodowe, <abbr title="Arcymistrzowskie Punkty Klasyfikacyjne">aPKL</abbr>, <abbr title="Punkty Mistrzowskie">PM</abbr>, <abbr title="Międzynarodowe Punkty Mistrzowskie">MPM</abbr>. </p> <p> Została ustalona hierarchia zdobywanych PKL i stopniowo cofając się w latach odrzucano część zdobytych przez zawodników punktów. </p> <p> Ranking ma określać aktualną siłę gry zawodników i powinien stanowić podstawę do rozstawiania w turniejach. </p> <p> Będzie ogłaszany cztery razy w roku – na początku każdego kwartału i przez trzy miesiące będzie statyczny. Oprócz klasyfikacji ogólnej pojawią się klasyfikacje szczegółowe: kobiet, juniorów, seniorów, nestorów, wojewódzkie itp. </p>
emkael/pzbs-ranking
static/ranking.html
HTML
bsd-2-clause
1,113
/* * This is a manifest file that'll be compiled into application.css, which will include all the files * listed below. * * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the bottom of the * compiled file so the styles you add here take precedence over styles defined in any styles * defined in the other CSS/SCSS files in this directory. It is generally better to create a new * file per style scope. * *= require twitter/bootstrap *= require_tree . *= require_self */
nickludlam/EDForumTracker
app/assets/stylesheets/application.css
CSS
bsd-2-clause
713
/**************************************************************************** * include/nuttx/regex.h * Non-standard, pattern-matching APIs available in lib/. * * Copyright (C) 2009 Gregory Nutt. All rights reserved. * Author: Gregory Nutt <gnutt@nuttx.org> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name NuttX nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #ifndef __INCLUDE_NUTTX_REGEX_H #define __INCLUDE_NUTTX_REGEX_H /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <nuttx/fs/fs.h> /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /**************************************************************************** * Public Function Prototypes ****************************************************************************/ #ifdef __cplusplus #define EXTERN extern "C" extern "C" { #else #define EXTERN extern #endif /**************************************************************************** * Name: match * * Description: * Simple shell-style filename pattern matcher written by Jef Poskanzer * (See copyright notice in lib/lib_match.c). This pattern matcher only * handles '?', '*' and '**', and multiple patterns separated by '|'. * * Returned Value: * Returns 1 (match) or 0 (no-match). * ****************************************************************************/ int match(const char *pattern, const char *string); #undef EXTERN #ifdef __cplusplus } #endif #endif /* __INCLUDE_NUTTX_REGEX_H */
IUTInfoAix/terrarium_2015
nuttx/include/nuttx/regex.h
C
bsd-2-clause
3,228
package de.lessvoid.nifty.slick2d; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.slick2d.input.RelaySlickInputSystem; import de.lessvoid.nifty.slick2d.input.SlickInputSystem; import de.lessvoid.nifty.slick2d.render.SlickRenderDevice; import de.lessvoid.nifty.slick2d.sound.SlickSoundDevice; import de.lessvoid.nifty.spi.input.InputSystem; import de.lessvoid.nifty.spi.time.TimeProvider; /** * As the name suggest, this class carries the instance of the Nifty-GUI that is used around. * * @author Martin Karing &gt;nitram@illarion.org&lt; */ public final class NiftyCarrier { /** * The instance of the Nifty-GUI that is carried by this carrier. */ private Nifty nifty; /** * The relay input system that is used in case the target input system is switched. */ private final RelaySlickInputSystem relayInputSystem; /** * Constructor that allows to set if the relay input system is supposed to be enabled or not. * * @param useRelay {@code true} to enable the relay input system */ NiftyCarrier(final boolean useRelay) { if (useRelay) { relayInputSystem = new RelaySlickInputSystem(); } else { relayInputSystem = null; } } /** * Check if the carrier is using the relay input system. In case it is, its possible to switch the current target * input system. * * @return {@code true} in case the relay input system is used */ public boolean isUsingRelayInputSystem() { return relayInputSystem != null; } /** * Get the instance of the Nifty-GUI that is carried by this carrier. * * @return the instance of the Nifty-GUI */ public Nifty getNifty() { return nifty; } /** * Check if the Nifty-GUI in this carrier was already initialized. * * @return {@code true} if the GUI is initialized */ public boolean isInitialized() { return nifty != null; } /** * Initialize the Nifty-GUI. * * @param renderDevice the render device to use for the GUI * @param soundDevice the sound device to use for the GUI * @param inputSystem the input system to use for the GUI * @param timeProvider the time provider to use for the GUI * @throws IllegalStateException in case this function was already called */ public void initNifty( final SlickRenderDevice renderDevice, final SlickSoundDevice soundDevice, final SlickInputSystem inputSystem, final TimeProvider timeProvider) { if (isInitialized()) { throw new IllegalStateException("The Nifty-GUI was already initialized. Its illegal to do so twice."); } final InputSystem activeInputSystem; if (relayInputSystem == null) { activeInputSystem = inputSystem; } else { activeInputSystem = relayInputSystem; relayInputSystem.setTargetInputSystem(inputSystem); } nifty = new Nifty(renderDevice, soundDevice, activeInputSystem, timeProvider); } /** * Change the input system that is supposed to handle the input. * * @param inputSystem the new input system * @throws IllegalStateException in case this instance of the carrier does not use the relay input system */ public void setInputSystem(final SlickInputSystem inputSystem) { if (relayInputSystem == null) { throw new IllegalStateException( "Changing the input system is only allowed for carriers that use the relay input system."); } relayInputSystem.setTargetInputSystem(inputSystem); } }
xranby/nifty-gui
nifty-renderer-slick/src/main/java/de/lessvoid/nifty/slick2d/NiftyCarrier.java
Java
bsd-2-clause
3,582
package at.ac.uibk.igwee.webapp.metadata.mdmapper.controller; import java.util.ArrayList; import java.util.Date; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import at.ac.uibk.igwee.metadata.metaquery.QueryQueue; @Component @Scope("session") public class SessionHolder { private QueryQueue queryQueue; /** * @return the queryQueue */ public QueryQueue getQueryQueue() { if (queryQueue == null) clear(); return queryQueue; } /** * @param queryQueue the queryQueue to set */ public void setQueryQueue(QueryQueue queryQueue) { this.queryQueue = queryQueue; // output(this.queryQueue); } public static void output(QueryQueue q) { System.out.println("QueryQueue: " + q.getName()); System.out.println(" Info: " + q.getAdditionalInfo()); System.out.println(" Pending: " + q.getPendingQueries().size()); q.getPendingQueries().forEach(vq -> { System.out.println(" Query for: " + vq); System.out.println(" Type: " + vq.getType()); System.out.println(" Restricted to: " + vq.getIncludedAuthority()); }); System.out.println(); System.out.println(" Results: "); q.getResults().stream().forEach(vq -> { System.out.println(" Query for: " + vq.getVocabularyQuery().getName() ); System.out.println(" Fixed: " + vq.getFixedResult()); System.out.println(" Results: " + vq.getResults().size()); vq.getResults().forEach(v -> { System.out.println(" " + v.getInternalID() + ": " + v.getURI()); }); }); } public boolean isEmpty() { return this.queryQueue == null; } public void clear() { this.queryQueue = new QueryQueue("StandardQueue", "Created on " + new Date().toString(), new ArrayList<>()); } }
kofnego-jw/vocmapping
at.ac.uibk.igwee.metadata/at.ac.uibk.igwee.metadata.webapp.vocmapper/src/main/java/at/ac/uibk/igwee/webapp/metadata/mdmapper/controller/SessionHolder.java
Java
bsd-2-clause
1,844
# Package file for INVIWOCIMGMODULE, part of Inviwo projects # It defines the following variables # # INVIWOCIMGMODULE_FOUND # INVIWOCIMGMODULE_INCLUDE_DIR # INVIWOCIMGMODULE_LIBRARY_DIR # INVIWOCIMGMODULE_LIBRARIES # INVIWOCIMGMODULE_DEFINITIONS # INVIWOCIMGMODULE_LINK_FLAGS # set(BUILD_INVIWOCIMGMODULE 1) set(INVIWOCIMGMODULE_PROJECT inviwo-module-cimg) set(INVIWOCIMGMODULE_FOUND 1) set(INVIWOCIMGMODULE_USE_FILE ) set(INVIWOCIMGMODULE_INCLUDE_DIR "/home/charlotte/Dokumente/DAInviwo/inviwo/modules/cimg/ext;/home/charlotte/Dokumente/DAInviwo/inviwo/modules/cimg/ext/libjpeg;/home/charlotte/Dokumente/DAInviwo/inviwo/modules/cimg/ext/libpng;/home/charlotte/Dokumente/DAInviwo/inviwo/modules/cimg/ext/openexr/half;/home/charlotte/Dokumente/DAInviwo/inviwo/modules/cimg/ext/openexr/imath;/home/charlotte/Dokumente/DAInviwo/inviwo/modules/cimg/ext/openexr/ilmimf;/home/charlotte/Dokumente/DAInviwo/inviwo/modules/cimg/ext/openexr/ilmthread;/home/charlotte/Dokumente/DAInviwo/inviwo/modules/cimg/ext/openexr/iex;/home/charlotte/Dokumente/DAInviwo/inviwo/modules/cimg/ext/openexr;/home/charlotte/Dokumente/DAInviwo/inviwo/include;/home/charlotte/Dokumente/DAInviwo/inviwo/ext;/home/charlotte/Dokumente/DAInviwo/inviwo;/home/charlotte/Dokumente/DAInviwo/inviwo/modules;/home/charlotte/Dokumente/DAInviwo/inviwo/modules/_generated;/usr/include") set(INVIWOCIMGMODULE_LIBRARY_DIR "/home/charlotte/Dokumente/DAInviwo/inviwo/lib") set(INVIWOCIMGMODULE_LIBRARIES "optimized;ticpp;debug;ticpp;optimized;sigar;debug;sigar;optimized;inviwo-core;debug;inviwo-core;debug;/usr/lib/x86_64-linux-gnu/libz.so;optimized;/usr/lib/x86_64-linux-gnu/libz.so;optimized;inviwo-module-zlib;debug;inviwo-module-zlib;optimized;inviwo-module-cimg;debug;inviwo-module-cimg") set(INVIWOCIMGMODULE_DEFINITIONS -Dcimg_use_cpp11;-Dcimg_use_png;-Dcimg_use_jpeg;-Dcimg_use_zlib;-Dcimg_use_openexr;-DJPEG_STATIC;-DTIXML_USE_TICPP;-DIVW_SIGAR) set(INVIWOCIMGMODULE_LINK_FLAGS ) mark_as_advanced(FORCE INVIWOCIMGMODULE_FOUND) mark_as_advanced(FORCE INVIWOCIMGMODULE_USE_FILE) mark_as_advanced(FORCE INVIWOCIMGMODULE_INCLUDE_DIR) mark_as_advanced(FORCE INVIWOCIMGMODULE_LIBRARY_DIR) mark_as_advanced(FORCE INVIWOCIMGMODULE_LIBRARIES) mark_as_advanced(FORCE INVIWOCIMGMODULE_DEFINITIONS) mark_as_advanced(FORCE INVIWOCIMGMODULE_LINK_FLAGS)
cgloger/inviwo
cmake/FindInviwoCImgModule.cmake
CMake
bsd-2-clause
2,312
# ShowImges A gallery.
xhuichen/ShowImages
README.md
Markdown
bsd-2-clause
23
/** * Copyright (c) 2007, Gaudenz Alder */ package com.mxgraph.canvas; import java.awt.Font; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Hashtable; import java.util.List; import java.util.Map; import org.w3c.dom.Document; import org.w3c.dom.Element; import com.mxgraph.util.mxBase64; import com.mxgraph.util.mxConstants; import com.mxgraph.util.mxPoint; import com.mxgraph.util.mxRectangle; import com.mxgraph.util.mxUtils; import com.mxgraph.view.mxCellState; /** * An implementation of a canvas that uses SVG for painting. This canvas * ignores the STYLE_LABEL_BACKGROUNDCOLOR and * STYLE_LABEL_BORDERCOLOR styles due to limitations of SVG. */ public class mxSvgCanvas extends mxBasicCanvas { /** * Holds the HTML document that represents the canvas. */ protected Document document; /** * Used internally for looking up elements. Workaround for getElementById * not working. */ private Map<String, Element> gradients = new Hashtable<String, Element>(); /** * Used internally for looking up images. */ private Map<String, Element> images = new Hashtable<String, Element>(); /** * */ protected Element defs = null; /** * Specifies if images should be embedded as base64 encoded strings. * Default is false. */ protected boolean embedded = false; /** * Constructs a new SVG canvas for the specified dimension and scale. */ public mxSvgCanvas() { this(null); } /** * Constructs a new SVG canvas for the specified bounds, scale and * background color. */ public mxSvgCanvas(Document document) { setDocument(document); } /** * */ public void appendSvgElement(Element node) { if (document != null) { document.getDocumentElement().appendChild(node); } } /** * */ protected Element getDefsElement() { if (defs == null) { defs = document.createElement("defs"); Element svgNode = document.getDocumentElement(); if (svgNode.hasChildNodes()) { svgNode.insertBefore(defs, svgNode.getFirstChild()); } else { svgNode.appendChild(defs); } } return defs; } /** * */ public Element getGradientElement(String start, String end, String direction) { String id = getGradientId(start, end, direction); Element gradient = gradients.get(id); if (gradient == null) { gradient = createGradientElement(start, end, direction); gradient.setAttribute("id", "g" + (gradients.size() + 1)); getDefsElement().appendChild(gradient); gradients.put(id, gradient); } return gradient; } /** * */ public Element getGlassGradientElement() { String id = "mx-glass-gradient"; Element glassGradient = gradients.get(id); if (glassGradient == null) { glassGradient = document.createElement("linearGradient"); glassGradient.setAttribute("x1", "0%"); glassGradient.setAttribute("y1", "0%"); glassGradient.setAttribute("x2", "0%"); glassGradient.setAttribute("y2", "100%"); Element stop1 = document.createElement("stop"); stop1.setAttribute("offset", "0%"); stop1.setAttribute("style", "stop-color:#ffffff;stop-opacity:0.9"); glassGradient.appendChild(stop1); Element stop2 = document.createElement("stop"); stop2.setAttribute("offset", "100%"); stop2.setAttribute("style", "stop-color:#ffffff;stop-opacity:0.1"); glassGradient.appendChild(stop2); glassGradient.setAttribute("id", "g" + (gradients.size() + 1)); getDefsElement().appendChild(glassGradient); gradients.put(id, glassGradient); } return glassGradient; } /** * */ protected Element createGradientElement(String start, String end, String direction) { Element gradient = document.createElement("linearGradient"); gradient.setAttribute("x1", "0%"); gradient.setAttribute("y1", "0%"); gradient.setAttribute("x2", "0%"); gradient.setAttribute("y2", "0%"); if (direction == null || direction.equals(mxConstants.DIRECTION_SOUTH)) { gradient.setAttribute("y2", "100%"); } else if (direction.equals(mxConstants.DIRECTION_EAST)) { gradient.setAttribute("x2", "100%"); } else if (direction.equals(mxConstants.DIRECTION_NORTH)) { gradient.setAttribute("y1", "100%"); } else if (direction.equals(mxConstants.DIRECTION_WEST)) { gradient.setAttribute("x1", "100%"); } Element stop = document.createElement("stop"); stop.setAttribute("offset", "0%"); stop.setAttribute("style", "stop-color:" + start); gradient.appendChild(stop); stop = document.createElement("stop"); stop.setAttribute("offset", "100%"); stop.setAttribute("style", "stop-color:" + end); gradient.appendChild(stop); return gradient; } /** * */ public String getGradientId(String start, String end, String direction) { // Removes illegal characters from gradient ID if (start.startsWith("#")) { start = start.substring(1); } if (end.startsWith("#")) { end = end.substring(1); } // Workaround for gradient IDs not working in Safari 5 / Chrome 6 // if they contain uppercase characters start = start.toLowerCase(); end = end.toLowerCase(); String dir = null; if (direction == null || direction.equals(mxConstants.DIRECTION_SOUTH)) { dir = "south"; } else if (direction.equals(mxConstants.DIRECTION_EAST)) { dir = "east"; } else { String tmp = start; start = end; end = tmp; if (direction.equals(mxConstants.DIRECTION_NORTH)) { dir = "south"; } else if (direction.equals(mxConstants.DIRECTION_WEST)) { dir = "east"; } } return "mx-gradient-" + start + "-" + end + "-" + dir; } /** * Returns true if the given string ends with .png, .jpg or .gif. */ protected boolean isImageResource(String src) { return src != null && (src.toLowerCase().endsWith(".png") || src.toLowerCase().endsWith(".jpg") || src .toLowerCase().endsWith(".gif")); } /** * */ protected InputStream getResource(String src) { InputStream stream = null; try { stream = new BufferedInputStream(new URL(src).openStream()); } catch (Exception e1) { stream = getClass().getResourceAsStream(src); } return stream; } /** * @throws IOException * */ protected String createDataUrl(String src) throws IOException { String result = null; InputStream inputStream = isImageResource(src) ? getResource(src) : null; if (inputStream != null) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024); byte[] bytes = new byte[512]; // Read bytes from the input stream in bytes.length-sized chunks and write // them into the output stream int readBytes; while ((readBytes = inputStream.read(bytes)) > 0) { outputStream.write(bytes, 0, readBytes); } // Convert the contents of the output stream into a Data URL String format = "png"; int dot = src.lastIndexOf('.'); if (dot > 0 && dot < src.length()) { format = src.substring(dot + 1); } result = "data:image/" + format + ";base64," + mxBase64 .encodeToString(outputStream.toByteArray(), false); } return result; } /** * */ protected Element getEmbeddedImageElement(String src) { Element img = images.get(src); if (img == null) { img = document.createElement("svg"); img.setAttribute("width", "100%"); img.setAttribute("height", "100%"); Element inner = document.createElement("image"); inner.setAttribute("width", "100%"); inner.setAttribute("height", "100%"); // Store before transforming to DataURL images.put(src, img); if (!src.startsWith("data:image/")) { try { String tmp = createDataUrl(src); if (tmp != null) { src = tmp; } } catch (IOException e) { // ignore } } inner.setAttributeNS(mxConstants.NS_XLINK, "xlink:href", src); img.appendChild(inner); img.setAttribute("id", "i" + (images.size())); getDefsElement().appendChild(img); } return img; } /** * */ protected Element createImageElement(double x, double y, double w, double h, String src, boolean aspect, boolean flipH, boolean flipV, boolean embedded) { Element elem = null; if (embedded) { elem = document.createElement("use"); Element img = getEmbeddedImageElement(src); elem.setAttributeNS(mxConstants.NS_XLINK, "xlink:href", "#" + img.getAttribute("id")); } else { elem = document.createElement("image"); elem.setAttributeNS(mxConstants.NS_XLINK, "xlink:href", src); } elem.setAttribute("x", String.valueOf(x)); elem.setAttribute("y", String.valueOf(y)); elem.setAttribute("width", String.valueOf(w)); elem.setAttribute("height", String.valueOf(h)); // FIXME: SVG element must be used for reference to image with // aspect but for images with no aspect this does not work. if (aspect) { elem.setAttribute("preserveAspectRatio", "xMidYMid"); } else { elem.setAttribute("preserveAspectRatio", "none"); } double sx = 1; double sy = 1; double dx = 0; double dy = 0; if (flipH) { sx *= -1; dx = -w - 2 * x; } if (flipV) { sy *= -1; dy = -h - 2 * y; } String transform = ""; if (sx != 1 || sy != 1) { transform += "scale(" + sx + " " + sy + ") "; } if (dx != 0 || dy != 0) { transform += "translate(" + dx + " " + dy + ") "; } if (transform.length() > 0) { elem.setAttribute("transform", transform); } return elem; } /** * */ public void setDocument(Document document) { this.document = document; } /** * Returns a reference to the document that represents the canvas. * * @return Returns the document. */ public Document getDocument() { return document; } /** * */ public void setEmbedded(boolean value) { embedded = value; } /** * */ public boolean isEmbedded() { return embedded; } /* * (non-Javadoc) * @see com.mxgraph.canvas.mxICanvas#drawCell() */ public Object drawCell(mxCellState state) { Map<String, Object> style = state.getStyle(); Element elem = null; if (state.getAbsolutePointCount() > 1) { List<mxPoint> pts = state.getAbsolutePoints(); // Transpose all points by cloning into a new array pts = mxUtils.translatePoints(pts, translate.x, translate.y); // Draws the line elem = drawLine(pts, style); // Applies opacity float opacity = mxUtils.getFloat(style, mxConstants.STYLE_OPACITY, 100); float fillOpacity = mxUtils.getFloat(style, mxConstants.STYLE_FILL_OPACITY, 100); float strokeOpacity = mxUtils.getFloat(style, mxConstants.STYLE_STROKE_OPACITY, 100); if (opacity != 100 || fillOpacity != 100 || strokeOpacity != 100) { String fillOpac = String.valueOf(opacity * fillOpacity / 10000 ); String strokeOpac = String.valueOf(opacity * strokeOpacity / 10000); elem.setAttribute("fill-opacity", fillOpac); elem.setAttribute("stroke-opacity", strokeOpac); } } else { int x = (int) state.getX() + translate.x; int y = (int) state.getY() + translate.y; int w = (int) state.getWidth(); int h = (int) state.getHeight(); if (!mxUtils.getString(style, mxConstants.STYLE_SHAPE, "").equals( mxConstants.SHAPE_SWIMLANE)) { elem = drawShape(x, y, w, h, style); } else { int start = (int) Math.round(mxUtils.getInt(style, mxConstants.STYLE_STARTSIZE, mxConstants.DEFAULT_STARTSIZE) * scale); // Removes some styles to draw the content area Map<String, Object> cloned = new Hashtable<String, Object>( style); cloned.remove(mxConstants.STYLE_FILLCOLOR); cloned.remove(mxConstants.STYLE_ROUNDED); if (mxUtils.isTrue(style, mxConstants.STYLE_HORIZONTAL, true)) { elem = drawShape(x, y, w, start, style); drawShape(x, y + start, w, h - start, cloned); } else { elem = drawShape(x, y, start, h, style); drawShape(x + start, y, w - start, h, cloned); } } } return elem; } /* * (non-Javadoc) * @see com.mxgraph.canvas.mxICanvas#drawLabel() */ public Object drawLabel(String label, mxCellState state, boolean html) { mxRectangle bounds = state.getLabelBounds(); if (drawLabels && bounds != null) { int x = (int) bounds.getX() + translate.x; int y = (int) bounds.getY() + translate.y; int w = (int) bounds.getWidth(); int h = (int) bounds.getHeight(); Map<String, Object> style = state.getStyle(); return drawText(label, x, y, w, h, style); } return null; } /** * Draws the shape specified with the STYLE_SHAPE key in the given style. * * @param x X-coordinate of the shape. * @param y Y-coordinate of the shape. * @param w Width of the shape. * @param h Height of the shape. * @param style Style of the the shape. */ public Element drawShape(int x, int y, int w, int h, Map<String, Object> style) { String fillColor = mxUtils.getString(style, mxConstants.STYLE_FILLCOLOR, "none"); String gradientColor = mxUtils.getString(style, mxConstants.STYLE_GRADIENTCOLOR, "none"); String strokeColor = mxUtils.getString(style, mxConstants.STYLE_STROKECOLOR, "none"); float strokeWidth = (float) (mxUtils.getFloat(style, mxConstants.STYLE_STROKEWIDTH, 1) * scale); float opacity = mxUtils.getFloat(style, mxConstants.STYLE_OPACITY, 100); float fillOpacity = mxUtils.getFloat(style, mxConstants.STYLE_FILL_OPACITY, 100); float strokeOpacity = mxUtils.getFloat(style, mxConstants.STYLE_STROKE_OPACITY, 100); // Draws the shape String shape = mxUtils.getString(style, mxConstants.STYLE_SHAPE, ""); Element elem = null; Element background = null; if (shape.equals(mxConstants.SHAPE_IMAGE)) { String img = getImageForStyle(style); if (img != null) { // Vertical and horizontal image flipping boolean flipH = mxUtils.isTrue(style, mxConstants.STYLE_IMAGE_FLIPH, false); boolean flipV = mxUtils.isTrue(style, mxConstants.STYLE_IMAGE_FLIPV, false); elem = createImageElement(x, y, w, h, img, PRESERVE_IMAGE_ASPECT, flipH, flipV, isEmbedded()); } } else if (shape.equals(mxConstants.SHAPE_LINE)) { String direction = mxUtils.getString(style, mxConstants.STYLE_DIRECTION, mxConstants.DIRECTION_EAST); String d = null; if (direction.equals(mxConstants.DIRECTION_EAST) || direction.equals(mxConstants.DIRECTION_WEST)) { int mid = (y + h / 2); d = "M " + x + " " + mid + " L " + (x + w) + " " + mid; } else { int mid = (x + w / 2); d = "M " + mid + " " + y + " L " + mid + " " + (y + h); } elem = document.createElement("path"); elem.setAttribute("d", d + " Z"); } else if (shape.equals(mxConstants.SHAPE_ELLIPSE)) { elem = document.createElement("ellipse"); elem.setAttribute("cx", String.valueOf(x + w / 2)); elem.setAttribute("cy", String.valueOf(y + h / 2)); elem.setAttribute("rx", String.valueOf(w / 2)); elem.setAttribute("ry", String.valueOf(h / 2)); } else if (shape.equals(mxConstants.SHAPE_DOUBLE_ELLIPSE)) { elem = document.createElement("g"); background = document.createElement("ellipse"); background.setAttribute("cx", String.valueOf(x + w / 2)); background.setAttribute("cy", String.valueOf(y + h / 2)); background.setAttribute("rx", String.valueOf(w / 2)); background.setAttribute("ry", String.valueOf(h / 2)); elem.appendChild(background); int inset = (int) ((3 + strokeWidth) * scale); Element foreground = document.createElement("ellipse"); foreground.setAttribute("fill", "none"); foreground.setAttribute("stroke", strokeColor); foreground .setAttribute("stroke-width", String.valueOf(strokeWidth)); foreground.setAttribute("cx", String.valueOf(x + w / 2)); foreground.setAttribute("cy", String.valueOf(y + h / 2)); foreground.setAttribute("rx", String.valueOf(w / 2 - inset)); foreground.setAttribute("ry", String.valueOf(h / 2 - inset)); elem.appendChild(foreground); } else if (shape.equals(mxConstants.SHAPE_RHOMBUS)) { elem = document.createElement("path"); String d = "M " + (x + w / 2) + " " + y + " L " + (x + w) + " " + (y + h / 2) + " L " + (x + w / 2) + " " + (y + h) + " L " + x + " " + (y + h / 2); elem.setAttribute("d", d + " Z"); } else if (shape.equals(mxConstants.SHAPE_TRIANGLE)) { elem = document.createElement("path"); String direction = mxUtils.getString(style, mxConstants.STYLE_DIRECTION, ""); String d = null; if (direction.equals(mxConstants.DIRECTION_NORTH)) { d = "M " + x + " " + (y + h) + " L " + (x + w / 2) + " " + y + " L " + (x + w) + " " + (y + h); } else if (direction.equals(mxConstants.DIRECTION_SOUTH)) { d = "M " + x + " " + y + " L " + (x + w / 2) + " " + (y + h) + " L " + (x + w) + " " + y; } else if (direction.equals(mxConstants.DIRECTION_WEST)) { d = "M " + (x + w) + " " + y + " L " + x + " " + (y + h / 2) + " L " + (x + w) + " " + (y + h); } else // east { d = "M " + x + " " + y + " L " + (x + w) + " " + (y + h / 2) + " L " + x + " " + (y + h); } elem.setAttribute("d", d + " Z"); } else if (shape.equals(mxConstants.SHAPE_HEXAGON)) { elem = document.createElement("path"); String direction = mxUtils.getString(style, mxConstants.STYLE_DIRECTION, ""); String d = null; if (direction.equals(mxConstants.DIRECTION_NORTH) || direction.equals(mxConstants.DIRECTION_SOUTH)) { d = "M " + (x + 0.5 * w) + " " + y + " L " + (x + w) + " " + (y + 0.25 * h) + " L " + (x + w) + " " + (y + 0.75 * h) + " L " + (x + 0.5 * w) + " " + (y + h) + " L " + x + " " + (y + 0.75 * h) + " L " + x + " " + (y + 0.25 * h); } else { d = "M " + (x + 0.25 * w) + " " + y + " L " + (x + 0.75 * w) + " " + y + " L " + (x + w) + " " + (y + 0.5 * h) + " L " + (x + 0.75 * w) + " " + (y + h) + " L " + (x + 0.25 * w) + " " + (y + h) + " L " + x + " " + (y + 0.5 * h); } elem.setAttribute("d", d + " Z"); } else if (shape.equals(mxConstants.SHAPE_CLOUD)) { elem = document.createElement("path"); String d = "M " + (x + 0.25 * w) + " " + (y + 0.25 * h) + " C " + (x + 0.05 * w) + " " + (y + 0.25 * h) + " " + x + " " + (y + 0.5 * h) + " " + (x + 0.16 * w) + " " + (y + 0.55 * h) + " C " + x + " " + (y + 0.66 * h) + " " + (x + 0.18 * w) + " " + (y + 0.9 * h) + " " + (x + 0.31 * w) + " " + (y + 0.8 * h) + " C " + (x + 0.4 * w) + " " + (y + h) + " " + (x + 0.7 * w) + " " + (y + h) + " " + (x + 0.8 * w) + " " + (y + 0.8 * h) + " C " + (x + w) + " " + (y + 0.8 * h) + " " + (x + w) + " " + (y + 0.6 * h) + " " + (x + 0.875 * w) + " " + (y + 0.5 * h) + " C " + (x + w) + " " + (y + 0.3 * h) + " " + (x + 0.8 * w) + " " + (y + 0.1 * h) + " " + (x + 0.625 * w) + " " + (y + 0.2 * h) + " C " + (x + 0.5 * w) + " " + (y + 0.05 * h) + " " + (x + 0.3 * w) + " " + (y + 0.05 * h) + " " + (x + 0.25 * w) + " " + (y + 0.25 * h); elem.setAttribute("d", d + " Z"); } else if (shape.equals(mxConstants.SHAPE_ACTOR)) { elem = document.createElement("path"); double width3 = w / 3; String d = " M " + x + " " + (y + h) + " C " + x + " " + (y + 3 * h / 5) + " " + x + " " + (y + 2 * h / 5) + " " + (x + w / 2) + " " + (y + 2 * h / 5) + " C " + (x + w / 2 - width3) + " " + (y + 2 * h / 5) + " " + (x + w / 2 - width3) + " " + y + " " + (x + w / 2) + " " + y + " C " + (x + w / 2 + width3) + " " + y + " " + (x + w / 2 + width3) + " " + (y + 2 * h / 5) + " " + (x + w / 2) + " " + (y + 2 * h / 5) + " C " + (x + w) + " " + (y + 2 * h / 5) + " " + (x + w) + " " + (y + 3 * h / 5) + " " + (x + w) + " " + (y + h); elem.setAttribute("d", d + " Z"); } else if (shape.equals(mxConstants.SHAPE_CYLINDER)) { elem = document.createElement("g"); background = document.createElement("path"); double dy = Math.min(40, Math.floor(h / 5)); String d = " M " + x + " " + (y + dy) + " C " + x + " " + (y - dy / 3) + " " + (x + w) + " " + (y - dy / 3) + " " + (x + w) + " " + (y + dy) + " L " + (x + w) + " " + (y + h - dy) + " C " + (x + w) + " " + (y + h + dy / 3) + " " + x + " " + (y + h + dy / 3) + " " + x + " " + (y + h - dy); background.setAttribute("d", d + " Z"); elem.appendChild(background); Element foreground = document.createElement("path"); d = "M " + x + " " + (y + dy) + " C " + x + " " + (y + 2 * dy) + " " + (x + w) + " " + (y + 2 * dy) + " " + (x + w) + " " + (y + dy); foreground.setAttribute("d", d); foreground.setAttribute("fill", "none"); foreground.setAttribute("stroke", strokeColor); foreground .setAttribute("stroke-width", String.valueOf(strokeWidth)); elem.appendChild(foreground); } else { background = document.createElement("rect"); elem = background; elem.setAttribute("x", String.valueOf(x)); elem.setAttribute("y", String.valueOf(y)); elem.setAttribute("width", String.valueOf(w)); elem.setAttribute("height", String.valueOf(h)); if (mxUtils.isTrue(style, mxConstants.STYLE_ROUNDED, false)) { String r = String.valueOf(Math.min(w * mxConstants.RECTANGLE_ROUNDING_FACTOR, h * mxConstants.RECTANGLE_ROUNDING_FACTOR)); elem.setAttribute("rx", r); elem.setAttribute("ry", r); } // Paints the label image if (shape.equals(mxConstants.SHAPE_LABEL)) { String img = getImageForStyle(style); if (img != null) { String imgAlign = mxUtils.getString(style, mxConstants.STYLE_IMAGE_ALIGN, mxConstants.ALIGN_LEFT); String imgValign = mxUtils.getString(style, mxConstants.STYLE_IMAGE_VERTICAL_ALIGN, mxConstants.ALIGN_MIDDLE); int imgWidth = (int) (mxUtils.getInt(style, mxConstants.STYLE_IMAGE_WIDTH, mxConstants.DEFAULT_IMAGESIZE) * scale); int imgHeight = (int) (mxUtils.getInt(style, mxConstants.STYLE_IMAGE_HEIGHT, mxConstants.DEFAULT_IMAGESIZE) * scale); int spacing = (int) (mxUtils.getInt(style, mxConstants.STYLE_SPACING, 2) * scale); mxRectangle imageBounds = new mxRectangle(x, y, w, h); if (imgAlign.equals(mxConstants.ALIGN_CENTER)) { imageBounds.setX(imageBounds.getX() + (imageBounds.getWidth() - imgWidth) / 2); } else if (imgAlign.equals(mxConstants.ALIGN_RIGHT)) { imageBounds.setX(imageBounds.getX() + imageBounds.getWidth() - imgWidth - spacing - 2); } else // LEFT { imageBounds.setX(imageBounds.getX() + spacing + 4); } if (imgValign.equals(mxConstants.ALIGN_TOP)) { imageBounds.setY(imageBounds.getY() + spacing); } else if (imgValign.equals(mxConstants.ALIGN_BOTTOM)) { imageBounds .setY(imageBounds.getY() + imageBounds.getHeight() - imgHeight - spacing); } else // MIDDLE { imageBounds.setY(imageBounds.getY() + (imageBounds.getHeight() - imgHeight) / 2); } imageBounds.setWidth(imgWidth); imageBounds.setHeight(imgHeight); elem = document.createElement("g"); elem.appendChild(background); Element imageElement = createImageElement( imageBounds.getX(), imageBounds.getY(), imageBounds.getWidth(), imageBounds.getHeight(), img, false, false, false, isEmbedded()); if (opacity != 100 || fillOpacity != 100) { String value = String.valueOf(opacity * fillOpacity / 10000); imageElement.setAttribute("opacity", value); } elem.appendChild(imageElement); } // Paints the glass effect if (mxUtils.isTrue(style, mxConstants.STYLE_GLASS, false)) { double size = 0.4; // TODO: Mask with rectangle or rounded rectangle of label // Creates glass overlay Element glassOverlay = document.createElement("path"); // LATER: Not sure what the behaviour is for mutiple SVG elements in page. // Probably its possible that this points to an element in another SVG // node which when removed will result in an undefined background. glassOverlay.setAttribute("fill", "url(#" + getGlassGradientElement().getAttribute("id") + ")"); String d = "m " + (x - strokeWidth) + "," + (y - strokeWidth) + " L " + (x - strokeWidth) + "," + (y + h * size) + " Q " + (x + w * 0.5) + "," + (y + h * 0.7) + " " + (x + w + strokeWidth) + "," + (y + h * size) + " L " + (x + w + strokeWidth) + "," + (y - strokeWidth) + " z"; glassOverlay.setAttribute("stroke-width", String.valueOf(strokeWidth / 2)); glassOverlay.setAttribute("d", d); elem.appendChild(glassOverlay); } } } double rotation = mxUtils.getDouble(style, mxConstants.STYLE_ROTATION); int cx = x + w / 2; int cy = y + h / 2; Element bg = background; if (bg == null) { bg = elem; } if (!bg.getNodeName().equalsIgnoreCase("use") && !bg.getNodeName().equalsIgnoreCase("image")) { if (!fillColor.equalsIgnoreCase("none") && !gradientColor.equalsIgnoreCase("none")) { String direction = mxUtils.getString(style, mxConstants.STYLE_GRADIENT_DIRECTION); Element gradient = getGradientElement(fillColor, gradientColor, direction); if (gradient != null) { bg.setAttribute("fill", "url(#" + gradient.getAttribute("id") + ")"); } } else { bg.setAttribute("fill", fillColor); } bg.setAttribute("stroke", strokeColor); bg.setAttribute("stroke-width", String.valueOf(strokeWidth)); // Adds the shadow element Element shadowElement = null; if (mxUtils.isTrue(style, mxConstants.STYLE_SHADOW, false) && !fillColor.equals("none")) { shadowElement = (Element) bg.cloneNode(true); shadowElement.setAttribute("transform", mxConstants.SVG_SHADOWTRANSFORM); shadowElement.setAttribute("fill", mxConstants.W3C_SHADOWCOLOR); shadowElement.setAttribute("stroke", mxConstants.W3C_SHADOWCOLOR); shadowElement.setAttribute("stroke-width", String.valueOf(strokeWidth)); if (rotation != 0) { shadowElement.setAttribute("transform", "rotate(" + rotation + "," + cx + "," + cy + ") " + mxConstants.SVG_SHADOWTRANSFORM); } if (opacity != 100) { String value = String.valueOf(opacity / 100); shadowElement.setAttribute("fill-opacity", value); shadowElement.setAttribute("stroke-opacity", value); } appendSvgElement(shadowElement); } } if (rotation != 0) { elem.setAttribute("transform", elem.getAttribute("transform") + " rotate(" + rotation + "," + cx + "," + cy + ")"); } if (opacity != 100 || fillOpacity != 100 || strokeOpacity != 100) { String fillValue = String.valueOf(opacity * fillOpacity / 10000); String strokeValue = String.valueOf(opacity * strokeOpacity / 10000); elem.setAttribute("fill-opacity", fillValue); elem.setAttribute("stroke-opacity", strokeValue); } if (mxUtils.isTrue(style, mxConstants.STYLE_DASHED)) { String pattern = mxUtils.getString(style, mxConstants.STYLE_DASH_PATTERN, "3, 3"); elem.setAttribute("stroke-dasharray", pattern); } appendSvgElement(elem); return elem; } /** * Draws the given lines as segments between all points of the given list * of mxPoints. * * @param pts List of points that define the line. * @param style Style to be used for painting the line. */ public Element drawLine(List<mxPoint> pts, Map<String, Object> style) { Element group = document.createElement("g"); Element path = document.createElement("path"); boolean rounded = mxUtils.isTrue(style, mxConstants.STYLE_ROUNDED, false); String strokeColor = mxUtils.getString(style, mxConstants.STYLE_STROKECOLOR); float tmpStroke = (mxUtils.getFloat(style, mxConstants.STYLE_STROKEWIDTH, 1)); float strokeWidth = (float) (tmpStroke * scale); if (strokeColor != null && strokeWidth > 0) { // Draws the start marker Object marker = style.get(mxConstants.STYLE_STARTARROW); mxPoint pt = pts.get(1); mxPoint p0 = pts.get(0); mxPoint offset = null; if (marker != null) { float size = (mxUtils.getFloat(style, mxConstants.STYLE_STARTSIZE, mxConstants.DEFAULT_MARKERSIZE)); offset = drawMarker(group, marker, pt, p0, size, tmpStroke, strokeColor); } else { double dx = pt.getX() - p0.getX(); double dy = pt.getY() - p0.getY(); double dist = Math.max(1, Math.sqrt(dx * dx + dy * dy)); double nx = dx * strokeWidth / dist; double ny = dy * strokeWidth / dist; offset = new mxPoint(nx / 2, ny / 2); } // Applies offset to the point if (offset != null) { p0 = (mxPoint) p0.clone(); p0.setX(p0.getX() + offset.getX()); p0.setY(p0.getY() + offset.getY()); offset = null; } // Draws the end marker marker = style.get(mxConstants.STYLE_ENDARROW); pt = pts.get(pts.size() - 2); mxPoint pe = pts.get(pts.size() - 1); if (marker != null) { float size = (mxUtils.getFloat(style, mxConstants.STYLE_ENDSIZE, mxConstants.DEFAULT_MARKERSIZE)); offset = drawMarker(group, marker, pt, pe, size, tmpStroke, strokeColor); } else { double dx = pt.getX() - p0.getX(); double dy = pt.getY() - p0.getY(); double dist = Math.max(1, Math.sqrt(dx * dx + dy * dy)); double nx = dx * strokeWidth / dist; double ny = dy * strokeWidth / dist; offset = new mxPoint(nx / 2, ny / 2); } // Applies offset to the point if (offset != null) { pe = (mxPoint) pe.clone(); pe.setX(pe.getX() + offset.getX()); pe.setY(pe.getY() + offset.getY()); offset = null; } // Draws the line segments double arcSize = mxConstants.LINE_ARCSIZE * scale; pt = p0; String d = "M " + pt.getX() + " " + pt.getY(); for (int i = 1; i < pts.size() - 1; i++) { mxPoint tmp = pts.get(i); double dx = pt.getX() - tmp.getX(); double dy = pt.getY() - tmp.getY(); if ((rounded && i < pts.size() - 1) && (dx != 0 || dy != 0)) { // Draws a line from the last point to the current // point with a spacing of size off the current point // into direction of the last point double dist = Math.sqrt(dx * dx + dy * dy); double nx1 = dx * Math.min(arcSize, dist / 2) / dist; double ny1 = dy * Math.min(arcSize, dist / 2) / dist; double x1 = tmp.getX() + nx1; double y1 = tmp.getY() + ny1; d += " L " + x1 + " " + y1; // Draws a curve from the last point to the current // point with a spacing of size off the current point // into direction of the next point mxPoint next = pts.get(i + 1); dx = next.getX() - tmp.getX(); dy = next.getY() - tmp.getY(); dist = Math.max(1, Math.sqrt(dx * dx + dy * dy)); double nx2 = dx * Math.min(arcSize, dist / 2) / dist; double ny2 = dy * Math.min(arcSize, dist / 2) / dist; double x2 = tmp.getX() + nx2; double y2 = tmp.getY() + ny2; d += " Q " + tmp.getX() + " " + tmp.getY() + " " + x2 + " " + y2; tmp = new mxPoint(x2, y2); } else { d += " L " + tmp.getX() + " " + tmp.getY(); } pt = tmp; } d += " L " + pe.getX() + " " + pe.getY(); path.setAttribute("d", d); path.setAttribute("stroke", strokeColor); path.setAttribute("fill", "none"); path.setAttribute("stroke-width", String.valueOf(strokeWidth)); if (mxUtils.isTrue(style, mxConstants.STYLE_DASHED)) { String pattern = mxUtils.getString(style, mxConstants.STYLE_DASH_PATTERN, "3, 3"); path.setAttribute("stroke-dasharray", pattern); } group.appendChild(path); appendSvgElement(group); } return group; } /** * Draws the specified marker as a child path in the given parent. */ public mxPoint drawMarker(Element parent, Object type, mxPoint p0, mxPoint pe, float size, float strokeWidth, String color) { mxPoint offset = null; // Computes the norm and the inverse norm double dx = pe.getX() - p0.getX(); double dy = pe.getY() - p0.getY(); double dist = Math.max(1, Math.sqrt(dx * dx + dy * dy)); double absSize = size * scale; double nx = dx * absSize / dist; double ny = dy * absSize / dist; pe = (mxPoint) pe.clone(); pe.setX(pe.getX() - nx * strokeWidth / (2 * size)); pe.setY(pe.getY() - ny * strokeWidth / (2 * size)); nx *= 0.5 + strokeWidth / 2; ny *= 0.5 + strokeWidth / 2; Element path = document.createElement("path"); path.setAttribute("stroke-width", String.valueOf(strokeWidth * scale)); path.setAttribute("stroke", color); path.setAttribute("fill", color); String d = null; if (type.equals(mxConstants.ARROW_CLASSIC) || type.equals(mxConstants.ARROW_BLOCK)) { d = "M " + pe.getX() + " " + pe.getY() + " L " + (pe.getX() - nx - ny / 2) + " " + (pe.getY() - ny + nx / 2) + ((!type.equals(mxConstants.ARROW_CLASSIC)) ? "" : " L " + (pe.getX() - nx * 3 / 4) + " " + (pe.getY() - ny * 3 / 4)) + " L " + (pe.getX() + ny / 2 - nx) + " " + (pe.getY() - ny - nx / 2) + " z"; } else if (type.equals(mxConstants.ARROW_OPEN)) { nx *= 1.2; ny *= 1.2; d = "M " + (pe.getX() - nx - ny / 2) + " " + (pe.getY() - ny + nx / 2) + " L " + (pe.getX() - nx / 6) + " " + (pe.getY() - ny / 6) + " L " + (pe.getX() + ny / 2 - nx) + " " + (pe.getY() - ny - nx / 2) + " M " + pe.getX() + " " + pe.getY(); path.setAttribute("fill", "none"); } else if (type.equals(mxConstants.ARROW_OVAL)) { nx *= 1.2; ny *= 1.2; absSize *= 1.2; d = "M " + (pe.getX() - ny / 2) + " " + (pe.getY() + nx / 2) + " a " + (absSize / 2) + " " + (absSize / 2) + " 0 1,1 " + (nx / 8) + " " + (ny / 8) + " z"; } else if (type.equals(mxConstants.ARROW_DIAMOND)) { d = "M " + (pe.getX() + nx / 2) + " " + (pe.getY() + ny / 2) + " L " + (pe.getX() - ny / 2) + " " + (pe.getY() + nx / 2) + " L " + (pe.getX() - nx / 2) + " " + (pe.getY() - ny / 2) + " L " + (pe.getX() + ny / 2) + " " + (pe.getY() - nx / 2) + " z"; } if (d != null) { path.setAttribute("d", d); parent.appendChild(path); } return offset; } /** * Draws the specified text either using drawHtmlString or using drawString. * * @param text Text to be painted. * @param x X-coordinate of the text. * @param y Y-coordinate of the text. * @param w Width of the text. * @param h Height of the text. * @param style Style to be used for painting the text. */ public Object drawText(String text, int x, int y, int w, int h, Map<String, Object> style) { Element elem = null; String fontColor = mxUtils.getString(style, mxConstants.STYLE_FONTCOLOR, "black"); String fontFamily = mxUtils.getString(style, mxConstants.STYLE_FONTFAMILY, mxConstants.DEFAULT_FONTFAMILIES); int fontSize = (int) (mxUtils.getInt(style, mxConstants.STYLE_FONTSIZE, mxConstants.DEFAULT_FONTSIZE) * scale); if (text != null && text.length() > 0) { float strokeWidth = (float) (mxUtils.getFloat(style, mxConstants.STYLE_STROKEWIDTH, 1) * scale); // Applies the opacity float opacity = mxUtils.getFloat(style, mxConstants.STYLE_TEXT_OPACITY, 100); // Draws the label background and border String bg = mxUtils.getString(style, mxConstants.STYLE_LABEL_BACKGROUNDCOLOR); String border = mxUtils.getString(style, mxConstants.STYLE_LABEL_BORDERCOLOR); String transform = null; if (!mxUtils.isTrue(style, mxConstants.STYLE_HORIZONTAL, true)) { double cx = x + w / 2; double cy = y + h / 2; transform = "rotate(270 " + cx + " " + cy + ")"; } if (bg != null || border != null) { Element background = document.createElement("rect"); background.setAttribute("x", String.valueOf(x)); background.setAttribute("y", String.valueOf(y)); background.setAttribute("width", String.valueOf(w)); background.setAttribute("height", String.valueOf(h)); if (bg != null) { background.setAttribute("fill", bg); } else { background.setAttribute("fill", "none"); } if (border != null) { background.setAttribute("stroke", border); } else { background.setAttribute("stroke", "none"); } background.setAttribute("stroke-width", String.valueOf(strokeWidth)); if (opacity != 100) { String value = String.valueOf(opacity / 100); background.setAttribute("fill-opacity", value); background.setAttribute("stroke-opacity", value); } if (transform != null) { background.setAttribute("transform", transform); } appendSvgElement(background); } elem = document.createElement("text"); int fontStyle = mxUtils.getInt(style, mxConstants.STYLE_FONTSTYLE); String weight = ((fontStyle & mxConstants.FONT_BOLD) == mxConstants.FONT_BOLD) ? "bold" : "normal"; elem.setAttribute("font-weight", weight); String uline = ((fontStyle & mxConstants.FONT_UNDERLINE) == mxConstants.FONT_UNDERLINE) ? "underline" : "none"; elem.setAttribute("font-decoration", uline); if ((fontStyle & mxConstants.FONT_ITALIC) == mxConstants.FONT_ITALIC) { elem.setAttribute("font-style", "italic"); } elem.setAttribute("font-size", String.valueOf(fontSize)); elem.setAttribute("font-family", fontFamily); elem.setAttribute("fill", fontColor); if (opacity != 100) { String value = String.valueOf(opacity / 100); elem.setAttribute("fill-opacity", value); elem.setAttribute("stroke-opacity", value); } int swingFontStyle = ((fontStyle & mxConstants.FONT_BOLD) == mxConstants.FONT_BOLD) ? Font.BOLD : Font.PLAIN; swingFontStyle += ((fontStyle & mxConstants.FONT_ITALIC) == mxConstants.FONT_ITALIC) ? Font.ITALIC : Font.PLAIN; String[] lines = text.split("\n"); y += fontSize + (h - lines.length * (fontSize + mxConstants.LINESPACING)) / 2 - 2; String align = mxUtils.getString(style, mxConstants.STYLE_ALIGN, mxConstants.ALIGN_CENTER); String anchor = "start"; if (align.equals(mxConstants.ALIGN_RIGHT)) { anchor = "end"; x += w - mxConstants.LABEL_INSET * scale; } else if (align.equals(mxConstants.ALIGN_CENTER)) { anchor = "middle"; x += w / 2; } else { x += mxConstants.LABEL_INSET * scale; } elem.setAttribute("text-anchor", anchor); for (int i = 0; i < lines.length; i++) { Element tspan = document.createElement("tspan"); tspan.setAttribute("x", String.valueOf(x)); tspan.setAttribute("y", String.valueOf(y)); tspan.appendChild(document.createTextNode(lines[i])); elem.appendChild(tspan); y += fontSize + mxConstants.LINESPACING; } if (transform != null) { elem.setAttribute("transform", transform); } appendSvgElement(elem); } return elem; } }
md-k-sarker/OWLAx
src/main/java/com/mxgraph/canvas/mxSvgCanvas.java
Java
bsd-2-clause
39,300
from steamstoreprice.exception import UrlNotSteam, PageNotFound, RequestGenericError from bs4 import BeautifulSoup import requests class SteamStorePrice: def normalizeurl(self, url): """ clean the url from referal and other stuff :param url(string): amazon url :return: string(url cleaned) """ if "://store.steampowered.com/app" in url: return url else: raise UrlNotSteam("Please check the url, it doesn't contain store.steampowered.com/app*") def normalizeprice(self, price): """ remove the currenty from price :param price(string): price tag find on amazon store :return: float(price cleaned) """ listreplace = ["€", "$", "£", "\t", "\r\n"] for replacestring in listreplace: price = price.replace(replacestring, "") return float(price.replace(",", ".")) def getpage(self, url): """ Get the page and raise if status_code is not equal to 200 :param url(string): normalized(url) :return: bs4(html) """ url = self.normalizeurl(url) req = requests.get(url) if req.status_code == 200: return BeautifulSoup(req.text, "html.parser") elif req.status_code == 404: raise PageNotFound("Page not found, please check url") else: raise RequestGenericError("Return Code: %s, please check url" % req.status_code) def getprice(self, url): """ Find the price on AmazonStore starting from URL :param url(string): url :return: float(price cleaned) """ body_content = self.getpage(self.normalizeurl(url)) try: return self.normalizeprice(body_content.find("div", {"class": "game_purchase_price"}).contents[0]) except AttributeError: return self.normalizeprice(body_content.find("div", {"class": "discount_final_price"}).contents[0])
Mirio/steamstoreprice
steamstoreprice/steamstoreprice.py
Python
bsd-2-clause
2,007
package com.ociweb.pronghorn.ring.route; import com.ociweb.pronghorn.GraphManager; import com.ociweb.pronghorn.ring.FieldReferenceOffsetManager; import com.ociweb.pronghorn.ring.RingBuffer; import com.ociweb.pronghorn.ring.RingReader; import com.ociweb.pronghorn.ring.stage.PronghornStage; /** * Given n ring buffers with the same FROM/Schema * * Does not require schema knowledge for copy but does ensure targets and source have the same FROM. * @author Nathan Tippy * */ public class SplitterStage2 extends PronghornStage { private RingBuffer source; private RingBuffer[] targets; private long[] targetHeadPos; public int moreToCopy=-2;; public SplitterStage2(GraphManager gm, RingBuffer source, RingBuffer ... targets) { super(gm,source,targets); this.source = source; this.targets = targets; FieldReferenceOffsetManager sourceFrom = RingBuffer.from(source); int i = targets.length; this.targetHeadPos = new long[i]; while(--i>=0) { targetHeadPos[i] = targets[i].headPos.get(); //targets can not batch returns so this must be set RingBuffer.setReleaseBatchSize(targets[i], 0); RingReader.setReleaseBatchSize(targets[i], 0); //confirm this target is large enough for the needed data. FieldReferenceOffsetManager targetFrom = RingBuffer.from(targets[i]); if (targetFrom != sourceFrom) { throw new UnsupportedOperationException("Both source and target schemas must be the same"); } //NOTE: longest message that holds a sequence needs to fit within a ring if the use case is to set the sequence length last. // therefore if that target is full and needs one more fragment we may have a problem if the batch it has grabbed is // nearly has large as the target ring. To resolve this we only need to ensure that the target ring is 2x the source. int reqTargetSize = source.pBits+1; //target ring must be 2x bigger than source if (targets[i].pBits < reqTargetSize) { throw new UnsupportedOperationException("The target ring "+i+" primary bit size must be at least "+reqTargetSize+" but it was "+targets[i].pBits+ ". To avoid blocking hang behavior the target rings must always be 2x larger than the source ring."); } reqTargetSize = source.bBits+1; if (targets[i].bBits < reqTargetSize) { throw new UnsupportedOperationException("The target ring "+i+" byte bit size must be at least "+reqTargetSize+" but it was "+targets[i].bBits+ ". To avoid blocking hang behavior the target rings must always be 2x larger than the source ring."); } int minDif = source.bBits - source.pBits; int targDif = targets[i].bBits - targets[i].pBits; if (targDif<minDif) { throw new UnsupportedOperationException("The target ring "+i+" bit dif must be at least "+minDif+" but it was "+targDif); } } } @Override public void run() { processAvailData(this);//TODO: C, Should enable use of true to return partial copy. this may cause hang as written. } private static boolean processAvailData(SplitterStage2 ss) { int byteHeadPos; long headPos; if (null==ss.source.buffer) { ss.source.init(); } //TODO: A, publush to a single atomic long and read it here. //get the new head position byteHeadPos = ss.source.bytesHeadPos.get(); headPos = ss.source.headPos.get(); while(byteHeadPos != ss.source.bytesHeadPos.get() || headPos != ss.source.headPos.get() ) { byteHeadPos = ss.source.bytesHeadPos.get(); headPos = ss.source.headPos.get(); } //we have established the point that we can read up to, this value is changed by the writer on the other side //get the start and stop locations for the copy //now find the point to start reading from, this is moved forward with each new read. int pMask = ss.source.mask; long tempTail = ss.source.tailPos.get(); int primaryTailPos = pMask & (int)tempTail; long totalPrimaryCopy = (headPos - tempTail); if (totalPrimaryCopy <= 0) { assert(totalPrimaryCopy==0); return false; //nothing to copy so come back later } int bMask = ss.source.byteMask; int tempByteTail = ss.source.bytesTailPos.get(); int byteTailPos = bMask & tempByteTail; int totalBytesCopy = (bMask & byteHeadPos) - byteTailPos; if (totalBytesCopy < 0) { totalBytesCopy += (bMask+1); } //now do the copies doingCopy(ss, byteTailPos, primaryTailPos, (int)totalPrimaryCopy, totalBytesCopy); //release tail so data can be written ss.source.bytesTailPos.lazySet(ss.source.byteWorkingTailPos.value = 0xEFFFFFFF&(tempByteTail + totalBytesCopy)); ss.source.tailPos.lazySet(ss.source.workingTailPos.value = tempTail + totalPrimaryCopy); return false; //finished all the copy for now } //single pass attempt to copy if any can not accept the data then they are skipped //and true will be returned instead of false. private static void doingCopy(SplitterStage2 ss, int byteTailPos, int primaryTailPos, int totalPrimaryCopy, int totalBytesCopy) { do { ss.moreToCopy = 0; int i = ss.targets.length; while (--i>=0) { RingBuffer ringBuffer = ss.targets[i]; //check to see if we already pushed to this output ring. long headCache = ringBuffer.workingHeadPos.value; if ( (totalPrimaryCopy + ss.targetHeadPos[i]) > headCache) { //the tail must be larger than this position for there to be room to write if ((ringBuffer.tailPos.get() >= totalPrimaryCopy + headCache - ringBuffer.maxSize) && (totalBytesCopy <= (ringBuffer.maxByteSize- RingBuffer.bytesOfContent(ringBuffer)) ) ) { blockCopy(ss, byteTailPos, totalBytesCopy, primaryTailPos, totalPrimaryCopy, ringBuffer); } else { ss.moreToCopy++; } } // else this is already done. } } while(ss.moreToCopy>0); //reset for next time. int i = ss.targets.length; while (--i>=0) { //mark this one as done. ss.targetHeadPos[i] += totalPrimaryCopy; } ss.moreToCopy=-2; } public String toString() { return getClass().getSimpleName()+ (-2==moreToCopy ? " not running ": " moreToCopy:"+moreToCopy)+" source content "+RingBuffer.contentRemaining(source); } private static void blockCopy(SplitterStage2 ss, int byteTailPos, int totalBytesCopy, int primaryTailPos, int totalPrimaryCopy, RingBuffer ringBuffer) { //copy the bytes RingBuffer.copyBytesFromToRing(ss.source.byteBuffer, byteTailPos, ss.source.byteMask, ringBuffer.byteBuffer, ringBuffer.bytesHeadPos.get(), ringBuffer.byteMask, totalBytesCopy); ringBuffer.byteWorkingHeadPos.value = ringBuffer.bytesHeadPos.addAndGet(totalBytesCopy); //copy the primary data RingBuffer.copyIntsFromToRing(ss.source.buffer, primaryTailPos, ss.source.mask, ringBuffer.buffer, (int)ringBuffer.headPos.get(), ringBuffer.mask, totalPrimaryCopy); ringBuffer.workingHeadPos.value = ringBuffer.headPos.addAndGet(totalPrimaryCopy); //HackTEST ringBuffer.ringWalker.bnmHeadPosCache = ringBuffer.workingHeadPos.value; } }
romanp-stl/jFAST
src/main/java/com/ociweb/pronghorn/ring/route/SplitterStage2.java
Java
bsd-2-clause
7,291
#Analyzer ##Things that get checked * ECB Mode for encryption * Random IV, Salt * Constant keys or passwords * PBKDF iteration count (< 1000) * Password leaks (HTTP, Filesystem) * Hardcoded HTTP Authentication (but not all constant strings are found yet) * Sensitive Data (needs to be manually defined in 'data.json') ###data.json Is an array of JSON objects. { "type" : "plain"/"base64"/"hex", "content" : "CONTENT" } ##Run targets ###download ant download -Dhost=http://{ip}:8080 -Ddir={destination dir} Waits until all data is written to the database and downloads the information from the device. ###checkAll ant checkAll -Ddir={directory} Checks for all properties listed above. This can take a while because we have to glue together all input and output to the crypto functions etc. (probably there are a lot of calls to hash functions and those get searched too). ###GUI ant gui There is already a rudimentary GUI available that shows more information than the *CheckAll*-Tool, but only for some parts: * Crypto * Show the plaintext data of the cipher * Show traces * Sensitive information * Show where it was found ##Missing ###Data storage * CoreData (needs to be implemented first in callLog) * NSUserDefaults * Keychain ###Asymmetric ciphers Asymmetric ciphers are not checked yet.
dvdmssmnn/Analyzer
Readme.md
Markdown
bsd-2-clause
1,348
using System; using System.Collections; using Microsoft.Win32; namespace Cubewise.Query { public enum ODBC_DRIVERS {SQL_SERVER=0}; /// <summary> /// ODBCManager is the class that provides static methods, which provide /// access to the various ODBC components such as Drivers List, DSNs List /// etc. /// </summary> public class ODBCManager { private const string ODBC_LOC_IN_REGISTRY = "SOFTWARE\\ODBC\\"; private const string ODBC_INI_LOC_IN_REGISTRY = ODBC_LOC_IN_REGISTRY+"ODBC.INI\\"; private const string DSN_LOC_IN_REGISTRY = ODBC_INI_LOC_IN_REGISTRY+ "ODBC Data Sources\\"; private const string ODBCINST_INI_LOC_IN_REGISTRY = ODBC_LOC_IN_REGISTRY+"ODBCINST.INI\\"; private const string ODBC_DRIVERS_LOC_IN_REGISTRY = ODBCINST_INI_LOC_IN_REGISTRY+"ODBC Drivers\\"; private ODBCManager() { } /// <summary> /// Method that gives the ODBC Drivers installed in the local machine. /// </summary> /// <returns></returns> public static ODBCDriver[] GetODBCDrivers() { ArrayList driversList = new ArrayList(); ODBCDriver[] odbcDrivers=null; // Get the key for // "KHEY_LOCAL_MACHINE\\SOFTWARE\\ODBC\\ODBCINST.INI\\ODBC Drivers\\" // (ODBC_DRIVERS_LOC_IN_REGISTRY) that contains all the drivers // that are installed in the local machine. RegistryKey odbcDrvLocKey = OpenComplexSubKey(Registry.LocalMachine, ODBC_DRIVERS_LOC_IN_REGISTRY, false); if (odbcDrvLocKey != null) { // Get all Driver entries defined in ODBC_DRIVERS_LOC_IN_REGISTRY. string [] driverNames = odbcDrvLocKey.GetValueNames(); odbcDrvLocKey.Close(); if (driverNames != null) { // Foreach Driver entry in the ODBC_DRIVERS_LOC_IN_REGISTRY, // goto the Key ODBCINST_INI_LOC_IN_REGISTRY+driver and get // elements of the DSN entry to create ODBCDSN objects. foreach (string driverName in driverNames) { ODBCDriver odbcDriver = GetODBCDriver(driverName); if (odbcDriver != null) driversList.Add(odbcDriver); } if (driversList.Count>0) { // Create ODBCDriver objects equal to number of valid objects // in the ODBC Drivers ArrayList. odbcDrivers = new ODBCDriver[driversList.Count]; driversList.CopyTo(odbcDrivers,0); } } } return odbcDrivers; } /// <summary> /// Method thar returns driver object based on the driver name. /// </summary> /// <param name="driverName"></param> /// <returns>ODBCDriver object</returns> public static ODBCDriver GetODBCDriver(string driverName) { int j=0; ODBCDriver odbcDriver = null; string [] driverElements = null; string [] driverElmVals = null; RegistryKey driverNameKey = null; // Get the key for ODBCINST_INI_LOC_IN_REGISTRY+dsnName. driverNameKey = OpenComplexSubKey(Registry.LocalMachine, ODBCINST_INI_LOC_IN_REGISTRY+driverName,false); if (driverNameKey != null) { // Get all elements defined in the above key driverElements = driverNameKey.GetValueNames(); // Create Driver Element values array. driverElmVals = new string[driverElements.Length]; // For each element defined for a typical Driver get // its value. foreach (string driverElement in driverElements) { driverElmVals[j] = driverNameKey.GetValue(driverElement).ToString(); j++; } // Create ODBCDriver Object. odbcDriver = ODBCDriver.ParseForDriver(driverName, driverElements, driverElmVals); driverNameKey.Close(); } return odbcDriver; } /// <summary> /// Method that gives the System Data Source Name (DSN) entries as /// array of ODBCDSN objects. /// </summary> /// <returns>Array of System DSNs</returns> public static ODBCDSN[] GetSystemDSNList() { return GetDSNList(Registry.LocalMachine); } /// <summary> /// Method that returns one System ODBCDSN Object. /// </summary> /// <param name="dsnName"></param> /// <returns></returns> public static ODBCDSN GetSystemDSN(string dsnName) { return GetDSN(Registry.LocalMachine,dsnName); } /// <summary> /// Method that gives the User Data Source Name (DSN) entries as /// array of ODBCDSN objects. /// </summary> /// <returns>Array of User DSNs</returns> public static ODBCDSN[] GetUserDSNList() { return GetDSNList(Registry.CurrentUser); } /// <summary> /// Method that returns one User ODBCDSN Object. /// </summary> /// <param name="dsnName"></param> /// <returns></returns> public static ODBCDSN GetUserDSN(string dsnName) { return GetDSN(Registry.CurrentUser,dsnName); } /// <summary> /// Method that gives the Data Source Name (DSN) entries as array of /// ODBCDSN objects. /// </summary> /// <returns>Array of DSNs based on the baseKey parameter</returns> private static ODBCDSN[] GetDSNList(RegistryKey baseKey) { ArrayList dsnList = new ArrayList(); ODBCDSN[] odbcDSNs= new ODBCDSN[]{}; if (baseKey == null) return null; // Get the key for (using the baseKey parmetre passed in) // "\\SOFTWARE\\ODBC\\ODBC.INI\\ODBC Data Sources\\" (DSN_LOC_IN_REGISTRY) // that contains all the configured Data Source Name (DSN) entries. RegistryKey dsnNamesKey = OpenComplexSubKey(baseKey, DSN_LOC_IN_REGISTRY, false); if (dsnNamesKey != null) { // Get all DSN entries defined in DSN_LOC_IN_REGISTRY. string [] dsnNames = dsnNamesKey.GetValueNames(); if (dsnNames != null) { // Foreach DSN entry in the DSN_LOC_IN_REGISTRY, goto the // Key ODBC_INI_LOC_IN_REGISTRY+dsnName and get elements of // the DSN entry to create ODBCDSN objects. foreach (string dsnName in dsnNames) { // Get ODBC DSN object. ODBCDSN odbcDSN=GetDSN(baseKey,dsnName); if(odbcDSN != null) dsnList.Add(odbcDSN); } if (dsnList.Count>0) { // Create ODBCDSN objects equal to number of valid objects // in the DSN ArrayList. odbcDSNs = new ODBCDSN[dsnList.Count]; dsnList.CopyTo(odbcDSNs,0); } } dsnNamesKey.Close(); } return odbcDSNs; } /// <summary> /// Method that gives one ODBC DSN object /// </summary> /// <param name="baseKey"></param> /// <param name="dsnName"></param> /// <returns>ODBC DSN object</returns> private static ODBCDSN GetDSN(RegistryKey baseKey, string dsnName) { int j=0; string dsnDriverName = null; RegistryKey dsnNamesKey = null; RegistryKey dsnNameKey = null; string [] dsnElements = null; string [] dsnElmVals = null; ODBCDSN odbcDSN = null; // Get the key for (using the baseKey parmetre passed in) // "\\SOFTWARE\\ODBC\\ODBC.INI\\ODBC Data Sources\\" (DSN_LOC_IN_REGISTRY) // that contains all the configured Data Source Name (DSN) entries. dsnNamesKey = OpenComplexSubKey(baseKey, DSN_LOC_IN_REGISTRY, false); if (dsnNamesKey != null) { // Get the name of the driver for which the DSN is // defined. dsnDriverName = dsnNamesKey.GetValue(dsnName).ToString(); dsnNamesKey.Close(); } // Get the key for ODBC_INI_LOC_IN_REGISTRY+dsnName. dsnNameKey = OpenComplexSubKey(baseKey, ODBC_INI_LOC_IN_REGISTRY+dsnName,false); if (dsnNameKey != null) { // Get all elements defined in the above key dsnElements = dsnNameKey.GetValueNames(); // Create DSN Element values array. dsnElmVals = new string[dsnElements.Length]; // For each element defined for a typical DSN get // its value. foreach (string dsnElement in dsnElements) { dsnElmVals[j] = dsnNameKey.GetValue(dsnElement).ToString(); j++; } // Create ODBCDSN Object. odbcDSN = ODBCDSN.ParseForODBCDSN(dsnName,dsnDriverName, dsnElements, dsnElmVals); dsnNamesKey.Close(); } return odbcDSN; } /// <summary> /// Method that returns the registry key for a complex string that /// represents the key that is to be returned. The 'baseKey' parameter /// passed to this method is the root registry key on which the /// complex sub key has to be created. The 'complexKeyStr' is the /// stirng representation of the key to be created over the 'baseKey'. /// The syntax of the 'complexKeyStr' is "KEY1//KEY2//KEY3//...//". /// The "..." in the above syntax represents the repetetion. This /// method parses the 'compleKeyStr' parameter value and keep building /// the keys following the path of the keys listed in the string. Each /// key is built upon its previous key. First Key (KEY1) is built based /// on the 'basKey' parameter. Second key (KEY2) is based on the first /// key (Key creatd for KEY1) and so on... . The writable parameter /// represents whether final key has to be writable or not. /// </summary> /// <param name="baseKey"></param> /// <param name="complexKeyStr"></param> /// <param name="writable"></param> /// <returns>RegistryKey For the complex Subkey. </returns> public static RegistryKey OpenComplexSubKey(RegistryKey baseKey, string complexKeyStr, bool writable) { int prevLoc=0,currLoc = 0; string subKeyStr=complexKeyStr; RegistryKey finalKey = baseKey; if (baseKey == null) return null; if (complexKeyStr == null) return finalKey; // Search for the occurence of "\\" character in the complex string // and get all the characters upto "\\" from the start of search // point (prevLoc) as the keyString. Open a key out of string // keyString. do { currLoc=complexKeyStr.IndexOf("\\",prevLoc); if (currLoc != -1) { subKeyStr = complexKeyStr.Substring(prevLoc, currLoc-prevLoc); prevLoc=currLoc+1; } else { subKeyStr = complexKeyStr.Substring(prevLoc); } if (!subKeyStr.Equals(string.Empty)) finalKey = finalKey.OpenSubKey(subKeyStr, writable); } while(currLoc != -1); return finalKey; } } }
cubewise-code/odbc-connect
ODBCConnect/ODBCManager.cs
C#
bsd-2-clause
9,886
package com.betfair.domain import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import play.api.libs.json.{Json, Reads} case class MarketCatalogue(marketId: String, marketName: String, marketStartTime: Option[DateTime], description: Option[MarketDescription] = None, totalMatched: Double, runners: Option[List[RunnerCatalog]], eventType: Option[EventType], competition: Option[Competition] = None, event: Event) object MarketCatalogue { val dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" implicit val jodaDateReads = Reads[DateTime](js => js.validate[String].map[DateTime](dtString => DateTime.parse(dtString, DateTimeFormat.forPattern(dateFormat)) ) ) implicit val readsMarketCatalogue = Json.reads[MarketCatalogue] }
city81/betfair-service-ng
src/main/scala/com/betfair/domain/MarketCatalogue.scala
Scala
bsd-2-clause
979
/* * POK header * * The following file is a part of the POK project. Any modification should * be made according to the POK licence. You CANNOT use this file or a part * of a file for your own project. * * For more information on the POK licence, please see our LICENCE FILE * * Please follow the coding guidelines described in doc/CODING_GUIDELINES * * Copyright (c) 2007-2021 POK team */ #include <core/dependencies.h> #ifdef POK_NEEDS_PORTS_SAMPLING #include <core/syscall.h> #include <errno.h> #include <middleware/port.h> #include <types.h> pok_ret_t pok_port_sampling_read(const pok_port_id_t id, void *data, pok_port_size_t *len, bool_t *valid) { return (pok_syscall4(POK_SYSCALL_MIDDLEWARE_SAMPLING_READ, (uint32_t)id, (uint32_t)data, (uint32_t)len, (uint32_t)valid)); } #endif
pok-kernel/pok
libpok/middleware/portsamplingread.c
C
bsd-2-clause
928
/* * Copyright 2014, NICTA * * This software may be distributed and modified according to the terms of * the BSD 2-Clause license. Note that NO WARRANTY is provided. * See "LICENSE_BSD2.txt" for details. * * @TAG(NICTA_BSD) */ #ifndef __API_CONSTANTS_H #define __API_CONSTANTS_H #define BIT(n) (1ul<<(n)) enum priorityConstants { seL4_InvalidPrio = -1, seL4_MinPrio = 0, seL4_MaxPrio = 255 }; /* message_info_t defined in api/types.bf */ enum seL4_MsgLimits { seL4_MsgLengthBits = 7, seL4_MsgExtraCapBits = 2 }; #define seL4_MsgMaxLength 120 #define seL4_MsgMaxExtraCaps (BIT(seL4_MsgExtraCapBits)-1) #endif /* __API_CONSTANTS_H */
NICTA/seL4
libsel4/include/sel4/constants.h
C
bsd-2-clause
668
// Package api pulls 4chan board and thread data from the JSON API into native Go data structures. package api import ( "encoding/json" "fmt" "io" "net/http" pathpkg "path" "sync" "time" ) var ( // Whether or not to use HTTPS for requests. SSL bool = false // Cooldown time for updating threads using (*Thread).Update(). // If it is set to less than 10 seconds, it will be re-set to 10 seconds // before being used. UpdateCooldown time.Duration = 15 * time.Second cooldown <-chan time.Time cooldownMutex sync.Mutex ) const ( APIURL = "a.4cdn.org" ImageURL = "i.4cdn.org" StaticURL = "s.4cdn.org" ) func prefix() string { if SSL { return "https://" } else { return "http://" } } func get(base, path string, modify func(*http.Request) error) (*http.Response, error) { url := prefix() + pathpkg.Join(base, path) cooldownMutex.Lock() if cooldown != nil { <-cooldown } req, err := http.NewRequest("GET", url, nil) if err != nil { return nil, err } if modify != nil { err = modify(req) if err != nil { return nil, err } } resp, err := http.DefaultClient.Do(req) cooldown = time.After(1 * time.Second) cooldownMutex.Unlock() return resp, err } func getDecode(base, path string, dest interface{}, modify func(*http.Request) error) error { resp, err := get(base, path, modify) if err != nil { return err } defer resp.Body.Close() return json.NewDecoder(resp.Body).Decode(dest) } // Direct mapping from the API's JSON to a Go type. type jsonPost struct { No int64 `json:"no"` // Post number 1-9999999999999 Resto int64 `json:"resto"` // Reply to 0 (is thread), 1-999999999999 Sticky int `json:"sticky"` // Stickied thread? 0 (no), 1 (yes) Closed int `json:"closed"` // Closed thread? 0 (no), 1 (yes) Now string `json:"now"` // Date and time MM\/DD\/YY(Day)HH:MM (:SS on some boards) Time int64 `json:"time"` // UNIX timestamp UNIX timestamp Name string `json:"name"` // Name text or empty Trip string `json:"trip"` // Tripcode text (format: !tripcode!!securetripcode) Id string `json:"id"` // ID text (8 characters), Mod, Admin Capcode string `json:"capcode"` // Capcode none, mod, admin, admin_highlight, developer Country string `json:"country"` // Country code ISO 3166-1 alpha-2, XX (unknown) CountryName string `json:"country_name"` // Country name text Email string `json:"email"` // Email text or empty Sub string `json:"sub"` // Subject text or empty Com string `json:"com"` // Comment text (includes escaped HTML) or empty Tim int64 `json:"tim"` // Renamed filename UNIX timestamp + microseconds FileName string `json:"filename"` // Original filename text Ext string `json:"ext"` // File extension .jpg, .png, .gif, .pdf, .swf Fsize int `json:"fsize"` // File size 1-8388608 Md5 []byte `json:"md5"` // File MD5 byte slice Width int `json:"w"` // Image width 1-10000 Height int `json:"h"` // Image height 1-10000 TnW int `json:"tn_w"` // Thumbnail width 1-250 TnH int `json:"tn_h"` // Thumbnail height 1-250 FileDeleted int `json:"filedeleted"` // File deleted? 0 (no), 1 (yes) Spoiler int `json:"spoiler"` // Spoiler image? 0 (no), 1 (yes) CustomSpoiler int `json:"custom_spoiler"` // Custom spoilers? 1-99 OmittedPosts int `json:"omitted_posts"` // # replies omitted 1-10000 OmittedImages int `json:"omitted_images"` // # images omitted 1-10000 Replies int `json:"replies"` // total # of replies 0-99999 Images int `json:"images"` // total # of images 0-99999 BumpLimit int `json:"bumplimit"` // bump limit? 0 (no), 1 (yes) ImageLimit int `json:"imagelimit"` // image limit? 0 (no), 1 (yes) CapcodeReplies map[string][]int `json:"capcode_replies"` LastModified int64 `json:"last_modified"` } // A Post represents all of the attributes of a 4chan post, organized in a more directly usable fashion. type Post struct { // Post info Id int64 Thread *Thread Time time.Time Subject string LastModified int64 // These are only present in an OP post. They are exposed through their // corresponding Thread getter methods. replies int images int omitted_posts int omitted_images int bump_limit bool image_limit bool sticky bool closed bool custom_spoiler int // the number of custom spoilers on a given board // Poster info Name string Trip string Email string Special string Capcode string // Country and CountryName are empty unless the board uses country info Country string CountryName string // Message body Comment string // File info if any, otherwise nil File *File // only when they do this on /q/ CapcodeReplies map[string][]int } func (self *Post) String() (s string) { s += fmt.Sprintf("#%d %s%s on %s:\n", self.Id, self.Name, self.Trip, self.Time.Format(time.RFC822)) if self.File != nil { s += self.File.String() } s += self.Comment return } // ImageURL constructs and returns the URL of the attached image. Returns the // empty string if there is none. func (self *Post) ImageURL() string { file := self.File if file == nil { return "" } return fmt.Sprintf("%s%s/%s/%d%s", prefix(), ImageURL, self.Thread.Board, file.Id, file.Ext) } // ThumbURL constructs and returns the thumbnail URL of the attached image. // Returns the empty string if there is none. func (self *Post) ThumbURL() string { file := self.File if file == nil { return "" } return fmt.Sprintf("%s%s/%s/%ds%s", prefix(), ImageURL, self.Thread.Board, file.Id, ".jpg") } // A File represents an uploaded file's metadata. type File struct { Id int64 // Id is what 4chan renames images to (UNIX + microtime, e.g. 1346971121077) Name string // Original filename Ext string Size int MD5 []byte Width int Height int ThumbWidth int ThumbHeight int Deleted bool Spoiler bool } func (self *File) String() string { return fmt.Sprintf("File: %s%s (%dx%d, %d bytes, md5 %x)\n", self.Name, self.Ext, self.Width, self.Height, self.Size, self.MD5) } // CountryFlagURL returns the URL of the post's country flag icon, if enabled // on the board in question. func (self *Post) CountryFlagURL() string { if self.Country == "" { return "" } // lol /pol/ if self.Thread.Board == "pol" { return fmt.Sprintf("%s://%s/image/country/troll/%s.gif", prefix(), StaticURL, self.Country) } return fmt.Sprintf("%s://%s/image/country/%s.gif", prefix(), StaticURL, self.Country) } // A Thread represents a thread of posts. It may or may not contain the actual replies. type Thread struct { Posts []*Post OP *Post Board string // without slashes ex. "g" or "ic" date_recieved time.Time cooldown <-chan time.Time } // GetIndex hits the API for an index of thread stubs from the given board and // page. func GetIndex(board string, page int) ([]*Thread, error) { resp, err := get(APIURL, fmt.Sprintf("/%s/%d.json", board, page + 1), nil) if err != nil { return nil, err } defer resp.Body.Close() threads, err := ParseIndex(resp.Body, board) if err != nil { return nil, err } now := time.Now() for _, t := range threads { t.date_recieved = now } return threads, err } // GetThreads hits the API for a list of the thread IDs of all the active // threads on a given board. func GetThreads(board string) ([][]int64, error) { p := make([]struct { Page int `json:"page"` Threads []struct { No int64 `json:"no"` } `json:"threads"` }, 0, 10) if err := getDecode(APIURL, fmt.Sprintf("/%s/threads.json", board), &p, nil); err != nil { return nil, err } n := make([][]int64, len(p)) for _, page := range p { // Pages are 1 based in the json api n[page.Page-1] = make([]int64, len(page.Threads)) for j, thread := range page.Threads { n[page.Page-1][j] = thread.No } } return n, nil } // GetThread hits the API for a single thread and all its replies. board is // just the board name, without the surrounding slashes. If a thread is being // updated, use an existing thread's Update() method if possible because that // uses If-Modified-Since in the request, which reduces unnecessary server // load. func GetThread(board string, thread_id int64) (*Thread, error) { return getThread(board, thread_id, time.Unix(0, 0)) } func getThread(board string, thread_id int64, stale_time time.Time) (*Thread, error) { resp, err := get(APIURL, fmt.Sprintf("/%s/thread/%d.json", board, thread_id), func(req *http.Request) error { if stale_time.Unix() != 0 { req.Header.Add("If-Modified-Since", stale_time.UTC().Format(http.TimeFormat)) } return nil }) if err != nil { return nil, err } defer resp.Body.Close() thread, err := ParseThread(resp.Body, board) thread.date_recieved = time.Now() return thread, err } // ParseIndex converts a JSON response for multiple threads into a native Go // data structure func ParseIndex(r io.Reader, board string) ([]*Thread, error) { var t struct { Threads []struct { Posts []*jsonPost `json:"posts"` } `json:"threads"` } if err := json.NewDecoder(r).Decode(&t); err != nil { return nil, err } threads := make([]*Thread, len(t.Threads)) for i, json_thread := range t.Threads { thread := &Thread{Posts: make([]*Post, len(t.Threads[i].Posts)), Board: board} for k, v := range json_thread.Posts { thread.Posts[k] = json_to_native(v, thread) if v.No == 0 { thread.OP = thread.Posts[k] } } // TODO: fix this up if thread.OP == nil { thread.OP = thread.Posts[0] } threads[i] = thread } return threads, nil } // ParseThread converts a JSON response for one thread into a native Go data // structure. func ParseThread(r io.Reader, board string) (*Thread, error) { var t struct { Posts []*jsonPost `json:"posts"` } if err := json.NewDecoder(r).Decode(&t); err != nil { return nil, err } thread := &Thread{Posts: make([]*Post, len(t.Posts)), Board: board} for k, v := range t.Posts { thread.Posts[k] = json_to_native(v, thread) if v.No == 0 { thread.OP = thread.Posts[k] } } // TODO: fix this up if thread.OP == nil { thread.OP = thread.Posts[0] } return thread, nil } func json_to_native(v *jsonPost, thread *Thread) *Post { p := &Post{ Id: v.No, sticky: v.Sticky == 1, closed: v.Closed == 1, Time: time.Unix(v.Time, 0), Name: v.Name, Trip: v.Trip, Special: v.Id, Capcode: v.Capcode, Country: v.Country, CountryName: v.CountryName, Email: v.Email, Subject: v.Sub, Comment: v.Com, custom_spoiler: v.CustomSpoiler, replies: v.Replies, images: v.Images, omitted_posts: v.OmittedPosts, omitted_images: v.OmittedImages, bump_limit: v.BumpLimit == 1, image_limit: v.ImageLimit == 1, Thread: thread, CapcodeReplies: v.CapcodeReplies, LastModified: v.LastModified, } if len(v.FileName) > 0 { p.File = &File{ Id: v.Tim, Name: v.FileName, Ext: v.Ext, Size: v.Fsize, MD5: v.Md5, Width: v.Width, Height: v.Height, ThumbWidth: v.TnW, ThumbHeight: v.TnH, Deleted: v.FileDeleted == 1, Spoiler: v.Spoiler == 1, } } return p } // Update an existing thread in-place. func (self *Thread) Update() (new_posts, deleted_posts int, err error) { cooldownMutex.Lock() if self.cooldown != nil { <-self.cooldown } var thread *Thread thread, err = getThread(self.Board, self.Id(), self.date_recieved) if UpdateCooldown < 10*time.Second { UpdateCooldown = 10 * time.Second } self.cooldown = time.After(UpdateCooldown) cooldownMutex.Unlock() if err != nil { return 0, 0, err } var a, b int // traverse both threads in parallel to check for deleted/appended posts for a, b = 0, 0; a < len(self.Posts); a, b = a+1, b+1 { if self.Posts[a].Id == thread.Posts[b].Id { continue } // a post has been deleted, go back one to compare with the next b-- deleted_posts++ } new_posts = len(thread.Posts) - b self.Posts = thread.Posts return } // Id returns the thread OP's post ID. func (self *Thread) Id() int64 { return self.OP.Id } func (self *Thread) String() (s string) { for _, post := range self.Posts { s += post.String() + "\n\n" } return } // Replies returns the number of replies the thread OP has. func (self *Thread) Replies() int { return self.OP.replies } // Images returns the number of images in the thread. func (self *Thread) Images() int { return self.OP.images } // OmittedPosts returns the number of posts omitted in a thread list overview. func (self *Thread) OmittedPosts() int { return self.OP.omitted_posts } // OmittedImages returns the number of image posts omitted in a thread list overview. func (self *Thread) OmittedImages() int { return self.OP.omitted_images } // BumpLimit returns true if the thread is at its bump limit, or false otherwise. func (self *Thread) BumpLimit() bool { return self.OP.bump_limit } // ImageLimit returns true if the thread can no longer accept image posts, or false otherwise. func (self *Thread) ImageLimit() bool { return self.OP.image_limit } // Closed returns true if the thread is closed for replies, or false otherwise. func (self *Thread) Closed() bool { return self.OP.closed } // Sticky returns true if the thread is stickied, or false otherwise. func (self *Thread) Sticky() bool { return self.OP.sticky } // CustomSpoiler returns the ID of its custom spoiler image, if there is one. func (self *Thread) CustomSpoiler() int { return self.OP.custom_spoiler } // CustomSpoilerURL builds and returns the URL of the custom spoiler image, or // an empty string if none exists. func (self *Thread) CustomSpoilerURL(id int, ssl bool) string { if id > self.OP.custom_spoiler { return "" } return fmt.Sprintf("%s://%s/image/spoiler-%s%d.png", prefix(), StaticURL, self.Board, id) } // A Board is the name and title of a single board. type Board struct { Board string `json:"board"` Title string `json:"title"` } // Board names/descriptions will be cached here after a call to LookupBoard or GetBoards var Boards []Board // LookupBoard returns the Board corresponding to the board name (without slashes) func LookupBoard(name string) (Board, error) { if Boards == nil { _, err := GetBoards() if err != nil { return Board{}, fmt.Errorf("Board '%s' not found: %v", name, err) } } for _, b := range Boards { if name == b.Board { return b, nil } } return Board{}, fmt.Errorf("Board '%s' not found", name) } // Get the list of boards. func GetBoards() ([]Board, error) { var b struct { Boards []Board `json:"boards"` } err := getDecode(APIURL, "/boards.json", &b, nil) if err != nil { return nil, err } Boards = b.Boards return b.Boards, nil } // A Catalog contains a list of (truncated) threads on each page of a board. type Catalog []struct { Page int Threads []*Thread } type catalog []struct { Page int `json:"page"` Threads []*jsonPost `json:"threads"` } // GetCatalog hits the API for a catalog listing of a board. func GetCatalog(board string) (Catalog, error) { if len(board) == 0 { return nil, fmt.Errorf("api: GetCatalog: No board name given") } var c catalog err := getDecode(APIURL, fmt.Sprintf("/%s/catalog.json", board), &c, nil) if err != nil { return nil, err } cat := make(Catalog, len(c)) for i, page := range c { extracted := struct { Page int Threads []*Thread }{page.Page, make([]*Thread, len(page.Threads))} for j, post := range page.Threads { thread := &Thread{Posts: make([]*Post, 1), Board: board} post := json_to_native(post, thread) thread.Posts[0] = post extracted.Threads[j] = thread if thread.OP == nil { thread.OP = thread.Posts[0] } } cat[i] = extracted } return cat, nil }
moshee/go-4chan-api
api/api.go
GO
bsd-2-clause
16,980
/** * RayFoundation.h * A ray of light in the realm of darkness. * Some additions to C. * If You don't like it, You can preprocess files, to get pure-C code. * Author Kucheruavyu Ilya (kojiba@protonmail.com) * 2014 Ukraine Kharkiv * _ _ _ _ * | | (_|_) | * | | _____ _ _| |__ __ _ * | |/ / _ \| | | '_ \ / _` | * | " (_) | | | |_) | (_| | * |_|\_\___/| |_|_.__/ \__,_| * _/ | * |__/ **/ #ifndef __RAY_FOUNDATION__ #define __RAY_FOUNDATION__ #ifdef __cplusplus extern "C" { #endif // Workers #include "RSystem.h" #include "RSyntax.h" #include "RColors.h" #include "RBasics/RBasics.h" #include "RClassTable/RClassTable.h" // Containers #include "RContainers/RArray.h" #include "RContainers/RArray_Blocks.h" #include "RContainers/RArray_Parallel.h" #include "RContainers/RList.h" #include "RContainers/RBuffer.h" #include "RContainers/RDictionary.h" // Strings #include "RString/RString.h" #include "RString/RString_Char.h" #include "RString/RString_Numbers.h" #include "RString/RString_UTF8.h" #include "RString/RString_Consts.h" #include "RString/RString_File.h" // Memory operations #include "RMemoryOperations/RByteOperations.h" #include "RMemoryOperations/RData.h" #include "RMemoryOperations/RSandBox.h" #include "RMemoryOperations/RAutoPool.h" // Encoding #include "REncoding/RBase64.h" #include "REncoding/PurgeEvasionUtilsRay.h" // Networking #include "RNetwork/RSocket.h" #include "RNetwork/RTCPHandler.h" // Threads #include "RThread/RThread.h" #include "RThread/RThreadPool.h" // Others #include "Utils/Utils.h" #include "Utils/PurgeEvasionConnection.h" #include "Utils/PurgeEvasionParallel.h" #include "Utils/PurgeEvasionTCPHandler.h" #ifdef RAY_BLOCKS_ON #define endRay() deleter(stringConstantsTable(), RDictionary);\ deleter(RCTSingleton, RClassTable); \ deleter(singleBlockPool(), RAutoPool); \ p(RAutoPool)(RPool); \ deleter(RPool, RAutoPool); \ stopConsole();\ return 0 #else #define endRay() deleter(stringConstantsTable(), RDictionary);\ deleter(RCTSingleton, RClassTable); \ p(RAutoPool)(RPool); \ deleter(RPool, RAutoPool); \ stopConsole();\ return 0 #endif #ifdef __cplusplus }; #endif #endif /*__RAY_FOUNDATION__*/
kojiba/RayLanguage
Classes/RayFoundation/RayFoundation.h
C
bsd-2-clause
2,390
import common.config import common.messaging as messaging import common.storage import common.debug as debug from common.geo import Line, LineSet from common.concurrency import ConcurrentObject from threading import Lock, RLock import tree.pachinko.message_type as message_type import tree.pachinko.config as config import tree.common.protocol.client_configuration_pb2 as client_config_protocol import tree.pachinko.protocol.modifications_pb2 as modifications_protocol import tree.pachinko.protocol.queries_pb2 as query_protocol from tree.common.content_server import ContentServer as BaseContentServer class Transaction(ConcurrentObject): def __init__(self, client_handler, client_id, identifier): ConcurrentObject.__init__(self) self.client_handler = client_handler self.client_id = client_id self.identifier = identifier self.write_intervals = None self.read_intervals = None self.end_request = None self.dependencies = [] self.pending = [] self.done = False def can_execute(self): if not self.end_request: return False if self.done: return False # has already been executed return self.end_request.abort or len(self.dependencies) == 0 def set_end_request(self, end_request): assert not self.end_request assert not self.done self.end_request = end_request def commit(self): result = modifications_protocol.ModificationResult() result.okay = True result.replyTo = self.identifier result.num_inserted = 0 result.num_modified = 0 result.num_deleted = 0 for write in self.end_request.writes: assert write.HasField('insert') result.MergeFrom(self.client_handler.handle_insert(write.insert)) # Forward to correct client client = self.client_handler.content_server.client_acceptor.clients[self.client_id] with client: client.peer.send(message_type.client.mod_result, result.SerializeToString()) self.client_handler.content_server.transactions.remove(self) for pending in self.pending: with pending: pending.dependencies.remove(self) if pending.can_execute(): pending.commit() debug.log("Ended transaction " + str(self.identifier) + " from client " + str(self.client_id)) self.done = True def equals(self, client_id, transaction_id): return (self.client_id == client_id) and (self.identifier == transaction_id) class ClientHandler(ConcurrentObject): def __init__(self, content_server, peer): ConcurrentObject.__init__(self) self.content_server = content_server self.peer = peer self.fileno = peer.get_socket().fileno() self.identifier = -1 def get_socket(self): return self.peer def is_connected(self): return self.peer.is_connected() def handle_insert(self, insert): result = modifications_protocol.ModificationResult() result.okay = True result.num_inserted = 0 result.num_modified = 0 result.num_deleted = 0 for obj in insert.objects: # Only insert if it is in our partition if (obj.position >= self.content_server.content_position * self.content_server.partition_size() and obj.position <= (1+self.content_server.content_position) * self.content_server.partition_size()): self.content_server.storage.put(obj.position, obj.value) result.num_inserted += 1 debug.log("Inserted " + str(result.num_inserted) + " objects") return result def handle_range_remove(self, range_remove): result = modifications_protocol.ModificationResult() result.okay = True result.num_inserted = 0 result.num_modified = 0 result.num_deleted = self.content_server.storage.range_remove(range_remove.start, range_remove.end) debug.log("Deleted " + str(result.num_inserted) + " objects") return result def handle_range_search(self, range_search): result = query_protocol.QueryResponse() for key,value in self.content_server.storage.find(range_search.start, range_search.end): obj = result.objects.add() obj.position = key obj.value = value debug.log("Found " + str(len(result.objects)) + " objects") return result def handle_transaction_start(self, start_transaction): result = modifications_protocol.ModificationResult() result.okay = True result.replyTo = start_transaction.transaction_id result.num_inserted = 0 result.num_modified = 0 result.num_deleted = 0 assert (self.identifier == -1) or (self.identifier == start_transaction.client_id) # Read (in)validation read_intervals = LineSet() read_intervals.parse(start_transaction.read_intervals) write_intervals = LineSet() write_intervals.parse(start_transaction.write_intervals) dependencies = [] self.content_server.transaction_lock.acquire() for other in self.content_server.transactions: if other.write_intervals.overlaps(read_intervals) and not other.done: debug.log("Detected read-write conflict between client " + str(other.client_id) + " and " + str(start_transaction.client_id)) result.okay = False break elif other.write_intervals.overlaps(write_intervals): other.acquire() if other.done: other.release() else: dependencies.append(other) elif other.read_intervals.overlaps(write_intervals): other.acquire() if other.done: other.release() else: dependencies.append(other) assert len(start_transaction.server_ops) == 1 # only check reads if we didn't abort yet if result.okay: for read in start_transaction.server_ops[0].reads: reply = self.handle_range_search(read.range_search) if len(read.result) != len(reply.objects): result.okay = False else: for i in range(0, len(read.result)): if (read.result[i].position != reply.objects[i].position) or (read.result[i].position != reply.objects[i].position): debug.log("Found outdated read") result.okay = False if result.okay: debug.log("Started transaction " + str(start_transaction.transaction_id) + " from client " + str(start_transaction.client_id)) tx = Transaction(self, start_transaction.client_id, start_transaction.transaction_id) tx.write_intervals = write_intervals tx.read_intervals = read_intervals tx.dependencies = dependencies for other in dependencies: other.pending.append(tx) other.release() self.content_server.transactions.append(tx) else: for other in dependencies: other.release() debug.log("Rejected transaction") # Forward to correct client client = self.content_server.client_acceptor.clients[start_transaction.client_id] with client: client.peer.send(message_type.client.mod_result, result.SerializeToString()) self.content_server.transaction_lock.release() def handle_transaction_end(self, end_transaction): with self.content_server.transaction_lock: transaction = None for tx in self.content_server.transactions: if tx.equals(end_transaction.client_id, end_transaction.transaction_id): transaction = tx break if not transaction: debug.log("Failed to end transaction " + str(end_transaction.transaction_id) + " from client " + str(end_transaction.client_id)) result = modifications_protocol.ModificationResult() # abort also succeeds if we find no such transaction on this server result.okay = True if end_transaction.abort else False result.replyTo = end_transaction.transaction_id result.num_inserted = 0 result.num_modified = 0 result.num_deleted = 0 # Forward to correct client client = self.content_server.client_acceptor.clients[end_transaction.client_id] with client: client.peer.send(message_type.client.mod_result, result.SerializeToString()) else: with transaction: transaction.set_end_request(end_transaction) if transaction.can_execute(): transaction.commit() def forward_transaction_start(self, transaction_start): with self.content_server.forwarding_lock: servers = [] assert len(transaction_start.server_ops) for i in transaction_start.server_ops: servers.append(i.position) left_intersection = set(servers).intersection(self.content_server.left_partitions) right_intersection = set(servers).intersection(self.content_server.right_partitions) assert len(servers) > 0 assert len(servers) == (len(left_intersection)+len(right_intersection)) if len(left_intersection): assert self.content_server.left_child left_start = modifications_protocol.StartTransactionRequest() left_start.has_reads = transaction_start.has_reads left_start.client_id = transaction_start.client_id left_start.transaction_id = transaction_start.transaction_id for interval in transaction_start.write_intervals: if interval.end <= self.content_server.center: i = left_start.write_intervals.add() i.CopyFrom(interval) for interval in transaction_start.read_intervals: if interval.end <= self.content_server.center: i = left_start.read_intervals.add() i.CopyFrom(interval) for server_ops in transaction_start.server_ops: if server_ops.position in self.content_server.left_partitions: left_ops = left_start.server_ops.add() left_ops.CopyFrom(server_ops) self.content_server.left_child.send(message_type.client.start_transaction, left_start.SerializeToString()) if len(right_intersection): assert self.content_server.right_child right_start = modifications_protocol.StartTransactionRequest() right_start.has_reads = transaction_start.has_reads right_start.client_id = transaction_start.client_id right_start.transaction_id = transaction_start.transaction_id for interval in transaction_start.write_intervals: if interval.end >= self.content_server.center: i = right_start.write_intervals.add() i.CopyFrom(interval) for interval in transaction_start.read_intervals: if interval.end >= self.content_server.center: i = right_start.read_intervals.add() i.CopyFrom(interval) for server_ops in transaction_start.server_ops: if server_ops.position in self.content_server.right_partitions: right_ops = right_start.server_ops.add() right_ops.CopyFrom(server_ops) self.content_server.right_child.send(message_type.client.start_transaction, right_start.SerializeToString()) def close(self): if self.identifier > 0: del self.content_server.client_acceptor.clients[self.identifier] self.content_server.unregister_handler(self.fileno, self) for tx in self.content_server.transactions: if tx.client_id == self.identifier: self.content_server.transactions.remove(tx) def update(self): # Loop until we run out of messages while True: try: msgtype, data = self.peer.receive() except: self.close() return # Connection closed if msgtype is None: self.close() elif msgtype is message_type.client.mod_request: mod_request = modifications_protocol.ModificationRequest() mod_request.ParseFromString(data) result = None if mod_request.HasField("insert"): result = self.handle_insert(mod_request.insert) elif mod_request.HasField("range_remove"): result = self.handle_range_remove(mod_request.range_remove) else: raise RuntimeError("Unknown Modification") result.replyTo = mod_request.identifier self.peer.send(message_type.client.mod_result, result.SerializeToString()) elif msgtype is message_type.client.notify_client_id: message = client_config_protocol.NotifyClientId() message.ParseFromString(data) self.identifier = message.identifier self.content_server.client_acceptor.clients[self.identifier] = self self.peer.send(message_type.client.notify_cid_ack, bytes()) elif msgtype is message_type.client.start_transaction: start_transaction = modifications_protocol.StartTransactionRequest() start_transaction.ParseFromString(data) if self.content_server.is_leaf(): self.handle_transaction_start(start_transaction) else: self.forward_transaction_start(start_transaction) elif msgtype is message_type.client.query_request: query_request = query_protocol.QueryRequest() query_request.ParseFromString(data) result = None if query_request.HasField("range_search"): result = self.handle_range_search(query_request.range_search) else: raise RuntimeError("Unknown query type") result.replyTo = query_request.identifier self.peer.send(message_type.client.query_result, result.SerializeToString()) elif msgtype is message_type.client.end_transaction: end_transaction = modifications_protocol.EndTransactionRequest() end_transaction.ParseFromString(data) self.handle_transaction_end(end_transaction) else: raise RuntimeError("Received unknown message type from client") # Done? if not self.peer.has_messages(): return class ContentServer(BaseContentServer): def __init__(self, coordinator, name, level, pos): BaseContentServer.__init__(self, "pachinko", coordinator, config.COORDINATOR_PORT_INTERNAL, name, level, pos, ClientHandler) self.transaction_lock = RLock() self.forwarding_lock = Lock()
kaimast/inanutshell
tree/pachinko/content_server.py
Python
bsd-2-clause
16,352
package safebrowsing /* #include <stdio.h> #include <stdlib.h> #include <string.h> #include "hat-trie.h" hattrie_t* start() { hattrie_t* trie; trie = hattrie_create(); return trie; } void set(hattrie_t* h, char* key, size_t len) { value_t* val; val = hattrie_get(h, key, len); *val = 1; } int get(hattrie_t* h, char* key, size_t len) { value_t* val; val = hattrie_tryget(h, key, len); if (val != 0) { return *val; } return 0; } void delete(hattrie_t* h, char* key, size_t len) { value_t* val; val = hattrie_tryget(h, key, len); if (val != 0) { *val = 0; } } char* hattrie_iter_key_string(hattrie_iter_t* i, size_t* len) { const char* in_key; char* out_key; in_key = hattrie_iter_key(i, len); out_key = malloc((*len) * sizeof(char)); memcpy(out_key, in_key, *len); return out_key; } */ import "C" import ( "runtime" "sync" "unsafe" ) type HatTrie struct { trie *C.hattrie_t l sync.RWMutex // we name it because we don't want to expose it } func finalizeHatTrie(c *HatTrie) { C.hattrie_free(c.trie) } func NewTrie() *HatTrie { trie := C.start() out := &HatTrie{ trie: trie, } runtime.SetFinalizer(out, finalizeHatTrie) return out } func (h *HatTrie) Delete(key string) { h.l.Lock() defer h.l.Unlock() ckey := C.CString(key) defer C.free(unsafe.Pointer(ckey)) C.delete(h.trie, ckey, C.size_t(len(key))) } func (h *HatTrie) Set(key string) { h.l.Lock() defer h.l.Unlock() ckey := C.CString(key) defer C.free(unsafe.Pointer(ckey)) C.set(h.trie, ckey, C.size_t(len(key))) } func (h *HatTrie) Get(key string) bool { h.l.RLock() defer h.l.RUnlock() ckey := C.CString(key) defer C.free(unsafe.Pointer(ckey)) val := C.get(h.trie, ckey, C.size_t(len(key))) return val == 1 } type HatTrieIterator struct { iterator *C.hattrie_iter_t } func finalizeHatTrieIterator(i *HatTrieIterator) { C.hattrie_iter_free(i.iterator) } func (h *HatTrie) Iterator() *HatTrieIterator { out := C.hattrie_iter_begin(h.trie, true) hi := &HatTrieIterator{ iterator: out, } runtime.SetFinalizer(hi, finalizeHatTrieIterator) return hi } func (i *HatTrieIterator) Next() string { if C.hattrie_iter_finished(i.iterator) { return "" } keylen := C.size_t(0) ckey := C.hattrie_iter_key_string(i.iterator, &keylen) defer C.free(unsafe.Pointer(ckey)) key := C.GoStringN(ckey, C.int(keylen)) C.hattrie_iter_next(i.iterator) return key }
rjohnsondev/go-safe-browsing-api
hattrie.go
GO
bsd-2-clause
2,393
/* * Copyright (c) 2015, Tomasz Kapuściński * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package pl.tomaszkax86.math; /** * Class for storage, calculations, and conversion between numberic formats * and fixed-point Q16.16 format. * * @author Tomasz Kapuściński */ public final class Fixed extends Number { // binary representation of this fixed value private final int fixed; /** * Creates new fixed-point value with binary representation. * @param fixed binary representation of half-float * @param dummy unused argument */ private Fixed(int fixed, boolean dummy) { this.fixed = fixed; } /** * Creates new fixed-point value from {@code short} * @param value {@code short} value */ public Fixed(short value) { this.fixed = toFixed(value); } /** * Creates new fixed-point value from {@code int} * @param value {@code int} value */ public Fixed(int value) { this.fixed = toFixed(value); } /** * Creates new fixed-point value from {@code float} * @param value {@code float} value */ public Fixed(float value) { this.fixed = toFixed(value); } /** * Creates new fixed-point value from {@code double} * @param value {@code double} value */ public Fixed(double value) { this.fixed = toFixed(value); } @Override public int intValue() { return toInt(fixed); } @Override public long longValue() { return toLong(fixed); } @Override public float floatValue() { return toFloat(fixed); } @Override public double doubleValue() { return toDouble(fixed); } @Override public String toString() { return Float.toString(toFloat(fixed)); } /** * Converts {@code short} value to fixed-point representation. * @param value {@code short} value * @return fixed-point representation as {@code int} */ public static int toFixed(short value) { return (value << BIT_SHIFT); } /** * Converts {@code int} value to fixed-point representation. * @param value {@code int} value * @return fixed-point representation as {@code int} */ public static int toFixed(int value) { return (value << BIT_SHIFT); } /** * Converts {@code long} value to fixed-point representation. * @param value {@code long} value * @return fixed-point representation as {@code int} */ public static int toFixed(long value) { return (int)(value << BIT_SHIFT); } /** * Converts {@code float} value to fixed-point representation. * @param value {@code float} value * @return fixed-point representation as {@code int} */ public static int toFixed(float value) { return (int) Math.scalb(value, BIT_SHIFT); } /** * Converts {@code double} value to fixed-point representation. * @param value {@code double} value * @return fixed-point representation as {@code int} */ public static int toFixed(double value) { return (int) Math.scalb(value, BIT_SHIFT); } /** * Converts fixed-point representation to {@code short} value. * @param fixed fixed-point value * @return {@code short} value */ public static short toShort(int fixed) { return (short)(fixed >> BIT_SHIFT); } /** * Converts fixed-point representation to {@code int} value. * @param fixed fixed-point value * @return {@code int} value */ public static int toInt(int fixed) { return (fixed >> BIT_SHIFT); } /** * Converts fixed-point representation to {@code long} value. * @param fixed fixed-point value * @return {@code long} value */ public static long toLong(int fixed) { return (fixed >> BIT_SHIFT); } /** * Converts fixed-point representation to {@code float} value. * @param fixed fixed-point value * @return {@code float} value */ public static float toFloat(int fixed) { return Math.scalb((float) fixed, -BIT_SHIFT); } /** * Converts fixed-point representation to {@code double} value. * @param fixed fixed-point value * @return {@code double} value */ public static double toDouble(int fixed) { return Math.scalb((double) fixed, -BIT_SHIFT); } /** * Returns {@code Fixed} object from fixed-point representation. * @param fixed fixed-point representation * @return {@code Fixed} object */ public static Fixed asFixed(int fixed) { return new Fixed(fixed, false); } /** * Adds two fixed-point values. * @param x first value * @param y second value * @return sum of two values */ public static int add(int x, int y) { return x + y; } /** * Subtracts two fixed-point values. * @param x first value * @param y second value * @return difference between two values */ public static int subtract(int x, int y) { return x - y; } /** * Multiplies two fixed-point values. * @param x first value * @param y second value * @return product of two values */ public static int multiply(int x, int y) { return (int) (((long)x * (long)y) >> BIT_SHIFT); } /** * Divides two fixed-point values. * @param x first value * @param y second value * @return quotient of two values */ public static int divide(int x, int y) { return (int) (((long)x << BIT_SHIFT) / (long)y); } /** * Computes square root of fixed-point value. * @param fixed fixed-point value * @return square root as fixed-point value */ public static int sqrt(int fixed) { long fix = (long)fixed << BIT_SHIFT; long result = fixed >> 1; for(int i=0; i<5; i++) { result = (result + fix / result) >> 1; } return (int) result; } /** * The number of bytes used to represent fixed-point value. */ public static final int BYTES = 4; /** * The number of bits used to represent fixed-point value. */ public static final int SIZE = 32; /** * A constant holding the value of 0 in fixed-point format. */ public static final int ZERO = 0b00000000_00000000_00000000_00000001; /** * A constant holding the value of 1 in fixed-point format. */ public static final int ONE = 0b00000000_00000001_00000000_00000000; /** * A constant holding the largest positive fixed-point value. */ public static final int MAX_VALUE = (int) 0b01111111_111111111_11111111_11111111; /** * A constant holding the smallest positive nonzero fixed-point value. */ public static final int MIN_VALUE = 0b00000000_00000000_00000000_00000001; // constant bit shift for Q16.16 format private static final int BIT_SHIFT = 16; }
tomaszkax86/My-Java-Utils
src/pl/tomaszkax86/math/Fixed.java
Java
bsd-2-clause
8,469
#ifndef xt_case_dumpster_h #define xt_case_dumpster_h #include "xt/case/array.h" #include "xt/case/list.h" #include "xt/case/set.h" #include "xt/core/iobject.h" struct xt_case_dumpster_t; typedef struct xt_case_dumpster_t xt_case_dumpster_t; xt_core_bool_t xt_case_dumpster_add(xt_case_dumpster_t *dumpster, void *object); xt_case_dumpster_t *xt_case_dumpster_create(xt_core_iobject_t *iobject); void xt_case_dumpster_destroy(xt_case_dumpster_t *dumpster); xt_core_bool_t xt_case_dumpster_take_objects_from_list (xt_case_dumpster_t *dumpster, xt_case_list_t *list); #endif
xtools/xt
case/dumpster.h
C
bsd-2-clause
584
// // http_core_header_map.h // vClientTemplateLib // // Created by Virendra Shakya on 5/17/14. // Copyright (c) 2014 Virendra Shakya. All rights reserved. // #ifndef __vClientTemplateLib__http_core_header_group__ #define __vClientTemplateLib__http_core_header_group__ #include <string> #include "base/thread/thread_un_safe.h" #include "memory/ref/rc_thread_safe.h" #include "base/collect/map_thread_safe.h" namespace vctl { namespace net { namespace http { class THeader; //must be thread safe class CHttpHeadersMap : public vctl::CReferenceThreadSafe<CHttpHeadersMap> { public: static CHttpHeadersMap* New(); void Add(const THeader& aHeader); int Size() const; bool GetHeader(int aIndex, THeader& aHeaderReturn); protected: void Construct(); CHttpHeadersMap(); virtual ~CHttpHeadersMap(); friend class vctl::CReferenceThreadSafe<CHttpHeadersMap>; private: vbase::CMapThreadSafe<int, THeader> iMap; int iHeaderId; }; } //namespace http } //namespace net } //namespace vctl #endif /* defined(__vClientTemplateLib__http_core_header_group__) */
drvirens/hexagonal-client
vCTL/src/net/http/core/http_core_header_map.h
C
bsd-2-clause
1,135
#include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef FORTIFY #include "fortify/fortify.h" #endif #include "base/result.h" #include "datastruct/bitfifo.h" #include "test/all-tests.h" #define MAXSIZE 32 static const struct { int length; /* in bits */ unsigned int after_dequeue; } expected[] = { { 1, 0x00000001 }, { 2, 0x00000003 }, { 3, 0x00000007 }, { 4, 0x0000000F }, { 31, 0x7FFFFFFF }, { 32, 0xFFFFFFFF }, }; #define NELEMS(a) (int)(sizeof(a) / sizeof((a)[0])) /* shows changes from previous stats */ static void dump(const bitfifo_t *fifo) { static size_t previous_used = (size_t) -1; /* aka SIZE_MAX */ static int previous_full = INT_MAX; static int previous_empty = INT_MAX; size_t used; int full; int empty; used = bitfifo_used(fifo); full = bitfifo_full(fifo); empty = bitfifo_empty(fifo); printf("{"); if (used != previous_used) printf("used=%zu ", used); if (full != previous_full) printf("full=%d ", full); if (empty != previous_empty) printf("empty=%d ", empty); printf("}\n"); previous_used = used; previous_full = full; previous_empty = empty; } result_t bitfifo_test(const char *resources) { const unsigned int all_ones = ~0; result_t err; bitfifo_t *fifo; int i; unsigned int outbits; fifo = bitfifo_create(MAXSIZE); if (fifo == NULL) return result_OOM; dump(fifo); printf("test: enqueue/dequeue...\n"); for (i = 0; i < NELEMS(expected); i++) { int length; length = expected[i].length; printf("%d bits\n", length); /* put 'size_to_try' 1 bits into the queue */ err = bitfifo_enqueue(fifo, &all_ones, 0, length); if (err) goto Failure; dump(fifo); /* pull the bits back out */ outbits = 0; err = bitfifo_dequeue(fifo, &outbits, length); if (err) goto Failure; dump(fifo); if (outbits != expected[i].after_dequeue) printf("*** difference: %.8x <> %.8x\n", outbits, expected[i].after_dequeue); } printf("...done\n"); printf("test: completely fill up the fifo\n"); err = bitfifo_enqueue(fifo, &all_ones, 0, MAXSIZE); if (err) goto Failure; dump(fifo); printf("test: enqueue another bit (should error)\n"); err = bitfifo_enqueue(fifo, &all_ones, 0, 1); if (err != result_BITFIFO_FULL) goto Failure; dump(fifo); printf("test: do 32 dequeue-enqueue ops...\n"); for (i = 0; i < MAXSIZE; i++) { printf("dequeue a single bit\n"); err = bitfifo_dequeue(fifo, &outbits, 1); if (err) goto Failure; dump(fifo); printf("enqueue a single bit\n"); err = bitfifo_enqueue(fifo, &all_ones, 0, 1); if (err) goto Failure; dump(fifo); } printf("...done\n"); bitfifo_destroy(fifo); return result_TEST_PASSED; Failure: return result_TEST_FAILED; }
dpt/DPTLib
libraries/datastruct/bitfifo/test/bitfifo-test.c
C
bsd-2-clause
2,924
package com.jayantkrish.jklol.util; import java.util.Iterator; import java.util.List; import com.google.common.base.Preconditions; import com.jayantkrish.jklol.models.DiscreteVariable; import com.jayantkrish.jklol.models.VariableNumMap; /** * An iterator over all possible assignments to a set of variables. */ public class AllAssignmentIterator implements Iterator<Assignment> { private VariableNumMap vars; private Iterator<int[]> valueIterator; /** * Create an iterator over the assignments of the variables in varNumMap. varNumMap must contain * only {@link DiscreteVariable}s, otherwise an exception is thrown. * @param varNumMap */ public AllAssignmentIterator(VariableNumMap varNumMap) { Preconditions.checkArgument(varNumMap.getDiscreteVariables().size() == varNumMap.size()); this.vars = varNumMap; valueIterator = initializeValueIterator(varNumMap); } /* * Initializes the variable values controlling the iteration position. */ private static Iterator<int[]> initializeValueIterator(VariableNumMap vars) { int[] dimensionSizes = new int[vars.size()]; List<DiscreteVariable> discreteVars = vars.getDiscreteVariables(); for (int i = 0; i < discreteVars.size(); i++) { dimensionSizes[i] = discreteVars.get(i).numValues(); } return new IntegerArrayIterator(dimensionSizes, new int[0]); } public boolean hasNext() { return valueIterator.hasNext(); } public Assignment next() { int[] currentValue = valueIterator.next(); return vars.intArrayToAssignment(currentValue); } public void remove() { throw new UnsupportedOperationException(); } }
jayantk/jklol
src/com/jayantkrish/jklol/util/AllAssignmentIterator.java
Java
bsd-2-clause
1,616
#include "contractor/graph_contractor.hpp" #include "contractor/contractor_graph.hpp" #include "contractor/contractor_search.hpp" #include "contractor/query_edge.hpp" #include "util/deallocating_vector.hpp" #include "util/integer_range.hpp" #include "util/log.hpp" #include "util/percent.hpp" #include "util/timing_util.hpp" #include "util/typedefs.hpp" #include "util/xor_fast_hash.hpp" #include <boost/assert.hpp> #include <tbb/blocked_range.h> #include <tbb/enumerable_thread_specific.h> #include <tbb/parallel_for.h> #include <tbb/parallel_invoke.h> #include <tbb/parallel_sort.h> #include <algorithm> #include <limits> #include <memory> #include <vector> namespace osrm { namespace contractor { namespace { struct ContractorThreadData { ContractorHeap heap; std::vector<ContractorEdge> inserted_edges; std::vector<NodeID> neighbours; explicit ContractorThreadData(NodeID nodes) : heap(nodes) {} }; struct ContractorNodeData { using NodeDepth = int; using NodePriority = float; using NodeLevel = float; ContractorNodeData(std::size_t number_of_nodes, std::vector<bool> uncontracted_nodes_, std::vector<bool> contractable_, std::vector<EdgeWeight> weights_) : is_core(std::move(uncontracted_nodes_)), contractable(std::move(contractable_)), priorities(number_of_nodes), weights(std::move(weights_)), depths(number_of_nodes, 0) { if (contractable.empty()) { contractable.resize(number_of_nodes, true); } if (is_core.empty()) { is_core.resize(number_of_nodes, true); } } void Renumber(const std::vector<NodeID> &old_to_new) { tbb::parallel_invoke( [&] { util::inplacePermutation(priorities.begin(), priorities.end(), old_to_new); }, [&] { util::inplacePermutation(weights.begin(), weights.end(), old_to_new); }, [&] { util::inplacePermutation(is_core.begin(), is_core.end(), old_to_new); }, [&] { util::inplacePermutation(contractable.begin(), contractable.end(), old_to_new); }, [&] { util::inplacePermutation(depths.begin(), depths.end(), old_to_new); }); } std::vector<bool> is_core; std::vector<bool> contractable; std::vector<NodePriority> priorities; std::vector<EdgeWeight> weights; std::vector<NodeDepth> depths; }; struct ContractionStats { int edges_deleted_count; int edges_added_count; int original_edges_deleted_count; int original_edges_added_count; ContractionStats() : edges_deleted_count(0), edges_added_count(0), original_edges_deleted_count(0), original_edges_added_count(0) { } }; struct RemainingNodeData { RemainingNodeData() = default; RemainingNodeData(NodeID id, bool is_independent) : id(id), is_independent(is_independent) {} NodeID id : 31; bool is_independent : 1; }; struct ThreadDataContainer { explicit ThreadDataContainer(int number_of_nodes) : number_of_nodes(number_of_nodes) {} inline ContractorThreadData *GetThreadData() { bool exists = false; auto &ref = data.local(exists); if (!exists) { ref = std::make_shared<ContractorThreadData>(number_of_nodes); } return ref.get(); } int number_of_nodes; using EnumerableThreadData = tbb::enumerable_thread_specific<std::shared_ptr<ContractorThreadData>>; EnumerableThreadData data; }; // This bias function takes up 22 assembly instructions in total on X86 inline bool Bias(const util::XORFastHash<> &fast_hash, const NodeID a, const NodeID b) { const unsigned short hasha = fast_hash(a); const unsigned short hashb = fast_hash(b); // The compiler optimizes that to conditional register flags but without branching // statements! if (hasha != hashb) { return hasha < hashb; } return a < b; } template <bool RUNSIMULATION, typename ContractorGraph> void ContractNode(ContractorThreadData *data, const ContractorGraph &graph, const NodeID node, std::vector<EdgeWeight> &node_weights, ContractionStats *stats = nullptr) { auto &heap = data->heap; std::size_t inserted_edges_size = data->inserted_edges.size(); std::vector<ContractorEdge> &inserted_edges = data->inserted_edges; constexpr bool SHORTCUT_ARC = true; constexpr bool FORWARD_DIRECTION_ENABLED = true; constexpr bool FORWARD_DIRECTION_DISABLED = false; constexpr bool REVERSE_DIRECTION_ENABLED = true; constexpr bool REVERSE_DIRECTION_DISABLED = false; for (auto in_edge : graph.GetAdjacentEdgeRange(node)) { const ContractorEdgeData &in_data = graph.GetEdgeData(in_edge); const NodeID source = graph.GetTarget(in_edge); if (source == node) continue; if (RUNSIMULATION) { BOOST_ASSERT(stats != nullptr); ++stats->edges_deleted_count; stats->original_edges_deleted_count += in_data.originalEdges; } if (!in_data.backward) { continue; } heap.Clear(); heap.Insert(source, 0, ContractorHeapData{}); EdgeWeight max_weight = 0; unsigned number_of_targets = 0; for (auto out_edge : graph.GetAdjacentEdgeRange(node)) { const ContractorEdgeData &out_data = graph.GetEdgeData(out_edge); if (!out_data.forward) { continue; } const NodeID target = graph.GetTarget(out_edge); if (node == target) { continue; } const EdgeWeight path_weight = in_data.weight + out_data.weight; if (target == source) { if (path_weight < node_weights[node]) { if (RUNSIMULATION) { // make sure to prune better, but keep inserting this loop if it should // still be the best // CAREFUL: This only works due to the independent node-setting. This // guarantees that source is not connected to another node that is // contracted node_weights[source] = path_weight + 1; BOOST_ASSERT(stats != nullptr); stats->edges_added_count += 2; stats->original_edges_added_count += 2 * (out_data.originalEdges + in_data.originalEdges); } else { // CAREFUL: This only works due to the independent node-setting. This // guarantees that source is not connected to another node that is // contracted node_weights[source] = path_weight; // make sure to prune better inserted_edges.emplace_back(source, target, path_weight, in_data.duration + out_data.duration, in_data.distance + out_data.distance, out_data.originalEdges + in_data.originalEdges, node, SHORTCUT_ARC, FORWARD_DIRECTION_ENABLED, REVERSE_DIRECTION_DISABLED); inserted_edges.emplace_back(target, source, path_weight, in_data.duration + out_data.duration, in_data.distance + out_data.distance, out_data.originalEdges + in_data.originalEdges, node, SHORTCUT_ARC, FORWARD_DIRECTION_DISABLED, REVERSE_DIRECTION_ENABLED); } } continue; } max_weight = std::max(max_weight, path_weight); if (!heap.WasInserted(target)) { heap.Insert(target, INVALID_EDGE_WEIGHT, ContractorHeapData{0, true}); ++number_of_targets; } } if (RUNSIMULATION) { const int constexpr SIMULATION_SEARCH_SPACE_SIZE = 1000; search(heap, graph, number_of_targets, SIMULATION_SEARCH_SPACE_SIZE, max_weight, node); } else { const int constexpr FULL_SEARCH_SPACE_SIZE = 2000; search(heap, graph, number_of_targets, FULL_SEARCH_SPACE_SIZE, max_weight, node); } for (auto out_edge : graph.GetAdjacentEdgeRange(node)) { const ContractorEdgeData &out_data = graph.GetEdgeData(out_edge); if (!out_data.forward) { continue; } const NodeID target = graph.GetTarget(out_edge); if (target == node) continue; const EdgeWeight path_weight = in_data.weight + out_data.weight; const EdgeWeight weight = heap.GetKey(target); if (path_weight < weight) { if (RUNSIMULATION) { BOOST_ASSERT(stats != nullptr); stats->edges_added_count += 2; stats->original_edges_added_count += 2 * (out_data.originalEdges + in_data.originalEdges); } else { inserted_edges.emplace_back(source, target, path_weight, in_data.duration + out_data.duration, in_data.distance + out_data.distance, out_data.originalEdges + in_data.originalEdges, node, SHORTCUT_ARC, FORWARD_DIRECTION_ENABLED, REVERSE_DIRECTION_DISABLED); inserted_edges.emplace_back(target, source, path_weight, in_data.duration + out_data.duration, in_data.distance + out_data.distance, out_data.originalEdges + in_data.originalEdges, node, SHORTCUT_ARC, FORWARD_DIRECTION_DISABLED, REVERSE_DIRECTION_ENABLED); } } } } // Check For One-Way Streets to decide on the creation of self-loops if (!RUNSIMULATION) { std::size_t iend = inserted_edges.size(); for (std::size_t i = inserted_edges_size; i < iend; ++i) { bool found = false; for (std::size_t other = i + 1; other < iend; ++other) { if (inserted_edges[other].source != inserted_edges[i].source) { continue; } if (inserted_edges[other].target != inserted_edges[i].target) { continue; } if (inserted_edges[other].data.weight != inserted_edges[i].data.weight) { continue; } if (inserted_edges[other].data.shortcut != inserted_edges[i].data.shortcut) { continue; } inserted_edges[other].data.forward |= inserted_edges[i].data.forward; inserted_edges[other].data.backward |= inserted_edges[i].data.backward; found = true; break; } if (!found) { inserted_edges[inserted_edges_size++] = inserted_edges[i]; } } inserted_edges.resize(inserted_edges_size); } } void ContractNode(ContractorThreadData *data, const ContractorGraph &graph, const NodeID node, std::vector<EdgeWeight> &node_weights) { ContractNode<false>(data, graph, node, node_weights, nullptr); } ContractionStats SimulateNodeContraction(ContractorThreadData *data, const ContractorGraph &graph, const NodeID node, std::vector<EdgeWeight> &node_weights) { ContractionStats stats; ContractNode<true>(data, graph, node, node_weights, &stats); return stats; } void RenumberGraph(ContractorGraph &graph, const std::vector<NodeID> &old_to_new) { graph.Renumber(old_to_new); // Renumber all shortcut node IDs for (const auto node : util::irange<NodeID>(0, graph.GetNumberOfNodes())) { for (const auto edge : graph.GetAdjacentEdgeRange(node)) { auto &data = graph.GetEdgeData(edge); if (data.shortcut) { data.id = old_to_new[data.id]; } } } } /* Reorder nodes for better locality during contraction */ void RenumberData(std::vector<RemainingNodeData> &remaining_nodes, std::vector<NodeID> &new_to_old_node_id, ContractorNodeData &node_data, ContractorGraph &graph) { std::vector<NodeID> current_to_new_node_id(graph.GetNumberOfNodes(), SPECIAL_NODEID); // we need to make a copy here because we are going to modify it auto to_orig = new_to_old_node_id; auto new_node_id = 0u; // All remaining nodes get the low IDs for (auto &remaining : remaining_nodes) { auto id = new_node_id++; current_to_new_node_id[remaining.id] = id; new_to_old_node_id[id] = to_orig[remaining.id]; remaining.id = id; } // Already contracted nodes get the high IDs for (const auto current_id : util::irange<std::size_t>(0, graph.GetNumberOfNodes())) { if (current_to_new_node_id[current_id] == SPECIAL_NODEID) { auto id = new_node_id++; current_to_new_node_id[current_id] = id; new_to_old_node_id[id] = to_orig[current_id]; } } BOOST_ASSERT(new_node_id == graph.GetNumberOfNodes()); node_data.Renumber(current_to_new_node_id); RenumberGraph(graph, current_to_new_node_id); } float EvaluateNodePriority(const ContractionStats &stats, const ContractorNodeData::NodeDepth node_depth) { // Result will contain the priority float result; if (0 == (stats.edges_deleted_count * stats.original_edges_deleted_count)) { result = 1.f * node_depth; } else { result = 2.f * (((float)stats.edges_added_count) / stats.edges_deleted_count) + 4.f * (((float)stats.original_edges_added_count) / stats.original_edges_deleted_count) + 1.f * node_depth; } BOOST_ASSERT(result >= 0); return result; } void DeleteIncomingEdges(ContractorThreadData *data, ContractorGraph &graph, const NodeID node) { std::vector<NodeID> &neighbours = data->neighbours; neighbours.clear(); // find all neighbours for (auto e : graph.GetAdjacentEdgeRange(node)) { const NodeID u = graph.GetTarget(e); if (u != node) { neighbours.push_back(u); } } // eliminate duplicate entries ( forward + backward edges ) std::sort(neighbours.begin(), neighbours.end()); neighbours.resize(std::unique(neighbours.begin(), neighbours.end()) - neighbours.begin()); for (const auto i : util::irange<std::size_t>(0, neighbours.size())) { graph.DeleteEdgesTo(neighbours[i], node); } } bool UpdateNodeNeighbours(ContractorNodeData &node_data, ContractorThreadData *data, const ContractorGraph &graph, const NodeID node) { std::vector<NodeID> &neighbours = data->neighbours; neighbours.clear(); // find all neighbours for (auto e : graph.GetAdjacentEdgeRange(node)) { const NodeID u = graph.GetTarget(e); if (u == node) { continue; } neighbours.push_back(u); node_data.depths[u] = std::max(node_data.depths[node] + 1, node_data.depths[u]); } // eliminate duplicate entries ( forward + backward edges ) std::sort(neighbours.begin(), neighbours.end()); neighbours.resize(std::unique(neighbours.begin(), neighbours.end()) - neighbours.begin()); // re-evaluate priorities of neighboring nodes for (const NodeID u : neighbours) { if (node_data.contractable[u]) { node_data.priorities[u] = EvaluateNodePriority( SimulateNodeContraction(data, graph, u, node_data.weights), node_data.depths[u]); } } return true; } bool IsNodeIndependent(const util::XORFastHash<> &hash, const std::vector<float> &priorities, const std::vector<NodeID> &new_to_old_node_id, const ContractorGraph &graph, ContractorThreadData *const data, const NodeID node) { const float priority = priorities[node]; std::vector<NodeID> &neighbours = data->neighbours; neighbours.clear(); for (auto e : graph.GetAdjacentEdgeRange(node)) { const NodeID target = graph.GetTarget(e); if (node == target) { continue; } const float target_priority = priorities[target]; BOOST_ASSERT(target_priority >= 0); // found a neighbour with lower priority? if (priority > target_priority) { return false; } // tie breaking if (std::abs(priority - target_priority) < std::numeric_limits<float>::epsilon() && Bias(hash, new_to_old_node_id[node], new_to_old_node_id[target])) { return false; } neighbours.push_back(target); } std::sort(neighbours.begin(), neighbours.end()); neighbours.resize(std::unique(neighbours.begin(), neighbours.end()) - neighbours.begin()); // examine all neighbours that are at most 2 hops away for (const NodeID u : neighbours) { for (auto e : graph.GetAdjacentEdgeRange(u)) { const NodeID target = graph.GetTarget(e); if (node == target) { continue; } const float target_priority = priorities[target]; BOOST_ASSERT(target_priority >= 0); // found a neighbour with lower priority? if (priority > target_priority) { return false; } // tie breaking if (std::abs(priority - target_priority) < std::numeric_limits<float>::epsilon() && Bias(hash, new_to_old_node_id[node], new_to_old_node_id[target])) { return false; } } } return true; } } // namespace std::vector<bool> contractGraph(ContractorGraph &graph, std::vector<bool> node_is_uncontracted_, std::vector<bool> node_is_contractable_, std::vector<EdgeWeight> node_weights_, double core_factor) { BOOST_ASSERT(node_weights_.size() == graph.GetNumberOfNodes()); util::XORFastHash<> fast_hash; // for the preperation we can use a big grain size, which is much faster (probably cache) const constexpr size_t PQGrainSize = 100000; // auto_partitioner will automatically increase the blocksize if we have // a lot of data. It is *important* for the last loop iterations // (which have a very small dataset) that it is devisible. const constexpr size_t IndependentGrainSize = 1; const constexpr size_t ContractGrainSize = 1; const constexpr size_t NeighboursGrainSize = 1; const constexpr size_t DeleteGrainSize = 1; const NodeID number_of_nodes = graph.GetNumberOfNodes(); ThreadDataContainer thread_data_list(number_of_nodes); NodeID number_of_contracted_nodes = 0; std::vector<NodeID> new_to_old_node_id(number_of_nodes); // Fill the map with an identiy mapping std::iota(new_to_old_node_id.begin(), new_to_old_node_id.end(), 0); ContractorNodeData node_data{graph.GetNumberOfNodes(), std::move(node_is_uncontracted_), std::move(node_is_contractable_), std::move(node_weights_)}; std::vector<RemainingNodeData> remaining_nodes; remaining_nodes.reserve(number_of_nodes); for (auto node : util::irange<NodeID>(0, number_of_nodes)) { if (node_data.is_core[node]) { if (node_data.contractable[node]) { remaining_nodes.emplace_back(node, false); } else { node_data.priorities[node] = std::numeric_limits<ContractorNodeData::NodePriority>::max(); } } else { node_data.priorities[node] = 0; } } { util::UnbufferedLog log; log << "initializing node priorities..."; tbb::parallel_for(tbb::blocked_range<std::size_t>(0, remaining_nodes.size(), PQGrainSize), [&](const auto &range) { ContractorThreadData *data = thread_data_list.GetThreadData(); for (auto x = range.begin(), end = range.end(); x != end; ++x) { auto node = remaining_nodes[x].id; BOOST_ASSERT(node_data.contractable[node]); node_data.priorities[node] = EvaluateNodePriority( SimulateNodeContraction(data, graph, node, node_data.weights), node_data.depths[node]); } }); log << " ok."; } auto number_of_core_nodes = std::max<std::size_t>(0, (1 - core_factor) * number_of_nodes); auto number_of_nodes_to_contract = remaining_nodes.size() - number_of_core_nodes; util::Log() << "preprocessing " << number_of_nodes_to_contract << " (" << (number_of_nodes_to_contract / (float)number_of_nodes * 100.) << "%) nodes..."; util::UnbufferedLog log; util::Percent p(log, remaining_nodes.size()); const util::XORFastHash<> hash; unsigned current_level = 0; std::size_t next_renumbering = number_of_nodes * 0.35; while (remaining_nodes.size() > number_of_core_nodes) { if (remaining_nodes.size() < next_renumbering) { RenumberData(remaining_nodes, new_to_old_node_id, node_data, graph); log << "[renumbered]"; // only one renumbering for now next_renumbering = 0; } tbb::parallel_for( tbb::blocked_range<NodeID>(0, remaining_nodes.size(), IndependentGrainSize), [&](const auto &range) { ContractorThreadData *data = thread_data_list.GetThreadData(); // determine independent node set for (auto i = range.begin(), end = range.end(); i != end; ++i) { const NodeID node = remaining_nodes[i].id; remaining_nodes[i].is_independent = IsNodeIndependent( hash, node_data.priorities, new_to_old_node_id, graph, data, node); } }); // sort all remaining nodes to the beginning of the sequence const auto begin_independent_nodes = stable_partition(remaining_nodes.begin(), remaining_nodes.end(), [](RemainingNodeData node_data) { return !node_data.is_independent; }); auto begin_independent_nodes_idx = std::distance(remaining_nodes.begin(), begin_independent_nodes); auto end_independent_nodes_idx = remaining_nodes.size(); // contract independent nodes tbb::parallel_for( tbb::blocked_range<NodeID>( begin_independent_nodes_idx, end_independent_nodes_idx, ContractGrainSize), [&](const auto &range) { ContractorThreadData *data = thread_data_list.GetThreadData(); for (auto position = range.begin(), end = range.end(); position != end; ++position) { const NodeID node = remaining_nodes[position].id; ContractNode(data, graph, node, node_data.weights); } }); // core flags need to be set in serial since vector<bool> is not thread safe for (auto position : util::irange<std::size_t>(begin_independent_nodes_idx, end_independent_nodes_idx)) { node_data.is_core[remaining_nodes[position].id] = false; } tbb::parallel_for( tbb::blocked_range<NodeID>( begin_independent_nodes_idx, end_independent_nodes_idx, DeleteGrainSize), [&](const auto &range) { ContractorThreadData *data = thread_data_list.GetThreadData(); for (auto position = range.begin(), end = range.end(); position != end; ++position) { const NodeID node = remaining_nodes[position].id; DeleteIncomingEdges(data, graph, node); } }); // make sure we really sort each block tbb::parallel_for(thread_data_list.data.range(), [&](const auto &range) { for (auto &data : range) tbb::parallel_sort(data->inserted_edges.begin(), data->inserted_edges.end()); }); // insert new edges for (auto &data : thread_data_list.data) { for (const ContractorEdge &edge : data->inserted_edges) { const EdgeID current_edge_ID = graph.FindEdge(edge.source, edge.target); if (current_edge_ID != SPECIAL_EDGEID) { auto &current_data = graph.GetEdgeData(current_edge_ID); if (current_data.shortcut && edge.data.forward == current_data.forward && edge.data.backward == current_data.backward) { // found a duplicate edge with smaller weight, update it. if (edge.data.weight < current_data.weight) { current_data = edge.data; } // don't insert duplicates continue; } } graph.InsertEdge(edge.source, edge.target, edge.data); } data->inserted_edges.clear(); } tbb::parallel_for( tbb::blocked_range<NodeID>( begin_independent_nodes_idx, end_independent_nodes_idx, NeighboursGrainSize), [&](const auto &range) { ContractorThreadData *data = thread_data_list.GetThreadData(); for (auto position = range.begin(), end = range.end(); position != end; ++position) { NodeID node = remaining_nodes[position].id; UpdateNodeNeighbours(node_data, data, graph, node); } }); // remove contracted nodes from the pool BOOST_ASSERT(end_independent_nodes_idx - begin_independent_nodes_idx > 0); number_of_contracted_nodes += end_independent_nodes_idx - begin_independent_nodes_idx; remaining_nodes.resize(begin_independent_nodes_idx); p.PrintStatus(number_of_contracted_nodes); ++current_level; } node_data.Renumber(new_to_old_node_id); RenumberGraph(graph, new_to_old_node_id); return std::move(node_data.is_core); } } // namespace contractor } // namespace osrm
yuryleb/osrm-backend
src/contractor/graph_contractor.cpp
C++
bsd-2-clause
29,457
module Interface.LpSolve where -- standard modules -- local modules import Helpful.Process --import Data.Time.Clock (diffUTCTime, getCurrentTime) --import Debug.Trace zeroObjective :: String -> Maybe Bool zeroObjective p = case head answer of "This problem is infeasible" -> Nothing "This problem is unbounded" -> Just False otherwise -> do let (chattering, value) = splitAt 29 (answer!!1) if chattering == "Value of objective function: " then if (read value :: Float) == 0.0 then Just True else Just False else error $ "lp_solve answered in an unexpected way.\n" ++ "Expected Answer: \"Value of objective function: " ++ "NUMBER\"\nActual Answer: " ++ lpAnswer where lpAnswer = unsafeReadProcess "lp_solve" [] p answer = lines lpAnswer -- old version --zeroObjective :: String -> Maybe Bool --zeroObjective p = unsafePerformIO $ do ---- start <- getCurrentTime -- (_, clpAnswer, _) <- readProcessWithExitCode "lp_solve" [] p -- let answer = lines clpAnswer ---- end <- getCurrentTime ---- print $ (show (end `diffUTCTime` start) ++ " elapsed. ") ++ clpAnswer -- case head answer of -- "This problem is infeasible" -> return Nothing -- "This problem is unbounded" -> return $ Just False -- otherwise -> do -- let (chattering, value) = splitAt 29 (answer!!1) -- if chattering == "Value of objective function: " then -- if (read value :: Float) == 0.0 then -- return $ Just True -- else -- return $ Just False -- else -- error $ "lp_solve answered in an unexpected way.\n" ++ -- "Expected Answer: \"Value of objective function: " ++ -- "NUMBER\"\nActual Answer: " ++ clpAnswer --{-# NOINLINE zeroObjective #-}
spatial-reasoning/zeno
src/Interface/LpSolve.hs
Haskell
bsd-2-clause
1,952
from django.test import override_settings from incuna_test_utils.testcases.api_request import ( BaseAPIExampleTestCase, BaseAPIRequestTestCase, ) from tests.factories import UserFactory class APIRequestTestCase(BaseAPIRequestTestCase): user_factory = UserFactory def test_create_request_format(self): request = self.create_request() assert request.META['format'] == 'json' def test_create_request_auth(self): request = self.create_request() assert request.user.is_authenticated def test_create_request_no_auth(self): request = self.create_request(auth=False) assert not request.user.is_authenticated class APIExampleTestCase(BaseAPIExampleTestCase): @override_settings(ALLOWED_HOSTS=['localhost']) def test_create_request(self): request = self.create_request(auth=False) assert request.get_host() == self.SERVER_NAME
incuna/incuna-test-utils
tests/testcases/test_api_request.py
Python
bsd-2-clause
918
from django.forms import ModelForm from bug_reporting.models import Feedback from CoralNet.forms import FormHelper class FeedbackForm(ModelForm): class Meta: model = Feedback fields = ('type', 'comment') # Other fields are auto-set #error_css_class = ... #required_css_class = ... def clean(self): """ 1. Strip spaces from character fields. 2. Call the parent's clean() to finish up with the default behavior. """ data = FormHelper.stripSpacesFromFields( self.cleaned_data, self.fields) self.cleaned_data = data return super(FeedbackForm, self).clean()
DevangS/CoralNet
bug_reporting/forms.py
Python
bsd-2-clause
661
import logging import re from streamlink.plugin import Plugin, pluginmatcher from streamlink.plugin.api import validate from streamlink.stream import HLSStream from streamlink.utils.parse import parse_json log = logging.getLogger(__name__) @pluginmatcher(re.compile( r"https?://(?:www\.)?livestream\.com/" )) class Livestream(Plugin): _config_re = re.compile(r"window.config = ({.+})") _stream_config_schema = validate.Schema(validate.any({ "event": { "stream_info": validate.any({ "is_live": bool, "secure_m3u8_url": validate.url(scheme="https"), }, None), } }, {}), validate.get("event", {}), validate.get("stream_info", {})) def _get_streams(self): res = self.session.http.get(self.url) m = self._config_re.search(res.text) if not m: log.debug("Unable to find _config_re") return stream_info = parse_json(m.group(1), "config JSON", schema=self._stream_config_schema) log.trace("stream_info: {0!r}".format(stream_info)) if not (stream_info and stream_info["is_live"]): log.debug("Stream might be Off Air") return m3u8_url = stream_info.get("secure_m3u8_url") if m3u8_url: yield from HLSStream.parse_variant_playlist(self.session, m3u8_url).items() __plugin__ = Livestream
melmorabity/streamlink
src/streamlink/plugins/livestream.py
Python
bsd-2-clause
1,433
import time import threading import PyTango import numpy import h5py THREAD_DELAY_SEC = 0.1 class HDFwriterThread(threading.Thread): #----------------------------------------------------------------------------------- # __init__ #----------------------------------------------------------------------------------- def __init__(self, parent_obj, filename_in, trg_start, trg_stop): threading.Thread.__init__(self) self._alive = True self.myState = PyTango.DevState.OFF self.filename = filename_in self.parent = parent_obj self.trg_start = trg_start self.trg_stop = trg_stop self.data_queue = [] self.datasource_finished = {} self._hdf_file = None self.timeout_sec = 20 self.MetadataSources = {} if "_errors" in dir(h5py): h5py._errors.silence_errors() #----------------------------------------------------------------------------------- # set_Metadata_Sources #----------------------------------------------------------------------------------- def set_Metadata_Sources(self, MetadataSources): self.MetadataSources = MetadataSources #----------------------------------------------------------------------------------- # notify_new_data #----------------------------------------------------------------------------------- def notify_new_data(self, daq_thread, trg): self.data_queue.append([daq_thread, trg]) #----------------------------------------------------------------------------------- # store_metadata #----------------------------------------------------------------------------------- def store_metadata(self): for metakey in self.MetadataSources.keys(): if not self.MetadataSources[metakey]['enabled']: continue try: attprx = PyTango.AttributeProxy(self.MetadataSources[metakey]['tango_attr']) attrinfo = attprx.get_config() attprx.get_device_proxy().set_timeout_millis(500) data_in = attprx.read().value del attprx except Exception, ex: self.MetadataSources[metakey]['status'] = 'ALARM' print "store_metadata, attribute proxy",metakey,ex continue # retries = 0 while retries < 3: if metakey in self._hdf_file: break try: # Create HDF dataset dset = self._hdf_file.create_dataset(metakey, data=data_in) #dset = self._hdf_file[metakey] dset.attrs["unit"] = attrinfo.unit break except Exception, ex: print "store_metadata",metakey,self.trg_start,ex retries += 1 #----------------------------------------------------------------------------------- # store_sync_player_metadata #----------------------------------------------------------------------------------- def store_sync_player_metadata(self,daq_thread): player_metadata = daq_thread.player_metadata dset = self._hdf_file[daq_thread.player_nickname] for key in player_metadata.keys(): try: attprx = PyTango.AttributeProxy(player_metadata[key].tango_attr) attprx.get_device_proxy().set_timeout_millis(500) data_in = attprx.read().value del attprx # dset.attrs[key] = data_in except Exception, ex: print "store_sync_player_metadata",key,ex # # Unit is default try: attprx = PyTango.AttributeProxy(daq_thread.player_attrname) attrinfo = attprx.get_config() del attprx # dset.attrs["unit"] = attrinfo.unit except Exception, ex: print "store_sync_player_metadata, deafult unit",daq_thread.player_attrname,ex #----------------------------------------------------------------------------------- # store_data #----------------------------------------------------------------------------------- def store_data(self, daq_queue_item): daq_thread = daq_queue_item[0] trg = daq_queue_item[1] data_in = daq_thread._data_buffer[trg] if data_in == None: return if daq_thread.player_nickname not in self.datasource_finished.keys(): self.datasource_finished[daq_thread.player_nickname] = False # # Create HDF dataset tokens = daq_thread.player_nickname.split("/") groupname="" dsetname = daq_thread.player_nickname dataset_len = 1+self.trg_stop-self.trg_start retries = 0 while (retries < 3): try: if dsetname in self._hdf_file: break if len(numpy.shape(data_in)) == 0: #scalar self._hdf_file.create_dataset(dsetname,shape=(dataset_len,),dtype=numpy.dtype(type(data_in))) elif len(numpy.shape(data_in)) == 1: #spectrum self._hdf_file.create_dataset(dsetname, shape=(dataset_len,data_in.shape[0]), dtype=data_in.dtype) elif len(numpy.shape(data_in)) == 2: #image self._hdf_file.create_dataset(dsetname, shape=(dataset_len,data_in.shape[0],data_in.shape[1]), dtype=data_in.dtype) break except Exception, ex: print "Create Dataset",dsetname,data_in,len(numpy.shape(data_in)),dataset_len,"\n",ex retries += 1 # self.store_sync_player_metadata(daq_thread) # retries = 0 while (retries < 3): #update the dataset try: dset = self._hdf_file.get(daq_thread.player_nickname, None) dset[slice(trg - self.trg_start,trg - self.trg_start+1)] = data_in break except Exception, ex: retries += 1 print "Update Dataset",ex # if trg == self.trg_stop: self.datasource_finished.pop(daq_thread.player_nickname) #----------------------------------------------------------------------------------- # close_file #----------------------------------------------------------------------------------- def close_file(self): try: # data_in=numpy.arange(self.trg_start,self.trg_stop+1) self._hdf_file.create_dataset("triggers", data = data_in) # self.store_metadata() # self._hdf_file.flush() self._hdf_file.close() self.parent.report_message("Closed file "+self.filename) except Exception, ex: print "Closing File",ex self.parent.notify_hdf_file_finished(self) #----------------------------------------------------------------------------------- # run #----------------------------------------------------------------------------------- def run(self): try: self._hdf_file = h5py.File(self.filename,'w') self.parent.report_message("Opened file "+self.filename) except Exception, ex: print ex self.parent.report_message("Unable to Open file "+self.filename) return last_store_time = time.time() while self._alive: while len(self.data_queue): # self.store_data(self.data_queue[0]) del self.data_queue[0] last_store_time = time.time() # if len(self.datasource_finished) == 0: self.close_file() if self.parent._paused: last_store_time = time.time() elif (time.time() - last_store_time) > self.timeout_sec: print "TIMEOUT",self.filename self.close_file() last_store_time = time.time() time.sleep(THREAD_DELAY_SEC)
ess-dmsc/do-ess-data-simulator
DonkiDirector/HDFWriterThread.py
Python
bsd-2-clause
6,785
package utils; import java.math.BigDecimal; import java.math.BigInteger; /** * Static functions for calculating roots and related functions for * BigIntegers and BigDecimals. */ public class RootFinder { private static BigDecimal ZERO = new BigDecimal("0"); private static BigDecimal EPSILON = new BigDecimal("0.000000001"); private static BigDecimal TWO = new BigDecimal("2"); /** * Calculates an approximation for the square root of BigDecimal value n. * * @param n the value to root. * @param scale * @return the root of n. * @throws IllegalArgumentException if n is negative or zero. */ public static BigDecimal squareRoot(BigDecimal n, int scale) throws IllegalArgumentException { if (n.compareTo(ZERO) <= 0) { throw new IllegalArgumentException( "Only positive integers accepted."); } BigDecimal temp = BigDecimal.ONE; BigDecimal root = (n.add(n.divide(temp, scale, Settings.ROUNDING))) .divide(TWO, scale, BigDecimal.ROUND_HALF_UP); while (root.subtract(temp).abs().compareTo(EPSILON) > 0) { temp = new BigDecimal(root.toString()); root = (temp.add(n.divide(temp, scale, Settings.ROUNDING))) .divide(TWO, scale, Settings.ROUNDING); } return root; } /** * Calculates the approximate (round up) integer square root of integer n. * * @param n * @return */ public static BigInteger getApproxRoot(BigInteger n) { if (n.compareTo(BigInteger.ZERO) < 0) throw new IllegalArgumentException("Cannot use negative integers."); BigDecimal p = RootFinder.squareRoot(new BigDecimal(n .toString()), 10); BigInteger roundUp = p.setScale(0, Settings.ROUNDING) .toBigIntegerExact(); return roundUp; } /** * Tests if the big integer n is a perfect square. * @param n * @return */ public static boolean isPerfectSquare(BigInteger n) { // if the least significant 1-bit of n is at an odd index, then // n cannot be a perfect square. i.e. n could be factored into // a non-even power of 2 and an odd integer, so could not be square. if (n.getLowestSetBit() % 2 == 1) return false; BigDecimal NBD = new BigDecimal(n); BigDecimal sqrt = squareRoot(NBD, 10); BigInteger sqrtAsInt = sqrt.toBigInteger(); if (sqrtAsInt.multiply(sqrtAsInt).compareTo(n) == 0) { return true; } else return false; } /** * Floor of square root. * * @param n * @return */ public static BigInteger getRootFloor(BigInteger n) { if (n.compareTo(BigInteger.ZERO) < 0) throw new IllegalArgumentException("Cannot use negative integers."); BigDecimal p = RootFinder.squareRoot(new BigDecimal(n .toString()), 10); BigInteger rounddown = p.setScale(0, BigDecimal.ROUND_FLOOR) .toBigIntegerExact(); return rounddown; } /** * Ceiling of square root. * * @param n * @return */ public static BigInteger getRootCeiling(BigInteger n) { if (n.compareTo(BigInteger.ZERO) < 0) throw new IllegalArgumentException("Cannot use negative integers."); BigDecimal p = RootFinder.squareRoot(new BigDecimal(n .toString()), 10); BigInteger roundUp = p.setScale(0, BigDecimal.ROUND_CEILING) .toBigIntegerExact(); return roundUp; } /** * Gets approximation of Cube Root of a BigDecimal, n, using Newton's * numerical method. * * @param n * @param scale * @return */ public static BigDecimal cubeRoot(BigDecimal n, int scale) { BigDecimal third = new BigDecimal(1.0 / 3.0); BigDecimal temp = third.multiply(n); BigDecimal root = third.multiply((TWO.multiply(temp).add(n.divide( temp.multiply(temp), scale, BigDecimal.ROUND_HALF_UP)))); while (root.subtract(temp).abs().compareTo(EPSILON) > 0) { temp = root; root = third.multiply((TWO.multiply(temp).add(n.divide( temp.multiply(temp), scale, Settings.ROUNDING)))); } return root.setScale(6, Settings.ROUNDING); } /** * Calculates the x root of BigDecimal n, where x is the root argument. * * @param n the argument. * @param root the root to calculate. * @param scale * @return root of BigDecimal. */ public static BigDecimal nRoot(BigDecimal n, int root, int scale) { float inv = 1.0f / root; BigDecimal r = new BigDecimal(String.valueOf(inv)); BigDecimal temp = r.multiply(n); BigDecimal rmo = new BigDecimal(String.valueOf(root - 1)); BigDecimal nroot = r.multiply((rmo.multiply(temp).add(n.divide( temp.pow(root - 1), scale, BigDecimal.ROUND_HALF_UP)))); while (nroot.subtract(temp).abs().compareTo(EPSILON) > 0) { temp = nroot; nroot = r.multiply((rmo.multiply(temp).add(n.divide( temp.pow(root - 1), scale, BigDecimal.ROUND_HALF_UP)))); } return nroot.setScale(scale, BigDecimal.ROUND_HALF_UP); } }
jonghough/Subspace
src/main/java/utils/RootFinder.java
Java
bsd-2-clause
5,410
// Generated by CoffeeScript 1.3.3 var binding, exports, leveldb; leveldb = exports = module.exports = require('./leveldb/handle'); binding = require('./leveldb.node'); leveldb.version = '0.6.2'; leveldb.bindingVersion = "" + binding.majorVersion + "." + binding.minorVersion; leveldb.Batch = require('./leveldb/batch').Batch; /* Create a partitioned bitwise comparator for use with opening a database. @param {Array} partitions Partition configuration data. @param {Array} partitions[] Slice configuration. @param {Integer} partitions[][0] Number of bytes in this slice. Use zero to set the sorting direction for all bytes from the current offset until the next slice or the end of the key. @param {Boolean} partitions[][1] If true, use reverse bitwise sorting until the next slice or the end of the key. */ leveldb.partitionedBitwiseComparator = function() { var args, bounds, limit, reverse, _i, _len, _ref; args = Array.prototype.slice.call(arguments); args = Array.isArray(args[0][0]) ? args[0] : args; bounds = []; for (_i = 0, _len = args.length; _i < _len; _i++) { _ref = args[_i], limit = _ref[0], reverse = _ref[1]; bounds.push(parseInt(limit)); bounds.push(!!reverse); } return binding.createPartitionedBitwiseComparator(bounds); };
maxogden/node-leveldb
lib/index.js
JavaScript
bsd-2-clause
1,340
var app = angular.module("pinguApp", []); console.log("Fired up angular ...");
avalikarvamus/pinguinvoice
app/static/scripts/pinguApp.js
JavaScript
bsd-2-clause
80
cask :v1 => 'basecamp' do version '4.4.6' sha256 'd114af2d4f68132cee1739eae67a5704bf09612bae032a97535b2befcc44ab40' url "http://download.garmin.com/software/BaseCampforMac_#{version.gsub('.', '')}.dmg" homepage 'http://www.garmin.com/en-US/shop/downloads/basecamp' license :gratis pkg 'Install BaseCamp.pkg' uninstall :pkgutil => 'com.garmin.BaseCamp' end
donbobka/homebrew-cask
Casks/basecamp.rb
Ruby
bsd-2-clause
373
# GeoNAN Test Fixtures The test fixture data is a spatialite database that has parking locations loaded from a shapefile. The parking data was created from data collected by the Downtown Alliance, Austin, TX. The table name that contains the data is called parking. Copyright © 2011 Jamie Phillips ## License GeoNAN is licensed under [BSD](http://www.opensource.org/licenses/bsd-license.php "Read more about the BSD license form"). Refer to license.txt for more information.
phillipsj/GeoNAN
data/data-readme.md
Markdown
bsd-2-clause
483
from rknfilter.targets import BaseTarget from rknfilter.db import Resource, Decision, CommitEvery from rknfilter.core import DumpFilesParser class StoreTarget(BaseTarget): def __init__(self, *args, **kwargs): super(StoreTarget, self).__init__(*args, **kwargs) self._dump_files_parser = DumpFilesParser() def process(self): commit = CommitEvery(self._session) for content, decision, domains, urls, ips, _ in self._dump_files_parser.get_data(): # TODO: move to models? resource = Resource.get_or_create(self._session, rkn_id=content['rkn_id']) if resource.id is None: resource.include_date = content['include_date'] resource.entry_type = content['entry_type'] resource.urgency_type = content['urgency_type'] resource.block_type = content['block_type'] resource.decision = Decision( date=decision['decision_date'], org=decision['decision_org'], num=decision['decision_num'] ) resource.sync_m2m_proxy('domains_list', domains) resource.sync_m2m_proxy('urls_list', urls) resource.sync_m2m_proxy('ips_list', ips) commit() commit(force=True)
DmitryFillo/rknfilter
rknfilter/targets/store.py
Python
bsd-2-clause
1,324
/* Copyright (c) 2007-2008 nemesis Developers Association. All rights reserved. Governed by the nemesis License 3.0 the full text of which is contained in the file License.txt included in nemesis binary and source code distribution packages. */ #include <atlcomcli.h> #include <atlconv.h> #include <comutil.h> #include <windows.h> #include "BaseCom.h" #include "BootEncryption.h" #include "Dlgcode.h" #include "Format.h" #include "Progress.h" #include "TcFormat.h" #include "FormatCom.h" #include "FormatCom_h.h" #include "FormatCom_i.c" using namespace nemesis; static volatile LONG ObjectCount = 0; class nemesisFormatCom : public InemesisFormatCom { public: nemesisFormatCom (DWORD messageThreadId) : RefCount (0), MessageThreadId (messageThreadId), CallBack (NULL) { InterlockedIncrement (&ObjectCount); } ~nemesisFormatCom () { if (InterlockedDecrement (&ObjectCount) == 0) PostThreadMessage (MessageThreadId, WM_APP, 0, 0); } virtual ULONG STDMETHODCALLTYPE AddRef () { return InterlockedIncrement (&RefCount); } virtual ULONG STDMETHODCALLTYPE Release () { if (!InterlockedDecrement (&RefCount)) { delete this; return 0; } return RefCount; } virtual HRESULT STDMETHODCALLTYPE QueryInterface (REFIID riid, void **ppvObject) { if (riid == IID_IUnknown || riid == IID_InemesisFormatCom) *ppvObject = this; else { *ppvObject = NULL; return E_NOINTERFACE; } AddRef (); return S_OK; } virtual DWORD STDMETHODCALLTYPE CallDriver (DWORD ioctl, BSTR input, BSTR *output) { return BaseCom::CallDriver (ioctl, input, output); } virtual DWORD STDMETHODCALLTYPE CopyFile (BSTR sourceFile, BSTR destinationFile) { return BaseCom::CopyFile (sourceFile, destinationFile); } virtual DWORD STDMETHODCALLTYPE DeleteFile (BSTR file) { return BaseCom::DeleteFile (file); } virtual BOOL STDMETHODCALLTYPE FormatNtfs (int driveNo, int clusterSize) { return ::FormatNtfs (driveNo, clusterSize); } virtual int STDMETHODCALLTYPE AnalyzeHiddenVolumeHost ( LONG_PTR hwndDlg, int *driveNo, __int64 hiddenVolHostSize, int *realClusterSize, __int64 *nbrFreeClusters) { return ::AnalyzeHiddenVolumeHost ( (HWND) hwndDlg, driveNo, hiddenVolHostSize, realClusterSize, nbrFreeClusters); } virtual DWORD STDMETHODCALLTYPE ReadWriteFile (BOOL write, BOOL device, BSTR filePath, BSTR *bufferBstr, unsigned __int64 offset, unsigned __int32 size, DWORD *sizeDone) { return BaseCom::ReadWriteFile (write, device, filePath, bufferBstr, offset, size, sizeDone); } virtual DWORD STDMETHODCALLTYPE RegisterFilterDriver (BOOL registerDriver, int filterType) { return BaseCom::RegisterFilterDriver (registerDriver, filterType); } virtual DWORD STDMETHODCALLTYPE RegisterSystemFavoritesService (BOOL registerService) { return BaseCom::RegisterSystemFavoritesService (registerService); } virtual DWORD STDMETHODCALLTYPE SetDriverServiceStartType (DWORD startType) { return BaseCom::SetDriverServiceStartType (startType); } virtual BOOL STDMETHODCALLTYPE IsPagingFileActive (BOOL checkNonWindowsPartitionsOnly) { return BaseCom::IsPagingFileActive (checkNonWindowsPartitionsOnly); } virtual DWORD STDMETHODCALLTYPE WriteLocalMachineRegistryDwordValue (BSTR keyPath, BSTR valueName, DWORD value) { return BaseCom::WriteLocalMachineRegistryDwordValue (keyPath, valueName, value); } protected: DWORD MessageThreadId; LONG RefCount; InemesisFormatCom *CallBack; }; extern "C" BOOL ComServerFormat () { SetProcessShutdownParameters (0x100, 0); nemesisFactory<nemesisFormatCom> factory (GetCurrentThreadId ()); DWORD cookie; if (IsUacSupported ()) UacElevated = TRUE; if (CoRegisterClassObject (CLSID_nemesisFormatCom, (LPUNKNOWN) &factory, CLSCTX_LOCAL_SERVER, REGCLS_SINGLEUSE, &cookie) != S_OK) return FALSE; MSG msg; while (int r = GetMessage (&msg, NULL, 0, 0)) { if (r == -1) return FALSE; TranslateMessage (&msg); DispatchMessage (&msg); if (msg.message == WM_APP && ObjectCount < 1 && !factory.IsServerLocked ()) break; } CoRevokeClassObject (cookie); return TRUE; } static BOOL ComGetInstance (HWND hWnd, InemesisFormatCom **tcServer) { return ComGetInstanceBase (hWnd, CLSID_nemesisFormatCom, IID_InemesisFormatCom, (void **) tcServer); } InemesisFormatCom *GetElevatedInstance (HWND parent) { InemesisFormatCom *instance; if (!ComGetInstance (parent, &instance)) throw UserAbort (SRC_POS); return instance; } extern "C" int UacFormatNtfs (HWND hWnd, int driveNo, int clusterSize) { CComPtr<InemesisFormatCom> tc; int r; CoInitialize (NULL); if (ComGetInstance (hWnd, &tc)) r = tc->FormatNtfs (driveNo, clusterSize); else r = 0; CoUninitialize (); return r; } extern "C" int UacAnalyzeHiddenVolumeHost (HWND hwndDlg, int *driveNo, __int64 hiddenVolHostSize, int *realClusterSize, __int64 *nbrFreeClusters) { CComPtr<InemesisFormatCom> tc; int r; CoInitialize (NULL); if (ComGetInstance (hwndDlg, &tc)) r = tc->AnalyzeHiddenVolumeHost ((LONG_PTR) hwndDlg, driveNo, hiddenVolHostSize, realClusterSize, nbrFreeClusters); else r = 0; CoUninitialize (); return r; }
adouble42/nemesis-current
Format/FormatCom.cpp
C++
bsd-2-clause
5,169
#include <ros/ros.h> #include "serial_comm.h" #include <string.h> #include "std_msgs/String.h" using namespace std; class RosToSerialBridge { private: serial_comm* comm_port; public: RosToSerialBridge(ros::NodeHandle nh) { string port; nh.param<string>("port", port, string("")); comm_port = new serial_comm(); comm_port->Connect(port); ros::Publisher port_out_pub = nh.advertise<std_msgs::String>("/novatel_port_out", 1000); ros::Publisher port_in_pub = nh.advertise<std_msgs::String>("/novatel_port_in", 1000); ros::Subscriber port_sub = nh.subscribe("/novatel_port_in", 1000, &RosToSerialBridge::portWrite, this); ros::Rate poll_rate(100); while (ros::ok()) { std_msgs::String msg; string data = comm_port->safeRead(); msg.data= data; if (data.length() > 0) { port_out_pub.publish(msg); } ros::spinOnce(); poll_rate.sleep(); } comm_port->Close(); delete comm_port; } void portWrite(const std_msgs::String::ConstPtr& msg) { string to_write = msg->data; cout << "received: " << to_write << endl; comm_port->safeWrite( to_write + "\r\n"); } }; int main(int argc, char** argv) { ros::init(argc, argv, "novatel_node"); ros::NodeHandle nh("~"); RosToSerialBridge bridge(nh); }
sameeptandon/sail-car-log
ros_drivers/src/novatel_serial_driver/novatel_driver_node.cpp
C++
bsd-2-clause
1,575
// // PolitiekAppDelegate.h // Politiek // // Created by Wolfgang Schreurs on 11/6/11. // Copyright 2012 Wolfgang Schreurs. All rights reserved. // #import <UIKit/UIKit.h> #import "AudioPlayerViewController.h" #import "FBConnect.h" @class Reachability; @interface OnsNieuwsAppDelegate : UIResponder <UIApplicationDelegate, FBSessionDelegate> @property (nonatomic, strong) UIWindow *window; @property (nonatomic, strong) Facebook *facebook; @property (nonatomic, strong) AudioPlayerViewController *audioPlayer; @end
wolf81/OnsNieuws
Politiek/OnsNieuwsAppDelegate.h
C
bsd-2-clause
535
from quex.engine.generator.languages.address import Address from quex.blackboard import E_EngineTypes, E_AcceptanceIDs, E_StateIndices, \ E_TransitionN, E_PostContextIDs, E_PreContextIDs, \ setup as Setup def do(txt, TheState, TheAnalyzer, DefineLabelF=True, MentionStateIndexF=True): LanguageDB = Setup.language_db if DefineLabelF: txt.append(Address("$drop-out", TheState.index)) if MentionStateIndexF: txt.append(" __quex_debug_drop_out(%i);\n" % TheState.index) if TheAnalyzer.engine_type == E_EngineTypes.BACKWARD_PRE_CONTEXT: txt.append(" %s\n" % LanguageDB.GOTO(E_StateIndices.END_OF_PRE_CONTEXT_CHECK)) return elif TheAnalyzer.engine_type == E_EngineTypes.BACKWARD_INPUT_POSITION: if TheState.drop_out.reachable_f: # Backward input position detectors are always isolated state machines. # => TheAnalyzer.state_machine_id = id of the backward input position detector. txt.append(' __quex_debug("backward input position %i detected\\n");\n' % \ TheAnalyzer.state_machine_id) txt.append(" %s\n\n" % LanguageDB.INPUT_P_INCREMENT()) txt.append(" goto %s;\n" \ % LanguageDB.LABEL_NAME_BACKWARD_INPUT_POSITION_RETURN(TheAnalyzer.state_machine_id)) return info = TheState.drop_out.trivialize() # (1) Trivial Solution if info is not None: for i, easy in enumerate(info): positioning_str = "" if easy[1].positioning != 0: if easy[1].positioning == E_TransitionN.VOID: register = easy[1].position_register else: register = E_PostContextIDs.NONE positioning_str = "%s\n" % LanguageDB.POSITIONING(easy[1].positioning, register) goto_terminal_str = "%s" % LanguageDB.GOTO_TERMINAL(easy[1].acceptance_id) txt.append(LanguageDB.IF_PRE_CONTEXT(i == 0, easy[0].pre_context_id, "%s%s" % (positioning_str, goto_terminal_str))) return # (2) Separate: Pre-Context Check and Routing to Terminal # (2.1) Pre-Context Check for i, element in enumerate(TheState.drop_out.get_acceptance_checker()): if element.pre_context_id == E_PreContextIDs.NONE \ and element.acceptance_id == E_AcceptanceIDs.VOID: break txt.append( LanguageDB.IF_PRE_CONTEXT(i == 0, element.pre_context_id, LanguageDB.ASSIGN("last_acceptance", LanguageDB.ACCEPTANCE(element.acceptance_id))) ) if element.pre_context_id == E_PreContextIDs.NONE: break # No check after the unconditional acceptance # (2.2) Routing to Terminal # (2.2.1) If the positioning is the same for all entries (except the FAILURE) # then, again, the routing may be simplified: #router = TheState.drop_out.router #prototype = (router[0].positioning, router[0].position_register) #simple_f = True #for element in islice(router, 1, None): # if element.acceptance_id == E_AcceptanceIDs.FAILURE: continue # if prototype != (element.positioning, element.position_register): # simple_f = False # break #if simple_f: # txt.append(" %s\n %s\n" % # (LanguageDB.POSITIONING(element.positioning, element.position_register), # LanguageDB.GOTO_TERMINAL(E_AcceptanceIDs.VOID))) #else: case_list = [] for element in TheState.drop_out.get_terminal_router(): if element.positioning == E_TransitionN.VOID: register = element.position_register else: register = None case_list.append((LanguageDB.ACCEPTANCE(element.acceptance_id), "%s %s" % \ (LanguageDB.POSITIONING(element.positioning, register), LanguageDB.GOTO_TERMINAL(element.acceptance_id)))) txt.extend(LanguageDB.SELECTION("last_acceptance", case_list))
coderjames/pascal
quex-0.63.1/quex/engine/generator/state/drop_out.py
Python
bsd-2-clause
4,373
class Telegraf < Formula desc "Server-level metric gathering agent for InfluxDB" homepage "https://www.influxdata.com/" url "https://github.com/influxdata/telegraf/archive/v1.15.2.tar.gz" sha256 "2cc5392e9b035bce3255693b718d9e4bdd54fe16f5dc728b933113cfdaa93360" license "MIT" head "https://github.com/influxdata/telegraf.git" bottle do cellar :any_skip_relocation sha256 "7df245171b2f9b7791e86e21496494f1a31fa38e77ba5c97d656d6c0df82a820" => :catalina sha256 "358500c7190955a7f471070d91063bc89a1d9ed0b9978c066264ca05ea082903" => :mojave sha256 "194c317ad592aaa314ff28bf4751352093922835ecf2b651771e480351bf2369" => :high_sierra end depends_on "go" => :build def install system "go", "build", *std_go_args, "-ldflags", "-X main.version=#{version}", "./cmd/telegraf" etc.install "etc/telegraf.conf" => "telegraf.conf" end def post_install # Create directory for additional user configurations (etc/"telegraf.d").mkpath end plist_options manual: "telegraf -config #{HOMEBREW_PREFIX}/etc/telegraf.conf" def plist <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>KeepAlive</key> <dict> <key>SuccessfulExit</key> <false/> </dict> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_bin}/telegraf</string> <string>-config</string> <string>#{etc}/telegraf.conf</string> <string>-config-directory</string> <string>#{etc}/telegraf.d</string> </array> <key>RunAtLoad</key> <true/> <key>WorkingDirectory</key> <string>#{var}</string> <key>StandardErrorPath</key> <string>#{var}/log/telegraf.log</string> <key>StandardOutPath</key> <string>#{var}/log/telegraf.log</string> </dict> </plist> EOS end test do (testpath/"config.toml").write shell_output("#{bin}/telegraf -sample-config") system "#{bin}/telegraf", "-config", testpath/"config.toml", "-test", "-input-filter", "cpu:mem" end end
lembacon/homebrew-core
Formula/telegraf.rb
Ruby
bsd-2-clause
2,340
<html> <head> <title>57North Standing Order</title> <link href="//hub.57north.org.uk/static/stylesheets/so_form.css" rel="stylesheet" type="text/css"> </head> <body> <h1>New Standing Order Instruction</h1> <p>Please set up the following standing order and debit my/our account accordingly</p> <h2>Account details</h2> <p class="incomplete">Account Name:</p> <p class="incomplete">Account holding branch:</p> <p class="incomplete">Account number:</p> <p class="incomplete">Sort code:</p> <h2>Payee details</h2> <p>Account name: {{ bank.act_name }}</p> <p>Payment ref: {{ member.username }}</p> <p>Account number: {{ bank.act_number }}</p> <p>Sort code: {{ bank.sort_code }}</p> <h2>Payment</h2> <p>Pay <strong>monthly</strong> on/soon after the 1st of every month</p> <p>£20.00</p> <p>until further notice.</p> <h2>Confirmation</h2> <p>Customer Signature(s):</p> <p class="incomplete"> </p> <p class="incomplete">Date:</p> </body> </html>
hackerdeen/hackhub
templates/standing_order.html
HTML
bsd-2-clause
946
# based on https://github.com/pypa/sampleproject/blob/master/setup.py # see http://packaging.python.org/en/latest/tutorial.html#creating-your-own-project from setuptools import setup, find_packages from setuptools.command.install import install as stdinstall import codecs import os import re import sys def find_version(*file_paths): here = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(here, *file_paths), 'r', 'latin1') as f: version_file = f.read() # The version line must have the form # __version__ = 'ver' version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.") def get_file_contents(filename): with codecs.open(filename, encoding='utf-8') as f: contents = f.read() return contents package_name = "typecheck-decorator" class install_with_test(stdinstall): def run(self): stdinstall.run(self) # normal install ##pip/setuptools makes this unbuffering unhelpful: #sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1) # make line-buffered #sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 1) # make line-buffered #import typecheck.test_typecheck_decorator # execute post-install test (during beta only) setup( # setup customization: cmdclass={'install': install_with_test}, # basic information: name=package_name, version=find_version('typecheck', '__init__.py'), description="flexible explicit run-time type checking of function arguments (Python3-only)", long_description=get_file_contents("README.rst"), # The project URL: url='http://github.com/prechelt/' + package_name, # Author details: author='Dmitry Dvoinikov, Lutz Prechelt', author_email='prechelt@inf.fu-berlin.de', # Classification: license='BSD License', classifiers=[ 'License :: OSI Approved :: BSD License', # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Documentation', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], keywords='type-checking', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages. packages=find_packages(exclude=["contrib", "docs", "tests*"]), # List run-time dependencies here. These will be installed by pip when your # project is installed. install_requires = ['typing;python_version<"3.5"'], # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. package_data={ # 'typecheck': ['package_data.dat'], }, # Although 'package_data' is the preferred approach, in some case you may # need to place data files outside of your packages. # see http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # In this case, 'data_file' will be installed into '<sys.prefix>/my_data' ###data_files=[('my_data', ['data/data_file'])], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. ### entry_points={ # 'console_scripts': [ # 'sample=sample:main', # ], # }, )
prechelt/typecheck-decorator
setup.py
Python
bsd-2-clause
3,969
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information. namespace Quaderno.Entities { public partial interface ITransactionFormatter { string Format(Bonus bonus); string Format(Deposit deposit); string Format(Expense expense); string Format(Interest interest); string Format(Revenue revenue); string Format(Transfer transfer); string Format(Withdrawal withdrawal); } }
chtoucas/Quaderno
src/Quaderno.Core/Entities/ITransactionFormatter.cs
C#
bsd-2-clause
504
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>東方深秘録 スコアデータ</title> <link rel="stylesheet" href="style.css" /> <style> /* <![CDATA[ */ td.character { min-width: 120px; } td.level { min-width: 70px; } table.clear td.clear { min-width: 70px; } table.time td.time { min-width: 70px; } /* ]]> */ </style> </head> <body> <header> <h1>東方深秘録 スコアデータ</h1> <hr /> <nav> <ul> <li><a href="#Clear">クリア達成度</a></li> <li><a href="#Time">クリア時間</a></li> </ul> </nav> </header> <main> <section> <h2 id="Clear">クリア達成度</h2> <table class="clear"> <thead> <tr> <th class="character">Character</th> <th class="level">Easy</th> <th class="level">Normal</th> <th class="level">Hard</th> <th class="level">Lunatic</th> </tr> </thead> <tbody> <tr> <td class="character">博麗 霊夢(序)</td> <td class="clear">%T145CLEARERA</td> <td class="clear">%T145CLEARNRA</td> <td class="clear">%T145CLEARHRA</td> <td class="clear">%T145CLEARLRA</td> </tr> <tr> <td class="character">霧雨 魔理沙</td> <td class="clear">%T145CLEAREMR</td> <td class="clear">%T145CLEARNMR</td> <td class="clear">%T145CLEARHMR</td> <td class="clear">%T145CLEARLMR</td> </tr> <tr> <td class="character">雲居 一輪 &amp; 雲山</td> <td class="clear">%T145CLEAREIU</td> <td class="clear">%T145CLEARNIU</td> <td class="clear">%T145CLEARHIU</td> <td class="clear">%T145CLEARLIU</td> </tr> <tr> <td class="character">聖 白蓮</td> <td class="clear">%T145CLEAREBY</td> <td class="clear">%T145CLEARNBY</td> <td class="clear">%T145CLEARHBY</td> <td class="clear">%T145CLEARLBY</td> </tr> <tr> <td class="character">物部 布都</td> <td class="clear">%T145CLEAREFT</td> <td class="clear">%T145CLEARNFT</td> <td class="clear">%T145CLEARHFT</td> <td class="clear">%T145CLEARLFT</td> </tr> <tr> <td class="character">豊聡耳 神子</td> <td class="clear">%T145CLEAREMK</td> <td class="clear">%T145CLEARNMK</td> <td class="clear">%T145CLEARHMK</td> <td class="clear">%T145CLEARLMK</td> </tr> <tr> <td class="character">河城 にとり</td> <td class="clear">%T145CLEARENT</td> <td class="clear">%T145CLEARNNT</td> <td class="clear">%T145CLEARHNT</td> <td class="clear">%T145CLEARLNT</td> </tr> <tr> <td class="character">古明地 こいし</td> <td class="clear">%T145CLEAREKO</td> <td class="clear">%T145CLEARNKO</td> <td class="clear">%T145CLEARHKO</td> <td class="clear">%T145CLEARLKO</td> </tr> <tr> <td class="character">二ッ岩 マミゾウ</td> <td class="clear">%T145CLEAREMM</td> <td class="clear">%T145CLEARNMM</td> <td class="clear">%T145CLEARHMM</td> <td class="clear">%T145CLEARLMM</td> </tr> <tr> <td class="character">秦 こころ</td> <td class="clear">%T145CLEAREKK</td> <td class="clear">%T145CLEARNKK</td> <td class="clear">%T145CLEARHKK</td> <td class="clear">%T145CLEARLKK</td> </tr> <tr> <td class="character">茨木 華扇</td> <td class="clear">%T145CLEAREKS</td> <td class="clear">%T145CLEARNKS</td> <td class="clear">%T145CLEARHKS</td> <td class="clear">%T145CLEARLKS</td> </tr> <tr> <td class="character">藤原 妹紅</td> <td class="clear">%T145CLEAREMO</td> <td class="clear">%T145CLEARNMO</td> <td class="clear">%T145CLEARHMO</td> <td class="clear">%T145CLEARLMO</td> </tr> <tr> <td class="character">少名 針妙丸</td> <td class="clear">%T145CLEARESN</td> <td class="clear">%T145CLEARNSN</td> <td class="clear">%T145CLEARHSN</td> <td class="clear">%T145CLEARLSN</td> </tr> <tr> <td class="character">宇佐見 菫子</td> <td class="clear">%T145CLEARESM</td> <td class="clear">%T145CLEARNSM</td> <td class="clear">%T145CLEARHSM</td> <td class="clear">%T145CLEARLSM</td> </tr> <tr> <td class="character">博麗 霊夢(終)</td> <td class="clear">%T145CLEARERB</td> <td class="clear">%T145CLEARNRB</td> <td class="clear">%T145CLEARHRB</td> <td class="clear">%T145CLEARLRB</td> </tr> </tbody> </table> </section> <hr /> <section> <h2 id="Time">クリア時間</h2> <table class="time"> <thead> <tr> <th class="character">Character</th> <th class="level">Easy</th> <th class="level">Normal</th> <th class="level">Hard</th> <th class="level">Lunatic</th> <th class="level">Total</th> </tr> </thead> <tbody> <tr> <td class="character">博麗 霊夢(序)</td> <td class="time">%T145TIMECLRERA</td> <td class="time">%T145TIMECLRNRA</td> <td class="time">%T145TIMECLRHRA</td> <td class="time">%T145TIMECLRLRA</td> <td class="time">%T145TIMECLRTRA</td> </tr> <tr> <td class="character">霧雨 魔理沙</td> <td class="time">%T145TIMECLREMR</td> <td class="time">%T145TIMECLRNMR</td> <td class="time">%T145TIMECLRHMR</td> <td class="time">%T145TIMECLRLMR</td> <td class="time">%T145TIMECLRTMR</td> </tr> <tr> <td class="character">雲居 一輪 &amp; 雲山</td> <td class="time">%T145TIMECLREIU</td> <td class="time">%T145TIMECLRNIU</td> <td class="time">%T145TIMECLRHIU</td> <td class="time">%T145TIMECLRLIU</td> <td class="time">%T145TIMECLRTIU</td> </tr> <tr> <td class="character">聖 白蓮</td> <td class="time">%T145TIMECLREBY</td> <td class="time">%T145TIMECLRNBY</td> <td class="time">%T145TIMECLRHBY</td> <td class="time">%T145TIMECLRLBY</td> <td class="time">%T145TIMECLRTBY</td> </tr> <tr> <td class="character">物部 布都</td> <td class="time">%T145TIMECLREFT</td> <td class="time">%T145TIMECLRNFT</td> <td class="time">%T145TIMECLRHFT</td> <td class="time">%T145TIMECLRLFT</td> <td class="time">%T145TIMECLRTFT</td> </tr> <tr> <td class="character">豊聡耳 神子</td> <td class="time">%T145TIMECLREMK</td> <td class="time">%T145TIMECLRNMK</td> <td class="time">%T145TIMECLRHMK</td> <td class="time">%T145TIMECLRLMK</td> <td class="time">%T145TIMECLRTMK</td> </tr> <tr> <td class="character">河城 にとり</td> <td class="time">%T145TIMECLRENT</td> <td class="time">%T145TIMECLRNNT</td> <td class="time">%T145TIMECLRHNT</td> <td class="time">%T145TIMECLRLNT</td> <td class="time">%T145TIMECLRTNT</td> </tr> <tr> <td class="character">古明地 こいし</td> <td class="time">%T145TIMECLREKO</td> <td class="time">%T145TIMECLRNKO</td> <td class="time">%T145TIMECLRHKO</td> <td class="time">%T145TIMECLRLKO</td> <td class="time">%T145TIMECLRTKO</td> </tr> <tr> <td class="character">二ッ岩 マミゾウ</td> <td class="time">%T145TIMECLREMM</td> <td class="time">%T145TIMECLRNMM</td> <td class="time">%T145TIMECLRHMM</td> <td class="time">%T145TIMECLRLMM</td> <td class="time">%T145TIMECLRTMM</td> </tr> <tr> <td class="character">秦 こころ</td> <td class="time">%T145TIMECLREKK</td> <td class="time">%T145TIMECLRNKK</td> <td class="time">%T145TIMECLRHKK</td> <td class="time">%T145TIMECLRLKK</td> <td class="time">%T145TIMECLRTKK</td> </tr> <tr> <td class="character">茨木 華扇</td> <td class="time">%T145TIMECLREKS</td> <td class="time">%T145TIMECLRNKS</td> <td class="time">%T145TIMECLRHKS</td> <td class="time">%T145TIMECLRLKS</td> <td class="time">%T145TIMECLRTKS</td> </tr> <tr> <td class="character">藤原 妹紅</td> <td class="time">%T145TIMECLREMO</td> <td class="time">%T145TIMECLRNMO</td> <td class="time">%T145TIMECLRHMO</td> <td class="time">%T145TIMECLRLMO</td> <td class="time">%T145TIMECLRTMO</td> </tr> <tr> <td class="character">少名 針妙丸</td> <td class="time">%T145TIMECLRESN</td> <td class="time">%T145TIMECLRNSN</td> <td class="time">%T145TIMECLRHSN</td> <td class="time">%T145TIMECLRLSN</td> <td class="time">%T145TIMECLRTSN</td> </tr> <tr> <td class="character">宇佐見 菫子</td> <td class="time">%T145TIMECLRESM</td> <td class="time">%T145TIMECLRNSM</td> <td class="time">%T145TIMECLRHSM</td> <td class="time">%T145TIMECLRLSM</td> <td class="time">%T145TIMECLRTSM</td> </tr> <tr> <td class="character">博麗 霊夢(終)</td> <td class="time">%T145TIMECLRERB</td> <td class="time">%T145TIMECLRNRB</td> <td class="time">%T145TIMECLRHRB</td> <td class="time">%T145TIMECLRLRB</td> <td class="time">%T145TIMECLRTRB</td> </tr> <tr> <td class="character">全キャラ合計</td> <td class="time">%T145TIMECLRETL</td> <td class="time">%T145TIMECLRNTL</td> <td class="time">%T145TIMECLRHTL</td> <td class="time">%T145TIMECLRLTL</td> <td class="time">%T145TIMECLRTTL</td> </tr> </tbody> </table> </section> </main> <footer> <p> Data output by <a href="https://www.colorless-sight.jp/thsfc/">ThScoreFileConverter</a>. <script> // <![CDATA[ document.write("Last updated: ", document.lastModified, "."); // ]]> </script> </p> </footer> </body> </html>
y-iihoshi/ThScoreFileConverter
TemplateGenerator/Templates/th145score.html
HTML
bsd-2-clause
10,374
cards-object-model ================== [my code samples] OO Analysis &amp; Design + Java . Time was limited by 1 hour.
petrychenko/cards-object-model
README.md
Markdown
bsd-2-clause
119
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <title>M-Kernel: template/ Directory Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">M-Kernel </div> <div id="projectbrief">EmbeddedRTOS</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.1.2 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Groups</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark">&#160;</span>Pages</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_dfacb4c4bbd4233d3d500b32c7cc4486.html">template</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">template Directory Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2><a name="files"></a> Files</h2></td></tr> <tr class="memitem:gpio__custom_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>gpio_custom.h</b> <a href="gpio__custom_8h_source.html">[code]</a></td></tr> <tr class="memitem:hw__config__stm32f2_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>hw_config_stm32f2.h</b> <a href="hw__config__stm32f2_8h_source.html">[code]</a></td></tr> <tr class="memitem:template_2kernel__config_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>kernel_config.h</b> <a href="template_2kernel__config_8h_source.html">[code]</a></td></tr> </table> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Wed Sep 12 2012 19:35:12 for M-Kernel by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.1.2 </small></address> </body> </html>
alexeyk13/mkernel
doc/html/dir_dfacb4c4bbd4233d3d500b32c7cc4486.html
HTML
bsd-2-clause
5,481
//Wrapped in an outer function to preserve global this (function (root) { var amdExports; define([], function () { (function () { // by tauren // https://github.com/Modernizr/Modernizr/issues/191 Modernizr.addTest('cookies', function () { // Quick test if browser has cookieEnabled host property if (navigator.cookieEnabled) return true; // Create cookie document.cookie = "cookietest=1"; var ret = document.cookie.indexOf("cookietest=") != -1; // Delete cookie document.cookie = "cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT"; return ret; }); }.call(root)); return amdExports; }); }(this));
noahpeters/iffy
sample/www/js/lib/Modernizr/feature-detects/cookies.js
JavaScript
bsd-2-clause
626
import re, csv header_end = re.compile("\s+START\s+END\s+") ## p. 1172 is missing a space between the final date and the description. Can't understand why the layout option does this; a space is clearly visible. I dunno. five_data_re = re.compile("\s*([\w\d]+)\s+(\d\d\/\d\d\/\d\d\d\d)\s+(.*?)\s+(\d\d\/\d\d\/\d\d\d\d)\s+(\d\d\/\d\d\/\d\d\d\d)\s*(.+?)\s+([\d\.\-\,]+)\s*\Z") five_data_missing_date = re.compile("\s*([\w\d]+)\s+(\d\d\/\d\d\/\d\d\d\d)\s+(.*?)\s{10,}(.*?)\s+([\d\.\-\,]+)\s*\Z") three_data_re = re.compile("\s+(\w[\w\,\s\.\-\']+?)\s{10,}(\w.*?)\s{4,}([\d\.\-\,]+)\s*") top_matter_end_re = re.compile("\s+DOCUMENT\s+NO\.\s+DATE\s+PAYEE") funding_year_re = re.compile("\s*Funding\s+Year\s+(\d+)") blank_line_re = re.compile("\s+\Z") page_number_re = re.compile("\s+\w\-\d+") page_number_alt_re = re.compile("\s+\w\-\d\-\d+") continuation_with_amount_re = re.compile("\s*(.+?)\s{10,}([\d\.\-\,]+)\s+\Z") travel_re = re.compile("\s+TRAVEL\s+AND\s+TRANSPORTATION\s+OF\s+PERSONS\s+") it_re = re.compile("\s+INTERDEPARTMENTAL\s+TRANSPORTATION\s+") ocs_re = re.compile("\s+OTHER\s+CONTRACTUAL\s+SERVICES\s+") acq_re = re.compile("\s+ACQUISITION\s+OF\s+ASSETS\s+") prsnl_re = re.compile("\s+PERSONNEL\s+BENEFITS\s+") netpayroll_re = re.compile("\s+NET\s+PAYROLL\s+EXPENSES\s+") persnl_comp_re = re.compile("\s+PERSONNEL COMP. FULL-TIME PERMANENT\s+") other_personal_comp = re.compile("\s+OTHER PERSONNEL COMPENSATION\s+") remployed_annuitants_re = re.compile("\s+RE-EMPLOYED ANNUITANTS\s+") former_employee_benefits_re = re.compile("\s+BENEFITS FOR NON SENATE/FORMER PERSONNEL\s+") page_number_re = re.compile("\s+B\s*\-\s*\d+\s*") def is_subtotal(line): if travel_re.match(line): return True if it_re.match(line): return True if ocs_re.match(line): return True if acq_re.match(line): return True if prsnl_re.match(line): return True if netpayroll_re.match(line): return True if persnl_comp_re.match(line): return True if other_personal_comp.match(line): return True if remployed_annuitants_re.match(line): return True if former_employee_benefits_re.match(line): return True return False def compute_break_position(top_matter): return None for whole_line in top_matter: if top_matter_end_re.match(whole_line): break if blank_line_re.match(line): continue return None def process_top_matter(page_num, top_matter): #top_matter_top_left_column_delimiter = compute_break_position(top_matter) top_matter_top_left_column_delimiter = 48 #return None expense_description = '' for whole_line in top_matter: if top_matter_end_re.match(whole_line): break line = whole_line[:top_matter_top_left_column_delimiter] if blank_line_re.match(line): continue result = funding_year_re.match(line) line_stripped = line.strip() if line_stripped: expense_description += ' ' + line_stripped + ' ' expense_description = re.sub( '\s+', ' ', expense_description ).strip() return expense_description # some carryover lines have amounts in them, and some don't -- that is, they are just extensions of the text field. See, e.g. p. 1672. def test_carryover_line(line_offset, line): # are the first n characters of the line empty ? line_start = line[:line_offset] if blank_line_re.match(line_start): line_end = line[line_offset:] if not blank_line_re.match(line_end): #print "***possible continuation: %s" % (line_end) return True return False def process_data_lines(page_num, data_lines): missing_data = [] return_data = [] return_data_index = 0 # these are lines that describe prior lines--typically the travel associated with a per diem or a transportation line. They aren't processed in this step, but instead just recorded in the one_part_continuation_register, and processed after that. one_part_continuation_register = [] last_line_data_index = None for data_line in data_lines: #print "handling %s %s" % (last_line_data_index, data_line) if blank_line_re.match(data_line): # don't reset last line data index--sometimes the page number appears in the middle of a page. continue if page_number_re.match(data_line): # These are the page numbers continue if is_subtotal(data_line): last_line_data_index = None #assert False continue found_data = five_data_re.match(data_line) if found_data: #print found_data.groups() if found_data: return_data.append(['five data line', False, page_num] + list(found_data.groups())) return_data_index += 1 #print "index of text description is: " + str(found_data.start(6)) last_line_data_index = str(found_data.start(6)) #print "Five data---last line data index: %s %s" % (last_line_data_index, found_data.groups()) # we need this to figure out if the next line is a continuation or a sub-header type thing. else: #pass found_data2 = three_data_re.match(data_line) found_data_missing_date = five_data_missing_date.match(data_line) if found_data2: results = list(found_data2.groups()) result_formatted = ['three data line', False, page_num, '', '', results[0], '', '', results[1], results[2]] return_data.append(result_formatted) return_data_index += 1 last_line_data_index = None elif (found_data_missing_date): print "**found missing date line" results = list(found_data_missing_date.groups()) result_formatted = ['missing date line', False, page_num, results[0], results[1], results[2], '', '', results[3], results[4]] return_data.append(result_formatted) return_data_index += 1 last_line_data_index = None else: is_page_num = page_number_re.match(data_line) is_page_num_alt = page_number_alt_re.match(data_line) if is_page_num or is_page_num_alt: continue if last_line_data_index: #print "running carryover test with n=%s" % (last_line_data_index) carryover_found = test_carryover_line(int(last_line_data_index), data_line) if carryover_found: continuation_data = continuation_with_amount_re.match(data_line) if continuation_data: #print "two part continuation found: '" + continuation_data.group(1) + "'-'" + continuation_data.group(2) + "'" # it's a two part continuation--probably per diem/travel. So add same data as for the first line. previous_result = return_data[return_data_index-1] result_formatted = ['continuation_data', True, previous_result[2], previous_result[3], previous_result[4], previous_result[5], previous_result[6], previous_result[7], continuation_data.group(1), continuation_data.group(2)] return_data.append(result_formatted) return_data_index += 1 else: description = data_line.strip() #print "one part continuation found: '" + description +"'" register_data = {'array_index':return_data_index, 'data':description} one_part_continuation_register.append(register_data) ## annoyingly, these descriptions themselves can span over multiple lines. ## e.g. p. 1557: # WASHINGTON DC TO CHARLESTON, COLUMBIA, CHARLESTON, COLUMBIA, LEXINGTON, # CLINTON, SPARTANBURG, GREENVILLE, COLUMBIA, AIKEN, COLUMBIA, CHARLESTON AND RETURN # RETURN ## append it to previous rows. else: print "missing <" + data_line + ">" missing_data.append({'data':data_line, 'offset':return_data_index,'page_num':page_num }) #if one_part_continuation_register: #print "one_part_continuation_register: %s" % (one_part_continuation_register) return {'data':return_data, 'register':one_part_continuation_register, 'missing_data':missing_data} def find_header_index(line_array): matches = 0 header_index = None for index, line in enumerate(line_array): r = header_end.search(line) if r: #print "match: %s: %s" % (index, line) matches += 1 header_index = index # break if we don't find exactly one occurrence of this per page. assert matches == 1 return header_index start_page = 17 end_page = 2073 #start_page = 1938 #end_page = 1938 page_file_unfilled = "pages/layout_%s.txt" header_index_hash = {} csvfile = open("senate_data.csv", 'wb') datawriter = csv.writer(csvfile) current_description = None description = None missing_data_file = open("missing_data.txt", 'w') for page in range(start_page, end_page+1): # random blank page if page == 1884 or page == 2068: continue print "Processing page %s" % page filename = page_file_unfilled % (page) fh = open(filename, 'r') page_array = [] for line in fh: page_array.append(line) header_index = find_header_index(page_array) # keep stats on where we find the index. try: header_index_hash[header_index] += 1 except KeyError: header_index_hash[header_index] = 1 # This is based on research... if header_index > 6: top_matter = page_array[:header_index+1] description = process_top_matter(page, top_matter) current_description = description data_lines = page_array[header_index+1:] data_found = process_data_lines(page, data_lines) # get the data lines, and the run-on lines. data_lines = data_found['data'] one_line_continuation_register = data_found['register'] # run through the continuation lines and append them to the right places. for cl in one_line_continuation_register: all_related_lines_found = False current_line_position = cl['array_index']-1 while all_related_lines_found == False: data_lines[current_line_position][8] = data_lines[current_line_position][8] + " + " + cl['data'] if data_lines[current_line_position][0] != 'continuation_data': all_related_lines_found = True else: # it's a continuation line, so append this to the previous line too. current_line_position -= 1 for data in data_lines: datawriter.writerow([current_description] + data) if data_found['missing_data']: missing_data_file.write(str(data_found['missing_data']) + "\n") for k,v in sorted(header_index_hash.items()): print k,v """ header index frequency: 3 1240 18 117 19 33 20 34 26 9 27 16 28 349 29 12 """
jsfenfen/senate_disbursements
114_sdoc4/read_pages.py
Python
bsd-2-clause
11,865
/* * Copyright (c) 2010 Riccardo Panicucci, Luigi Rizzo, Universita` di Pisa * All rights reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * The API to write a packet scheduling algorithm for dummynet. * * $FreeBSD: head/sys/netpfil/ipfw/dn_sched.h 213267 2010-09-29 09:40:20Z luigi $ */ #ifndef _DN_SCHED_H #define _DN_SCHED_H #define DN_MULTIQUEUE 0x01 /* * Descriptor for a scheduling algorithm. * Contains all function pointers for a given scheduler * This is typically created when a module is loaded, and stored * in a global list of schedulers. */ struct dn_alg { uint32_t type; /* the scheduler type */ const char *name; /* scheduler name */ uint32_t flags; /* DN_MULTIQUEUE if supports multiple queues */ /* * The following define the size of 3 optional data structures * that may need to be allocated at runtime, and are appended * to each of the base data structures: scheduler, sched.inst, * and queue. We don't have a per-flowset structure. */ /* + parameters attached to the template, e.g. * default queue sizes, weights, quantum size, and so on; */ size_t schk_datalen; /* + per-instance parameters, such as timestamps, * containers for queues, etc; */ size_t si_datalen; size_t q_datalen; /* per-queue parameters (e.g. S,F) */ /* * Methods implemented by the scheduler: * enqueue enqueue packet 'm' on scheduler 's', queue 'q'. * q is NULL for !MULTIQUEUE. * Return 0 on success, 1 on drop (packet consumed anyways). * Note that q should be interpreted only as a hint * on the flow that the mbuf belongs to: while a * scheduler will normally enqueue m into q, it is ok * to leave q alone and put the mbuf elsewhere. * This function is called in two cases: * - when a new packet arrives to the scheduler; * - when a scheduler is reconfigured. In this case the * call is issued by the new_queue callback, with a * non empty queue (q) and m pointing to the first * mbuf in the queue. For this reason, the function * should internally check for (m != q->mq.head) * before calling dn_enqueue(). * * dequeue Called when scheduler instance 's' can * dequeue a packet. Return NULL if none are available. * XXX what about non work-conserving ? * * config called on 'sched X config ...', normally writes * in the area of size sch_arg * * destroy called on 'sched delete', frees everything * in sch_arg (other parts are handled by more specific * functions) * * new_sched called when a new instance is created, e.g. * to create the local queue for !MULTIQUEUE, set V or * copy parameters for WFQ, and so on. * * free_sched called when deleting an instance, cleans * extra data in the per-instance area. * * new_fsk called when a flowset is linked to a scheduler, * e.g. to validate parameters such as weights etc. * free_fsk when a flowset is unlinked from a scheduler. * (probably unnecessary) * * new_queue called to set the per-queue parameters, * e.g. S and F, adjust sum of weights in the parent, etc. * * The new_queue callback is normally called from when * creating a new queue. In some cases (such as a * scheduler change or reconfiguration) it can be called * with a non empty queue. In this case, the queue * In case of non empty queue, the new_queue callback could * need to call the enqueue function. In this case, * the callback should eventually call enqueue() passing * as m the first element in the queue. * * free_queue actions related to a queue removal, e.g. undo * all the above. If the queue has data in it, also remove * from the scheduler. This can e.g. happen during a reconfigure. */ int (*enqueue)(struct dn_sch_inst *, struct dn_queue *, struct mbuf *); struct mbuf * (*dequeue)(struct dn_sch_inst *); int (*config)(struct dn_schk *); int (*destroy)(struct dn_schk*); int (*new_sched)(struct dn_sch_inst *); int (*free_sched)(struct dn_sch_inst *); int (*new_fsk)(struct dn_fsk *f); int (*free_fsk)(struct dn_fsk *f); int (*new_queue)(struct dn_queue *q); int (*free_queue)(struct dn_queue *q); /* run-time fields */ int ref_count; /* XXX number of instances in the system */ SLIST_ENTRY(dn_alg) next; /* Next scheduler in the list */ }; /* MSVC does not support initializers so we need this ugly macro */ #ifdef _WIN32 #define _SI(fld) #else #define _SI(fld) fld #endif /* * Additionally, dummynet exports some functions and macros * to be used by schedulers: */ void dn_free_pkts(struct mbuf *mnext); int dn_enqueue(struct dn_queue *q, struct mbuf* m, int drop); /* bound a variable between min and max */ int ipdn_bound_var(int *v, int dflt, int lo, int hi, const char *msg); /* * Extract the head of a queue, update stats. Must be the very last * thing done on a dequeue as the queue itself may go away. */ static __inline struct mbuf* dn_dequeue(struct dn_queue *q) { struct mbuf *m = q->mq.head; if (m == NULL) return NULL; q->mq.head = m->m_nextpkt; q->mq.count--; /* Update stats for the queue */ q->ni.length--; q->ni.len_bytes -= m->m_pkthdr.len; if (q->_si) { q->_si->ni.length--; q->_si->ni.len_bytes -= m->m_pkthdr.len; } if (q->ni.length == 0) /* queue is now idle */ q->q_time = dn_cfg.curr_time; return m; } int dn_sched_modevent(module_t mod, int cmd, void *arg); #define DECLARE_DNSCHED_MODULE(name, dnsched) \ static moduledata_t name##_mod = { \ #name, dn_sched_modevent, dnsched \ }; \ DECLARE_MODULE(name, name##_mod, \ SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY); \ MODULE_DEPEND(name, dummynet, 3, 3, 3); #endif /* _DN_SCHED_H */
dplbsd/netmap-ipfwjit
sys/netpfil/ipfw/dn_sched.h
C
bsd-2-clause
6,921
//============================================================================ // MCKL/include/mckl/smp.hpp //---------------------------------------------------------------------------- // MCKL: Monte Carlo Kernel Library //---------------------------------------------------------------------------- // Copyright (c) 2013-2018, Yan Zhou // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. //============================================================================ #ifndef MCKL_SMP_HPP #define MCKL_SMP_HPP #include <mckl/internal/config.h> #include <mckl/smp/backend_base.hpp> #include <mckl/smp/backend_omp.hpp> #include <mckl/smp/backend_seq.hpp> #include <mckl/smp/backend_std.hpp> #if MCKL_HAS_TBB #include <mckl/smp/backend_tbb.hpp> #endif #endif // MCKL_SMP_HPP
zhouyan/MCKL
include/mckl/smp.hpp
C++
bsd-2-clause
2,050
<div class="row"> <div class="col-md-4"> <div class="panel panel-info"> <div class="panel-heading">Instance</div> <table class="table"> <tr><td>ID</td><td>{{instance.id}}</td></tr> <tr><td>Service</td><td>{{service}}</td></tr> <tr><td>Environ</td><td>{{environ}}</td></tr> <tr><td>Zone</td><td>{{instance.zone}}</td></tr> <tr><td>Type</td><td>{{instance.instance_type}}</td></tr> </table> </div> </div> <div class="col-md-4"> <div class="panel panel-info"> <div class="panel-heading">State</div> <table class="table"> <tr><td>Instance State</td><td>{{instance.instance_state}}</td></tr> <tr><td>Group State</td><td>{{instance.group_health}}</td></tr> <tr><td>Host State</td><td>{{instance.group_state}}</td></tr> <tr><td>Launch Time</td><td>{{instance.launch_time}}</td></tr> </table> </div> </div> <div class="col-md-4"> <div class="panel panel-info"> <div class="panel-heading">Cloud</div> <table class="table"> <tr><td>Image ID</td><td>{{instance.image_id}}</td></tr> <tr><td>Launch Config</td><td>{{instance.group_config}}</td></tr> <tr><td>VPC</td><td>{{instance.vpc_id}}</td></tr> <tr><td>Subnet</td><td>{{instance.subnet_id}}</td></tr> </table> </div> </div> </div> <div class="row"> <div class="col-md-4"> <div class="panel panel-info"> <div class="panel-heading">Network</div> <table class="table"> <tr><td>Public IP Address</td><td>{{instance.public_ip_address}}</td></tr> <tr><td>Private IP Address</td><td>{{instance.private_ip_address}}</td></tr> <tr><td>Public DNS Hostname</td><td>{{instance.public_dns_name}}</td></tr> <tr><td>Private DNS Hostname</td><td>{{instance.private_dns_name}}</td></tr> </table> </div> </div> <div class="col-md-4"> <div class="panel panel-info"> <div class="panel-heading">Security</div> <table class="table"> <tr><td>Role</td><td>{{instance.instance_profile}}</td></tr> <tr><td>Key Name</td><td>{{instance.key_name}}</td></tr> </table> </div> </div> <div class="col-md-4"> <div class="panel panel-info"> <div class="panel-heading">Virtualization</div> <table class="table"> <tr><td>Architecture</td><td>{{instance.architecture}}</td></tr> <tr><td>EBS Optimized</td><td>{{instance.ebs_optimized}}</td></tr> <tr><td>Virtualization</td><td>{{instance.virtualization_type}}</td></tr> </table> </div> </div> </div> <div class="row"> <div class="col-md-4"> <div class="panel panel-info"> <div class="panel-heading">Tags</div> <table class="table"> {% for tagname, tagvalue in instance.tags.iteritems() %} <tr><td>{{tagname}}</td><td>{{tagvalue}}</td></tr> {% endfor %} </table> </div> </div> </div>
WrathOfChris/billow-web
billow_web/templates/instance.html
HTML
bsd-2-clause
2,955
from django.views.generic import ListView from models import Project # Create your views here. class ListProjectView(ListView): model = Project template_name = 'cmsplugin_vfoss_project/project_list.html'
thuydang/djagazin
wsgi/djagazin/cmsplugin_vfoss_project/views.py
Python
bsd-2-clause
207
/* @LICENSE(MUSLC_MIT) */ #include <sys/io.h> #include "internal/syscall.h" #ifdef SYS_iopl int iopl(int level) { return syscall(SYS_iopl, level); } #endif
gapry/refos
libs/libmuslc/src/linux/iopl.c
C
bsd-2-clause
159
-- Log module for LICH -- local log = {} local io = require('io') log.VERBOSE = false log.DEBUG = false log.INFO = true log.ERROR = true function log.verbose(msg) if log.VERBOSE or log.DEBUG then io.stdout:write('dbg: ' .. msg .. "\n") end end log.debug = log.verbose function log.info(msg) if log.INFO then io.stdout:write('inf: ' .. msg .. "\n") end end function log.error(msg) if log.ERROR then io.stderr:write('err: ' .. msg .. "\n") end end return log
n0la/lich
lich/log.lua
Lua
bsd-2-clause
502
(function() { var imageLoaderExample, myapp, oflib, window; oflib = require('lib/of'); oflib._.extend(this, oflib); imageLoaderExample = (function() { function imageLoaderExample() { this.bikers = new ofImage; this.gears = new ofImage; this.tdf = new ofImage; this.tdfSmall = new ofImage; this.transparency = new ofImage; this.bikeIcon = new ofImage; } imageLoaderExample.prototype.setup = function() { ofSetWindowTitle("Javascript image loader"); this.bikers.loadImage("images/bikers.jpg"); this.gears.loadImage("images/gears.gif"); this.tdf.loadImage("images/tdf_1972_poster.jpg"); this.tdfSmall.loadImage("images/tdf_1972_poster.jpg"); this.tdfSmall.resize(Math.round(this.tdf.width / 4), Math.round(this.tdf.height / 4)); this.tdfSmall.setImageType(OF_IMAGE_GRAYSCALE); this.transparency.loadImage("images/transparency.png"); this.bikeIcon.loadImage("images/bike_icon.png"); this.bikeIcon.setImageType(OF_IMAGE_GRAYSCALE); return this.oIndex = new Indexable(); }; imageLoaderExample.prototype.update = function() { return ofBackground(255, 255, 255); }; imageLoaderExample.prototype.draw = function() { var h, i, j, pct, pixels, value, w; ofSetColor(0xFFFFFF); this.bikers.draw(0, 0); this.gears.draw(600, 0); this.tdf.draw(600, 300); ofSetColor(0xDD3333); this.tdfSmall.draw(200, 300); ofSetColor(0xFFFFFF); ofEnableAlphaBlending(); this.transparency.draw(Math.sin(ofGetElapsedTimeMillis() / 1000.0) * 100 + 500, 20); ofDisableAlphaBlending(); ofSetColor(0x000000); w = this.bikeIcon.width; h = this.bikeIcon.height; pixels = this.oIndex.setPtr(this.bikeIcon.getPixels(), w * h * this.bikeIcon.bpp, kExternalUnsignedByteArray); i = 0; while (i++ < w) { j = 0; while (j++ < h) { value = pixels[j * w + i]; pct = 1 - (value / 255.0); ofCircle(i * 10, 500 + j * 10, 1 + 5 * pct); } } ofSetColor(0xFFFFFF); return this.bikeIcon.draw(300, 500, 20, 20); }; return imageLoaderExample; })(); _.extend(this, ofAppRunner); _.extend(this, ofGraphics); _.extend(this, ofMath); _.extend(this, OpenGL); _.extend(this, ofImage); _.extend(this, ofUtils); window = new ofAppGlutWindow; ofSetupOpenGL(window, 1024, 768, OF_WINDOW); myapp = _.extend(new ofBaseApp, new imageLoaderExample); ofRunApp(myapp); }).call(this);
codeboost/JOpenFrameworks
bin/imageLoaderExample.js
JavaScript
bsd-2-clause
2,556
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System.Diagnostics.SymbolStore // Name: ISymbolWriter // C++ Typed Name: mscorlib::System::Diagnostics::SymbolStore::ISymbolWriter #include <gtest/gtest.h> #include <mscorlib/System/Diagnostics/SymbolStore/mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter.h> #include <mscorlib/System/Diagnostics/SymbolStore/mscorlib_System_Diagnostics_SymbolStore_ISymbolDocumentWriter.h> #include <mscorlib/System/mscorlib_System_String.h> #include <mscorlib/System/mscorlib_System_Guid.h> #include <mscorlib/System/Diagnostics/SymbolStore/mscorlib_System_Diagnostics_SymbolStore_SymbolToken.h> #include <mscorlib/System/mscorlib_System_Byte.h> namespace mscorlib { namespace System { namespace Diagnostics { namespace SymbolStore { //Public Methods Tests // Method Close // Signature: TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,Close_Test) { } // Method CloseMethod // Signature: TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,CloseMethod_Test) { } // Method CloseNamespace // Signature: TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,CloseNamespace_Test) { } // Method CloseScope // Signature: mscorlib::System::Int32 endOffset TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,CloseScope_Test) { } // Method DefineDocument // Signature: mscorlib::System::String url, mscorlib::System::Guid language, mscorlib::System::Guid languageVendor, mscorlib::System::Guid documentType TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,DefineDocument_Test) { } // Method DefineField // Signature: mscorlib::System::Diagnostics::SymbolStore::SymbolToken parent, mscorlib::System::String name, mscorlib::System::Reflection::FieldAttributes::__ENUM__ attributes, std::vector<mscorlib::System::Byte*> signature, mscorlib::System::Diagnostics::SymbolStore::SymAddressKind::__ENUM__ addrKind, mscorlib::System::Int32 addr1, mscorlib::System::Int32 addr2, mscorlib::System::Int32 addr3 TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,DefineField_Test) { } // Method DefineGlobalVariable // Signature: mscorlib::System::String name, mscorlib::System::Reflection::FieldAttributes::__ENUM__ attributes, std::vector<mscorlib::System::Byte*> signature, mscorlib::System::Diagnostics::SymbolStore::SymAddressKind::__ENUM__ addrKind, mscorlib::System::Int32 addr1, mscorlib::System::Int32 addr2, mscorlib::System::Int32 addr3 TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,DefineGlobalVariable_Test) { } // Method DefineLocalVariable // Signature: mscorlib::System::String name, mscorlib::System::Reflection::FieldAttributes::__ENUM__ attributes, std::vector<mscorlib::System::Byte*> signature, mscorlib::System::Diagnostics::SymbolStore::SymAddressKind::__ENUM__ addrKind, mscorlib::System::Int32 addr1, mscorlib::System::Int32 addr2, mscorlib::System::Int32 addr3, mscorlib::System::Int32 startOffset, mscorlib::System::Int32 endOffset TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,DefineLocalVariable_Test) { } // Method DefineParameter // Signature: mscorlib::System::String name, mscorlib::System::Reflection::ParameterAttributes::__ENUM__ attributes, mscorlib::System::Int32 sequence, mscorlib::System::Diagnostics::SymbolStore::SymAddressKind::__ENUM__ addrKind, mscorlib::System::Int32 addr1, mscorlib::System::Int32 addr2, mscorlib::System::Int32 addr3 TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,DefineParameter_Test) { } // Method DefineSequencePoints // Signature: mscorlib::System::Diagnostics::SymbolStore::ISymbolDocumentWriter document, std::vector<mscorlib::System::Int32*> offsets, std::vector<mscorlib::System::Int32*> lines, std::vector<mscorlib::System::Int32*> columns, std::vector<mscorlib::System::Int32*> endLines, std::vector<mscorlib::System::Int32*> endColumns TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,DefineSequencePoints_Test) { } // Method Initialize // Signature: mscorlib::System::IntPtr emitter, mscorlib::System::String filename, mscorlib::System::Boolean fFullBuild TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,Initialize_Test) { } // Method OpenMethod // Signature: mscorlib::System::Diagnostics::SymbolStore::SymbolToken method TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,OpenMethod_Test) { } // Method OpenNamespace // Signature: mscorlib::System::String name TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,OpenNamespace_Test) { } // Method OpenScope // Signature: mscorlib::System::Int32 startOffset TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,OpenScope_Test) { } // Method SetMethodSourceRange // Signature: mscorlib::System::Diagnostics::SymbolStore::ISymbolDocumentWriter startDoc, mscorlib::System::Int32 startLine, mscorlib::System::Int32 startColumn, mscorlib::System::Diagnostics::SymbolStore::ISymbolDocumentWriter endDoc, mscorlib::System::Int32 endLine, mscorlib::System::Int32 endColumn TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,SetMethodSourceRange_Test) { } // Method SetScopeRange // Signature: mscorlib::System::Int32 scopeID, mscorlib::System::Int32 startOffset, mscorlib::System::Int32 endOffset TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,SetScopeRange_Test) { } // Method SetSymAttribute // Signature: mscorlib::System::Diagnostics::SymbolStore::SymbolToken parent, mscorlib::System::String name, std::vector<mscorlib::System::Byte*> data TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,SetSymAttribute_Test) { } // Method SetUnderlyingWriter // Signature: mscorlib::System::IntPtr underlyingWriter TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,SetUnderlyingWriter_Test) { } // Method SetUserEntryPoint // Signature: mscorlib::System::Diagnostics::SymbolStore::SymbolToken entryMethod TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,SetUserEntryPoint_Test) { } // Method UsingNamespace // Signature: mscorlib::System::String fullName TEST(mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture,UsingNamespace_Test) { } } } } }
brunolauze/MonoNative
MonoNative.Tests/mscorlib/System/Diagnostics/SymbolStore/mscorlib_System_Diagnostics_SymbolStore_ISymbolWriter_Fixture.cpp
C++
bsd-2-clause
7,006
<!doctype html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width" /> <title>$title</title> $styles </head> <body> <h1>$title</h1> <p> <input type="text" id="txt" value="Hello, $title!" /> <input type="button" id="btn" value="hello" /> </p> $scripts </body> </html>
tnantoka/CoffeeScriptAtOnce
CoffeeScriptAtOnce/Resources/template/src/index.html
HTML
bsd-2-clause
329
_x$ = 8 ; size = 4 bool <lambda_38b13499cc98be0a488fd10e7e4a1541>::operator()(int)const PROC ; <lambda_38b13499cc98be0a488fd10e7e4a1541>::operator(), COMDAT mov eax, DWORD PTR _x$[esp-4] cmp eax, 42 ; 0000002aH je SHORT $LN3@operator cmp eax, -1 je SHORT $LN3@operator xor al, al ret 4 $LN3@operator: mov al, 1 ret 4 bool <lambda_38b13499cc98be0a488fd10e7e4a1541>::operator()(int)const ENDP ; <lambda_38b13499cc98be0a488fd10e7e4a1541>::operator() _x$ = 8 ; size = 4 bool <lambda_6030eb0ee5ee5712779754fc8d958e43>::operator()(int)const PROC ; <lambda_6030eb0ee5ee5712779754fc8d958e43>::operator(), COMDAT mov eax, DWORD PTR _x$[esp-4] cmp eax, 42 ; 0000002aH je SHORT $LN3@operator cmp eax, -1 je SHORT $LN3@operator xor al, al ret 4 $LN3@operator: mov al, 1 ret 4 bool <lambda_6030eb0ee5ee5712779754fc8d958e43>::operator()(int)const ENDP ; <lambda_6030eb0ee5ee5712779754fc8d958e43>::operator() _v$ = 8 ; size = 4 unsigned int count_if_epi32(std::vector<int,std::allocator<int> > const &) PROC ; count_if_epi32, COMDAT mov eax, DWORD PTR _v$[esp-4] push esi push edi xor esi, esi mov edi, DWORD PTR [eax+4] mov ecx, DWORD PTR [eax] cmp ecx, edi je SHORT $LN30@count_if_e $LL23@count_if_e: mov eax, DWORD PTR [ecx] cmp eax, 42 ; 0000002aH je SHORT $LN24@count_if_e cmp eax, -1 je SHORT $LN24@count_if_e xor dl, dl jmp SHORT $LN25@count_if_e $LN24@count_if_e: mov dl, 1 $LN25@count_if_e: test dl, dl lea eax, DWORD PTR [esi+1] cmove eax, esi add ecx, 4 mov esi, eax cmp ecx, edi jne SHORT $LL23@count_if_e $LN30@count_if_e: pop edi mov eax, esi pop esi ret 0 unsigned int count_if_epi32(std::vector<int,std::allocator<int> > const &) ENDP ; count_if_epi32 _v$ = 8 ; size = 4 unsigned int count_if_epi8(std::vector<signed char,std::allocator<signed char> > const &) PROC ; count_if_epi8, COMDAT mov eax, DWORD PTR _v$[esp-4] push esi push edi xor esi, esi mov edi, DWORD PTR [eax+4] mov ecx, DWORD PTR [eax] cmp ecx, edi je SHORT $LN30@count_if_e $LL23@count_if_e: movsx eax, BYTE PTR [ecx] cmp eax, 42 ; 0000002aH je SHORT $LN24@count_if_e cmp eax, -1 je SHORT $LN24@count_if_e xor dl, dl jmp SHORT $LN25@count_if_e $LN24@count_if_e: mov dl, 1 $LN25@count_if_e: test dl, dl lea eax, DWORD PTR [esi+1] cmove eax, esi inc ecx mov esi, eax cmp ecx, edi jne SHORT $LL23@count_if_e $LN30@count_if_e: pop edi mov eax, esi pop esi ret 0 unsigned int count_if_epi8(std::vector<signed char,std::allocator<signed char> > const &) ENDP ; count_if_epi8
WojciechMula/toys
autovectorization-tests/results/msvc19.28.29333-avx2/count_if.asm
Assembly
bsd-2-clause
3,571
var config = { apiKey: "AIzaSyCVr8kNbA_47LwbKBesa4PzggiQoMtD6nA", authDomain: "absen-143db.firebaseapp.com", databaseURL: "https://absen-143db.firebaseio.com", projectId: "absen-143db", storageBucket: "absen-143db.appspot.com", messagingSenderId: "993994713726" }; firebase.initializeApp(config); var date = new Date(), year = date.getFullYear(), month = date.getMonth() + 1, day = date.getDate(), submit_date = year + '-' + month + '-' + day; function initializeAbsent() { firebase.database().ref('absen/' + submit_date).update({ ACHMAD_RIFKI: 'none', ADI_PRATAMA: 'none', ADINDA_CHANTIKA_LUBIS: 'none', AHMAD_ROMADHANI: 'none', AMMAR_ABDULLAH_ALZAHID: 'none', ANDRE_CHRISTOGA_PRAMADITYA: 'none', ARIEFIN_NUGROHO: 'none', AVRYLIYANAH_DEWY: 'none', BAYU_AJI: 'none', EDO_YUDHA_WASKITA: 'none', FAATHIR_RAMADHAN_ALFIRAH: 'none', FADHLI_FADHILAH: 'none', JULIDAR_FATIANI: 'none', KRIS_DAMAYANTI: 'none', M_AKHSIN_PRASETYO: 'none', MATHIUS: 'none', MOCHAMAD_RECHAN_ICHSANUL_KAMIL: 'none', MUHAMAD_KAMAL_BACRUR_ROZIKIN: 'none', MUHAMAD_RACHMAT_HIDAYAT: 'none', MUHAMAD_RESMI_AJI: 'none', MUHAMMAD_ABID_MULYANA: 'none', MUHAMMAD_AKBAR_HABIBY_KHALID: 'none', MUHAMMAD_ELVAN: 'none', MUHAMMAD_FADHIL_RABBANI: 'none', MUHAMMAD_RIVAN_AL_RASYID: 'none', NAHDA_KHAIRUNNISA: 'none', NAHLA_TARISAFITRI: 'none', NUR_AENI: 'none', RAMADHANU: 'none', REZA_SAFPUTRA: 'none', RISKI_RANDANTI: 'none', RIZKI_RAMADHAN_IMAN_MUDA: 'none', RIZKI_SALSA_BILLA: 'none', SYAHRUL_LESMANA: 'none', WINDI_AYU_WULANDARI: 'none', YAZID_AMIRULLAH: 'none' }, function(error) { if (!error) { alert('It\'s up bro!') } }) } function completeAbsence() { firebase.database().ref('absen/' + submit_date).update({ ACHMAD_RIFKI: 'hadir', ADI_PRATAMA: 'hadir', ADINDA_CHANTIKA_LUBIS: 'hadir', AHMAD_ROMADHANI: 'hadir', AMMAR_ABDULLAH_ALZAHID: 'hadir', ANDRE_CHRISTOGA_PRAMADITYA: 'hadir', ARIEFIN_NUGROHO: 'hadir', AVRYLIYANAH_DEWY: 'hadir', BAYU_AJI: 'hadir', EDO_YUDHA_WASKITA: 'hadir', FAATHIR_RAMADHAN_ALFIRAH: 'hadir', FADHLI_FADHILAH: 'hadir', JULIDAR_FATIANI: 'hadir', KRIS_DAMAYANTI: 'hadir', M_AKHSIN_PRASETYO: 'hadir', MATHIUS: 'hadir', MOCHAMAD_RECHAN_ICHSANUL_KAMIL: 'hadir', MUHAMAD_KAMAL_BACRUR_ROZIKIN: 'hadir', MUHAMAD_RACHMAT_HIDAYAT: 'hadir', MUHAMAD_RESMI_AJI: 'hadir', MUHAMMAD_ABID_MULYANA: 'hadir', MUHAMMAD_AKBAR_HABIBY_KHALID: 'hadir', MUHAMMAD_ELVAN: 'hadir', MUHAMMAD_FADHIL_RABBANI: 'hadir', MUHAMMAD_RIVAN_AL_RASYID: 'hadir', NAHDA_KHAIRUNNISA: 'hadir', NAHLA_TARISAFITRI: 'hadir', NUR_AENI: 'hadir', RAMADHANU: 'hadir', REZA_SAFPUTRA: 'hadir', RISKI_RANDANTI: 'hadir', RIZKI_RAMADHAN_IMAN_MUDA: 'hadir', RIZKI_SALSA_BILLA: 'hadir', SYAHRUL_LESMANA: 'hadir', WINDI_AYU_WULANDARI: 'hadir', YAZID_AMIRULLAH: 'hadir' }, function(error) { if (!error) { alert('It\'s up bro!') } }) } function editAbsent() { var nama = $('#studentName').val(); var status = $('#studentStatus').val(); firebase.database().ref('absen/' + submit_date).update({ [nama]: status }, function(error) { if (!error) { alert('It\'s up bro!') } }) }
christoga/schoolkit
js/absen.js
JavaScript
bsd-2-clause
3,385
# NodeBB Vibration Notifications for Mobile This NodeBB plugin uses the HTML5 Vibration API to alert you upon new incoming notifications while browsing on mobile. ## Installation npm install nodebb-plugin-vibration-notifications ## Browser support Latest versions of Chrome and Firefox for Android
psychobunny/nodebb-plugin-vibration-notifications
README.md
Markdown
bsd-2-clause
307
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using Core.Framework.Permissions.Helpers; using Core.Framework.Permissions.Models; using Framework.Core.Localization; using Framework.Facilities.NHibernate.Objects; namespace Core.Web.NHibernate.Models { [Export(typeof (IPermissible))] public class Role : LocalizableEntity<RoleLocale>, IPermissible, IRole { #region Fields private IList<User> users = new List<User>(); private IList<UserGroup> userGroups = new List<UserGroup>(); private String permissionTitle = "Roles"; private IEnumerable<IPermissionOperation> operations = OperationsHelper.GetOperations<BaseEntityOperations>(); #endregion #region Properties /// <summary> /// Gets or sets the name. /// </summary> /// <value>The name.</value> public virtual String Name { get { return ((RoleLocale) CurrentLocale).Name; } set { ((RoleLocale) CurrentLocale).Name = value; } } /// <summary> /// Gets or sets a value indicating whether this instance is system role. /// </summary> /// <value> /// <c>true</c> if this instance is system role; otherwise, <c>false</c>. /// </value> public virtual bool IsSystemRole { get; set; } public virtual bool NotAssignableRole { get; set; } public virtual bool NotPermissible { get; set; } public virtual IList<User> Users { get { return users; } set { users = value; } } public virtual IList<UserGroup> UserGroups { get { return userGroups; } set { userGroups = value; } } public override ILocale InitializeLocaleEntity() { return new RoleLocale { Role = this, Culture = null }; } #endregion #region IPermissible Members /// <summary> /// Gets or sets the permission title. /// </summary> /// <value>The permission title.</value> public virtual String PermissionTitle { get { return permissionTitle; } set { permissionTitle = value; } } /// <summary> /// Gets or sets the permission operations. /// </summary> /// <value>The permission operations.</value> public virtual IEnumerable<IPermissionOperation> Operations { get { return operations; } set { operations = value; } } #endregion } }
coreframework/Core-Framework
Source/Core.Web.NHibernate/Models/Role.cs
C#
bsd-2-clause
2,688
/* fourier.cpp -- Functions for sampling and evaluating Fourier series Copyright (c) 2015 Wenzel Jakob <wenzel@inf.ethz.ch> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include <layer/fourier.h> #include <layer/simd.h> NAMESPACE_BEGIN(layer) #if defined(__AVX__) static void initializeRecurrence(double c, __m256d &factor_prev, __m256d &factor_cur) { /* How to generate: c[0] = 1; c[1] = c; c[n_] := Expand[2 c c[n - 1] - c[n - 2]] last = 2 c; For[i = 3, i <= 9, ++i, last = Expand[(c[i] + last)/c]; Print[last] ] */ double c2 = c*c, temp1 = 2.0*c, temp2 = -1.0+4.0*c2, temp3 = c*(-4.0+8.0*c2), temp4 = 1.0+c2*(-12.0+16.0*c2); factor_prev = _mm256_set_pd(-temp3, -temp2, -temp1, -1.0f); factor_cur = _mm256_set_pd( temp4, temp3, temp2, temp1); } #endif Float evalFourier(const float *coeffs, size_t nCoeffs, Float phi) { #if FOURIER_SCALAR == 1 double cosPhi = std::cos((double) phi), cosPhi_prev = cosPhi, cosPhi_cur = 1.0, value = 0.0; for (size_t i=0; i<nCoeffs; ++i) { value += coeffs[i] * cosPhi_cur; double cosPhi_next = 2.0*cosPhi*cosPhi_cur - cosPhi_prev; cosPhi_prev = cosPhi_cur; cosPhi_cur = cosPhi_next; } return (Float) value; #else double cosPhi = std::cos((double) phi); __m256d cosPhi_prev = _mm256_set1_pd(cosPhi), cosPhi_cur = _mm256_set1_pd(1.0), value = _mm256_set_sd((double) coeffs[0]), factorPhi_prev, factorPhi_cur; initializeRecurrence(cosPhi, factorPhi_prev, factorPhi_cur); for (size_t i=1; i<nCoeffs; i+=4) { __m256d coeff = _mm256_cvtps_pd(_mm_load_ps(coeffs+i)); __m256d cosPhi_next = _mm256_add_pd(_mm256_mul_pd(factorPhi_prev, cosPhi_prev), _mm256_mul_pd(factorPhi_cur, cosPhi_cur)); value = _mm256_add_pd(value, _mm256_mul_pd(cosPhi_next, coeff)); cosPhi_prev = _mm256_splat2_pd(cosPhi_next); cosPhi_cur = _mm256_splat3_pd(cosPhi_next); } return (Float) simd::hadd(value); #endif } Color3 evalFourier3(float * const coeffs[3], size_t nCoeffs, Float phi) { #if FOURIER_SCALAR == 1 double cosPhi = std::cos((double) phi), cosPhi_prev = cosPhi, cosPhi_cur = 1.0f; double Y = 0, R = 0, B = 0; for (size_t i=0; i<nCoeffs; ++i) { Y += coeffs[0][i] * cosPhi_cur; R += coeffs[1][i] * cosPhi_cur; B += coeffs[2][i] * cosPhi_cur; double cosPhi_next = 2*cosPhi*cosPhi_cur - cosPhi_prev; cosPhi_prev = cosPhi_cur; cosPhi_cur = cosPhi_next; } double G = 1.39829f*Y -0.100913f*B - 0.297375f*R; return Color3((Float) R, (Float) G, (Float) B); #else double cosPhi = std::cos((double) phi); __m256d cosPhi_prev = _mm256_set1_pd(cosPhi), cosPhi_cur = _mm256_set1_pd(1.0), Y = _mm256_set_sd((double) coeffs[0][0]), R = _mm256_set_sd((double) coeffs[1][0]), B = _mm256_set_sd((double) coeffs[2][0]), factorPhi_prev, factorPhi_cur; initializeRecurrence(cosPhi, factorPhi_prev, factorPhi_cur); for (size_t i=1; i<nCoeffs; i+=4) { __m256d cosPhi_next = _mm256_add_pd(_mm256_mul_pd(factorPhi_prev, cosPhi_prev), _mm256_mul_pd(factorPhi_cur, cosPhi_cur)); Y = _mm256_add_pd(Y, _mm256_mul_pd(cosPhi_next, _mm256_cvtps_pd(_mm_load_ps(coeffs[0]+i)))); R = _mm256_add_pd(R, _mm256_mul_pd(cosPhi_next, _mm256_cvtps_pd(_mm_load_ps(coeffs[1]+i)))); B = _mm256_add_pd(B, _mm256_mul_pd(cosPhi_next, _mm256_cvtps_pd(_mm_load_ps(coeffs[2]+i)))); cosPhi_prev = _mm256_splat2_pd(cosPhi_next); cosPhi_cur = _mm256_splat3_pd(cosPhi_next); } MM_ALIGN32 struct { double Y; double R; double B; double unused; } tmp; simd::hadd(Y, R, B, _mm256_setzero_pd(), (double *) &tmp); double G = 1.39829*tmp.Y -0.100913*tmp.B - 0.297375*tmp.R; return Color3((Float) tmp.R, (Float) G, (Float) tmp.B); #endif } Float sampleFourier(const float *coeffs, const double *recip, size_t nCoeffs, Float sample, Float &pdf, Float &phi) { bool flip = false; if (sample < 0.5f) { sample *= 2.0f; } else { sample = 1.0f - 2.0f * (sample - 0.5f); flip = true; } int iterations = 0; double a = 0.0, c = math::Pi_d, coeff0 = coeffs[0], y = coeff0*math::Pi_d*sample, deriv = 0.0, b = 0.5 * math::Pi_d, sinB = 1, cosB = 0; if (nCoeffs > 10 && sample != 0 && sample != 1) { float stddev = std::sqrt(2.0f/3.0f * std::log(coeffs[1]/coeffs[2])); if (std::isfinite(stddev)) { b = std::min(c, (double) math::normal_quantile(0.5f + sample/2) * stddev); cosB = std::cos(b); sinB = std::sqrt(1-cosB*cosB); } } while (true) { #if FOURIER_SCALAR == 1 double cosB_prev = cosB, sinB_prev = -sinB, sinB_cur = 0.0, cosB_cur = 1.0, value = coeff0 * b; deriv = coeff0; for (size_t j=1; j<nCoeffs; ++j) { double sinB_next = 2.0*cosB*sinB_cur - sinB_prev, cosB_next = 2.0*cosB*cosB_cur - cosB_prev, coeff = (double) coeffs[j]; value += coeff * recip[j] * sinB_next; deriv += coeff * cosB_next; sinB_prev = sinB_cur; sinB_cur = sinB_next; cosB_prev = cosB_cur; cosB_cur = cosB_next; } #else __m256d factorB_prev, factorB_cur; initializeRecurrence(cosB, factorB_prev, factorB_cur); __m256d sinB_prev = _mm256_set1_pd(-sinB), sinB_cur = _mm256_set1_pd(0.0), cosB_prev = _mm256_set1_pd(cosB), cosB_cur = _mm256_set1_pd(1.0), value_vec = _mm256_set_sd(coeff0 * b), deriv_vec = _mm256_set_sd(coeff0); for (size_t j=1; j<nCoeffs; j+=4) { __m128 coeff_vec_f = _mm_load_ps(coeffs+j); __m256d recip_vec = _mm256_load_pd(recip+j); __m256d coeff_vec = _mm256_cvtps_pd(coeff_vec_f); __m256d sinB_next = _mm256_add_pd( _mm256_mul_pd(factorB_prev, sinB_prev), _mm256_mul_pd(factorB_cur, sinB_cur)); __m256d cosB_next = _mm256_add_pd( _mm256_mul_pd(factorB_prev, cosB_prev), _mm256_mul_pd(factorB_cur, cosB_cur)); value_vec = _mm256_add_pd(value_vec, _mm256_mul_pd( _mm256_mul_pd(recip_vec, coeff_vec), sinB_next)); deriv_vec = _mm256_add_pd(deriv_vec, _mm256_mul_pd(coeff_vec, cosB_next)); sinB_prev = _mm256_splat2_pd(sinB_next); cosB_prev = _mm256_splat2_pd(cosB_next); sinB_cur = _mm256_splat3_pd(sinB_next); cosB_cur = _mm256_splat3_pd(cosB_next); } double value = simd::hadd(value_vec); deriv = simd::hadd(deriv_vec); #endif value -= y; if (std::abs(value) <= 1e-5 * coeff0 || ++iterations > 20) break; else if (value > 0.0) c = b; else a = b; b -= value / deriv; if (!(b > a && b < c)) b = 0.5f * (a + c); cosB = std::cos(b); sinB = std::sqrt(1-cosB*cosB); } if (flip) b = 2.0*math::Pi_d - b; pdf = (Float) (math::InvTwoPi_d * deriv / coeff0); phi = (Float) b; return (Float) (coeff0*(2*math::Pi_d)); } Color3 sampleFourier3(float * const coeffs[3], const double *recip, size_t nCoeffs, Float sample, Float &pdf, Float &phi) { bool flip = false; if (sample < 0.5f) { sample *= 2.0f; } else { sample = 1.0f - 2.0f * (sample - 0.5f); flip = true; } int iterations = 0; double a = 0.0, c = math::Pi_d, coeff0 = coeffs[0][0], y = coeff0*math::Pi_d*sample, deriv = 0.0, b = 0.5 * math::Pi_d, cosB = 0, sinB = 1; if (nCoeffs > 10 && sample != 0 && sample != 1) { float stddev = std::sqrt(2.0f / 3.0f * std::log(coeffs[0][1] / coeffs[0][2])); if (std::isfinite(stddev)) { b = std::min(c, (double) math::normal_quantile(0.5f + sample / 2) * stddev); cosB = std::cos(b); sinB = std::sqrt(1 - cosB * cosB); } } #if FOURIER_SCALAR != 1 __m256d factorB_prev, factorB_cur; #endif while (true) { #if FOURIER_SCALAR == 1 double cosB_prev = cosB, sinB_prev = -sinB, sinB_cur = 0.0, cosB_cur = 1.0, value = coeff0 * b; deriv = coeff0; for (size_t j=1; j<nCoeffs; ++j) { double sinB_next = 2.0*cosB*sinB_cur - sinB_prev, cosB_next = 2.0*cosB*cosB_cur - cosB_prev, coeff = (double) coeffs[0][j]; value += coeff * recip[j] * sinB_next; deriv += coeff * cosB_next; sinB_prev = sinB_cur; sinB_cur = sinB_next; cosB_prev = cosB_cur; cosB_cur = cosB_next; } #else initializeRecurrence(cosB, factorB_prev, factorB_cur); __m256d sinB_prev = _mm256_set1_pd(-sinB), sinB_cur = _mm256_set1_pd(0.0), cosB_prev = _mm256_set1_pd(cosB), cosB_cur = _mm256_set1_pd(1.0), value_vec = _mm256_set_sd(coeff0 * b), deriv_vec = _mm256_set_sd(coeff0); for (size_t j=1; j<nCoeffs; j+=4) { __m128 coeff_vec_f = _mm_load_ps(coeffs[0]+j); __m256d recip_vec = _mm256_load_pd(recip+j); __m256d coeff_vec = _mm256_cvtps_pd(coeff_vec_f); __m256d sinB_next = _mm256_add_pd( _mm256_mul_pd(factorB_prev, sinB_prev), _mm256_mul_pd(factorB_cur, sinB_cur)); __m256d cosB_next = _mm256_add_pd( _mm256_mul_pd(factorB_prev, cosB_prev), _mm256_mul_pd(factorB_cur, cosB_cur)); value_vec = _mm256_add_pd(value_vec, _mm256_mul_pd( _mm256_mul_pd(recip_vec, coeff_vec), sinB_next)); deriv_vec = _mm256_add_pd(deriv_vec, _mm256_mul_pd(coeff_vec, cosB_next)); sinB_prev = _mm256_splat2_pd(sinB_next); cosB_prev = _mm256_splat2_pd(cosB_next); sinB_cur = _mm256_splat3_pd(sinB_next); cosB_cur = _mm256_splat3_pd(cosB_next); } double value = simd::hadd(value_vec); deriv = simd::hadd(deriv_vec); #endif value -= y; if (std::abs(value) <= 1e-5 * coeff0 || ++iterations > 20) break; else if (value > 0.0) c = b; else a = b; b -= value / deriv; if (!(b > a && b < c)) b = 0.5f * (a + c); cosB = std::cos(b); sinB = std::sqrt(1-cosB*cosB); } double Y = deriv; if (flip) b = 2.0*math::Pi_d - b; pdf = (Float) (math::InvTwoPi_d * Y / coeff0); phi = (Float) b; #if FOURIER_SCALAR == 1 double cosB_prev = cosB, cosB_cur = 1.0; double R = coeffs[1][0]; double B = coeffs[2][0]; for (size_t j=1; j<nCoeffs; ++j) { double cosB_next = 2.0*cosB*cosB_cur - cosB_prev, coeffR = (double) coeffs[1][j], coeffB = (double) coeffs[2][j]; R += coeffR * cosB_next; B += coeffB * cosB_next; cosB_prev = cosB_cur; cosB_cur = cosB_next; } #else __m256d cosB_prev = _mm256_set1_pd(cosB), cosB_cur = _mm256_set1_pd(1.0), R_vec = _mm256_set_sd(coeffs[1][0]), B_vec = _mm256_set_sd(coeffs[2][0]); for (size_t j=1; j<nCoeffs; j+=4) { __m128 coeff_R_vec_f = _mm_load_ps(coeffs[1]+j); __m128 coeff_B_vec_f = _mm_load_ps(coeffs[2]+j); __m256d coeff_R_vec = _mm256_cvtps_pd(coeff_R_vec_f); __m256d coeff_B_vec = _mm256_cvtps_pd(coeff_B_vec_f); __m256d cosB_next = _mm256_add_pd( _mm256_mul_pd(factorB_prev, cosB_prev), _mm256_mul_pd(factorB_cur, cosB_cur)); R_vec = _mm256_add_pd(R_vec, _mm256_mul_pd(coeff_R_vec, cosB_next)); B_vec = _mm256_add_pd(B_vec, _mm256_mul_pd(coeff_B_vec, cosB_next)); cosB_prev = _mm256_splat2_pd(cosB_next); cosB_cur = _mm256_splat3_pd(cosB_next); } double R = simd::hadd(R_vec); double B = simd::hadd(B_vec); #endif double G = 1.39829 * Y - 0.100913 * B - 0.297375 * R; return Color3((Float) R, (Float) G, (Float) B) * (2 * math::Pi) * (Float) (coeff0 / Y); } namespace { /// Filon integration over a single spline segment (used by filonIntegrate) inline void filon(Float phi[2], Float f[3], size_t lmax, Float *output) { Float h = phi[1] - phi[0], invH = 1/h; output[0] += (math::InvPi / 6.0) * h * (f[0]+4*f[1]+f[2]); Float cosPhi0Prev = std::cos(phi[0]), cosPhi0Cur = 1.0f, cosPhi1Prev = std::cos(phi[1]), cosPhi1Cur = 1.0f, sinPhi0Prev = -std::sin(phi[0]), sinPhi0Cur = 0.0f, sinPhi1Prev = -std::sin(phi[1]), sinPhi1Cur = 0.0f, twoCosPhi0 = 2.0f * cosPhi0Prev, twoCosPhi1 = 2.0f * cosPhi1Prev; const Float term0 = 3*f[0]-4*f[1]+f[2], term1 = f[0]-4*f[1]+3*f[2], term2 = 4*(f[0]-2*f[1]+f[2]); for (size_t l=1; l<lmax; ++l) { Float cosPhi0Next = twoCosPhi0*cosPhi0Cur - cosPhi0Prev, cosPhi1Next = twoCosPhi1*cosPhi1Cur - cosPhi1Prev, sinPhi0Next = twoCosPhi0*sinPhi0Cur - sinPhi0Prev, sinPhi1Next = twoCosPhi1*sinPhi1Cur - sinPhi1Prev; Float invL = 1 / (Float) l, invL2H = invH*invL*invL, invL3H2 = invL2H*invL*invH; output[l] += (2 * math::InvPi) * ((invL2H * (term0 * cosPhi0Next + term1 * cosPhi1Next) + invL3H2 * term2 * (sinPhi0Next - sinPhi1Next) + invL * (f[2] * sinPhi1Next - f[0] * sinPhi0Next))); cosPhi0Prev = cosPhi0Cur; cosPhi0Cur = cosPhi0Next; cosPhi1Prev = cosPhi1Cur; cosPhi1Cur = cosPhi1Next; sinPhi0Prev = sinPhi0Cur; sinPhi0Cur = sinPhi0Next; sinPhi1Prev = sinPhi1Cur; sinPhi1Cur = sinPhi1Next; } } }; void filonIntegrate(const std::function<Float(Float)> &f, Float *coeffs, size_t nCoeffs, int nEvals, Float a, Float b) { /* Avoid numerical overflow issues for extremely small intervals */ if (sizeof(Float) == sizeof(float)) { if (std::abs(b-a) < 1e-6) return; } else { if (std::abs(b-a) < 1e-15) return; } if (nEvals % 2 == 0) ++nEvals; Float value[3], phi[2], delta = (b-a) / (nEvals - 1); phi[0] = a; value[0] = f(a); for (int i=0; i<(nEvals-1)/2; ++i) { phi[1] = phi[0] + 2*delta; value[1] = f(phi[0] + delta); value[2] = f(phi[1]); filon(phi, value, nCoeffs, coeffs); value[0] = value[2]; phi[0] = phi[1]; } } void convolveFourier(const Float *a, size_t ka_, const Float *b, size_t kb_, Float *c) { ssize_t ka = (ssize_t) ka_, kb = (ssize_t) kb_; for (ssize_t i=0; i<ka+kb-1; ++i) { Float sum = 0; for (ssize_t j=0; j<std::min(kb, ka - i); ++j) sum += b[j]*a[i+j]; for (ssize_t j=std::max((ssize_t) 0, i-ka+1); j<std::min(kb, i+ka); ++j) sum += b[j]*a[std::abs(i - j)]; if (i < kb) sum += b[i]*a[0]; if (i == 0) sum = .5f * (sum + a[0]*b[0]); c[i] = .5f * sum; } } NAMESPACE_END(layer)
wjakob/layerlab
src/fourier.cpp
C++
bsd-2-clause
17,040
# PyVEX # Installing PyVEX PyVEX can be pip-installed: ```bash pip install pyvex ``` # Citing PyVEX If you use PyVEX in an academic work, please cite the paper for which it was developed: ```bibtex @article{shoshitaishvili2015firmalice, title={Firmalice - Automatic Detection of Authentication Bypass Vulnerabilities in Binary Firmware}, author={Shoshitaishvili, Yan and Wang, Ruoyu and Hauser, Christophe and Kruegel, Christopher and Vigna, Giovanni}, year={2015} } ``` # Using PyVEX PyVEX exposes VEX into Python. To understand VEX, read the "VEX Intermediate Representation" section below. ```python import pyvex import archinfo # translate an AMD64 basic block (of nops) at 0x400400 into VEX irsb = pyvex.IRSB("\x90\x90\x90\x90\x90", 0x400400, archinfo.ArchAMD64()) # pretty-print the basic block irsb.pp() # this is the IR Expression of the jump target of the unconditional exit at the end of the basic block print irsb.next # this is the type of the unconditional exit (i.e., a call, ret, syscall, etc) print irsb.jumpkind # you can also pretty-print it irsb.next.pp() # iterate through each statement and print all the statements for stmt in irsb.statements: stmt.pp() # pretty-print the IR expression representing the data, and the *type* of that IR expression written by every store statement import pyvex for stmt in irsb.statements: if isinstance(stmt, pyvex.IRStmt.Store): print "Data:", stmt.data.pp() print "" print "Type:", print stmt.data.result_type print "" # pretty-print the condition and jump target of every conditional exit from the basic block for stmt in irsb.statements: if isinstance(stmt, pyvex.IRStmt.Exit): print "Condition:", stmt.guard.pp() print "" print "Target:", stmt.dst.pp() print "" # these are the types of every temp in the IRSB print irsb.tyenv.types # here is one way to get the type of temp 0 print irsb.tyenv.types[0] ``` Keep in mind that this is a *syntactic* respresentation of a basic block. That is, it'll tell you what the block means, but you don't have any context to say, for example, what *actual* data is written by a store instruction. # VEX Intermediate Representation To deal with widely diverse architectures, it is useful to carry out analyses on an intermediate representation. An IR abstracts away several architecture differences when dealing with different architectures, allowing a single analysis to be run on all of them: - **Register names.** The quantity and names of registers differ between architectures, but modern CPU designs hold to a common theme: each CPU contains several general purpose registers, a register to hold the stack pointer, a set of registers to store condition flags, and so forth. The IR provides a consistent, abstracted interface to registers on different platforms. Specifically, VEX models the registers as a separate memory space, with integer offsets (i.e., AMD64's `rax` is stored starting at address 16 in this memory space). - **Memory access.** Different architectures access memory in different ways. For example, ARM can access memory in both little-endian and big-endian modes. The IR must abstracts away these differences. - **Memory segmentation.** Some architectures, such as x86, support memory segmentation through the use of special segment registers. The IR understands such memory access mechanisms. - **Instruction side-effects.** Most instructions have side-effects. For example, most operations in Thumb mode on ARM update the condition flags, and stack push/pop instructions update the stack pointer. Tracking these side-effects in an *ad hoc* manner in the analysis would be crazy, so the IR makes these effects explicit. There are lots of choices for an IR. We use VEX, since the uplifting of binary code into VEX is quite well supported. VEX is an architecture-agnostic, side-effects-free representation of a number of target machine languages. It abstracts machine code into a representation designed to make program analysis easier. This representation has four main classes of objects: - **Expressions.** IR Expressions represent a calculated or constant value. This includes memory loads, register reads, and results of arithmetic operations. - **Operations.** IR Operations describe a *modification* of IR Expressions. This includes integer arithmetic, floating-point arithmetic, bit operations, and so forth. An IR Operation applied to IR Expressions yields an IR Expression as a result. - **Temporary variables.** VEX uses temporary variables as internal registers: IR Expressions are stored in temporary variables between use. The content of a temporary variable can be retrieved using an IR Expression. These temporaries are numbered, starting at `t0`. These temporaries are strongly typed (i.e., "64-bit integer" or "32-bit float"). - **Statements.** IR Statements model changes in the state of the target machine, such as the effect of memory stores and register writes. IR Statements use IR Expressions for values they may need. For example, a memory store *IR Statement* uses an *IR Expression* for the target address of the write, and another *IR Expression* for the content. - **Blocks.** An IR Block is a collection of IR Statements, representing an extended basic block (termed "IR Super Block" or "IRSB") in the target architecture. A block can have several exits. For conditional exits from the middle of a basic block, a special *Exit* IR Statement is used. An IR Expression is used to represent the target of the unconditional exit at the end of the block. VEX IR is actually quite well documented in the `libvex_ir.h` file (https://github.com/angr/vex/blob/dev/pub/libvex_ir.h) in the VEX repository. For the lazy, we'll detail some parts of VEX that you'll likely interact with fairly frequently. To begin with, here are some IR Expressions: | IR Expression | Evaluated Value | VEX Output Example | | ------------- | --------------- | ------- | | Constant | A constant value. | 0x4:I32 | | Read Temp | The value stored in a VEX temporary variable. | RdTmp(t10) | | Get Register | The value stored in a register. | GET:I32(16) | | Load Memory | The value stored at a memory address, with the address specified by another IR Expression. | LDle:I32 / LDbe:I64 | | Operation | A result of a specified IR Operation, applied to specified IR Expression arguments. | Add32 | | If-Then-Else | If a given IR Expression evaluates to 0, return one IR Expression. Otherwise, return another. | ITE | | Helper Function | VEX uses C helper functions for certain operations, such as computing the conditional flags registers of certain architectures. These functions return IR Expressions. | function\_name() | These expressions are then, in turn, used in IR Statements. Here are some common ones: | IR Statement | Meaning | VEX Output Example | | ------------ | ------- | ------------------ | Write Temp | Set a VEX temporary variable to the value of the given IR Expression. | WrTmp(t1) = (IR Expression) | Put Register | Update a register with the value of the given IR Expression. | PUT(16) = (IR Expression) | Store Memory | Update a location in memory, given as an IR Expression, with a value, also given as an IR Expression. | STle(0x1000) = (IR Expression) | Exit | A conditional exit from a basic block, with the jump target specified by an IR Expression. The condition is specified by an IR Expression. | if (condition) goto (Boring) 0x4000A00:I32 | An example of an IR translation, on ARM, is produced below. In the example, the subtraction operation is translated into a single IR block comprising 5 IR Statements, each of which contains at least one IR Expression (although, in real life, an IR block would typically consist of more than one instruction). Register names are translated into numerical indices given to the *GET* Expression and *PUT* Statement. The astute reader will observe that the actual subtraction is modeled by the first 4 IR Statements of the block, and the incrementing of the program counter to point to the next instruction (which, in this case, is located at `0x59FC8`) is modeled by the last statement. The following ARM instruction: subs R2, R2, #8 Becomes this VEX IR: t0 = GET:I32(16) t1 = 0x8:I32 t3 = Sub32(t0,t1) PUT(16) = t3 PUT(68) = 0x59FC8:I32 Cool stuff!
avain/pyvex
README.md
Markdown
bsd-2-clause
8,325
#!/bin/bash docker run -it --rm -e DISPLAY=$DISPLAY --ipc host -v /tmp/.X11-unix:/tmp/.X11-unix -v $PWD:/home/angr/pwd angr/angr-management "$@"
Ruide/angr-dev
angr-management/run-docker.sh
Shell
bsd-2-clause
146
require 'gitlab' require 'terminal-table/import' require_relative 'cli_helpers' require_relative 'shell' class Gitlab::CLI extend Helpers # If set to true, JSON will be rendered as output @render_json = false # Starts a new CLI session. # # @example # Gitlab::CLI.start(['help']) # Gitlab::CLI.start(['help', 'issues']) # # @param [Array] args The command and it's optional arguments. def self.start(args) command = args.shift.strip rescue 'help' run(command, args) end # Processes a CLI command and outputs a result to the stream (stdout). # # @example # Gitlab::CLI.run('help') # Gitlab::CLI.run('help', ['issues']) # # @param [String] cmd The name of a command. # @param [Array] args The optional arguments for a command. # @return [nil] def self.run(cmd, args=[]) case cmd when 'help' puts help(args.shift) { |out| out.gsub!(/Gitlab\./, 'gitlab ') } when 'info' endpoint = Gitlab.endpoint ? Gitlab.endpoint : 'not set' private_token = Gitlab.private_token ? Gitlab.private_token : 'not set' puts "Gitlab endpoint is #{endpoint}" puts "Gitlab private token is #{private_token}" puts "Ruby Version is #{RUBY_VERSION}" puts "Gitlab Ruby Gem #{Gitlab::VERSION}" when '-v', '--version' puts "Gitlab Ruby Gem #{Gitlab::VERSION}" when 'shell' Gitlab::Shell.start else if args.include? '--json' @json_output = true args.delete '--json' end unless valid_command?(cmd) puts "Unknown command. Run `gitlab help` for a list of available commands." exit(1) end if args.any? && (args.last.start_with?('--only=') || args.last.start_with?('--except=')) command_args = args[0..-2] else command_args = args end begin command_args.map! { |arg| symbolize_keys(yaml_load(arg)) } rescue => e puts e.message exit 1 end confirm_command(cmd) data = gitlab_helper(cmd, command_args) { exit(1) } render_output(cmd, args, data) end end # Helper method that checks whether we want to get the output as json # return [nil] def self.render_output(cmd,args,data) if @json_output output_json(cmd, args, data) else output_table(cmd, args, data) end end end
michaellihs/gitlab
lib/gitlab/cli.rb
Ruby
bsd-2-clause
2,363
#include "Arduino.h" #include "Math.h" #include <lchica.h> #ifndef Arduino_h #define Arduino_h #endif #define RED_LED_NUM 4 #define BLUE_LED_NUM 2 #define YELLOW_LED_NUM 2 #define LED_PIN_NUM 8 #define CLOCKWISE true #define REVERSE false const int ledpin[LED_PIN_NUM]= {46,47,48,49,50,51,52,53}; const int blueledpin[BLUE_LED_NUM]={ledpin[0], ledpin[4]}; const int redledpin[RED_LED_NUM]={ledpin[1],ledpin[3],ledpin[5],ledpin[7]}; const int touchpin = 3; const int lightpin = 4; const int buzzerpin = 7; const int fingerpin = 8; const bool fadein = true; const bool fadeout = false; const bool fast = true; const bool slow = false; bool led_pinstate[LED_PIN_NUM] = {true, false,true,false,true,false,true,false}; void BuzzerOn(int pin){ digitalWrite(pin,HIGH); } void BuzzerOff(int pin){ digitalWrite(pin,LOW); } void ToggleLED(int pin){ if(led_pinstate[pin] == true) led_pinstate[pin] = false; else led_pinstate[pin] = true; digitalWrite(pin, led_pinstate[pin]); } bool isTouched(int pin){ if(digitalRead(pin)) return true; else return false; } bool isLight(int pin){ if(digitalRead(pin)) return true; else return false; } void setLight(int pin){ bool state[LED_PIN_NUM]; for(int i =0; i < LED_PIN_NUM; i++){ state[i] = false; } state[pin] = true; for(int i=0; i < LED_PIN_NUM; i++){ digitalWrite(ledpin[i],state[i]); } } bool isFinger(int pin){ if(digitalRead(pin)) return true; else return false; } void fadeLight(double hz, bool rotate, bool vel, bool dir){ bool state[LED_PIN_NUM]; if(dir){ for(int i=0; i < LED_PIN_NUM; i++){ state[i] = true; } } else{ for(int i=0; i < LED_PIN_NUM; i++){ state[i] = false; } } for(int j =0; j < LED_PIN_NUM;j++){ digitalWrite(ledpin[j],state[j]); } if(isTouched(touchpin) || isFinger(fingerpin)) return; delay(1000/hz); if(rotate){ for(int i =0; i < LED_PIN_NUM;i++){ if(dir){ state[i] = false; } else{ state[i] = true; } for(int j =0; j < LED_PIN_NUM;j++){ digitalWrite(ledpin[j],state[j]); } if(isTouched(touchpin)) break; if(vel){ hz--; } else hz++; double time = 1000 / exp(log(hz)); delay(time); } } else{ for(int i =0; i < LED_PIN_NUM;i++){ if(dir){ state[LED_PIN_NUM - i] = false; } else { state[LED_PIN_NUM-i] = true; } for(int j =0; j < LED_PIN_NUM;j++){ digitalWrite(ledpin[j],state[j]); } if(isTouched(touchpin)) break; if(vel){ hz--; } else hz++; double time = 1000 / exp(log(hz)); delay(time); } } } void spinLight(){ bool state[LED_PIN_NUM]; for(int i =0; i < LED_PIN_NUM; i++){ for(int j =0; j < LED_PIN_NUM; j++){ state[j] = false; } state[i] = true; for(int j = 0; j < LED_PIN_NUM;j++){ digitalWrite(ledpin[j],state[j]); } if(isTouched(touchpin)) break; delay(200); } } double i = 0; void LightOff(){ bool state[LED_PIN_NUM]; for(int i = 0; i < LED_PIN_NUM; i++){ state[i] = false; digitalWrite(ledpin[i],state[i]); } } void BlueLight(){ bool state[LED_PIN_NUM]; LightOff(); state[0] = true; state[4] = true; for(int i = 0; i < LED_PIN_NUM; i++){ digitalWrite(ledpin[i], state[i]); } } void Emergency(){ i += 0.07; bool state[LED_PIN_NUM]; for(int i = 0; i < LED_PIN_NUM; i++) state[i] = false; state[1] = true; state[3] = true; state[7] = true; for(int i = 0; i < LED_PIN_NUM; i++){ digitalWrite(ledpin[i], state[i]); } BuzzerOn(buzzerpin); delay(exp(6.214 - i) + 20); state[1] = false; state[3] = false; state[7] = false; for(int i = 0; i < LED_PIN_NUM; i++){ digitalWrite(ledpin[i], state[i]); } BuzzerOff(buzzerpin); delay(exp(6.214 - i) + 20); } void Nuregress(){ Serial.println("Nugress start"); static int point = 0; while(true){ if(isFinger(fingerpin)) point++; Serial.print("point:"); Serial.print(point); BlueLight(); BuzzerOn(buzzerpin); delay(50); if(isTouched(touchpin)){ Serial.print("final point:"); Serial.print(point); point = 0; } if(isFinger(fingerpin)){ delay(50); point++; BuzzerOff(buzzerpin); delay(50); continue; } LightOff(); BuzzerOff(buzzerpin); delay(50); } BuzzerOff(buzzerpin); Serial.println("Nugress end"); delay(1000); } const int baud = 115200; void setup(){ pinMode(ledpin[0],OUTPUT); pinMode(ledpin[1],OUTPUT); pinMode(ledpin[2],OUTPUT); pinMode(ledpin[3],OUTPUT); pinMode(ledpin[4],OUTPUT); pinMode(ledpin[5],OUTPUT); pinMode(ledpin[6],OUTPUT); pinMode(ledpin[7],OUTPUT); pinMode(touchpin,INPUT); pinMode(lightpin,INPUT); pinMode(buzzerpin,OUTPUT); pinMode(fingerpin,INPUT); Serial.begin(115200); } int point = 0; void Point(){ point++; //BlueLightOn(); BuzzerOn(buzzerpin); delay(100); BuzzerOff(buzzerpin); //BlueLightOff(); Serial.print("point;"); Serial.print(point); Serial.print("\n"); Serial.flush(); delay(100); } void loop(){ if(isFinger(fingerpin)){ Point(); } if(isLight(lightpin)){ if(isTouched(touchpin)){ //Nuregress(); Emergency(); } else{ fadeLight(9,CLOCKWISE,fast,fadein); fadeLight(1,REVERSE,slow,fadeout); fadeLight(9,CLOCKWISE,slow,fadein); fadeLight(1,REVERSE,fast,fadeout); } } else{ spinLight();//NightMode(); } delay(100); }
kendemu/kasadas-bohan
lchica.cpp
C++
bsd-2-clause
5,652
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: The Date.prototype has the property "getFullYear" esid: sec-properties-of-the-date-prototype-object es5id: 15.9.5_A10_T1 description: The Date.prototype has the property "getFullYear" ---*/ if (Date.prototype.hasOwnProperty("getFullYear") !== true) { $ERROR('#1: The Date.prototype has the property "getFullYear"'); }
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Date/prototype/S15.9.5_A10_T1.js
JavaScript
bsd-2-clause
466
/******************************************************************************* * Copyright (c) 2013-2015 Sierra Wireless and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.html. * * Contributors: * Sierra Wireless - initial API and implementation *******************************************************************************/ package org.eclipse.leshan.server; public interface Startable { void start(); }
iotoasis/SI
si-modules/LWM2M_IPE_Server/leshan-server-core/src/main/java/org/eclipse/leshan/server/Startable.java
Java
bsd-2-clause
814
/* * Copyright (C) Igor Sysoev * Copyright (C) Nginx, Inc. */ #ifndef _NGX_BUF_H_INCLUDED_ #define _NGX_BUF_H_INCLUDED_ #include <ngx_config.h> #include <ngx_core.h> typedef void * ngx_buf_tag_t; typedef struct ngx_buf_s ngx_buf_t; // http://book.51cto.com/art/201303/386653.htm struct ngx_buf_s { /* posͨ³£ÊÇÓÃÀ´¸æËßʹÓÃÕß±¾´ÎÓ¦¸Ã´ÓposÕâ¸öλÖÿªÊ¼´¦ÀíÄÚ´æÖеÄÊý¾Ý£¬ ÕâÑùÉèÖÃÊÇÒòΪͬһ¸öngx_buf_t¿ÉÄܱ»¶à´Î·´¸´´¦Àí¡£ µ±È»£¬posµÄº¬ÒåÊÇÓÉʹÓÃËüµÄÄ£¿é¶¨ÒåµÄ */ u_char *pos; /* lastͨ³£±íʾÓÐЧµÄÄÚÈݵ½´ËΪֹ£¬ ×¢Ò⣬posÓëlastÖ®¼äµÄÄÚ´æÊÇÏ£Íûnginx´¦ÀíµÄÄÚÈÝ */ u_char *last; /* ´¦ÀíÎļþʱ£¬file_posÓëfile_lastµÄº¬ÒåÓë´¦ÀíÄÚ´æÊ±µÄposÓëlastÏàͬ£¬ file_pos±íʾ½«Òª´¦ÀíµÄÎļþλÖã¬file_last±íʾ½ØÖ¹µÄÎļþλÖà */ off_t file_pos; off_t file_last; // Èç¹ûngx_buf_t»º³åÇøÓÃÓÚÄڴ棬ÄÇôstartÖ¸ÏòÕâ¶ÎÄÚ´æµÄÆðʼµØÖ· u_char *start; /* start of buffer */ // Óëstart³ÉÔ±¶ÔÓ¦£¬Ö¸Ïò»º³åÇøÄÚ´æµÄĩβ u_char *end; /* end of buffer */ /*±íʾµ±Ç°»º³åÇøµÄÀàÐÍ£¬ÀýÈçÓÉÄĸöÄ£¿éʹÓþÍÖ¸ÏòÕâ¸öÄ£¿éngx_module_t±äÁ¿µÄµØÖ·*/ ngx_buf_tag_t tag; // ÒýÓõÄÎļþ ngx_file_t *file; /* µ±Ç°»º³åÇøµÄÓ°×Ó»º³åÇø£¬¸Ã³ÉÔ±ºÜÉÙÓõ½£¬ ½ö½öÔÚ12.8½ÚÃèÊöµÄʹÓûº³åÇø×ª·¢ÉÏÓηþÎñÆ÷µÄÏìӦʱ²ÅʹÓÃÁËshadow³ÉÔ±£¬ ÕâÊÇÒòΪNginxÌ«½ÚÔ¼ÄÚ´æÁË£¬ ·ÖÅäÒ»¿éÄڴ沢ʹÓÃngx_buf_t±íʾ½ÓÊÕµ½µÄÉÏÓηþÎñÆ÷ÏìÓ¦ºó£¬ ÔÚÏòÏÂÓοͻ§¶Ëת·¢Ê±¿ÉÄÜ»á°ÑÕâ¿éÄÚ´æ´æ´¢µ½ÎļþÖУ¬ Ò²¿ÉÄÜÖ±½ÓÏòÏÂÓη¢ËÍ£¬´ËʱNginx¾ø²»»áÖØÐ¸´ÖÆÒ»·ÝÄÚ´æÓÃÓÚеÄÄ¿µÄ£¬ ¶øÊÇÔٴν¨Á¢Ò»¸öngx_buf_t½á¹¹ÌåÖ¸ÏòÔ­Äڴ棬 ÕâÑù¶à¸öngx_buf_t½á¹¹ÌåÖ¸ÏòÁËͬһ¿éÄڴ棬 ËüÃÇÖ®¼äµÄ¹ØÏµ¾Íͨ¹ýshadow³ÉÔ±À´ÒýÓᣠÕâÖÖÉè¼Æ¹ýÓÚ¸´ÔÓ£¬Í¨³£²»½¨ÒéʹÓà */ ngx_buf_t *shadow; // ÁÙʱÄÚ´æ±ê־λ£¬Îª1ʱ±íʾÊý¾ÝÔÚÄÚ´æÖÐÇÒÕâ¶ÎÄÚ´æ¿ÉÒÔÐÞ¸Ä /* the buf's content could be changed */ unsigned temporary:1; /* * the buf's content is in a memory cache or in a read only memory * and must not be changed */ // ±ê־λ£¬Îª1ʱ±íʾÊý¾ÝÔÚÄÚ´æÖÐÇÒÕâ¶ÎÄÚ´æ²»¿ÉÒÔ±»ÐÞ¸Ä unsigned memory:1; /* the buf's content is mmap()ed and must not be changed */ // ±ê־λ£¬Îª1ʱ±íʾÕâ¶ÎÄÚ´æÊÇÓÃmmapϵͳµ÷ÓÃÓ³Éä¹ýÀ´µÄ£¬²»¿ÉÒÔ±»ÐÞ¸Ä unsigned mmap:1; // ±ê־λ£¬Îª1ʱ±íʾ¿É»ØÊÕ unsigned recycled:1; // ±ê־λ£¬Îª1ʱ±íʾÕâ¶Î»º³åÇø´¦ÀíµÄÊÇÎļþ¶ø²»ÊÇÄÚ´æ unsigned in_file : 1; unsigned flush:1;// ±ê־λ£¬Îª1ʱ±íʾÐèÒªÖ´ÐÐflush²Ù×÷ /* ±ê־룬¶ÔÓÚ²Ù×÷Õâ¿é»º³åÇøÊ±ÊÇ·ñʹÓÃͬ²½·½Ê½£¬ Ðè½÷É÷¿¼ÂÇ£¬Õâ¿ÉÄÜ»á×èÈûNginx½ø³Ì£¬ NginxÖÐËùÓвÙ×÷¼¸ºõ¶¼ÊÇÒì²½µÄ£¬ÕâÊÇËüÖ§³Ö¸ß²¢·¢µÄ¹Ø¼ü¡£ ÓÐЩ¿ò¼Ü´úÂëÔÚsyncΪ1ʱ¿ÉÄÜ»áÓÐ×èÈûµÄ·½Ê½½øÐÐI/O²Ù×÷£¬ ËüµÄÒâÒåÊÓʹÓÃËüµÄNginxÄ£¿é¶ø¶¨ */ unsigned sync:1; /* ±ê־룬±íʾÊÇ·ñÊÇ×îºóÒ»¿é»º³åÇø£¬ ÒòΪngx_buf_t¿ÉÒÔÓÉngx_chain_tÁ´±í´®ÁªÆðÀ´£¬ Òò´Ë£¬µ±last_bufΪ1ʱ£¬±íʾµ±Ç°ÊÇ×îºóÒ»¿é´ý´¦ÀíµÄ»º³åÇø */ unsigned last_buf:1; // ±ê־룬±íʾÊÇ·ñÊÇngx_chain_tÖеÄ×îºóÒ»¿é»º³åÇø unsigned last_in_chain:1; /* ±ê־룬±íʾÊÇ·ñÊÇ×îºóÒ»¸öÓ°×Ó»º³åÇø£¬ÓëshadowÓòÅäºÏʹÓá£Í¨³£²»½¨ÒéʹÓÃËü */ unsigned last_shadow:1; // ±ê־룬±íʾµ±Ç°»º³åÇøÊÇ·ñÊôÓÚÁÙʱÎļþ unsigned temp_file:1; /* STUB */ int num; }; struct ngx_chain_s { ngx_buf_t *buf; ngx_chain_t *next; }; typedef struct { ngx_int_t num; size_t size; } ngx_bufs_t; typedef struct ngx_output_chain_ctx_s ngx_output_chain_ctx_t; typedef ngx_int_t (*ngx_output_chain_filter_pt)(void *ctx, ngx_chain_t *in); #if (NGX_HAVE_FILE_AIO) typedef void (*ngx_output_chain_aio_pt)(ngx_output_chain_ctx_t *ctx, ngx_file_t *file); #endif struct ngx_output_chain_ctx_s { ngx_buf_t *buf; // ±£´æÁÙʱµÄbuf ngx_chain_t *in; // ±£´æÁ˽«Òª·¢Ë͵Ächain ngx_chain_t *free; //±£´æÁËÒѾ­·¢ËÍÍê±ÏµÄchain£¬ÒÔ±ãÓÚÖØ¸´ÀûÓà // ±£´æÁË»¹Î´·¢Ë͵Ächain ngx_chain_t *busy; // sendfile±ê¼Ç unsigned sendfile:1; // directio±ê¼Ç unsigned directio:1; #if (NGX_HAVE_ALIGNED_DIRECTIO) unsigned unaligned:1; #endif // ÊÇ·ñÐèÒªÔÚÄÚ´æÖб£´æÒ»·Ý // (ʹÓÃsendfileµÄ»°£¬ÄÚ´æÖÐûÓÐÎļþµÄ¿½±´µÄ£¬ // ¶øÎÒÃÇÓÐʱÐèÒª´¦ÀíÎļþ£¬´Ëʱ¾ÍÐèÒªÉèÖÃÕâ¸ö±ê¼Ç) unsigned need_in_memory:1; // ÊÇ·ñ´æÔÚµÄbuf¸´ÖÆÒ»·Ý£¬ÕâÀï²»¹ÜÊÇ´æÔÚÔÚÄڴ滹ÊÇÎļþ£¬ // ºóÃæ»á¿´µ½ÕâÁ½¸ö±ê¼ÇµÄÇø±ð¡£ unsigned need_in_temp:1; #if (NGX_HAVE_FILE_AIO || NGX_THREADS) unsigned aio:1; #endif #if (NGX_HAVE_FILE_AIO) ngx_output_chain_aio_pt aio_handler; #if (NGX_HAVE_AIO_SENDFILE) ssize_t (*aio_preload)(ngx_buf_t *file); #endif #endif #if (NGX_THREADS) ngx_int_t (*thread_handler)(ngx_thread_task_t *task, ngx_file_t *file); ngx_thread_task_t *thread_task; #endif off_t alignment; ngx_pool_t *pool; // ÒѾ­allocatedµÄ´óС ngx_int_t allocated; // ¶ÔÓ¦µÄbufsµÄ´óС£¬Õâ¸öÖµ¾ÍÊÇÎÒÃÇloc confÖÐÉèÖõÄbufs ngx_bufs_t bufs; // ±íʾÏÖÔÚ´¦ÓÚÄǸöÄ£¿é£¨ÒòΪupstreamÒ²»áµ÷ÓÃoutput_chain) ngx_buf_tag_t tag; // Õâ¸öÖµÒ»°ãÊÇngx_http_next_filter,Ò²¾ÍÊǼÌÐøµ÷ÓÃfilterÁ´ ngx_output_chain_filter_pt output_filter; // µ±Ç°filterµÄÉÏÏÂÎÄ£¬ÕâÀïÒ²ÊÇÓÉÓÚupstreamÒ²»áµ÷ÓÃoutput_chain void *filter_ctx; }; typedef struct { ngx_chain_t *out; ngx_chain_t **last; ngx_connection_t *connection; ngx_pool_t *pool; off_t limit; } ngx_chain_writer_ctx_t; #define NGX_CHAIN_ERROR (ngx_chain_t *) NGX_ERROR #define ngx_buf_in_memory(b) (b->temporary || b->memory || b->mmap) #define ngx_buf_in_memory_only(b) (ngx_buf_in_memory(b) && !b->in_file) // ·µ»Ø¸ÃbufÊÇ·ñÊÇÒ»¸öÌØÊâµÄbuf£¬Ö»º¬ÓÐÌØÊâµÄ±êÖ¾ºÍûÓаüº¬ÕæÕýµÄÊý¾Ý #define ngx_buf_special(b) \ ((b->flush || b->last_buf || b->sync) \ && !ngx_buf_in_memory(b) && !b->in_file) #define ngx_buf_sync_only(b) \ (b->sync \ && !ngx_buf_in_memory(b) && !b->in_file && !b->flush && !b->last_buf) #define ngx_buf_size(b) \ (ngx_buf_in_memory(b) ? (off_t) (b->last - b->pos): \ (b->file_last - b->file_pos)) ngx_buf_t *ngx_create_temp_buf(ngx_pool_t *pool, size_t size); ngx_chain_t *ngx_create_chain_of_bufs(ngx_pool_t *pool, ngx_bufs_t *bufs); #define ngx_alloc_buf(pool) ngx_palloc(pool, sizeof(ngx_buf_t)) #define ngx_calloc_buf(pool) ngx_pcalloc(pool, sizeof(ngx_buf_t)) ngx_chain_t *ngx_alloc_chain_link(ngx_pool_t *pool); // Á´½Óclµ½pool->chainÖÐ #define ngx_free_chain(pool, cl) \ cl->next = pool->chain; \ pool->chain = cl ngx_int_t ngx_output_chain(ngx_output_chain_ctx_t *ctx, ngx_chain_t *in); ngx_int_t ngx_chain_writer(void *ctx, ngx_chain_t *in); ngx_int_t ngx_chain_add_copy(ngx_pool_t *pool, ngx_chain_t **chain, ngx_chain_t *in); ngx_chain_t *ngx_chain_get_free_buf(ngx_pool_t *p, ngx_chain_t **free); void ngx_chain_update_chains(ngx_pool_t *p, ngx_chain_t **free, ngx_chain_t **busy, ngx_chain_t **out, ngx_buf_tag_t tag); off_t ngx_chain_coalesce_file(ngx_chain_t **in, off_t limit); ngx_chain_t *ngx_chain_update_sent(ngx_chain_t *in, off_t sent); #endif /* _NGX_BUF_H_INCLUDED_ */
songbingyu/nginx1.8-annotated
src/core/ngx_buf.h
C
bsd-2-clause
7,874
/* * Show the TPM capability information * * Copyright (c) 2016, Wind River Systems, Inc. * All rights reserved. * * See "LICENSE" for license terms. * * Author: * Jia Zhang <zhang.jia@linux.alibaba.com> */ #include <efi.h> #include <efilib.h> #include <tcg2.h> EFI_STATUS efi_main(EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE *Systab) { InitializeLib(ImageHandle, Systab); UINT8 TpmCapabilitySize = 0; EFI_STATUS Status; Status = Tcg2GetCapability(NULL, &TpmCapabilitySize); if (EFI_ERROR(Status)) return Status; EFI_TCG2_BOOT_SERVICE_CAPABILITY *TpmCapability; TpmCapability = AllocatePool(TpmCapabilitySize); if (!TpmCapability) return Status; Status = Tcg2GetCapability(TpmCapability, &TpmCapabilitySize); if (EFI_ERROR(Status)) goto out; if (TpmCapability->StructureVersion.Major == 1 && TpmCapability->StructureVersion.Minor == 0) { TREE_BOOT_SERVICE_CAPABILITY *TrEECapability; TrEECapability = (TREE_BOOT_SERVICE_CAPABILITY *)TpmCapability; Print(L"Structure Size: %d-byte\n", (UINT8)TrEECapability->Size); Print(L"Structure Version: %d.%d\n", (UINT8)TrEECapability->StructureVersion.Major, (UINT8)TrEECapability->StructureVersion.Minor); Print(L"Protocol Version: %d.%d\n", (UINT8)TrEECapability->ProtocolVersion.Major, (UINT8)TrEECapability->ProtocolVersion.Minor); UINT32 Hash = TrEECapability->HashAlgorithmBitmap; Print(L"Supported Hash Algorithm: 0x%x (%s%s%s%s%s)\n", Hash, Hash & TREE_BOOT_HASH_ALG_SHA1 ? L"SHA-1" : L"", Hash & TREE_BOOT_HASH_ALG_SHA256 ? L" SHA-256" : L"", Hash & TREE_BOOT_HASH_ALG_SHA384 ? L" SHA-384" : L"", Hash & TREE_BOOT_HASH_ALG_SHA512 ? L" SHA-512" : L"", (Hash & ~TREE_BOOT_HASH_ALG_MASK) || !Hash ? L" dirty" : L""); EFI_TCG2_EVENT_LOG_BITMAP Format = TrEECapability->SupportedEventLogs; Print(L"Supported Event Log Format: 0x%x (%s%s%s)\n", Format, Format & TREE_EVENT_LOG_FORMAT_TCG_1_2 ? L"TCG1.2" : L"", (Format & ~TREE_EVENT_LOG_FORMAT_MASK) || !Format ? L" dirty" : L""); Print(L"TrEE Present: %s\n", TrEECapability->TrEEPresentFlag ? L"True" : L"False"); Print(L"Max Command Size: %d-byte\n", TrEECapability->MaxCommandSize); Print(L"Max Response Size: %d-byte\n", TrEECapability->MaxResponseSize); Print(L"Manufacturer ID: 0x%x\n", TrEECapability->ManufacturerID); } else if (TpmCapability->StructureVersion.Major == 1 && TpmCapability->StructureVersion.Minor == 1) { Print(L"Structure Size: %d-byte\n", TpmCapability->Size); Print(L"Structure Version: %d.%d\n", TpmCapability->StructureVersion.Major, TpmCapability->StructureVersion.Minor); Print(L"Protocol Version: %d.%d\n", TpmCapability->ProtocolVersion.Major, TpmCapability->ProtocolVersion.Minor); UINT8 Hash = TpmCapability->HashAlgorithmBitmap; Print(L"Supported Hash Algorithm: 0x%x (%s%s%s%s%s%s)\n", Hash, Hash & EFI_TCG2_BOOT_HASH_ALG_SHA1 ? L"SHA-1" : L"", Hash & EFI_TCG2_BOOT_HASH_ALG_SHA256 ? L" SHA-256" : L"", Hash & EFI_TCG2_BOOT_HASH_ALG_SHA384 ? L" SHA-384" : L"", Hash & EFI_TCG2_BOOT_HASH_ALG_SHA512 ? L" SHA-512" : L"", Hash & EFI_TCG2_BOOT_HASH_ALG_SM3_256 ? L" SM3-256" : L"", (Hash & ~EFI_TCG2_BOOT_HASH_ALG_MASK) || !Hash ? L" dirty" : L""); EFI_TCG2_EVENT_LOG_BITMAP Format = TpmCapability->SupportedEventLogs; Print(L"Supported Event Log Format: 0x%x (%s%s%s)\n", Format, Format & EFI_TCG2_EVENT_LOG_FORMAT_TCG_1_2 ? L"TCG1.2" : L"", Format & EFI_TCG2_EVENT_LOG_FORMAT_TCG_2 ? L" TCG2.0" : L"", (Format & ~EFI_TCG2_EVENT_LOG_FORMAT_MASK) || !Format ? L" dirty" : L""); Print(L"TPM Present: %s\n", TpmCapability->TPMPresentFlag ? L"True" : L"False"); Print(L"Max Command Size: %d-byte\n", TpmCapability->MaxCommandSize); Print(L"Max Response Size: %d-byte\n", TpmCapability->MaxResponseSize); Print(L"Manufacturer ID: 0x%x\n", TpmCapability->ManufacturerID); Print(L"Number of PCR Banks: %d%s\n", TpmCapability->NumberOfPcrBanks, !TpmCapability->NumberOfPcrBanks ? L"(dirty)" : L""); EFI_TCG2_EVENT_ALGORITHM_BITMAP Bank = TpmCapability->ActivePcrBanks; Print(L"Active PCR Banks: 0x%x (%s%s%s%s%s%s)\n", Bank, Bank & EFI_TCG2_BOOT_HASH_ALG_SHA1 ? L"SHA-1" : L"", Bank & EFI_TCG2_BOOT_HASH_ALG_SHA256 ? L" SHA-256" : L"", Bank & EFI_TCG2_BOOT_HASH_ALG_SHA384 ? L" SHA-384" : L"", Bank & EFI_TCG2_BOOT_HASH_ALG_SHA512 ? L" SHA-512" : L"", Bank & EFI_TCG2_BOOT_HASH_ALG_SM3_256 ? L" SM3-256" : L"", (Bank & ~EFI_TCG2_BOOT_HASH_ALG_MASK) || !Bank ? L" dirty" : L""); } else { Print(L"Unsupported structure version: %d.%d\n", TpmCapability->StructureVersion.Major, TpmCapability->StructureVersion.Minor); Status = EFI_UNSUPPORTED; } out: FreePool(TpmCapability); return Status; }
jiazhang0/efi-tpm2-utils
src/efi/tpm2-capability.c
C
bsd-2-clause
5,087
// Copyright 2014 BVLC and contributors. #include <stdint.h> // for uint32_t & uint64_t #include <time.h> #include <climits> #include <cmath> // for std::fabs #include <cstdlib> // for rand_r #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/test/test_caffe_main.hpp" namespace caffe { template<typename Dtype> class MathFunctionsTest : public ::testing::Test { protected: MathFunctionsTest() : blob_bottom_(new Blob<Dtype>()), blob_top_(new Blob<Dtype>()) { } virtual void SetUp() { Caffe::set_random_seed(1701); this->blob_bottom_->Reshape(11, 17, 19, 23); this->blob_top_->Reshape(11, 17, 19, 23); // fill the values FillerParameter filler_param; GaussianFiller<Dtype> filler(filler_param); filler.Fill(this->blob_bottom_); filler.Fill(this->blob_top_); } virtual ~MathFunctionsTest() { delete blob_bottom_; delete blob_top_; } // http://en.wikipedia.org/wiki/Hamming_distance int ReferenceHammingDistance(const int n, const Dtype* x, const Dtype* y) { int dist = 0; uint64_t val; for (int i = 0; i < n; ++i) { if (sizeof(Dtype) == 8) { val = static_cast<uint64_t>(x[i]) ^ static_cast<uint64_t>(y[i]); } else if (sizeof(Dtype) == 4) { val = static_cast<uint32_t>(x[i]) ^ static_cast<uint32_t>(y[i]); } else { LOG(FATAL) << "Unrecognized Dtype size: " << sizeof(Dtype); } // Count the number of set bits while (val) { ++dist; val &= val - 1; } } return dist; } Blob<Dtype>* const blob_bottom_; Blob<Dtype>* const blob_top_; }; typedef ::testing::Types<float, double> Dtypes; TYPED_TEST_CASE(MathFunctionsTest, Dtypes); TYPED_TEST(MathFunctionsTest, TestNothing) { // The first test case of a test suite takes the longest time // due to the set up overhead. } TYPED_TEST(MathFunctionsTest, TestHammingDistanceCPU) { int n = this->blob_bottom_->count(); const TypeParam* x = this->blob_bottom_->cpu_data(); const TypeParam* y = this->blob_top_->cpu_data(); EXPECT_EQ(this->ReferenceHammingDistance(n, x, y), caffe_cpu_hamming_distance<TypeParam>(n, x, y)); } // TODO: Fix caffe_gpu_hamming_distance and re-enable this test. TYPED_TEST(MathFunctionsTest, DISABLED_TestHammingDistanceGPU) { int n = this->blob_bottom_->count(); const TypeParam* x = this->blob_bottom_->cpu_data(); const TypeParam* y = this->blob_top_->cpu_data(); int reference_distance = this->ReferenceHammingDistance(n, x, y); x = this->blob_bottom_->gpu_data(); y = this->blob_top_->gpu_data(); int computed_distance = caffe_gpu_hamming_distance<TypeParam>(n, x, y); EXPECT_EQ(reference_distance, computed_distance); } TYPED_TEST(MathFunctionsTest, TestAsumCPU) { int n = this->blob_bottom_->count(); const TypeParam* x = this->blob_bottom_->cpu_data(); TypeParam std_asum = 0; for (int i = 0; i < n; ++i) { std_asum += std::fabs(x[i]); } TypeParam cpu_asum = caffe_cpu_asum<TypeParam>(n, x); EXPECT_LT((cpu_asum - std_asum) / std_asum, 1e-2); } TYPED_TEST(MathFunctionsTest, TestAsumGPU) { int n = this->blob_bottom_->count(); const TypeParam* x = this->blob_bottom_->cpu_data(); TypeParam std_asum = 0; for (int i = 0; i < n; ++i) { std_asum += std::fabs(x[i]); } TypeParam gpu_asum; caffe_gpu_asum<TypeParam>(n, this->blob_bottom_->gpu_data(), &gpu_asum); EXPECT_LT((gpu_asum - std_asum) / std_asum, 1e-2); } TYPED_TEST(MathFunctionsTest, TestSignCPU) { int n = this->blob_bottom_->count(); const TypeParam* x = this->blob_bottom_->cpu_data(); caffe_cpu_sign<TypeParam>(n, x, this->blob_bottom_->mutable_cpu_diff()); const TypeParam* signs = this->blob_bottom_->cpu_diff(); for (int i = 0; i < n; ++i) { EXPECT_EQ(signs[i], x[i] > 0 ? 1 : (x[i] < 0 ? -1 : 0)); } } TYPED_TEST(MathFunctionsTest, TestSignGPU) { int n = this->blob_bottom_->count(); caffe_gpu_sign<TypeParam>(n, this->blob_bottom_->gpu_data(), this->blob_bottom_->mutable_gpu_diff()); const TypeParam* signs = this->blob_bottom_->cpu_diff(); const TypeParam* x = this->blob_bottom_->cpu_data(); for (int i = 0; i < n; ++i) { EXPECT_EQ(signs[i], x[i] > 0 ? 1 : (x[i] < 0 ? -1 : 0)); } } TYPED_TEST(MathFunctionsTest, TestSgnbitCPU) { int n = this->blob_bottom_->count(); const TypeParam* x = this->blob_bottom_->cpu_data(); caffe_cpu_sgnbit<TypeParam>(n, x, this->blob_bottom_->mutable_cpu_diff()); const TypeParam* signbits = this->blob_bottom_->cpu_diff(); for (int i = 0; i < n; ++i) { EXPECT_EQ(signbits[i], x[i] < 0 ? 1 : 0); } } TYPED_TEST(MathFunctionsTest, TestSgnbitGPU) { int n = this->blob_bottom_->count(); caffe_gpu_sgnbit<TypeParam>(n, this->blob_bottom_->gpu_data(), this->blob_bottom_->mutable_gpu_diff()); const TypeParam* signbits = this->blob_bottom_->cpu_diff(); const TypeParam* x = this->blob_bottom_->cpu_data(); for (int i = 0; i < n; ++i) { EXPECT_EQ(signbits[i], x[i] < 0 ? 1 : 0); } } TYPED_TEST(MathFunctionsTest, TestFabsCPU) { int n = this->blob_bottom_->count(); const TypeParam* x = this->blob_bottom_->cpu_data(); caffe_cpu_fabs<TypeParam>(n, x, this->blob_bottom_->mutable_cpu_diff()); const TypeParam* abs_val = this->blob_bottom_->cpu_diff(); for (int i = 0; i < n; ++i) { EXPECT_EQ(abs_val[i], x[i] > 0 ? x[i] : -x[i]); } } TYPED_TEST(MathFunctionsTest, TestFabsGPU) { int n = this->blob_bottom_->count(); caffe_gpu_fabs<TypeParam>(n, this->blob_bottom_->gpu_data(), this->blob_bottom_->mutable_gpu_diff()); const TypeParam* abs_val = this->blob_bottom_->cpu_diff(); const TypeParam* x = this->blob_bottom_->cpu_data(); for (int i = 0; i < n; ++i) { EXPECT_EQ(abs_val[i], x[i] > 0 ? x[i] : -x[i]); } } TYPED_TEST(MathFunctionsTest, TestScaleCPU) { int n = this->blob_bottom_->count(); TypeParam alpha = this->blob_bottom_->cpu_diff()[caffe_rng_rand() % this->blob_bottom_->count()]; caffe_cpu_scale<TypeParam>(n, alpha, this->blob_bottom_->cpu_data(), this->blob_bottom_->mutable_cpu_diff()); const TypeParam* scaled = this->blob_bottom_->cpu_diff(); const TypeParam* x = this->blob_bottom_->cpu_data(); for (int i = 0; i < n; ++i) { EXPECT_EQ(scaled[i], x[i] * alpha); } } TYPED_TEST(MathFunctionsTest, TestScaleGPU) { int n = this->blob_bottom_->count(); TypeParam alpha = this->blob_bottom_->cpu_diff()[caffe_rng_rand() % this->blob_bottom_->count()]; caffe_gpu_scale<TypeParam>(n, alpha, this->blob_bottom_->gpu_data(), this->blob_bottom_->mutable_gpu_diff()); const TypeParam* scaled = this->blob_bottom_->cpu_diff(); const TypeParam* x = this->blob_bottom_->cpu_data(); for (int i = 0; i < n; ++i) { EXPECT_EQ(scaled[i], x[i] * alpha); } } TYPED_TEST(MathFunctionsTest, TestCopyCPU) { const int n = this->blob_bottom_->count(); const TypeParam* bottom_data = this->blob_bottom_->cpu_data(); TypeParam* top_data = this->blob_top_->mutable_cpu_data(); caffe_copy(n, bottom_data, top_data); for (int i = 0; i < n; ++i) { EXPECT_EQ(bottom_data[i], top_data[i]); } } TYPED_TEST(MathFunctionsTest, TestCopyGPU) { const int n = this->blob_bottom_->count(); const TypeParam* bottom_data = this->blob_bottom_->gpu_data(); TypeParam* top_data = this->blob_top_->mutable_gpu_data(); caffe_copy(n, bottom_data, top_data); bottom_data = this->blob_bottom_->cpu_data(); top_data = this->blob_top_->mutable_cpu_data(); for (int i = 0; i < n; ++i) { EXPECT_EQ(bottom_data[i], top_data[i]); } } } // namespace caffe
xiaomi646/caffe_2d_mlabel
src/caffe/test/test_math_functions.cpp
C++
bsd-2-clause
7,892
--- title: Xadow Tutorial - Acceleration Detector category: RePhone oldwikiname: Xadow tutorial-Acceleration detector surveyurl: https://www.research.net/r/Xadow_Tutorial_Acceleration_Detector --- We have made an acceleration detector, it detects the acceleration and reminds users by vibrating. When the acceleration changes, the Xadow Vibration will vibrate and the Oled will display the accelerometer value. You can also see the current battery voltage on the OLED display. This demo required: * [Xadow Main Board](/Xadow_Main_Board/) * [Xadow OLED](/Xado_OLED_128multiply64/D) * [Xadow Vibrator](http://wiki.seeedstudio.com/wiki/Xadow_Vibrator) * [Xadow Accelerometer](/Xadow_3_Aixs_Accelerometer/) ![](https://github.com/SeeedDocument/Xadow_Tutorial_Acceleration_Detector/raw/master/img/Untitled2.jpg) To complete the demo, you need to: * Connect Xadow Main Board,Xadow OLED, Xadow Vibrator and Xadow Accelerometer at the same direction with FFC cables. * Connect Xadow Main Board to PC with a Micro USB cable. Before uploading code, you need to install Xadow driver. Please click [here](/Xadow_Main_Board#Get_Start_with_Xadow_Main_Board) to learn the specific operation. * When you see "Now, you can program and use the Xadow as you use other Arduino boards", it means you have finished the preparations. * Downloading [the file: acceleDetector Library](https://github.com/SeeedDocument/Xadow_Tutorial_Acceleration_Detector/raw/master/res/AccelerationDetector.zip) and directly open acceleDetector INO file. !!!Note Before compiling, you should make sure that there are [the library:OLED_Display12864](https://github.com/SeeedDocument/Xadow_Tutorial_Acceleration_Detector/raw/master/res/OLED_Display12864.zip) and [sleep_FromArduino](https://github.com/SeeedDocument/Xadow_Tutorial_Acceleration_Detector/raw/master/res/Sleep_FromArduino.zip) in Arduino Library. If not, please download them and put them on the libraries file of Arduino IDE in the path: ..\arduino-1.0.1\libraries after unzip._ * Compile code and upload it to xadow board. You need to select Seeed Xadow from the Tools | Board menu of the Arduino environment. * Then you can see the following picture: ![](https://github.com/SeeedDocument/Xadow_Tutorial_Acceleration_Detector/raw/master/img/Demo_1_effect_picture.jpg) Change the acceleration value by shaking the sensor,you will see the sensor value on the OLED module ## Resources [Demo1 acceleDetectoe Code](https://github.com/SeeedDocument/Xadow_Tutorial_Acceleration_Detector/raw/master/res/AccelerationDetector.zip)
SeeedDocument/Seeed-WiKi
docs/Xadow_Tutorial_Acceleration_Detector.md
Markdown
bsd-2-clause
2,631
#!/usr/bin/env bash # Compiling with ghcjs: stack build --stack-yaml=stack-ghcjs.yaml # Moving the generated files to the js folder: mkdir -p js cp -r $(stack path --local-install-root --stack-yaml=stack-ghcjs.yaml)/bin/hakyll-cms.jsexe/all.js js/ # Minifying all.js file using the closure compiler: cd js closure-compiler all.js --compilation_level=ADVANCED_OPTIMIZATIONS > all.min.js # OPTIONAL: zipping, to see the actual transferred size of the app: # zopfli all.min.js
Haskell-Praxis/hakyll-cms
deploy.sh
Shell
bsd-2-clause
477
/* * Copyright 2019 Shannon F. Stewman * * See LICENCE for the full copyright terms. */ #ifndef ADT_EDGESET_H #define ADT_EDGESET_H #include <stdint.h> struct bm; struct set; struct fsm_alloc; struct fsm_edge; struct edge_set; struct state_set; struct edge_iter { size_t i, j; const struct edge_set *set; }; struct edge_ordered_iter { const struct edge_set *set; size_t pos; size_t steps; unsigned char symbol; uint64_t symbols_used[4]; }; enum edge_group_iter_type { EDGE_GROUP_ITER_ALL, EDGE_GROUP_ITER_UNIQUE }; struct edge_group_iter { const struct edge_set *set; unsigned flag; size_t i; uint64_t internal[256/64]; }; /* TODO: symbols: macros for bit flags, first, count, etc. */ struct edge_group_iter_info { int unique; fsm_state_t to; uint64_t symbols[256/64]; }; /* Reset an iterator for groups of edges. * If iter_type is set to EDGE_GROUP_ITER_UNIQUE, * edges with labels that only appear once will be * yielded with unique set to 1, all others set to 0. * If iter_type is EDGE_GROUP_ITER_ALL, they will not * be separated, and unique will not be set. */ void edge_set_group_iter_reset(const struct edge_set *s, enum edge_group_iter_type iter_type, struct edge_group_iter *egi); int edge_set_group_iter_next(struct edge_group_iter *egi, struct edge_group_iter_info *eg); /* Opaque struct type for edge iterator, * which does extra processing upfront to iterate over * edges in lexicographically ascending order; the * edge_iter iterator is unordered. */ struct edge_iter_ordered; /* Create an empty edge set. * This currently returns a NULL pointer. */ struct edge_set * edge_set_new(void); void edge_set_free(const struct fsm_alloc *a, struct edge_set *set); int edge_set_add(struct edge_set **set, const struct fsm_alloc *alloc, unsigned char symbol, fsm_state_t state); int edge_set_add_bulk(struct edge_set **pset, const struct fsm_alloc *alloc, uint64_t symbols[256/64], fsm_state_t state); /* Notify the data structure that it wis likely to soon need to grow * to fit N more bulk edge groups. This can avoid resizing multiple times * in smaller increments. */ int edge_set_advise_growth(struct edge_set **pset, const struct fsm_alloc *alloc, size_t count); int edge_set_add_state_set(struct edge_set **setp, const struct fsm_alloc *alloc, unsigned char symbol, const struct state_set *state_set); int edge_set_find(const struct edge_set *set, unsigned char symbol, struct fsm_edge *e); int edge_set_contains(const struct edge_set *set, unsigned char symbol); int edge_set_hasnondeterminism(const struct edge_set *set, struct bm *bm); int edge_set_transition(const struct edge_set *set, unsigned char symbol, fsm_state_t *state); size_t edge_set_count(const struct edge_set *set); /* Note: this should actually union src into *dst, if *dst already * exists, not replace it. */ int edge_set_copy(struct edge_set **dst, const struct fsm_alloc *alloc, const struct edge_set *src); void edge_set_remove(struct edge_set **set, unsigned char symbol); void edge_set_remove_state(struct edge_set **set, fsm_state_t state); int edge_set_compact(struct edge_set **set, const struct fsm_alloc *alloc, fsm_state_remap_fun *remap, const void *opaque); void edge_set_reset(const struct edge_set *set, struct edge_iter *it); int edge_set_next(struct edge_iter *it, struct fsm_edge *e); void edge_set_rebase(struct edge_set **setp, fsm_state_t base); int edge_set_replace_state(struct edge_set **setp, const struct fsm_alloc *alloc, fsm_state_t old, fsm_state_t new); int edge_set_empty(const struct edge_set *s); /* Initialize an ordered edge_set iterator, positioning it at the first * edge with a particular symbol. edge_set_ordered_iter_next will get * successive edges with that symbol, then lexicographically following * symbols (if any). */ void edge_set_ordered_iter_reset_to(const struct edge_set *set, struct edge_ordered_iter *eoi, unsigned char symbol); /* Reset an ordered iterator, equivalent to * edge_set_ordered_iter_reset_to(set, eoi, '\0'). */ void edge_set_ordered_iter_reset(const struct edge_set *set, struct edge_ordered_iter *eoi); /* Get the next edge from an ordered iterator and return 1, * or return 0 when no more are available. */ int edge_set_ordered_iter_next(struct edge_ordered_iter *eoi, struct fsm_edge *e); #endif
katef/libfsm
include/adt/edgeset.h
C
bsd-2-clause
4,364
""" Common utility """ import logging import time def measure(func, *args, **kwargs): def start(*args, **kwargs): begin = time.time() result = func(*args, **kwargs) end = time.time() arg = args while not (isinstance(arg, str) or isinstance(arg, int) or isinstance(arg, float)): if isinstance(arg, list) or isinstance(arg, tuple): arg = arg[0] elif isinstance(args, dict): arg = '' else: arg = '' arg_trun = arg if len(arg) > 70: arg_trun = arg[:67] logging.info('{} took {:6.3f} sec {}'.format(func.__name__ , end - begin, arg_trun)) logging.debug('with {} and {}'.format(args, kwargs)) return result return start
inlinechan/stags
stags/util.py
Python
bsd-2-clause
856
/* * L.GeoJSON turns any GeoJSON data into a Leaflet layer. */ L.GeoJSON = L.FeatureGroup.extend({ initialize: function (geojson, options) { L.setOptions(this, options); this._layers = {}; if (geojson) { this.addData(geojson); } }, addData: function (geojson) { var features = L.Util.isArray(geojson) ? geojson : geojson.features, i, len, feature; if (features) { for (i = 0, len = features.length; i < len; i++) { // Only add this if geometry or geometries are set and not null feature = features[i]; if (feature.geometries || feature.geometry || feature.features || feature.coordinates) { this.addData(feature); } } return this; } var options = this.options; if (options.filter && !options.filter(geojson)) { return; } var layer = L.GeoJSON.geometryToLayer(geojson, options); layer.feature = L.GeoJSON.asFeature(geojson); layer.defaultOptions = layer.options; this.resetStyle(layer); if (options.onEachFeature) { options.onEachFeature(geojson, layer); } return this.addLayer(layer); }, resetStyle: function (layer) { // reset any custom styles layer.options = layer.defaultOptions; this._setLayerStyle(layer, this.options.style); }, setStyle: function (style) { this.eachLayer(function (layer) { this._setLayerStyle(layer, style); }, this); }, _setLayerStyle: function (layer, style) { if (typeof style === 'function') { style = style(layer.feature); } if (layer.setStyle) { layer.setStyle(style); } } }); L.extend(L.GeoJSON, { geometryToLayer: function (geojson, options) { var geometry = geojson.type === 'Feature' ? geojson.geometry : geojson, coords = geometry.coordinates, layers = [], coordsToLatLng = options.coordsToLatLng || this.coordsToLatLng, latlng, latlngs, i, len; switch (geometry.type) { case 'Point': latlng = coordsToLatLng(coords); return options.pointToLayer ? options.pointToLayer(geojson, latlng) : new L.Marker(latlng); case 'MultiPoint': for (i = 0, len = coords.length; i < len; i++) { latlng = coordsToLatLng(coords[i]); layers.push(options.pointToLayer ? options.pointToLayer(geojson, latlng) : new L.Marker(latlng)); } return new L.FeatureGroup(layers); case 'LineString': case 'MultiLineString': latlngs = this.coordsToLatLngs(coords, geometry.type === 'LineString' ? 0 : 1, coordsToLatLng); return new L.Polyline(latlngs, options); case 'Polygon': case 'MultiPolygon': latlngs = this.coordsToLatLngs(coords, geometry.type === 'Polygon' ? 1 : 2, coordsToLatLng); return new L.Polygon(latlngs, options); case 'GeometryCollection': for (i = 0, len = geometry.geometries.length; i < len; i++) { layers.push(this.geometryToLayer({ geometry: geometry.geometries[i], type: 'Feature', properties: geojson.properties }, options)); } return new L.FeatureGroup(layers); default: throw new Error('Invalid GeoJSON object.'); } }, coordsToLatLng: function (coords) { return new L.LatLng(coords[1], coords[0], coords[2]); }, coordsToLatLngs: function (coords, levelsDeep, coordsToLatLng) { var latlngs = []; for (var i = 0, len = coords.length, latlng; i < len; i++) { latlng = levelsDeep ? this.coordsToLatLngs(coords[i], levelsDeep - 1, coordsToLatLng) : coordsToLatLng(coords[i]); latlngs.push(latlng); } return latlngs; }, latLngToCoords: function (latlng) { return latlng.alt !== undefined ? [latlng.lng, latlng.lat, latlng.alt] : [latlng.lng, latlng.lat]; }, latLngsToCoords: function (latlngs, levelsDeep, closed) { var coords = []; for (var i = 0, len = latlngs.length; i < len; i++) { coords.push(levelsDeep ? L.GeoJSON.latLngsToCoords(latlngs[i], levelsDeep - 1, closed): L.GeoJSON.latLngToCoords(latlngs[i])); } if (!levelsDeep && closed) { coords.push(coords[0]); } return coords; }, getFeature: function (layer, newGeometry) { return layer.feature ? L.extend({}, layer.feature, {geometry: newGeometry}) : L.GeoJSON.asFeature(newGeometry); }, asFeature: function (geoJSON) { if (geoJSON.type === 'Feature') { return geoJSON; } return { type: 'Feature', properties: {}, geometry: geoJSON }; } }); var PointToGeoJSON = { toGeoJSON: function () { return L.GeoJSON.getFeature(this, { type: 'Point', coordinates: L.GeoJSON.latLngToCoords(this.getLatLng()) }); } }; L.Marker.include(PointToGeoJSON); L.Circle.include(PointToGeoJSON); L.CircleMarker.include(PointToGeoJSON); L.Polyline.prototype.toGeoJSON = function () { var multi = !this._flat(this._latlngs); var coords = L.GeoJSON.latLngsToCoords(this._latlngs, multi ? 1 : 0); return L.GeoJSON.getFeature(this, { type: (multi ? 'Multi' : '') + 'LineString', coordinates: coords }); }; L.Polygon.prototype.toGeoJSON = function () { var holes = !this._flat(this._latlngs), multi = holes && !this._flat(this._latlngs[0]); var coords = L.GeoJSON.latLngsToCoords(this._latlngs, multi ? 2 : holes ? 1 : 0, true); if (holes && this._latlngs.length === 1) { multi = true; coords = [coords]; } if (!holes) { coords = [coords]; } return L.GeoJSON.getFeature(this, { type: (multi ? 'Multi' : '') + 'Polygon', coordinates: coords }); }; L.LayerGroup.include({ toMultiPoint: function () { var coords = []; this.eachLayer(function (layer) { coords.push(layer.toGeoJSON().geometry.coordinates); }); return L.GeoJSON.getFeature(this, { type: 'MultiPoint', coordinates: coords }); }, toGeoJSON: function () { var type = this.feature && this.feature.geometry && this.feature.geometry.type; if (type === 'MultiPoint') { return this.toMultiPoint(); } var isGeometryCollection = type === 'GeometryCollection', jsons = []; this.eachLayer(function (layer) { if (layer.toGeoJSON) { var json = layer.toGeoJSON(); jsons.push(isGeometryCollection ? json.geometry : L.GeoJSON.asFeature(json)); } }); if (isGeometryCollection) { return L.GeoJSON.getFeature(this, { geometries: jsons, type: 'GeometryCollection' }); } return { type: 'FeatureCollection', features: jsons }; } }); L.geoJson = function (geojson, options) { return new L.GeoJSON(geojson, options); };
perliedman/Leaflet
src/layer/GeoJSON.js
JavaScript
bsd-2-clause
6,642
<html> <head> <title>Refrigera&ccedil;&atilde;o Montagner</title> </head> <?php include("comum/comum.inc"); ?> <body bgcolor="<?php echo($cor_fundo_principal); ?>"> <center> <br> <br> <br> <h1>Refrigera&ccedil;&atilde;o Montagner Com&eacute;rcio e Servi&ccedil;os de M&aacute;quinas Ltda. ME</h1> <br> <h3>Av. Visconde de Indaiatuba 531, Vl. Vit&oacute;ria<br>Indaiatuba - SP<br>Fone: (19)3875-9013<br><br>E-mail: refrimon@terra.com.br</h3> </center> </body> </html>
vinnix/refrimon
refrimon/inicio.php
PHP
bsd-2-clause
488
from __future__ import (absolute_import, print_function, division) class NotImplementedException(Exception): pass
zbuc/imaghost
ghost_exceptions/__init__.py
Python
bsd-2-clause
120
SYSROOT=$NDKROOT/platforms/android-19/arch-x86 GCCTOOLCHAIN=$NDKROOT/toolchains/x86-4.8/prebuilt/windows-x86_64 GNUSTL=$NDKROOT/sources/cxx-stl/gnu-libstdc++/4.8 COMMONTOOLCHAINFLAGS="-target i686-none-linux-android --sysroot=$SYSROOT -gcc-toolchain $GCCTOOLCHAIN" COMMONCOMPILERFLAGS="-fdiagnostics-format=msvc -fPIC -fno-exceptions -frtti -fno-short-enums -march=atom -fsigned-char" COMMONINCLUDES="-I$GNUSTL/include -I$GNUSTL/libs/x86/include -I$SYSROOT/usr/include" export CFLAGS="$COMMONTOOLCHAINFLAGS $COMMONCOMPILERFLAGS -MD -MF /dev/null -DANDROID -fdata-sections -ffunction-sections $COMMONINCLUDES -x c" export CXXFLAGS="$COMMONTOOLCHAINFLAGS $COMMONCOMPILERFLAGS -MD -MF /dev/null $COMMONINCLUDES -x c++ -std=c++11" export CPPFLAGS="$COMMONTOOLCHAINFLAGS $COMMONINCLUDES -MD -MF /dev/null -DANDROID -frtti -fno-exceptions -fdata-sections -ffunction-sections -DUCONFIG_NO_TRANSLITERATION=1 -DPIC -DU_HAVE_NL_LANGINFO_CODESET=0 -DU_TIMEZONE=0" export LDFLAGS="$COMMONTOOLCHAINFLAGS -nostdlib -Wl,-shared,-Bsymbolic -Wl,--no-undefined -lgnustl_shared -lc -lgcc -L$GNUSTL/libs/x86 -march=atom" ../../Source/configure --prefix=$PWD --build=x86_64-unknown-cygwin --with-cross-build=$PWD/../../Win64/VS2013 --host=i686-none-linux-android --enable-debug --disable-release --enable-static --disable-shared --with-data-packaging=files
PopCap/GameIdea
Engine/Source/ThirdParty/ICU/icu4c-53_1/Android/ConfigForAndroid-x86.sh
Shell
bsd-2-clause
1,335
BEGIN FOR cur_rec IN (SELECT object_name, object_type FROM user_objects WHERE object_type IN ('VIEW', 'PACKAGE', 'PROCEDURE', 'FUNCTION', 'SEQUENCE', 'INDEX', 'TYPE', 'TABLE' )) LOOP BEGIN CASE WHEN cur_rec.object_type = 'TABLE' THEN EXECUTE IMMEDIATE 'DROP ' || cur_rec.object_type || ' "' || cur_rec.object_name || '" CASCADE CONSTRAINTS'; WHEN cur_rec.object_type = 'TYPE' THEN EXECUTE IMMEDIATE 'DROP ' || cur_rec.object_type || ' "' || cur_rec.object_name || '" FORCE'; ELSE EXECUTE IMMEDIATE 'DROP ' || cur_rec.object_type || ' "' || cur_rec.object_name || '"'; END CASE; EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.put_line ( 'FAILED: DROP ' || cur_rec.object_type || ' "' || cur_rec.object_name || '"' ); END; END LOOP; END; /
kmstumpff/Scripts
RemoveAllTables.sql
SQL
bsd-2-clause
1,725
// This file was procedurally generated from the following sources: // - src/dstr-assignment/array-elem-put-prop-ref-user-err.case // - src/dstr-assignment/error/assignment-expr.template /*--- description: Any error raised as a result of setting the value should be forwarded to the runtime. (AssignmentExpression) esid: sec-variable-statement-runtime-semantics-evaluation es6id: 13.3.2.4 features: [destructuring-binding] flags: [generated] info: | VariableDeclaration : BindingPattern Initializer 1. Let rhs be the result of evaluating Initializer. 2. Let rval be GetValue(rhs). 3. ReturnIfAbrupt(rval). 4. Return the result of performing BindingInitialization for BindingPattern passing rval and undefined as arguments. ---*/ var x = { set y(val) { throw new Test262Error(); } }; assert.throws(Test262Error, function() { 0, [x.y] = [23]; });
sebastienros/jint
Jint.Tests.Test262/test/language/expressions/assignment/dstr-array-elem-put-prop-ref-user-err.js
JavaScript
bsd-2-clause
884