text
stringlengths
2
99.9k
meta
dict
<?php namespace Illuminate\Contracts\Cache; interface Store { /** * Retrieve an item from the cache by key. * * @param string|array $key * @return mixed */ public function get($key); /** * Retrieve multiple items from the cache by key. * * Items not found in the cache will have a null value. * * @param array $keys * @return array */ public function many(array $keys); /** * Store an item in the cache for a given number of seconds. * * @param string $key * @param mixed $value * @param int $seconds * @return bool */ public function put($key, $value, $seconds); /** * Store multiple items in the cache for a given number of seconds. * * @param array $values * @param int $seconds * @return bool */ public function putMany(array $values, $seconds); /** * Increment the value of an item in the cache. * * @param string $key * @param mixed $value * @return int|bool */ public function increment($key, $value = 1); /** * Decrement the value of an item in the cache. * * @param string $key * @param mixed $value * @return int|bool */ public function decrement($key, $value = 1); /** * Store an item in the cache indefinitely. * * @param string $key * @param mixed $value * @return bool */ public function forever($key, $value); /** * Remove an item from the cache. * * @param string $key * @return bool */ public function forget($key); /** * Remove all items from the cache. * * @return bool */ public function flush(); /** * Get the cache key prefix. * * @return string */ public function getPrefix(); }
{ "pile_set_name": "Github" }
/** * DescribeAddressesResponseType.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.5.1 Built on : Oct 19, 2009 (10:59:34 EDT) */ package com.amazon.ec2; /** * DescribeAddressesResponseType bean class */ public class DescribeAddressesResponseType implements org.apache.axis2.databinding.ADBBean{ /* This type was generated from the piece of schema that had name = DescribeAddressesResponseType Namespace URI = http://ec2.amazonaws.com/doc/2010-11-15/ Namespace Prefix = ns1 */ private static java.lang.String generatePrefix(java.lang.String namespace) { if(namespace.equals("http://ec2.amazonaws.com/doc/2010-11-15/")){ return "ns1"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * field for RequestId */ protected java.lang.String localRequestId ; /** * Auto generated getter method * @return java.lang.String */ public java.lang.String getRequestId(){ return localRequestId; } /** * Auto generated setter method * @param param RequestId */ public void setRequestId(java.lang.String param){ this.localRequestId=param; } /** * field for AddressesSet */ protected com.amazon.ec2.DescribeAddressesResponseInfoType localAddressesSet ; /** * Auto generated getter method * @return com.amazon.ec2.DescribeAddressesResponseInfoType */ public com.amazon.ec2.DescribeAddressesResponseInfoType getAddressesSet(){ return localAddressesSet; } /** * Auto generated setter method * @param param AddressesSet */ public void setAddressesSet(com.amazon.ec2.DescribeAddressesResponseInfoType param){ this.localAddressesSet=param; } /** * isReaderMTOMAware * @return true if the reader supports MTOM */ public static boolean isReaderMTOMAware(javax.xml.stream.XMLStreamReader reader) { boolean isReaderMTOMAware = false; try{ isReaderMTOMAware = java.lang.Boolean.TRUE.equals(reader.getProperty(org.apache.axiom.om.OMConstants.IS_DATA_HANDLERS_AWARE)); }catch(java.lang.IllegalArgumentException e){ isReaderMTOMAware = false; } return isReaderMTOMAware; } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement ( final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{ org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this,parentQName){ public void serialize(org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { DescribeAddressesResponseType.this.serialize(parentQName,factory,xmlWriter); } }; return new org.apache.axiom.om.impl.llom.OMSourcedElementImpl( parentQName,factory,dataSource); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ serialize(parentQName,factory,xmlWriter,false); } public void serialize(final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory, org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ java.lang.String prefix = null; java.lang.String namespace = null; prefix = parentQName.getPrefix(); namespace = parentQName.getNamespaceURI(); if ((namespace != null) && (namespace.trim().length() > 0)) { java.lang.String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, parentQName.getLocalPart()); } else { if (prefix == null) { prefix = generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, parentQName.getLocalPart(), namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } else { xmlWriter.writeStartElement(parentQName.getLocalPart()); } if (serializeType){ java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://ec2.amazonaws.com/doc/2010-11-15/"); if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){ writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", namespacePrefix+":DescribeAddressesResponseType", xmlWriter); } else { writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", "DescribeAddressesResponseType", xmlWriter); } } namespace = "http://ec2.amazonaws.com/doc/2010-11-15/"; if (! namespace.equals("")) { prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); xmlWriter.writeStartElement(prefix,"requestId", namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } else { xmlWriter.writeStartElement(namespace,"requestId"); } } else { xmlWriter.writeStartElement("requestId"); } if (localRequestId==null){ // write the nil attribute throw new org.apache.axis2.databinding.ADBException("requestId cannot be null!!"); }else{ xmlWriter.writeCharacters(localRequestId); } xmlWriter.writeEndElement(); if (localAddressesSet==null){ throw new org.apache.axis2.databinding.ADBException("addressesSet cannot be null!!"); } localAddressesSet.serialize(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2010-11-15/","addressesSet"), factory,xmlWriter); xmlWriter.writeEndElement(); } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) { prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException{ java.util.ArrayList elementList = new java.util.ArrayList(); java.util.ArrayList attribList = new java.util.ArrayList(); elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2010-11-15/", "requestId")); if (localRequestId != null){ elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localRequestId)); } else { throw new org.apache.axis2.databinding.ADBException("requestId cannot be null!!"); } elementList.add(new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2010-11-15/", "addressesSet")); if (localAddressesSet==null){ throw new org.apache.axis2.databinding.ADBException("addressesSet cannot be null!!"); } elementList.add(localAddressesSet); return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray()); } /** * Factory class that keeps the parse method */ public static class Factory{ /** * static method to create the object * Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable * If this object is not an element, it is a complex type and the reader is at the event just after the outer start element * Postcondition: If this object is an element, the reader is positioned at its end element * If this object is a complex type, the reader is positioned at the end element of its outer element */ public static DescribeAddressesResponseType parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ DescribeAddressesResponseType object = new DescribeAddressesResponseType(); int event; java.lang.String nillableValue = null; java.lang.String prefix =""; java.lang.String namespaceuri =""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){ java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"); if (fullTypeName!=null){ java.lang.String nsPrefix = null; if (fullTypeName.indexOf(":") > -1){ nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":")); } nsPrefix = nsPrefix==null?"":nsPrefix; java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1); if (!"DescribeAddressesResponseType".equals(type)){ //find namespace for the prefix java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (DescribeAddressesResponseType)com.amazon.ec2.ExtensionMapper.getTypeObject( nsUri,type,reader); } } } // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); reader.next(); while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2010-11-15/","requestId").equals(reader.getName())){ java.lang.String content = reader.getElementText(); object.setRequestId( org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content)); reader.next(); } // End of if for expected property start element else{ // A start element we are not expecting indicates an invalid parameter was passed throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName()); } while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() && new javax.xml.namespace.QName("http://ec2.amazonaws.com/doc/2010-11-15/","addressesSet").equals(reader.getName())){ object.setAddressesSet(com.amazon.ec2.DescribeAddressesResponseInfoType.Factory.parse(reader)); reader.next(); } // End of if for expected property start element else{ // A start element we are not expecting indicates an invalid parameter was passed throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName()); } while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement()) // A start element we are not expecting indicates a trailing invalid property throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName()); } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }//end of factory class }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/ic_blokada" android:tint="@color/switch_on"></bitmap>
{ "pile_set_name": "Github" }
#ifndef _PERF_DWARF_REGS_H_ #define _PERF_DWARF_REGS_H_ #ifdef DWARF_SUPPORT const char *get_arch_regstr(unsigned int n); #endif #endif
{ "pile_set_name": "Github" }
require 'aristotle/logic' require 'aristotle/utility' require 'aristotle/command' require 'aristotle/presenter'
{ "pile_set_name": "Github" }
''' From Marc-Antoine Martinod No particular license or rights, you can change it as you feel, just be honest. :) For python puritain, sorry if this script is not "pythonic". Significant changes made by Hanno Rein, August 23, 2020 ''' ''' This script picks up the magnitudes and the spectral type from Simbad website. *How to use it: ***In variable "path", put the path of the repo where you have the XMLs. ***Run the script *Structure: ***HTMLparser class to extract information from a webpage. ***Two main functions : magnitude : pick up magnitudes from Simbad spectralType : pick up spectral type from Simbad, it is currently commented because I don't need to run it at the moment. ***A list generator function : create a file containing the name of the XML files in "path". *Logs: ***Log_planet.txt has all files for which there was a 404 error. This file is not reset when the script is rerun. It works for both functions. *Troubleshooting: ***If Simbad don't recognize this name, either you search manually or you create a list with the other names for a system (Kepler, 2MASS...) and you rename the file with this name to let the script writing in it. *Improvements: ***You can improve this script by a multi-name recognition :for a system, if there is a 404 error on simbad web page the script can try another name picked up in the XMLs and try it. This would avoid to make a manual reasearch or rename the files, recreate a list and rerun the script. ***There can be a problem with binaries system. Simbad always has only SP (spectral type) and mag for one star (don't know which) or the whole system but if this information exists for each star of a binary system, this script doesn't deal with it. ***Adapt it for other kind of extraction or for other website. ''' from html.parser import HTMLParser from urllib.request import urlopen from urllib.parse import quote_plus import xml.etree.ElementTree as ET import re import os import glob import time def indent(elem, level=0): i = "\n" + level * "\t" if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + "\t" if not elem.tail or not elem.tail.strip(): elem.tail = i for elem in elem: indent(elem, level + 1) if not elem.tail or not elem.tail.strip(): elem.tail = i else: if level and (not elem.tail or not elem.tail.strip()): elem.tail = i class MyHTMLParser(HTMLParser):#HTML parser to get the information from the webpage def handle_starttag(self, tag, attrs): #get start tag and may store its attributes global boolean, dictio_mags, data2, dictio_ident, inname if tag =="a" and section=="identifiers": inname = 1 if boolean == 1 and section == "mag": dictio_mags.append(data2) boolean = 0 if boolean == 1 and section == "identifiers": if len(data2): worthyCats = ["HD", "GJ", "Gaia DR2", "NAME", "HIP", "KOI", "Kepler", "KIC", "TYC"] for wc in worthyCats: if wc in data2 and not "**" in data2: data2 = data2.replace("NAME","").strip() dictio_ident.append(data2) boolean = 0 inname = 0 data2 = "" def handle_endtag(self, tag): global inname if tag=="tt": inname = 0 pass def handle_data(self, data): global data2, boolean, section, inname, dictio_distance, dictio_coord, dictio_spectral if section=="mag" and re.findall("[A-Z] +\d*\.?\d*? *\[+.+\]", data):#Search magnitude data2 = data data2 = data2.replace("\n", "").replace(" ","") boolean = 1 if section=="identifiers" and inname==1: data2 = data2+data data2 = data2.replace("\n", "").replace("\"", "").strip() boolean = 1 if re.findall("Identifiers \(\d+\) :", data): section = "identifiers" data2 = "" if re.findall("Spectral type:", data): section = "spectraltype" if section=="spectraltype" and re.findall("[OBAFGKM]",data): dictio_spectral = data.strip() section = "spectral done" if re.findall("Plots and Images", data): section = "plotsandimages" if re.findall("ICRS", data): section = "ICRS" if section=="ICRS" and re.findall("coord.",data): section = "ICRScoord" if section=="ICRScoord": res = re.search(r"\s+(\d\d \d\d \d\d\.\d{4})\d+ ([\+\-]\d\d \d\d \d\d\.\d{4})\d+",data) if res: dictio_coord = [res.group(1), res.group(2)] section = "coords done" if re.findall("distance Q unit", data): section = "distance" res = re.search(r"\s+\|\s*(\d+\.\d+)\s+pc\s+\|\s+\-(\d+\.\d+)\s+\+(\d+\.\d+)\s+\|",data) if res: dictio_distance = [res.group(1), res.group(2), res.group(3)] #Another script exists for that. Splitting the two functions lets me to control #the list is in correct format and won't bring any troubles. #However, as it is a copy/paste of the script, it should work. def generateList(path): with open("list.txt", "w") as planet_list: for filename in glob.glob(path+"/*.xml"): # Open file name = os.path.split(filename) name = name[1] name = name.replace(".xml","") planet_list.write(name+"\n") #****************************MAIN********************************* parser = MyHTMLParser() path = "systems" # systems or systems_kepler generateList(path) system_list = open("list.txt","r") #list of the systems to process lines = system_list.readlines() lines = [line.replace('\n','') for line in lines] try: willskip = open("simbad_skip.txt","r").readlines() #list of the systems to process willskip = [s.strip() for s in willskip] except: willskip = [] nummax = 10000 for line in lines:#read all the list of systems and run the parser class and the magnitude function for each one filename = path+"/"+line+".xml" f = open(filename, 'rt') root = ET.parse(f).getroot() stars = root.findall(".//star") binaries = root.findall(".//binary") systemname = root.findtext("./name") if line in willskip: continue if len(binaries): continue if root.findall(".//spectraltype"): continue ## One request per star for stari, star in enumerate(stars): starnames = star.findall("./name") # do request dictio_mags = [] dictio_ident = [] dictio_distance = [] dictio_coord = [] dictio_spectral = [] section = "mag" boolean = 0 data2 = "" starname = starnames[0].text try: print('Requesting: http://simbad.u-strasbg.fr/simbad/sim-basic?Ident='+quote_plus(starname)) code_source = urlopen('http://simbad.u-strasbg.fr/simbad/sim-basic?Ident='+quote_plus(starname)).read() code_source = code_source.decode('utf-8') except IOError: print('Lookup failed for {} - skipping'.format(starname)) continue if re.findall("Identifier not found in the database", code_source): print('Identifier not found in the database. - skipping') continue if re.findall("Extra-solar Confirmed Planet", code_source): print('Got planet, not star. - skipping') continue parser.feed(code_source) dictio_mags.sort() # Work on new star names lastnameindex = -1 for ind, child in enumerate(star): if child.text == starnames[-1].text: lastnameindex = ind starnames = [n.text for n in starnames] for newstarname in dictio_ident: if newstarname not in starnames: nsn = ET.Element("name") nsn.text = newstarname star.insert(lastnameindex+1,nsn) print("New star name added: ", newstarname) for key in dictio_mags:#concatenate magnitudes in the string from XML expr = key if not "[~]" in expr: sigma = re.findall('\[+.+\]', expr) sigma = str(sigma[0].replace('[','').replace(']','')) else: sigma = "" expr = re.sub('\[+.+\]', '', expr)#Remove uncertainty from string expr2 = re.sub('[A-Z]', '', expr)#Remove letters from string, just mag left. magletters = ["J", "H","K","V","B","R","I"] #find location to insert (after current mags, after names) maginsertindex = -1 for magletter in magletters: mags = star.findall("./mag"+magletter) for mag in mags: for ind, child in enumerate(star): if child.text == mag.text: maginsertindex = max(maginsertindex,ind) names = star.findall("./name") for name in names: for ind, child in enumerate(star): if child.text == name.text: maginsertindex = max(maginsertindex,ind) for magletter in magletters: if magletter in expr: if not star.findtext("./mag"+magletter): nmag = ET.Element("mag"+magletter) nmag.text = expr2 if sigma: nmag.attrib['errorminus'] = sigma nmag.attrib['errorplus'] = sigma star.insert(maginsertindex+1,nmag) print("New mag",magletter,"added: ",expr2,sigma) if len(dictio_spectral): if not star.findtext("./spectraltype"): spectraltype = ET.Element("spectraltype") spectraltype.text = dictio_spectral star.insert(maginsertindex+1,spectraltype) print("New spectraltype added: ",dictio_spectral) ## Planet Names planets = star.findall("./planet") for planet in planets: planetname = planet.findtext("./name") planetsuffix = planetname.replace(starname,"") if planetsuffix in [" b"," c"," d"," e"," f"," g"," h"," i"," j"]: # will attempt to add other names planetnames = planet.findall("./name") lastnameindex = -1 for ind, child in enumerate(planet): if child.text == planetnames[-1].text: lastnameindex = ind planetnames = [n.text for n in planetnames] for starname in dictio_ident: newplanetname = starname + planetsuffix if newplanetname not in planetnames: nne = ET.Element("name") nne.text = newplanetname planet.insert(lastnameindex+1,nne) print("New planet name added: ", newplanetname) ## System parameters based on last star in system systemnames = root.findall("./name") lastnameindex = -1 for ind, child in enumerate(root): if child.text == systemnames[-1].text: lastnameindex = ind if not root.findtext("./distance") and len(dictio_distance): distance = ET.Element("distance") distance.text = dictio_distance[0] distance.attrib['errorminus'] = dictio_distance[1] distance.attrib['errorplus'] = dictio_distance[2] print("New distance added: ", dictio_distance) root.insert(lastnameindex+1,distance) if len(dictio_coord): coord = root.findtext("./declination") if coord: if coord[:6] in dictio_coord[1] and len(coord)<len(dictio_coord[1]): for ind, child in enumerate(root): if child.tag == "declination": lastnameindex = ind-1 print("Old declination removed: ", coord) root.remove(child) coord = None break if not coord: declination = ET.Element("declination") declination.text = dictio_coord[1] print("New declination added: ", dictio_coord[1]) root.insert(lastnameindex+1,declination) coord = root.findtext("./rightascension") if coord: if coord[:5] in dictio_coord[0] and len(coord)<len(dictio_coord[0]): for ind, child in enumerate(root): if child.tag == "rightascension": lastnameindex = ind-1 print("Old rightascension removed: ", coord) root.remove(child) coord = None break if not coord: rightascension = ET.Element("rightascension") rightascension.text = dictio_coord[0] print("New rightascension added: ", dictio_coord[0]) root.insert(lastnameindex+1,rightascension) indent(root) with open(filename, 'wb') as outfile: ET.ElementTree(root).write(outfile, encoding="UTF-8", xml_declaration=False) with open("simbad_skip.txt", "a+") as skip_list: skip_list.write(line+"\n") print("") time.sleep(1) nummax-=1 if nummax==0: break
{ "pile_set_name": "Github" }
/* * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.jfr.internal; import java.io.IOException; import java.security.AccessControlContext; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import jdk.jfr.RecordingState; /** * Class responsible for dumping recordings on exit * */ final class ShutdownHook implements Runnable { private final PlatformRecorder recorder; Object tlabDummyObject; ShutdownHook(PlatformRecorder recorder) { this.recorder = recorder; } @Override public void run() { // this allocation is done in order to fetch a new TLAB before // starting any "real" operations. In low memory situations, // we would like to take an OOM as early as possible. tlabDummyObject = new Object(); for (PlatformRecording recording : recorder.getRecordings()) { if (recording.getDumpOnExit() && recording.getState() == RecordingState.RUNNING) { dump(recording); } } recorder.destroy(); } private void dump(PlatformRecording recording) { try { WriteableUserPath dest = recording.getDestination(); if (dest == null) { dest = makeDumpOnExitPath(recording); recording.setDestination(dest); } if (dest != null) { recording.stop("Dump on exit"); } } catch (Exception e) { Logger.log(LogTag.JFR, LogLevel.DEBUG, () -> "Could not dump recording " + recording.getName() + " on exit."); } } private WriteableUserPath makeDumpOnExitPath(PlatformRecording recording) { try { String name = Utils.makeFilename(recording.getRecording()); AccessControlContext acc = recording.getNoDestinationDumpOnExitAccessControlContext(); return AccessController.doPrivileged(new PrivilegedExceptionAction<WriteableUserPath>() { @Override public WriteableUserPath run() throws Exception { return new WriteableUserPath(recording.getDumpOnExitDirectory().toPath().resolve(name)); } }, acc); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof SecurityException) { Logger.log(LogTag.JFR, LogLevel.WARN, "Not allowed to create dump path for recording " + recording.getId() + " on exit."); } if (t instanceof IOException) { Logger.log(LogTag.JFR, LogLevel.WARN, "Could not dump " + recording.getId() + " on exit."); } return null; } } static final class ExceptionHandler implements Thread.UncaughtExceptionHandler { public void uncaughtException(Thread t, Throwable e) { JVM.getJVM().uncaughtException(t, e); } } }
{ "pile_set_name": "Github" }
[%# View style info for a user for the purpose of troubleshooting. # # Authors: # import r26.1 livejournal -- original page # Jen Griffin <[email protected]> -- TT conversion # # Copyright (c) 2008-2020 by Dreamwidth Studios, LLC. # # This code was forked from the LiveJournal project owned and operated # by Live Journal, Inc. The code has been modified and expanded by # Dreamwidth Studios, LLC. These files were originally licensed under # the terms of the license supplied by Live Journal, Inc. # # In accordance with the original license, this code and all its # modifications are provided under the GNU General Public License. # A copy of that license can be found in the LICENSE file included as # part of this distribution. %] [%- sections.title = '.title' | ml -%] [%- CALL dw.active_resource_group( "foundation" ) -%] [%- sections.head = BLOCK %] <style type="text/css"> #content input { height: auto; width: auto; display: inline; } </style> [% END %] <form method='POST'> [% form.textbox( label = dw.ml( '.label.viewuser' ), name = 'user', size = maxlength_user, maxlength = maxlength_user ); form.submit( value = dw.ml( '.btn.view' ) ) %] </form> [%- IF u -%] <hr /> [%- IF s2style -%] <h3>[% '.header.s2style' | ml( stylename = s2style.name ) %]</h3> <ul> <li>[% '.label.styleid' | ml %] [% s2style.styleid %]</li> <li>[% '.label.lastmod' | ml %] [% mysql_time( s2style.modtime ) %]</li> <li>[% '.label.layers' | ml %]</li> <ul> [%- FOREACH layer IN sort_keys( s2style.layer ); layerid = s2style.layer.$layer -%] <li>[% layer %]: [%- IF layerid %] <a href='[% dw.create_url( '/customize/advanced/layerbrowse', args => { id => layerid } ) %]'> [%- layerview = public.$layerid.defined ? 'public' : 'custom'; ".txt.$layerview" | ml %]</a> (#[% layerid %]) [%- ELSE; '.txt.nolayer' | ml; END %] </li> [%- END -%] </ul> </ul> [%- ELSE -%] <p>[% '.txt.nostyle' | ml %]</p> [%- END -%] [%- END -%]
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <title>欢迎使用iTalk聊天室</title> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <meta name="description" content=""> <meta name="keywords" content=""> <meta name="author" content=""> <link rel="icon" href="../static/images/logo.png" > <script> function browserRedirect() { var sUserAgent = navigator.userAgent.toLowerCase(); var bIsIpad = sUserAgent.match(/ipad/i) == "ipad"; var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os"; var bIsMidp = sUserAgent.match(/midp/i) == "midp"; var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4"; var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb"; var bIsAndroid = sUserAgent.match(/android/i) == "android"; var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce"; var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile"; if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) { } else { console.log('在pc端浏览'); window.location.href="./index.html" } } browserRedirect(); </script> <link rel="stylesheet" href="../static/css/iconfont.css"> <link rel="stylesheet" href="../static/css/iTalk.css"> </head> <body> <div id="app"></div> <template id="tpl"> <div class="tpl"> <div class="it-warp" v-if="loginUser"> <div class="it-panel" v-show="currentMenu=='session'"> <div class="it-search-warp" > <img :src="loginUser.avatarUrl" alt=""> <div class="it-search-group"> <span class="iconfont icon-search"></span> <input type="text" placeholder="搜索" v-model="keyword"> </div> </div> <div class="wt-session-listBox wt-scroll"> <div class="wt-users-item" v-for="item in searchUser(keyword)" :class="{active:item.id==sessionId}" @click="changeSession(item)"> <div class="wt-user-avatar"> <img :src="item.avatarUrl" alt=""> </div> <div class="wt-item-info"> <div class="wt-item-name"> {{item.name}} <span class="wt-message-time" v-if="getLastMessage(item.id).time">{{getLastMessage(item.id).time | friendlyTime}}</span> </div> <div class="wt-item-message"> {{getLastMessage(item.id).content}} <span class="wt-message-num" v-if="getUnReaderNum(item.id)!=0">{{getUnReaderNum(item.id)}}</span> </div> </div> </div> </div> </div> <div class="it-panel" v-show="currentMenu=='setting'"> <div class="it-setting-banner"> <div class="it-loginAvatar"> <img :src="loginUser.avatarUrl" alt=""> </div> </div> <div class="it-setting-list"> <div class="it-setting-item"> <span>用户名:{{loginUser.name}}</span> </div> <div class="it-setting-item"> <span>消息提示音</span> <div class="it-switch"> <input type="checkbox" id="voice" v-model="setting.isVoice"> <label for="voice"></label> </div> </div> <div class="it-setting-item"> <span>显示用户名称</span> <div class="it-switch"> <input type="checkbox" id="name" v-model="setting.isName"> <label for="name"></label> </div> </div> <div class="it-setting-item"> <span>显示消息时间</span> <div class="it-switch"> <input type="checkbox" id="switch" v-model="setting.isTime"> <label for="switch"></label> </div> </div> </div> <span class="iconfont icon-bug it-bug" @click.stop="showLogs()"></span> </div> <div class="it-panel" v-show="currentMenu=='about'"> <h2 class="it-about-title">关于</h2> <div class="it-about-list"> <div class="it-about-item">版本:v1.0</div> <div class="it-about-item"><span>协议:MIT</span></div> <div class="it-about-item"><span>GitHub:<a href="https://github.com/cleverqin/node-websocket-Chatroom" target="_blank">源码地址</a></span></div> <div class="it-about-item"><span>邮箱:[email protected]</span></div> <div class="it-about-item"><span><a href="https://github.com/cleverqin/node-websocket-Chatroom" target="_blank"><img src="https://img.shields.io/github/stars/cleverqin/node-websocket-Chatroom?label=Star&style=flat&logo=github" alt="" style="vertical-align: middle;"></a> <a href="https://github.com/cleverqin/node-websocket-Chatroom" target="_blank"><img src="https://img.shields.io/github/forks/cleverqin/node-websocket-Chatroom?label=Fork&style=flat&logo=github" alt="" style="vertical-align: middle;"></a></span></div> </div> <span class="iconfont icon-bug it-bug" @click.stop="showLogs()"></span> </div> <div class="it-menuBox"> <div class="item-menu-item " :class="{active:currentMenu=='session'}" @click="currentMenu='session'"> <span class="iconfont icon-comments"></span> <p>会话</p> </div> <div class="item-menu-item " :class="{active:currentMenu=='setting'}" @click="currentMenu='setting'"> <span class="iconfont icon-cog"></span> <p>设置</p> </div> <div class="item-menu-item " :class="{active:currentMenu=='about'}" @click="currentMenu='about'"> <span class="iconfont icon-info"></span> <p>关于</p> </div> </div> <div class="it-session-window" v-if="session"> <div class="it-session-header"> <span class="iconfont icon-left it-back" @click="sessionId=''"></span> <img :src="session.avatarUrl" alt=""> <span>{{session.name}}</span> <span class="iconfont icon-phone" v-if="session.deviceType=='touch'"></span> <span class="iconfont icon-pc" v-if="session.deviceType=='pc'"></span> <template v-if="session.type=='group'"> <span class="wt-session-address">({{sessionList.length}})</span> </template> </div> <div class="it-session-container" :style="{bottom:!isShow?'41px':'181px'}"> <div class="wt-window-messageList wt-scroll" ref="messageList"> <template v-for="item in messageList"> <div class="wt-message-item" :class="item.from.id==loginUser.id?'wt-message-send':'wt-message-receive'" > <div class="wt-avatarBox"> <img :src="item.from.avatarUrl" alt=""> </div> <div class="wt-message-body"> <template v-if="setting.isName"> <div class="wt-from-info" v-if="item.from.id!=loginUser.id"> <span >{{item.from.name}}</span> <span class="wt-time-span" v-if="setting.isTime">{{item.time | friendlyTime}}</span> </div> <div class="wt-from-info" v-else> <span class="wt-time-span" v-if="setting.isTime">{{item.time | friendlyTime}}</span> <span >{{item.from.name}}</span> </div> </template> <div class="wt-message-text" v-html="parseText(item.content)"></div> </div> </div> </template> </div> </div> <div class="it-session-footer"> <div class="it-send-form"> <span class="iconfont icon-expression" @click.stop="showExpression()"></span> <div class="it-input"><input type="text" v-model="text" @keyup.enter="sendMessage(text)"></div> <span class="it-sendBtn" @click="sendMessage(text)">发送</span> </div> <div class="it-expression-warp" v-show="isShow"> <div class="it-expression-list"> <div class="it-expression-item" v-for="item in qqExpression" @click.stop="selectExpression(item)"> <img :src="baseUrl+item.url" alt="" > </div> </div> </div> </div> </div> <transition name="slider"> <div class="wt-logBox" v-show="isShowLog"> <div class="wt-logHeader"> 连接日志 <span class="wt-log-closeBtn iconfont icon-close" @click.stop="isShowLog=false"></span> </div> <div class="wt-log-container" @click.stop=""> <div class="ui-scroll wt-log-list" id="log-container"> <div class="wt-log-item" v-for="log in logs"> <span :class="'wt-log-'+log.type">{{log.text}}</span> <span class="wt-log-time">{{log.time|formatTime}}</span> </div> </div> </div> </div> </transition> </div> <transition name="slider"> <div class="wt-alter-message" v-show="isAlter">{{alterMessage}}</div> </transition> <login @login="userLogin" v-if="!loginUser"></login> <audio src="../static/images/8400.mp3" ref="audio"></audio> </div> </template> <template id="login"> <div class="iTalk-container iTalk-loginBox"> <div class="iTalk-loginForm-box"> <transition name="slider"> <div class="wt-error-message" v-if="errorMsg">{{errorMsg}}</div> </transition> <form class="iTalk-login-form"> <div class="iTalk-loginUser-avatarBox"> <img :src="user.avatarUrl" alt="" @click.stop="isShow=!isShow"> </div> <div class="iTalk-form-inputBox"> <input type="text" class="iTalk-user-name" placeholder="用户名" v-model="user.name"> <input type="text" class="iTalk-user-password" placeholder="密码"> <button type="button" class="iTalk-formBtn" @click="login(user)">登录</button> </div> </form> </div> <transition name="slider"> <div class="iTalk-select-imgBox" v-show="isShow"> <div class="iTalk-addAvatar-box"> <input type="text" v-model="QQ" placeholder="输入QQ号添加使用QQ头像" @click.stop="" @keyup.enter="addQQAvatar(QQ)"> </div> <ul class="iTalk-avatar-list"> <li :class="{active:user.avatarUrl==item}" v-for="item in avatars"> <img :src="item" alt="" @click="user.avatarUrl=item"> </li> </ul> </div> </transition> </div> </template> <script src="../static/js/vue.min.2.2.0.js"></script> <script src="../static/js/vue-resource.js"></script> <script src="../static/js/socket.io.js"></script> <script src="../static/js/example.js"></script> </body> </html>
{ "pile_set_name": "Github" }
{ "name": "webpack-cross-origin", "private": true, "version": "0.5.5", "description": "An example of using the Perspective Webpack plugin to build a JS file with Webpack.", "scripts": { "start": "npm-run-all -l -p webpack-watch host:app host:bundles", "host:app": "http-server ./dist/public -p 5150 -c-1", "host:bundles": "http-server ./dist -p 8080 -c-1 --cors", "webpack-watch": "webpack --watch" }, "keywords": [], "license": "Apache-2.0", "dependencies": { "@finos/perspective": "^0.5.5", "@finos/perspective-viewer": "^0.5.5", "@finos/perspective-viewer-d3fc": "^0.5.5", "@finos/perspective-viewer-datagrid": "^0.5.5" }, "devDependencies": { "@finos/perspective-webpack-plugin": "^0.5.5", "css-loader": "^0.28.7", "html-webpack-plugin": "^3.2.0", "http-server": "^0.11.1", "less-loader": "^4.0.5", "npm-run-all": "^4.1.3", "style-loader": "^0.18.2", "webpack": "^4.41.2", "webpack-dev-server": "3.9.0" } }
{ "pile_set_name": "Github" }
# Part 27: Regression Testing and a Nice Surprise We've had a few large-ish steps recently in our compiler writing journey, so I thought we should have a bit of a breather in this step. We can slow down a bit and review our progress so far. In the last step I noticed that we didn't have a way to confirm that our syntax and semantic error checking was working correctly. So I've just rewritten the scripts in the `tests/` folder to do this. I've been using Unix since the late 1980s, so my go-to automation tools are shell scripts and Makefiles or, if I need more complex tools, scripts written in Python or Perl (yes, I'm that old). So let's quickly look at the `runtest` script in the `tests/` directory. Even though I said I'd been using Unix scripts forever, I'm definitely not an uber script writer. ## The `runtest` Script The job of this script is to take a set of input programs, get our compiler to compile them, run the executable and compare its output against known-good output. If they match, the test is a success. If not, it's a failure. I've just extended it so that, if there is an "error" file associated with an input, we run our compiler and capture its error output. If this error output matches the expected error output, the test is a success as the compiler correctly detected the bad input. So let's look at the sections of the `runtest` script in stages. ``` # Build our compiler if needed if [ ! -f ../comp1 ] then (cd ..; make) fi ``` I'm using the '( ... )' syntax here to create a *sub-shell*. This can change its working directory without affecting the original shell, so we can move up a directory and rebuild our compiler. ``` # Try to use each input source file for i in input* # We can't do anything if there's no file to test against do if [ ! -f "out.$i" -a ! -f "err.$i" ] then echo "Can't run test on $i, no output file!" ``` The '[' thing is actually the external Unix tool, *test(1)*. Oh, if you've never seen this syntax before, *test(1)* means the manual page for *test* is in Section One of the man pages, and you can do: ``` $ man 1 test ``` to read the manual for *test* in Section One of the man pages. The `/usr/bin/[` executable is usually linked to `/usr/bin/test`, so that when you use '[' in a shell script, it's the same as running the *test* command. We can read the line `[ ! -f "out.$i" -a ! -f "err.$i" ]` as saying: test if there is no file "out.$i" and no file "err.$i". If both don't exist, we can give the error message. ``` # Output file: compile the source, run it and # capture the output, and compare it against # the known-good output else if [ -f "out.$i" ] then # Print the test name, compile it # with our compiler echo -n $i ../comp1 $i # Assemble the output, run it # and get the output in trial.$i cc -o out out.s ../lib/printint.c ./out > trial.$i # Compare this agains the correct output cmp -s "out.$i" "trial.$i" # If different, announce failure # and print out the difference if [ "$?" -eq "1" ] then echo ": failed" diff -c "out.$i" "trial.$i" echo # No failure, so announce success else echo ": OK" fi ``` This is the bulk of the script. I think the comments explain what is going on, but perhaps there are some subtleties to flesh out. `cmp -s` compares two text files; the `-s` flag means produce no output but set the exit value that `cmp` gives when it exits to: > 0 if inputs are the same, 1 if different, 2 if trouble. (from the man page) The line `if [ "$?" -eq "1" ]` says: if the exit value of the last command is equal to the number 1. So, if the compiler's output is different to the known-good output, we announce this and use the `diff` tool to show the differences between the two files. ``` # Error file: compile the source and # capture the error messages. Compare # against the known-bad output. Same # mechanism as before else if [ -f "err.$i" ] then echo -n $i ../comp1 $i 2> "trial.$i" cmp -s "err.$i" "trial.$i" ... ``` This section gets executed when there is an error document, "err.$i". This time, we use the shell syntax `2>` to capture our compiler's standard error output to the file "trial.$i" and compare that against the correct error output. The logic after this is the same as before. ## What We Are Doing: Regression Testing I haven't talked much before about testing, but now's the time. I've taught software development in the past so it would be remiss of me not to cover testing at some point. What we are doing here is [**regression testing**](https://en.wikipedia.org/wiki/Regression_testing). Wikipedia gives this definition: > Regression testing is the action of re-running functional and non-functional tests > to ensure that previously developed and tested software still performs after a change. As our compiler is changing at each step, we have to ensure that each new change doesn't break the functionality (and the error checking) of the previous steps. So each time I introduce a change, I add one or more tests to a) prove that it works and b) re-run this test on future changes. As long as all the tests pass, I'm sure that the new code hasn't broken the old code. ### Functional Tests The `runtests` script looks for files with the `out` prefix to do the functional testing. Right now, we have: ``` tests/out.input01.c tests/out.input12.c tests/out.input22.c tests/out.input02.c tests/out.input13.c tests/out.input23.c tests/out.input03.c tests/out.input14.c tests/out.input24.c tests/out.input04.c tests/out.input15.c tests/out.input25.c tests/out.input05.c tests/out.input16.c tests/out.input26.c tests/out.input06.c tests/out.input17.c tests/out.input27.c tests/out.input07.c tests/out.input18a.c tests/out.input28.c tests/out.input08.c tests/out.input18.c tests/out.input29.c tests/out.input09.c tests/out.input19.c tests/out.input30.c tests/out.input10.c tests/out.input20.c tests/out.input53.c tests/out.input11.c tests/out.input21.c tests/out.input54.c ``` That's 33 separate tests of the compiler's functionality. Right now, I know for a fact that our compiler is a bit fragile. None of these tests really stress the compiler in any way: they are simple tests of a few lines each. Later on, we will start to add some nasty stress tests to help strengthen the compiler and make it more resilient. ### Non-Functional Tests The `runtests` script looks for files with the `err` prefix to do the functional testing. Right now, we have: ``` tests/err.input31.c tests/err.input39.c tests/err.input47.c tests/err.input32.c tests/err.input40.c tests/err.input48.c tests/err.input33.c tests/err.input41.c tests/err.input49.c tests/err.input34.c tests/err.input42.c tests/err.input50.c tests/err.input35.c tests/err.input43.c tests/err.input51.c tests/err.input36.c tests/err.input44.c tests/err.input52.c tests/err.input37.c tests/err.input45.c tests/err.input38.c tests/err.input46.c ``` I created these 22 tests of the compiler's error checking in this step of our journey by looking for `fatal()` calls in the compiler. For each one, I've tried to write a small input file which would trigger it. Have a read of the matching source files and see if you can work out what syntax or semantic error each one triggers. ## Other Forms of Testing This isn't a course on software development methodologies, so I won't give too much more coverage on testing. But I'll give you links to a few more thing that I would highly recommend that you look at: + [Unit testing](https://en.wikipedia.org/wiki/Unit_testing) + [Test-driven development](https://en.wikipedia.org/wiki/Test-driven_development) + [Continuous integration](https://en.wikipedia.org/wiki/Continuous_integration) + [Version control](https://en.wikipedia.org/wiki/Version_control) I haven't done any unit testing with our compiler. The main reason here is that the code is very fluid in terms of the APIs for the functions. I'm not using a traditional waterfall model of development, so I'd be spending too much time rewriting my unit tests to match the latest APIs of all the functions. So, in some sense I am living dangerously here: there will be a number of latent bugs in the code which we haven't detected yet. However, there are guaranteed to be *many* more bugs where the compiler looks like it accepts the C language, but of course this isn't true. The compiler is failing the [principle of least astonishment](https://en.wikipedia.org/wiki/Principle_of_least_astonishment). We will need to spend some time adding in functionality that a "normal" C programmer expects to see. ## And a Nice Surprise Finally, we have a nice functional surprise with the compiler as it stands. A while back, I purposefully left out the code to test that the number and type of arguments to a function call matches the function's prototype (in `expr.c`): ``` // XXX Check type of each argument against the function's prototype ``` I left this out as I didn't want to add too much new code in one of our steps. Now that we have prototypes, I've wanted to finally add support for `printf()` so that we can ditch our homegrown `printint()` and `printchar()` functions. But we can't do this just yet, because `printf()` is a [variadic function](https://en.wikipedia.org/wiki/Variadic_function): it can accept a variable number of parameters. And, right now, our compiler only allows a function declaration with a fixed number of parameters. *However* (and this is the nice surprise), because we don't check the number of arguments in a function call, we can pass *any* number of arguments to `printf()` as long as we have given it an existing prototype. So, at present, this code (`tests/input53.c`) works: ```c int printf(char *fmt); int main() { printf("Hello world, %d\n", 23); return(0); } ``` And that's a nice thing! There is a gotcha. With the given `printf()` prototype, the cleanup code in `cgcall()` won't adjust the stack pointer when the function returns, as there are less than six parameters in the prototype. But we could call `printf()` with ten arguments: we'd push four of them on the stack, but `cgcall()` wouldn't clean up these four arguments when `printf()` returns. ## Conclusion and What's Next There is no new compiler code in this step, but we are now testing the error checking capability of the compiler, and we now have 54 regression tests to help ensure we don't break the compiler when we add new functionality. And, fortuitously, we can now use `printf()` as well as the other external fixed parameter count functions. In the next part of our compiler writing journey, I think I'll try to: + add support for an external pre-processor + allow the compiler to compile multiple files named on the command line + add the `-o`, `-c` and `-S` flags to the compiler to make it feel more like a "normal" C compiler
{ "pile_set_name": "Github" }
/*============================================================================= Copyright (c) 2010 Christopher Schmidt Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef BOOST_FUSION_INCLUDE_ADAPT_ASSOC_ADT_HPP #define BOOST_FUSION_INCLUDE_ADAPT_ASSOC_ADR_HPP #include <boost/fusion/support/config.hpp> #include <boost/fusion/adapted/adt/adapt_assoc_adt.hpp> #endif
{ "pile_set_name": "Github" }
% Generated by roxygen2 (4.1.0): do not edit by hand % Please edit documentation in R/bsCollapse.R \name{bsCollapse} \alias{bsCollapse} \title{bsCollapse} \usage{ bsCollapse(..., id = NULL, multiple = FALSE, open = NULL) } \arguments{ \item{id}{\bold{Optional} You can use \code{input$id} in your Server logic to determine which panels are open, and \code{\link{updateCollapse}} to open/close panels.} \item{multiple}{Can more than one panel be open at a time? Defaults to \code{FALSE}.} \item{open}{The \code{value}, (or if none was supplied, the \code{title}) of the panel(s) you want open on load.} \item{\dots}{\code{\link{bsCollapsePanel}} elements to include in the Collapse.} } \description{ \code{bsCollapse} is used in your UI to create a collapse panel group. Use \code{\link{bsCollapsePanel}} to populate this object with panels. } \details{ See \link{Collapses} for more information about how to use \code{bsCollapse} with the rest of the Collapses family. } \note{ Run \code{bsExample("Collapses")} for an example of \code{bsCollapse} functionality. } \seealso{ \href{http://getbootstrap.com}{Twitter Bootstrap 3} Other Collapses: \code{\link{Collapses}}; \code{\link{bsCollapsePanel}}; \code{\link{updateCollapse}} }
{ "pile_set_name": "Github" }
\relax \providecommand\hyper@newdestlabel[2]{} \catcode `"\active \providecommand\HyperFirstAtBeginDocument{\AtBeginDocument} \HyperFirstAtBeginDocument{\ifx\hyper@anchor\@undefined \global\let\oldcontentsline\contentsline \gdef\contentsline#1#2#3#4{\oldcontentsline{#1}{#2}{#3}} \global\let\oldnewlabel\newlabel \gdef\newlabel#1#2{\newlabelxx{#1}#2} \gdef\newlabelxx#1#2#3#4#5#6{\oldnewlabel{#1}{{#2}{#3}}} \AtEndDocument{\ifx\hyper@anchor\@undefined \let\contentsline\oldcontentsline \let\newlabel\oldnewlabel \fi} \fi} \global\let\hyper@last\relax \gdef\HyperFirstAtBeginDocument#1{#1} \providecommand\HyField@AuxAddToFields[1]{} \providecommand\HyField@AuxAddToCoFields[2]{} \select@language{ngerman} \@writefile{toc}{\select@language{ngerman}} \@writefile{lof}{\select@language{ngerman}} \@writefile{lot}{\select@language{ngerman}} \@input{00-preface.aux} \@input{10-features.aux} \@input{20-hardware.aux} \@input{30-manual.aux} \@input{40-configuring.aux} \@input{50-measurement.aux} \@input{51-semicon.aux} \@input{52-resistors.aux} \@input{53-capacitors.aux} \@input{54-inductors.aux} \@input{55-selftest.aux} \@input{56-frequency.aux} \@input{60-generators.aux} \@input{70-errors.aux} \@input{80-special.aux} \@input{90-todo.aux} \bibcite{Frejek}{1} \bibcite{ATmega8}{2} \bibcite{ATmega168}{3} \bibcite{AVR126}{4} \bibcite{AVR121}{5} \bibcite{LaTeX}{6} \bibcite{Gnuplot}{7} \bibcite{ESR}{8} \bibcite{Xfig}{9} \bibcite{gimp}{10} \bibcite{markus1}{11} \bibcite{avrdude}{12} \bibcite{markus2}{13} \bibcite{karlheinz1}{14} \bibcite{karlheinz2}{15} \bibcite{winavr1}{16} \bibcite{winavr2}{17} \bibcite{winavr3}{18} \bibcite{st7565}{19} \bibcite{ds3231}{20} \bibcite{ds3231m}{21}
{ "pile_set_name": "Github" }
form=五律 tags= 忽忽动中私, 人间何所之。 老过离乱世, 生在太平时。 桃李春无主, 杉松寺有期。 曾吟子山赋, 何啻旧凌迟。
{ "pile_set_name": "Github" }
/** * Copyright (C) 2004-2011 Jive Software. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tic.tac.toe; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashSet; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import org.jivesoftware.resource.Res; import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.StanzaListener; import org.jivesoftware.smack.filter.StanzaIdFilter; import org.jivesoftware.smack.iqrequest.AbstractIqRequestHandler; import org.jivesoftware.smack.iqrequest.IQRequestHandler; import org.jivesoftware.smack.packet.IQ; import org.jivesoftware.smack.packet.Stanza; import org.jivesoftware.smack.packet.StanzaError; import org.jivesoftware.smack.provider.ProviderManager; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.plugin.Plugin; import org.jivesoftware.spark.ui.ChatRoom; import org.jivesoftware.spark.ui.ChatRoomButton; import org.jivesoftware.spark.ui.ChatRoomListener; import org.jivesoftware.spark.ui.ChatRoomListenerAdapter; import org.jivesoftware.spark.ui.rooms.ChatRoomImpl; import org.jivesoftware.spark.util.log.Log; import org.jxmpp.jid.EntityBareJid; import org.jxmpp.jid.EntityFullJid; import org.jxmpp.jid.parts.Localpart; import tic.tac.toe.packet.GameOfferPacket; import tic.tac.toe.packet.InvalidMove; import tic.tac.toe.packet.MovePacket; import tic.tac.toe.ui.GamePanel; /** * Tic Tac Toe plugin for Spark * * @author wolf.posdorfer * @version 16.06.2011 * */ public class TicTacToePlugin implements Plugin { private ChatRoomListener _chatRoomListener; private IQRequestHandler _gameOfferHandler; private HashSet<EntityBareJid> _currentInvitations; private ImageIcon buttonimg; @Override public void initialize() { ClassLoader cl = getClass().getClassLoader(); buttonimg = new ImageIcon(cl.getResource("ttt.button.png")); _currentInvitations = new HashSet<>(); ProviderManager.addIQProvider(GameOfferPacket.ELEMENT_NAME, GameOfferPacket.NAMESPACE, new GameOfferPacket.Provider() ); ProviderManager.addExtensionProvider(MovePacket.ELEMENT_NAME, MovePacket.NAMESPACE, new MovePacket.Provider() ); ProviderManager.addExtensionProvider(InvalidMove.ELEMENT_NAME, InvalidMove.NAMESPACE, new InvalidMove.Provider() ); // Add IQ listener to listen for incoming game invitations. _gameOfferHandler = new AbstractIqRequestHandler( GameOfferPacket.ELEMENT_NAME, GameOfferPacket.NAMESPACE, IQ.Type.get, IQRequestHandler.Mode.async) { public IQ handleIQRequest(IQ request) { showInvitationAlert((GameOfferPacket) request); return null; } }; SparkManager.getConnection().registerIQRequestHandler(_gameOfferHandler); addButtonToToolBar(); } /** * Add the TTT-Button to every opening Chatroom * and create Listeners for it */ private void addButtonToToolBar() { _chatRoomListener = new ChatRoomListenerAdapter() { @Override public void chatRoomOpened(final ChatRoom room) { if(!(room instanceof ChatRoomImpl)) { // Don't do anything if this is not a 1on1-Chat return; } final ChatRoomButton sendGameButton = new ChatRoomButton(buttonimg); room.getToolBar().addChatRoomButton(sendGameButton); final EntityFullJid opponentJID = ((ChatRoomImpl) room).getJID(); sendGameButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(_currentInvitations.contains(opponentJID.asBareJid())) { return; } final GameOfferPacket offer = new GameOfferPacket(); offer.setTo(opponentJID); offer.setType(IQ.Type.get ); _currentInvitations.add(opponentJID.asEntityBareJid()); room.getTranscriptWindow().insertCustomText (TTTRes.getString("ttt.request.sent"), false, false, Color.BLUE); try { SparkManager.getConnection().sendStanza(offer); } catch ( SmackException.NotConnectedException | InterruptedException e1 ) { Log.warning( "Unable to send offer to " + opponentJID, e1 ); } SparkManager.getConnection().addAsyncStanzaListener( new StanzaListener() { @Override public void processStanza(Stanza stanza) { if (stanza.getError() != null) { room.getTranscriptWindow().insertCustomText (TTTRes.getString("ttt.request.decline"), false, false, Color.RED); _currentInvitations.remove(opponentJID.asBareJid()); return; } GameOfferPacket answer = (GameOfferPacket)stanza; answer.setStartingPlayer(offer.isStartingPlayer()); answer.setGameID(offer.getGameID()); if (answer.getType() == IQ.Type.result) { // ACCEPT _currentInvitations.remove(opponentJID.asBareJid()); room.getTranscriptWindow().insertCustomText (TTTRes.getString("ttt.request.accept"), false, false, Color.BLUE); createTTTWindow(answer, opponentJID); } else { // DECLINE room.getTranscriptWindow().insertCustomText (TTTRes.getString("ttt.request.decline"), false, false, Color.RED); _currentInvitations.remove(opponentJID.asBareJid()); } } }, // TODO: Just filtering by stanza id is insure, should use Smack's IQ send-response mechanisms. new StanzaIdFilter(offer)); } }); } @Override public void chatRoomClosed(ChatRoom room) { if (room instanceof ChatRoomImpl) { ChatRoomImpl cri = (ChatRoomImpl) room; _currentInvitations.remove(cri.getParticipantJID()); } } }; SparkManager.getChatManager().addChatRoomListener(_chatRoomListener); } @Override public void shutdown() { _currentInvitations.clear(); SparkManager.getChatManager().removeChatRoomListener(_chatRoomListener); SparkManager.getConnection().unregisterIQRequestHandler(_gameOfferHandler); } @Override public boolean canShutDown() { return false; } @Override public void uninstall() { } /** * insert the Invitation Dialog into the Chat * * @param invitation */ private void showInvitationAlert(final GameOfferPacket invitation) { invitation.setType(IQ.Type.result); invitation.setTo(invitation.getFrom()); final ChatRoom room = SparkManager.getChatManager().getChatRoom( invitation.getFrom().asBareJid()); Localpart name = invitation.getFrom().getLocalpartOrThrow(); final JPanel panel = new JPanel(); JLabel text = new JLabel(TTTRes.getString("ttt.game.request",name)); JLabel game = new JLabel(TTTRes.getString("ttt.game.name")); game.setFont(new Font("Dialog", Font.BOLD, 24)); game.setForeground(Color.RED); JButton accept = new JButton(Res.getString("button.accept").replace("&", "")); JButton decline = new JButton(Res.getString("button.decline").replace("&", "")); panel.add(text); panel.add(game); panel.add(accept); panel.add(decline); room.getTranscriptWindow().addComponent(panel); accept.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { SparkManager.getConnection().sendStanza(invitation); } catch ( SmackException.NotConnectedException | InterruptedException e1 ) { Log.warning( "Unable to send invitation accept to " + invitation.getTo(), e1 ); } invitation.setStartingPlayer(!invitation.isStartingPlayer()); createTTTWindow(invitation, invitation.getTo().asEntityFullJidOrThrow()); panel.remove(3); panel.remove(2); panel.repaint(); panel.revalidate(); } }); decline.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { invitation.setType(IQ.Type.error); invitation.setError( StanzaError.getBuilder().setCondition(StanzaError.Condition.undefined_condition).setDescriptiveEnText("User declined your request.")); try { SparkManager.getConnection().sendStanza(invitation); } catch ( SmackException.NotConnectedException | InterruptedException e1 ) { Log.warning( "Unable to send invitation decline to " + invitation.getTo(), e1 ); } panel.remove(3); panel.remove(2); panel.repaint(); panel.revalidate(); } }); } /** * Creates The TicTacToe Window and starts the Game * @param gop * @param opponentJID */ private void createTTTWindow(GameOfferPacket gop, EntityFullJid opponentJID) { Localpart name = opponentJID.getLocalpart(); // tictactoe versus ${name} JFrame f = new JFrame(TTTRes.getString("ttt.window.title", TTTRes.getString("ttt.game.name"),name.toString() )); f.setIconImage(buttonimg.getImage()); GamePanel gp = new GamePanel(SparkManager.getConnection(), gop.getGameID(), gop.isStartingPlayer(), opponentJID,f); f.add(gp); f.pack(); f.setLocationRelativeTo(SparkManager.getChatManager().getChatContainer()); f.setVisible(true); } }
{ "pile_set_name": "Github" }
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Vladimír Vondruš <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #if defined(INSTANCED_OBJECT_ID) && !defined(GL_ES) && !defined(NEW_GLSL) #extension GL_EXT_gpu_shader4: require #endif #ifndef NEW_GLSL #define in attribute #define out varying #endif #ifdef EXPLICIT_UNIFORM_LOCATION layout(location = 0) #endif uniform highp mat4 transformationMatrix #ifndef GL_ES = mat4(1.0) #endif ; #ifdef EXPLICIT_UNIFORM_LOCATION layout(location = 1) #endif uniform highp mat4 projectionMatrix #ifndef GL_ES = mat4(1.0) #endif ; #if LIGHT_COUNT #ifdef EXPLICIT_UNIFORM_LOCATION layout(location = 2) #endif uniform mediump mat3 normalMatrix #ifndef GL_ES = mat3(1.0) #endif ; #endif #ifdef TEXTURE_TRANSFORMATION #ifdef EXPLICIT_UNIFORM_LOCATION layout(location = 3) #endif uniform mediump mat3 textureMatrix #ifndef GL_ES = mat3(1.0) #endif ; #endif #if LIGHT_COUNT /* Needs to be last because it uses locations 11 to 11 + LIGHT_COUNT - 1 */ #ifdef EXPLICIT_UNIFORM_LOCATION layout(location = 11) #endif uniform highp vec4 lightPositions[LIGHT_COUNT] #ifndef GL_ES = vec4[](LIGHT_POSITION_INITIALIZER) #endif ; #endif #ifdef EXPLICIT_ATTRIB_LOCATION layout(location = POSITION_ATTRIBUTE_LOCATION) #endif in highp vec4 position; #if LIGHT_COUNT #ifdef EXPLICIT_ATTRIB_LOCATION layout(location = NORMAL_ATTRIBUTE_LOCATION) #endif in mediump vec3 normal; #ifdef NORMAL_TEXTURE #ifdef EXPLICIT_ATTRIB_LOCATION layout(location = TANGENT_ATTRIBUTE_LOCATION) #endif in mediump #ifndef BITANGENT vec4 #else vec3 #endif tangent; #endif #ifdef BITANGENT #ifdef EXPLICIT_ATTRIB_LOCATION layout(location = BITANGENT_ATTRIBUTE_LOCATION) #endif in mediump vec3 bitangent; #endif #endif #ifdef TEXTURED #ifdef EXPLICIT_ATTRIB_LOCATION layout(location = TEXTURECOORDINATES_ATTRIBUTE_LOCATION) #endif in mediump vec2 textureCoordinates; out mediump vec2 interpolatedTextureCoordinates; #endif #ifdef VERTEX_COLOR #ifdef EXPLICIT_ATTRIB_LOCATION layout(location = COLOR_ATTRIBUTE_LOCATION) #endif in lowp vec4 vertexColor; out lowp vec4 interpolatedVertexColor; #endif #ifdef INSTANCED_OBJECT_ID #ifdef EXPLICIT_ATTRIB_LOCATION layout(location = OBJECT_ID_ATTRIBUTE_LOCATION) #endif in highp uint instanceObjectId; flat out highp uint interpolatedInstanceObjectId; #endif #ifdef INSTANCED_TRANSFORMATION #ifdef EXPLICIT_ATTRIB_LOCATION layout(location = TRANSFORMATION_MATRIX_ATTRIBUTE_LOCATION) #endif in highp mat4 instancedTransformationMatrix; #ifdef EXPLICIT_ATTRIB_LOCATION layout(location = NORMAL_MATRIX_ATTRIBUTE_LOCATION) #endif in highp mat3 instancedNormalMatrix; #endif #ifdef INSTANCED_TEXTURE_OFFSET #ifdef EXPLICIT_ATTRIB_LOCATION layout(location = TEXTURE_OFFSET_ATTRIBUTE_LOCATION) #endif in mediump vec2 instancedTextureOffset; #endif #if LIGHT_COUNT out mediump vec3 transformedNormal; #ifdef NORMAL_TEXTURE #ifndef BITANGENT out mediump vec4 transformedTangent; #else out mediump vec3 transformedTangent; out mediump vec3 transformedBitangent; #endif #endif out highp vec4 lightDirections[LIGHT_COUNT]; out highp vec3 cameraDirection; #endif void main() { /* Transformed vertex position */ highp vec4 transformedPosition4 = transformationMatrix* #ifdef INSTANCED_TRANSFORMATION instancedTransformationMatrix* #endif position; highp vec3 transformedPosition = transformedPosition4.xyz/transformedPosition4.w; #if LIGHT_COUNT /* Transformed normal and tangent vector */ transformedNormal = normalMatrix* #ifdef INSTANCED_TRANSFORMATION instancedNormalMatrix* #endif normal; #ifdef NORMAL_TEXTURE #ifndef BITANGENT transformedTangent = vec4(normalMatrix* #ifdef INSTANCED_TRANSFORMATION instancedNormalMatrix* #endif tangent.xyz, tangent.w); #else transformedTangent = normalMatrix* #ifdef INSTANCED_TRANSFORMATION instancedNormalMatrix* #endif tangent; transformedBitangent = normalMatrix* #ifdef INSTANCED_TRANSFORMATION instancedNormalMatrix* #endif bitangent; #endif #endif /* Direction to the light. Directional lights have the last component set to 0, which gets used to ignore the transformed position. */ for(int i = 0; i < LIGHT_COUNT; ++i) lightDirections[i] = vec4(lightPositions[i].xyz - transformedPosition*lightPositions[i].w, lightPositions[i].w); /* Direction to the camera */ cameraDirection = -transformedPosition; #endif /* Transform the position */ gl_Position = projectionMatrix*transformedPosition4; #ifdef TEXTURED /* Texture coordinates, if needed */ interpolatedTextureCoordinates = #ifdef TEXTURE_TRANSFORMATION (textureMatrix*vec3( #ifdef INSTANCED_TEXTURE_OFFSET instancedTextureOffset + #endif textureCoordinates, 1.0)).xy #else textureCoordinates #endif ; #endif #ifdef VERTEX_COLOR /* Vertex colors, if enabled */ interpolatedVertexColor = vertexColor; #endif #ifdef INSTANCED_OBJECT_ID /* Instanced object ID, if enabled */ interpolatedInstanceObjectId = instanceObjectId; #endif }
{ "pile_set_name": "Github" }
 Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.25420.1 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "AIServer", "Server\AIServer\proj-AIServer.vcxproj", "{36A92A8F-3820-435C-AC63-E861A556C1BB}" ProjectSection(ProjectDependencies) = postProject {C2FEB024-8E46-4533-918B-7196CAAA4E7D} = {C2FEB024-8E46-4533-918B-7196CAAA4E7D} {476399DF-6832-45BE-86A7-DF43728B9938} = {476399DF-6832-45BE-86A7-DF43728B9938} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "GameServer", "Server\GameServer\proj-GameServer.vcxproj", "{99006BDF-4BBD-4687-99C3-1424F32D95FC}" ProjectSection(ProjectDependencies) = postProject {C2FEB024-8E46-4533-918B-7196CAAA4E7D} = {C2FEB024-8E46-4533-918B-7196CAAA4E7D} {476399DF-6832-45BE-86A7-DF43728B9938} = {476399DF-6832-45BE-86A7-DF43728B9938} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "LogInServer", "Server\LogInServer\proj-LogInServer.vcxproj", "{F68DA1BF-90B2-4166-8DDB-B82D813EA961}" ProjectSection(ProjectDependencies) = postProject {C2FEB024-8E46-4533-918B-7196CAAA4E7D} = {C2FEB024-8E46-4533-918B-7196CAAA4E7D} {476399DF-6832-45BE-86A7-DF43728B9938} = {476399DF-6832-45BE-86A7-DF43728B9938} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Lua", "Server\scripting\Lua.vcxproj", "{476399DF-6832-45BE-86A7-DF43728B9938}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "N3Base", "Client\N3Base\N3Base.vcxproj", "{5E45D92A-702B-4128-A1AF-504A17271D94}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "WarFare", "Client\WarFare\WarFare.vcxproj", "{02A7C2DE-6DB6-477A-977A-ADF0BF2204A6}" ProjectSection(ProjectDependencies) = postProject {5E45D92A-702B-4128-A1AF-504A17271D94} = {5E45D92A-702B-4128-A1AF-504A17271D94} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ItemEditor", "ItemEditor\ItemEditor.vcxproj", "{734350E8-5586-46D9-8197-EEEEA3034D86}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "shared", "Server\shared\shared.vcxproj", "{C2FEB024-8E46-4533-918B-7196CAAA4E7D}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 Debug|x64 = Debug|x64 Release|Win32 = Release|Win32 Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {36A92A8F-3820-435C-AC63-E861A556C1BB}.Debug|Win32.ActiveCfg = Debug|Win32 {36A92A8F-3820-435C-AC63-E861A556C1BB}.Debug|Win32.Build.0 = Debug|Win32 {36A92A8F-3820-435C-AC63-E861A556C1BB}.Debug|x64.ActiveCfg = Debug|Win32 {36A92A8F-3820-435C-AC63-E861A556C1BB}.Debug|x64.Build.0 = Debug|Win32 {36A92A8F-3820-435C-AC63-E861A556C1BB}.Release|Win32.ActiveCfg = Release|Win32 {36A92A8F-3820-435C-AC63-E861A556C1BB}.Release|Win32.Build.0 = Release|Win32 {36A92A8F-3820-435C-AC63-E861A556C1BB}.Release|x64.ActiveCfg = Release|Win32 {36A92A8F-3820-435C-AC63-E861A556C1BB}.Release|x64.Build.0 = Release|Win32 {99006BDF-4BBD-4687-99C3-1424F32D95FC}.Debug|Win32.ActiveCfg = Debug|Win32 {99006BDF-4BBD-4687-99C3-1424F32D95FC}.Debug|Win32.Build.0 = Debug|Win32 {99006BDF-4BBD-4687-99C3-1424F32D95FC}.Debug|x64.ActiveCfg = Debug|Win32 {99006BDF-4BBD-4687-99C3-1424F32D95FC}.Debug|x64.Build.0 = Debug|Win32 {99006BDF-4BBD-4687-99C3-1424F32D95FC}.Release|Win32.ActiveCfg = Release|Win32 {99006BDF-4BBD-4687-99C3-1424F32D95FC}.Release|Win32.Build.0 = Release|Win32 {99006BDF-4BBD-4687-99C3-1424F32D95FC}.Release|x64.ActiveCfg = Release|Win32 {99006BDF-4BBD-4687-99C3-1424F32D95FC}.Release|x64.Build.0 = Release|Win32 {F68DA1BF-90B2-4166-8DDB-B82D813EA961}.Debug|Win32.ActiveCfg = Debug|Win32 {F68DA1BF-90B2-4166-8DDB-B82D813EA961}.Debug|Win32.Build.0 = Debug|Win32 {F68DA1BF-90B2-4166-8DDB-B82D813EA961}.Debug|x64.ActiveCfg = Debug|Win32 {F68DA1BF-90B2-4166-8DDB-B82D813EA961}.Debug|x64.Build.0 = Debug|Win32 {F68DA1BF-90B2-4166-8DDB-B82D813EA961}.Release|Win32.ActiveCfg = Release|Win32 {F68DA1BF-90B2-4166-8DDB-B82D813EA961}.Release|Win32.Build.0 = Release|Win32 {F68DA1BF-90B2-4166-8DDB-B82D813EA961}.Release|x64.ActiveCfg = Release|Win32 {F68DA1BF-90B2-4166-8DDB-B82D813EA961}.Release|x64.Build.0 = Release|Win32 {476399DF-6832-45BE-86A7-DF43728B9938}.Debug|Win32.ActiveCfg = Debug|Win32 {476399DF-6832-45BE-86A7-DF43728B9938}.Debug|Win32.Build.0 = Debug|Win32 {476399DF-6832-45BE-86A7-DF43728B9938}.Debug|x64.ActiveCfg = Debug|Win32 {476399DF-6832-45BE-86A7-DF43728B9938}.Debug|x64.Build.0 = Debug|Win32 {476399DF-6832-45BE-86A7-DF43728B9938}.Release|Win32.ActiveCfg = Release|Win32 {476399DF-6832-45BE-86A7-DF43728B9938}.Release|Win32.Build.0 = Release|Win32 {476399DF-6832-45BE-86A7-DF43728B9938}.Release|x64.ActiveCfg = Release|Win32 {476399DF-6832-45BE-86A7-DF43728B9938}.Release|x64.Build.0 = Release|Win32 {5E45D92A-702B-4128-A1AF-504A17271D94}.Debug|Win32.ActiveCfg = Debug|Win32 {5E45D92A-702B-4128-A1AF-504A17271D94}.Debug|Win32.Build.0 = Debug|Win32 {5E45D92A-702B-4128-A1AF-504A17271D94}.Debug|x64.ActiveCfg = Debug|x64 {5E45D92A-702B-4128-A1AF-504A17271D94}.Debug|x64.Build.0 = Debug|x64 {5E45D92A-702B-4128-A1AF-504A17271D94}.Release|Win32.ActiveCfg = Release|Win32 {5E45D92A-702B-4128-A1AF-504A17271D94}.Release|Win32.Build.0 = Release|Win32 {5E45D92A-702B-4128-A1AF-504A17271D94}.Release|x64.ActiveCfg = Release|x64 {5E45D92A-702B-4128-A1AF-504A17271D94}.Release|x64.Build.0 = Release|x64 {02A7C2DE-6DB6-477A-977A-ADF0BF2204A6}.Debug|Win32.ActiveCfg = Debug|Win32 {02A7C2DE-6DB6-477A-977A-ADF0BF2204A6}.Debug|Win32.Build.0 = Debug|Win32 {02A7C2DE-6DB6-477A-977A-ADF0BF2204A6}.Debug|x64.ActiveCfg = Debug|x64 {02A7C2DE-6DB6-477A-977A-ADF0BF2204A6}.Debug|x64.Build.0 = Debug|x64 {02A7C2DE-6DB6-477A-977A-ADF0BF2204A6}.Release|Win32.ActiveCfg = Release|Win32 {02A7C2DE-6DB6-477A-977A-ADF0BF2204A6}.Release|Win32.Build.0 = Release|Win32 {02A7C2DE-6DB6-477A-977A-ADF0BF2204A6}.Release|x64.ActiveCfg = Release|x64 {02A7C2DE-6DB6-477A-977A-ADF0BF2204A6}.Release|x64.Build.0 = Release|x64 {734350E8-5586-46D9-8197-EEEEA3034D86}.Debug|Win32.ActiveCfg = Debug|Win32 {734350E8-5586-46D9-8197-EEEEA3034D86}.Debug|Win32.Build.0 = Debug|Win32 {734350E8-5586-46D9-8197-EEEEA3034D86}.Debug|x64.ActiveCfg = Debug|x64 {734350E8-5586-46D9-8197-EEEEA3034D86}.Debug|x64.Build.0 = Debug|x64 {734350E8-5586-46D9-8197-EEEEA3034D86}.Release|Win32.ActiveCfg = Release|Win32 {734350E8-5586-46D9-8197-EEEEA3034D86}.Release|Win32.Build.0 = Release|Win32 {734350E8-5586-46D9-8197-EEEEA3034D86}.Release|x64.ActiveCfg = Release|x64 {734350E8-5586-46D9-8197-EEEEA3034D86}.Release|x64.Build.0 = Release|x64 {C2FEB024-8E46-4533-918B-7196CAAA4E7D}.Debug|Win32.ActiveCfg = Debug|Win32 {C2FEB024-8E46-4533-918B-7196CAAA4E7D}.Debug|Win32.Build.0 = Debug|Win32 {C2FEB024-8E46-4533-918B-7196CAAA4E7D}.Debug|x64.ActiveCfg = Debug|x64 {C2FEB024-8E46-4533-918B-7196CAAA4E7D}.Debug|x64.Build.0 = Debug|x64 {C2FEB024-8E46-4533-918B-7196CAAA4E7D}.Release|Win32.ActiveCfg = Release|Win32 {C2FEB024-8E46-4533-918B-7196CAAA4E7D}.Release|Win32.Build.0 = Release|Win32 {C2FEB024-8E46-4533-918B-7196CAAA4E7D}.Release|x64.ActiveCfg = Release|x64 {C2FEB024-8E46-4533-918B-7196CAAA4E7D}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal
{ "pile_set_name": "Github" }
using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Uno.UI.Samples.Controls; using Windows.UI.Xaml; namespace UITests.Shared.Windows_UI_Xaml_Input.RoutedEvents { [SampleControlInfo("Routed Events", "GotFocus/LostFocus")] public sealed partial class RoutedEvent_Focus : Page { public RoutedEvent_Focus() { this.InitializeComponent(); this.GotFocus += (snd, evt) => txtRoot.Text += $"GOTFOCUS (handler) sender={GetName(snd)}, originalSource={GetName(evt.OriginalSource)}\n"; this.LostFocus += (snd, evt) => txtRoot.Text += $"LOSTFOCUS (handler) sender={GetName(snd)}, originalSource={GetName(evt.OriginalSource)}\n"; } private static string GetName(object element) { if (element == null) { return "<null>"; } if (element is FrameworkElement fe) { return string.IsNullOrWhiteSpace(fe.Name) ? fe.ToString() : fe.Name; } return element.ToString(); } protected override void OnGotFocus(RoutedEventArgs e) { base.OnGotFocus(e); txtRoot.Text += $"GOTFOCUS (override) originalSource={GetName(e.OriginalSource)}\n"; } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); txtRoot.Text += $"LOSTFOCUS (override) originalSource={GetName(e.OriginalSource)}\n"; } } }
{ "pile_set_name": "Github" }
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package protoimpl contains the default implementation for messages // generated by protoc-gen-go. // // WARNING: This package should only ever be imported by generated messages. // The compatibility agreement covers nothing except for functionality needed // to keep existing generated messages operational. Breakages that occur due // to unauthorized usages of this package are not the author's responsibility. package protoimpl import ( "google.golang.org/protobuf/internal/filedesc" "google.golang.org/protobuf/internal/filetype" "google.golang.org/protobuf/internal/impl" ) // UnsafeEnabled specifies whether package unsafe can be used. const UnsafeEnabled = impl.UnsafeEnabled type ( // Types used by generated code in init functions. DescBuilder = filedesc.Builder TypeBuilder = filetype.Builder // Types used by generated code to implement EnumType, MessageType, and ExtensionType. EnumInfo = impl.EnumInfo MessageInfo = impl.MessageInfo ExtensionInfo = impl.ExtensionInfo // Types embedded in generated messages. MessageState = impl.MessageState SizeCache = impl.SizeCache WeakFields = impl.WeakFields UnknownFields = impl.UnknownFields ExtensionFields = impl.ExtensionFields ExtensionFieldV1 = impl.ExtensionField Pointer = impl.Pointer ) var X impl.Export
{ "pile_set_name": "Github" }
:103E000001C0B1C011248FE594E09EBF8DBF84B77F :103E1000882361F0982F9A70923041F081FF02C0A0 :103E200097EF94BF282E80E0B9D0EAC085E08EBD20 :103E300082E08BB988E18AB986E880BD87E189B9DB :103E40008EE0ACD0B89A84E02FE13FEF44E051E03F :103E50003DBD2CBD48BF08B602FEFDCF98B39527E7 :103E600098BBA8955F9902C0815091F790D081349A :103E700079F48DD0182F96D0123811F480E004C058 :103E800088E0113809F083E07ED080E17CD0EECF6D :103E9000823419F484E18ED0F8CF853411F485E0B2 :103EA000FACF853541F473D0C82F71D0D82FCC0FFD :103EB000DD1F78D0EACF863519F484E07BD0DECFE1 :103EC000843699F564D063D0182F61D0D82E012F95 :103ED00090E6E92EF12C57018FEFA81AB80A57D0B7 :103EE000F701808301507501B1F75CD0F5E4DF1272 :103EF00001C0FFCF50E040E063E0CE0134D07E014E :103F000080E6C82ED12CF601419151916F0161E0FC :103F1000C70129D0F2E0EF0EF11C1250A1F750E0DA :103F200040E065E0CE011FD0B0CF843771F42FD0D0 :103F30002ED0F82E2CD036D08E01F80185918F012D :103F400022D0FA94F110F9CFA0CF853731F42AD0DE :103F50008EE119D084E917D096CF813509F0A9CF29 :103F600088E01CD0A6CFFC010A0167BFE8951124A8 :103F700007B600FCFDCF667029F0452B19F481E1EE :103F800087BFE89508955D9BFECF8CB908955F9B30 :103F9000FECF5C9901C0A8958CB1089598E191BDC0 :103FA00081BD0895F4DF803219F088E0F7DFFFCF9C :103FB00084E1E9CFCF93C82FEADFC150E9F7CF9171 :023FC000F1CF3F :023FFE000008B9 :0400000300003E00BB :00000001FF
{ "pile_set_name": "Github" }
{ "_args": [ [ "[email protected]", "/home/beka/Dev/Web/appinventor-sources/appinventor" ] ], "_development": true, "_from": "[email protected]", "_id": "[email protected]", "_inBundle": false, "_integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", "_location": "/cliui/string-width", "_phantomChildren": {}, "_requested": { "type": "version", "registry": true, "raw": "[email protected]", "name": "string-width", "escapedName": "string-width", "rawSpec": "3.1.0", "saveSpec": null, "fetchSpec": "3.1.0" }, "_requiredBy": [ "/cliui" ], "_resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", "_spec": "3.1.0", "_where": "/home/beka/Dev/Web/appinventor-sources/appinventor", "author": { "name": "Sindre Sorhus", "email": "[email protected]", "url": "sindresorhus.com" }, "bugs": { "url": "https://github.com/sindresorhus/string-width/issues" }, "dependencies": { "emoji-regex": "^7.0.1", "is-fullwidth-code-point": "^2.0.0", "strip-ansi": "^5.1.0" }, "description": "Get the visual width of a string - the number of columns required to display it", "devDependencies": { "ava": "^1.0.1", "xo": "^0.23.0" }, "engines": { "node": ">=6" }, "files": [ "index.js" ], "homepage": "https://github.com/sindresorhus/string-width#readme", "keywords": [ "string", "str", "character", "char", "unicode", "width", "visual", "column", "columns", "fullwidth", "full-width", "full", "ansi", "escape", "codes", "cli", "command-line", "terminal", "console", "cjk", "chinese", "japanese", "korean", "fixed-width" ], "license": "MIT", "name": "string-width", "repository": { "type": "git", "url": "git+https://github.com/sindresorhus/string-width.git" }, "scripts": { "test": "xo && ava" }, "version": "3.1.0" }
{ "pile_set_name": "Github" }
// // Copyright 2020 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #ifndef PXR_IMAGING_HGI_METAL_GRAPHICS_CMDS_H #define PXR_IMAGING_HGI_METAL_GRAPHICS_CMDS_H #include "pxr/pxr.h" #include "pxr/base/gf/vec4i.h" #include "pxr/imaging/hgiMetal/api.h" #include "pxr/imaging/hgi/graphicsCmds.h" #include <cstdint> #include <Metal/Metal.h> PXR_NAMESPACE_OPEN_SCOPE struct HgiGraphicsCmdsDesc; /// \class HgiMetalGraphicsCmds /// /// Metal implementation of HgiGraphicsEncoder. /// class HgiMetalGraphicsCmds final : public HgiGraphicsCmds { public: HGIMETAL_API ~HgiMetalGraphicsCmds() override; HGIMETAL_API void SetViewport(GfVec4i const& vp) override; HGIMETAL_API void SetScissor(GfVec4i const& sc) override; HGIMETAL_API void BindPipeline(HgiGraphicsPipelineHandle pipeline) override; HGIMETAL_API void BindResources(HgiResourceBindingsHandle resources) override; HGIMETAL_API void SetConstantValues( HgiGraphicsPipelineHandle pipeline, HgiShaderStage stages, uint32_t bindIndex, uint32_t byteSize, const void* data) override; HGIMETAL_API void BindVertexBuffers( uint32_t firstBinding, HgiBufferHandleVector const& buffers, std::vector<uint32_t> const& byteOffsets) override; HGIMETAL_API void DrawIndexed( HgiBufferHandle const& indexBuffer, uint32_t indexCount, uint32_t indexBufferByteOffset, uint32_t firstIndex, uint32_t vertexOffset, uint32_t instanceCount) override; HGIMETAL_API void PushDebugGroup(const char* label) override; HGIMETAL_API void PopDebugGroup() override; protected: friend class HgiMetal; HGIMETAL_API HgiMetalGraphicsCmds( HgiMetal* hgi, HgiGraphicsCmdsDesc const& desc); HGIMETAL_API bool _Submit(Hgi* hgi) override; private: HgiMetalGraphicsCmds() = delete; HgiMetalGraphicsCmds & operator=(const HgiMetalGraphicsCmds&) = delete; HgiMetalGraphicsCmds(const HgiMetalGraphicsCmds&) = delete; HgiMetal* _hgi; id<MTLRenderCommandEncoder> _encoder; HgiGraphicsCmdsDesc _descriptor; bool _hasWork; }; PXR_NAMESPACE_CLOSE_SCOPE #endif
{ "pile_set_name": "Github" }
package Introduction; public class FibonacciC { public static int fibonacci(int n) { if (n == 0) return 0; else if (n == 1) return 1; int[] memo = new int[n]; memo[0] = 0; memo[1] = 1; for (int i = 2; i < n; i++) { memo[i] = memo[i - 1] + memo[i - 2]; } return memo[n - 1] + memo[n - 2]; } /** * @param args */ public static void main(String[] args) { int max = 100; // Make this as big as you want! (Though you'll exceed the bounds of a long around 46) int trials = 10; // Run code multiple times to compute average time. double[] times = new double[max]; // Store times for (int j = 0; j < trials; j++) { // Run this 10 times to compute for (int i = 0; i < max; i++) { long start = System.currentTimeMillis(); System.out.println(fibonacci(i)); long end = System.currentTimeMillis(); long time = end - start; times[i] += time; } } for (int j = 0; j < max; j++) { //System.out.println(j + ": " + times[j] / trials + "ms"); } } }
{ "pile_set_name": "Github" }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // type_traits // is_const #include <type_traits> #include "test_macros.h" template <class T> void test_is_const() { static_assert(!std::is_const<T>::value, ""); static_assert( std::is_const<const T>::value, ""); static_assert(!std::is_const<volatile T>::value, ""); static_assert( std::is_const<const volatile T>::value, ""); #if TEST_STD_VER > 14 static_assert(!std::is_const_v<T>, ""); static_assert( std::is_const_v<const T>, ""); static_assert(!std::is_const_v<volatile T>, ""); static_assert( std::is_const_v<const volatile T>, ""); #endif } int main() { test_is_const<void>(); test_is_const<int>(); test_is_const<double>(); test_is_const<int*>(); test_is_const<const int*>(); test_is_const<char[3]>(); test_is_const<char[]>(); static_assert(!std::is_const<int&>::value, ""); static_assert(!std::is_const<const int&>::value, ""); }
{ "pile_set_name": "Github" }
package mesosphere.marathon package api.v2 import mesosphere.UnitTest import mesosphere.marathon.state.{AbsolutePathId, AppDefinition} class LabelSelectorParsersTest extends UnitTest { "LabelSelectorParsers" should { "A valid existence label query can be parsed" in { val parser = new LabelSelectorParsers val existence = parser.parsed("existence") existence.selectors should have size 1 existence.selectors.head.key should be("existence") existence.selectors.head.value should have size 0 existence.matches(AppDefinition(id = runSpecId, labels = Map("existence" -> "one"), role = "*")) should be(true) existence.matches(AppDefinition(id = runSpecId, labels = Map("none" -> "one"), role = "*")) should be(false) } "A valid label equals query can be parsed" in { val parser = new LabelSelectorParsers val in = parser.parsed("foo == one") val in2 = parser.parsed("foo==one") in.selectors should have size 1 in.selectors.head.key should be("foo") in.selectors.head.value should be(List("one")) in2.selectors.head.value should be(List("one")) in.matches(AppDefinition(id = runSpecId, labels = Map("foo" -> "one"), role = "*")) should be(true) in.matches(AppDefinition(id = runSpecId, labels = Map("foo" -> "four"), role = "*")) should be(false) in.matches(AppDefinition(id = runSpecId, labels = Map("bla" -> "one"), role = "*")) should be(false) } "A valid label not equals query can be parsed" in { val parser = new LabelSelectorParsers val in = parser.parsed("foo != one") in.selectors should have size 1 in.selectors.head.key should be("foo") in.selectors.head.value should be(List("one")) in.matches(AppDefinition(id = runSpecId, labels = Map("foo" -> "one"), role = "*")) should be(false) in.matches(AppDefinition(id = runSpecId, labels = Map("foo" -> "four"), role = "*")) should be(true) in.matches(AppDefinition(id = runSpecId, labels = Map("bla" -> "one"), role = "*")) should be(false) } "A valid label set query can be parsed" in { val parser = new LabelSelectorParsers val in = parser.parsed("""foo in (one, two, three\ is\ cool)""") in.selectors should have size 1 in.selectors.head.key should be("foo") in.selectors.head.value should be(List("one", "two", "three is cool")) in.matches(AppDefinition(id = runSpecId, labels = Map("foo" -> "one"), role = "*")) should be(true) in.matches(AppDefinition(id = runSpecId, labels = Map("foo" -> "four"), role = "*")) should be(false) in.matches(AppDefinition(id = runSpecId, labels = Map("bla" -> "one"), role = "*")) should be(false) } "A valid notin label set query can be parsed" in { val parser = new LabelSelectorParsers val notin = parser.parsed("bla notin (one, two, three)") notin.selectors should have size 1 notin.selectors.head.key should be("bla") notin.selectors.head.value should be(List("one", "two", "three")) notin.matches(AppDefinition(id = runSpecId, labels = Map("bla" -> "one"), role = "*")) should be(false) notin.matches(AppDefinition(id = runSpecId, labels = Map("bla" -> "four"), role = "*")) should be(true) notin.matches(AppDefinition(id = runSpecId, labels = Map("rest" -> "one"), role = "*")) should be(false) } "A valid combined label query can be parsed" in { val parser = new LabelSelectorParsers val combined = parser.parsed("foo==one, bla!=one, foo in (one, two, three), bla notin (one, two, three), existence") combined.selectors should have size 5 combined.matches( AppDefinition(id = runSpecId, labels = Map("foo" -> "one", "bla" -> "four", "existence" -> "true"), role = "*") ) should be(true) combined.matches(AppDefinition(id = runSpecId, labels = Map("foo" -> "one"), role = "*")) should be(false) combined.matches(AppDefinition(id = runSpecId, labels = Map("bla" -> "four"), role = "*")) should be(false) } "A valid combined label query without alphanumeric characters can be parsed" in { val parser = new LabelSelectorParsers val combined = parser.parsed("""\{\{\{ in (\*\*\*, \&\&\&, \$\$\$), \^\^\^ notin (\-\-\-, \!\!\!, \@\@\@), \#\#\#""") combined.selectors should have size 3 combined.matches(AppDefinition(id = runSpecId, labels = Map("{{{" -> "&&&", "^^^" -> "&&&", "###" -> "&&&"), role = "*")) should be( true ) combined.matches(AppDefinition(id = runSpecId, labels = Map("^^^" -> "---"), role = "*")) should be(false) combined.matches(AppDefinition(id = runSpecId, labels = Map("###" -> "four"), role = "*")) should be(false) } "An invalid combined label query can not be parsed" in { intercept[IllegalArgumentException] { new LabelSelectorParsers().parsed("foo some (one, two, three)") } intercept[IllegalArgumentException] { new LabelSelectorParsers().parsed("foo in one") } intercept[IllegalArgumentException] { new LabelSelectorParsers().parsed("foo test") } } } val runSpecId = AbsolutePathId("/test") }
{ "pile_set_name": "Github" }
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for apply(). This converts apply(func, v, k) into (func)(*v, **k).""" # Local imports from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Call, Comma, parenthesize class FixApply(fixer_base.BaseFix): BM_compatible = True PATTERN = """ power< 'apply' trailer< '(' arglist< (not argument<NAME '=' any>) func=any ',' (not argument<NAME '=' any>) args=any [',' (not argument<NAME '=' any>) kwds=any] [','] > ')' > > """ def transform(self, node, results): syms = self.syms assert results func = results["func"] args = results["args"] kwds = results.get("kwds") prefix = node.prefix func = func.clone() if (func.type not in (token.NAME, syms.atom) and (func.type != syms.power or func.children[-2].type == token.DOUBLESTAR)): # Need to parenthesize func = parenthesize(func) func.prefix = "" args = args.clone() args.prefix = "" if kwds is not None: kwds = kwds.clone() kwds.prefix = "" l_newargs = [pytree.Leaf(token.STAR, "*"), args] if kwds is not None: l_newargs.extend([Comma(), pytree.Leaf(token.DOUBLESTAR, "**"), kwds]) l_newargs[-2].prefix = " " # that's the ** token # XXX Sometimes we could be cleverer, e.g. apply(f, (x, y) + t) # can be translated into f(x, y, *t) instead of f(*(x, y) + t) #new = pytree.Node(syms.power, (func, ArgList(l_newargs))) return Call(func, l_newargs, prefix=prefix)
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE FixtureDefinition> <FixtureDefinition xmlns="http://www.qlcplus.org/FixtureDefinition"> <Creator> <Name>Q Light Controller Plus</Name> <Version>4.12.3 GIT</Version> <Author>Jasper Zevering</Author> </Creator> <Manufacturer>Robe</Manufacturer> <Model>Robin Viva CMY</Model> <Type>Moving Head</Type> <Channel Name="Pan" Default="128" Preset="PositionPan"/> <Channel Name="Pan Fine" Preset="PositionPanFine"/> <Channel Name="Tilt" Default="128" Preset="PositionTilt"/> <Channel Name="Tilt Fine" Preset="PositionTiltFine"/> <Channel Name="Pan/Tilt speed , Pan/Tilt time"> <Group Byte="0">Speed</Group> <Capability Min="0" Max="0">Standard mode (0=default)</Capability> <Capability Min="1" Max="1">Max. Speed Mode</Capability> <Capability Min="2" Max="255">Speed from max. to min. (Time from 0.2 s to 25.5 sec.)</Capability> </Channel> <Channel Name="Power/Special functions"> <Group Byte="0">Maintenance</Group> <Capability Min="0" Max="9">Reserved (0=default)</Capability> <Capability Min="10" Max="14">DMX input: Wired DMX *</Capability> <Capability Min="15" Max="19">DMX input: Wireless DMX *</Capability> <Capability Min="20" Max="24">Graphic display On</Capability> <Capability Min="25" Max="29">Graphic display Off</Capability> <Capability Min="30" Max="49">Reserved</Capability> <Capability Min="50" Max="54">Dimmer curve: Square law</Capability> <Capability Min="55" Max="59">Dimmer curve: Linear</Capability> <Capability Min="60" Max="64">Fans mode: Auto</Capability> <Capability Min="65" Max="69">Fans mode: High</Capability> <Capability Min="70" Max="89">Reserved</Capability> <Capability Min="90" Max="94">Pan/Tilt speed mode</Capability> <Capability Min="95" Max="99">Pan/Tilt time mode</Capability> <Capability Min="100" Max="104">Blackout while pan/tilt moving</Capability> <Capability Min="105" Max="109">Disabled blackout while pan/tilt moving</Capability> <Capability Min="110" Max="114">Blackout while colour wheels moving</Capability> <Capability Min="115" Max="119">Disabled blackout while colour wheels moving</Capability> <Capability Min="120" Max="139">Reserved</Capability> <Capability Min="140" Max="149" Preset="ResetPanTilt">Pan/Tilt reset</Capability> <Capability Min="150" Max="159" Preset="ResetColor">Colour system reset</Capability> <Capability Min="160" Max="169">Gobo wheels + iris reset</Capability> <Capability Min="170" Max="179">Reserved</Capability> <Capability Min="180" Max="189">Zoom/focus/frost/prism reset</Capability> <Capability Min="190" Max="199">Reserved</Capability> <Capability Min="200" Max="209" Preset="ResetAll">Total reset</Capability> <Capability Min="210" Max="239">Reserved</Capability> <Capability Min="240" Max="240">Disable &quot;Quiet mode&quot;</Capability> <Capability Min="241" Max="255">&quot;Quiet mode&quot; - fan noise control from min. to max.</Capability> </Channel> <Channel Name="Colour wheel"> <Group Byte="0">Colour</Group> <Capability Min="0" Max="17" Preset="ColorMacro" Res1="#ffffff">Open/white (0=default)</Capability> <Capability Min="18" Max="36" Preset="ColorMacro" Res1="#ff0000">Deep red</Capability> <Capability Min="37" Max="54" Preset="ColorMacro" Res1="#00ff00">Green</Capability> <Capability Min="55" Max="72" Preset="ColorMacro" Res1="#ffd433">CTO</Capability> <Capability Min="73" Max="90" Preset="ColorMacro" Res1="#ffaa00">Orange</Capability> <Capability Min="91" Max="108" Preset="ColorMacro" Res1="#ff80ff">Lavender</Capability> <Capability Min="109" Max="127" Preset="ColorMacro" Res1="#0000ff">Congo blue</Capability> <Capability Min="128" Max="129" Preset="ColorMacro" Res1="#ffffff">Open/white</Capability> <Capability Min="130" Max="139" Preset="ColorMacro" Res1="#fc0107">Deep Red</Capability> <Capability Min="140" Max="149" Preset="ColorMacro" Res1="#21ff06">Green</Capability> <Capability Min="150" Max="159" Preset="ColorMacro" Res1="#ffd433">CTO</Capability> <Capability Min="160" Max="169" Preset="ColorMacro" Res1="#ffb600">Orange</Capability> <Capability Min="170" Max="179" Preset="ColorMacro" Res1="#ff7fff">Lavender</Capability> <Capability Min="180" Max="189" Preset="ColorMacro" Res1="#0000ff">Congo Blue</Capability> <Capability Min="190" Max="215">Forwards rainbow effect from fast to slow</Capability> <Capability Min="216" Max="217">No rotation</Capability> <Capability Min="218" Max="243">Backwards rainbow effect from slow to fast</Capability> <Capability Min="244" Max="249">Random colour selection by audio control</Capability> <Capability Min="250" Max="255">Auto random colour selection from fast to slow</Capability> </Channel> <Channel Name="Colour wheel - fine positioning" Preset="ColorWheelFine"/> <Channel Name="Cyan" Preset="IntensityCyan"/> <Channel Name="Magenta" Preset="IntensityMagenta"/> <Channel Name="Yellow" Preset="IntensityYellow"/> <Channel Name="Virtual colour wheel"> <Group Byte="0">Colour</Group> <Capability Min="0" Max="0">No function (0=default)</Capability> <Capability Min="1" Max="2">LEE 4 (Medium Bastard Amber)</Capability> <Capability Min="3" Max="4">LEE 10 (Medium Yellow)</Capability> <Capability Min="5" Max="6">LEE 19 (Fire)</Capability> <Capability Min="7" Max="8">LEE 24 (Scarlet)</Capability> <Capability Min="9" Max="10">LEE 58 (Lavender)</Capability> <Capability Min="11" Max="12">LEE 68 (Sky Blue)</Capability> <Capability Min="13" Max="14">LEE 71 (Tokyo Blue)</Capability> <Capability Min="15" Max="16">LEE 79 (Just Blue)</Capability> <Capability Min="17" Max="18">LEE 88 (Lime Green)</Capability> <Capability Min="19" Max="20">LEE 90 (Dark Yellow Green)</Capability> <Capability Min="21" Max="22">LEE 100 (Spring Yellow)</Capability> <Capability Min="23" Max="24">LEE 101 (Yellow)</Capability> <Capability Min="25" Max="26">LEE 102 (Light Amber)</Capability> <Capability Min="27" Max="28">LEE 103 (Straw)</Capability> <Capability Min="29" Max="30">Lee 104 (Deep Amber)</Capability> <Capability Min="31" Max="32">LEE 105 (Orange)</Capability> <Capability Min="33" Max="34">LEE 781 (Terry Red)</Capability> <Capability Min="35" Max="36">LEE 111 (Dark Pink)</Capability> <Capability Min="37" Max="38">LEE 115 (Peacock Blue)</Capability> <Capability Min="39" Max="40">LEE 505 (Sally Green)</Capability> <Capability Min="41" Max="42">LEE 117 (Steel Blue)</Capability> <Capability Min="43" Max="44">LEE 118 (Light Blue)</Capability> <Capability Min="45" Max="46">LEE 724 (Ocean Blue)</Capability> <Capability Min="47" Max="48">LEE 725 (Old Steel Blue</Capability> <Capability Min="49" Max="50">LEE 121 (LEE Green)</Capability> <Capability Min="51" Max="52">LEE 128 (Bright Pink)</Capability> <Capability Min="53" Max="54">LEE 131 (Marine Blue)</Capability> <Capability Min="55" Max="56">LEE 132 (Medium Blue)</Capability> <Capability Min="57" Max="58">LEE 134 (Golden Amber)</Capability> <Capability Min="59" Max="60">LEE 135 (Deep Golden Amber)</Capability> <Capability Min="61" Max="62">LEE 136 (Pale Lavender)</Capability> <Capability Min="63" Max="64">LEE 137 (Special Lavender)</Capability> <Capability Min="65" Max="66">LEE 138 (Pale Green)</Capability> <Capability Min="67" Max="68">LEE 139 (Primary Green)</Capability> <Capability Min="69" Max="70">LEE 141 (Bright Blue)</Capability> <Capability Min="71" Max="72">LEE 147 (Apricot)</Capability> <Capability Min="73" Max="74">LEE 148 (Bright Rose)</Capability> <Capability Min="75" Max="76">LEE 152 (Pale Gold)</Capability> <Capability Min="77" Max="78">LEE 154 (Pale Rose)</Capability> <Capability Min="79" Max="80">LEE 157 (Pink)</Capability> <Capability Min="81" Max="82">LEE 158 (Deep Orange)</Capability> <Capability Min="83" Max="84">LEE 162 (Bastard Amber)</Capability> <Capability Min="85" Max="86">LEE 164 (Flame Red)</Capability> <Capability Min="87" Max="88">LEE 165 (Daylight Blue)</Capability> <Capability Min="89" Max="90">LEE 169 (Lilac Tint)</Capability> <Capability Min="91" Max="92">LEE 170 (Deep Lavender)</Capability> <Capability Min="93" Max="94">LEE 172 (Lagoon Blue)</Capability> <Capability Min="95" Max="96">LEE 179 (Chrome Orange)</Capability> <Capability Min="97" Max="98">LEE 180 (Dark Lavender)</Capability> <Capability Min="99" Max="100">LEE 181 (Congo Blue)</Capability> <Capability Min="101" Max="102">LEE 197 (Alice Blue)</Capability> <Capability Min="103" Max="104">LEE 201 (Full C.T. Blue)</Capability> <Capability Min="105" Max="106">LEE 202 (Half C.T. Blue)</Capability> <Capability Min="107" Max="108">LEE 203 (Quarter C.T. Blue)</Capability> <Capability Min="109" Max="110">LEE 204 (Full C.T. Orange)</Capability> <Capability Min="111" Max="112">LEE 205 (Half C.T. Orange)</Capability> <Capability Min="113" Max="114">LEE 206 (Quarter C.T. Orange)</Capability> <Capability Min="115" Max="116">LEE 247 (LEE Minus Green)</Capability> <Capability Min="117" Max="118">LEE 248 (Half Minus Green)</Capability> <Capability Min="119" Max="120">LEE 281 (Three Quarter C.T. Blue)</Capability> <Capability Min="121" Max="122">LEE 285 (Three Quarter C.T. Orange)</Capability> <Capability Min="123" Max="124">LEE 352 (Glacier Blue)</Capability> <Capability Min="125" Max="126">LEE 353 (Lighter Blue)</Capability> <Capability Min="127" Max="128">LEE 715 (Cabana Blue)</Capability> <Capability Min="129" Max="130">LEE 778 (Millennium Gold)</Capability> <Capability Min="131" Max="132">LEE 328 (Follies Pink)</Capability> <Capability Min="133" Max="255">Reserved</Capability> </Channel> <Channel Name="Effect speed"> <Group Byte="0">Speed</Group> <Capability Min="0" Max="255">Speed of CMY and rot.gobo/static gobo selection from max. to min.</Capability> </Channel> <Channel Name="Colour wheel + CMY time"> <Group Byte="0">Speed</Group> <Capability Min="0" Max="0">Function is off (0=default)</Capability> <Capability Min="1" Max="255">Time of Colour wheel +CMY movement (0.1sec--&gt;25.5sec.)</Capability> </Channel> <Channel Name="Stat. Gobo+Zoom+Focus+Frost+Iris+Prism time"> <Group Byte="0">Speed</Group> <Capability Min="0" Max="0">Function is off (0=default)</Capability> <Capability Min="1" Max="255">Time of stat. Gobo, zoom, focus,iris and frost movement (0.1 sec-- &gt;25.5 sec.) 1-50 Time of prism movement (0.1 sec--&gt;5 sec.)</Capability> </Channel> <Channel Name="Static gobo wheel"> <Group Byte="0">Gobo</Group> <Capability Min="0" Max="8">Open/hole (0=default)</Capability> <Capability Min="9" Max="17">Gobo 1</Capability> <Capability Min="18" Max="26">Gobo 2</Capability> <Capability Min="27" Max="35">Gobo 3</Capability> <Capability Min="36" Max="44">Gobo 4</Capability> <Capability Min="45" Max="53">Gobo 5</Capability> <Capability Min="54" Max="62">Gobo 6</Capability> <Capability Min="63" Max="71">Gobo 7</Capability> <Capability Min="72" Max="80">Gobo 8</Capability> <Capability Min="81" Max="91">Gobo 9</Capability> <Capability Min="92" Max="103">Gobo 1 shaking</Capability> <Capability Min="104" Max="115">Gobo 2 shaking</Capability> <Capability Min="116" Max="127">Gobo 3 shaking</Capability> <Capability Min="128" Max="139">Gobo 4 shaking</Capability> <Capability Min="140" Max="151">Gobo 5 shaking</Capability> <Capability Min="152" Max="163">Gobo 6 shaking</Capability> <Capability Min="164" Max="175">Gobo 7 shaking</Capability> <Capability Min="176" Max="187">Gobo 8 shaking</Capability> <Capability Min="188" Max="199">Gobo 9 shaking</Capability> <Capability Min="200" Max="201">Open/hole</Capability> <Capability Min="202" Max="222">Forwards gobo wheel rotation from fast to slow</Capability> <Capability Min="223" Max="243">Backwards gobo wheel rotation from slow to fast</Capability> <Capability Min="244" Max="249">Random gobo selection by audio control</Capability> <Capability Min="250" Max="255">Auto random gobo selection from fast to slow</Capability> </Channel> <Channel Name="Rotating gobo wheel"> <Group Byte="0">Gobo</Group> <Capability Min="0" Max="3">Gobo 1 Index</Capability> <Capability Min="4" Max="7">Gobo 2 Index</Capability> <Capability Min="8" Max="11">Gobo 3 Index</Capability> <Capability Min="12" Max="15">Gobo 4 Index</Capability> <Capability Min="16" Max="19">Gobo 5 Index</Capability> <Capability Min="20" Max="23">Gobo 6 Index</Capability> <Capability Min="24" Max="27">Gobo 7 Index</Capability> <Capability Min="28" Max="31">Gobo 8 Index</Capability> <Capability Min="32" Max="35">Gobo 1 rotation</Capability> <Capability Min="36" Max="39">Gobo 2 rotation</Capability> <Capability Min="40" Max="43">Gobo 3 rotation</Capability> <Capability Min="44" Max="47">Gobo 4 rotation</Capability> <Capability Min="48" Max="51">Gobo 5 rotation</Capability> <Capability Min="52" Max="55">Gobo 6 rotation</Capability> <Capability Min="56" Max="59">Gobo 7 rotation</Capability> <Capability Min="60" Max="69">Gobo 7 shaking</Capability> <Capability Min="70" Max="79">Gobo 7 shaking</Capability> <Capability Min="80" Max="89">Gobo 7 shaking</Capability> <Capability Min="90" Max="99">Gobo 7 shaking</Capability> <Capability Min="100" Max="109">Gobo 7 shaking</Capability> <Capability Min="110" Max="119">Gobo 7 shaking</Capability> <Capability Min="120" Max="129">Gobo 7 shaking</Capability> <Capability Min="130" Max="139">Gobo 1 rotation + shaking</Capability> <Capability Min="140" Max="149">Gobo 2 rotation + shaking</Capability> <Capability Min="150" Max="159">Gobo 3 rotation + shaking</Capability> <Capability Min="160" Max="169">Gobo 4 rotation + shaking</Capability> <Capability Min="170" Max="179">Gobo 5 rotation + shaking</Capability> <Capability Min="180" Max="189">Gobo 6 rotation + shaking</Capability> <Capability Min="190" Max="199">Gobo 7 rotation + shaking</Capability> <Capability Min="200" Max="201">Open/hole</Capability> <Capability Min="202" Max="222">Forwards gobo wheel rotation from fast to slow</Capability> <Capability Min="223" Max="243">Backwards gobo wheel rotation from slow to fast</Capability> <Capability Min="244" Max="249">Random gobo selection by audio control</Capability> <Capability Min="250" Max="255">Auto random gobo selection from fast to slow</Capability> </Channel> <Channel Name="Rot. Gobo indexing/rotation"> <Group Byte="0">Speed</Group> <Capability Min="0" Max="255">0-255 Gobo indexing // 1 - 127 Forwards gobo rotation from fast to slow 128 No rotation 129 - 255 Backwards gobo rotation from slow to fast</Capability> </Channel> <Channel Name="Rot. Gobo indexing/rotation - fine"> <Group Byte="1">Speed</Group> <Capability Min="0" Max="255">Fine indexing/rotation (0=default)</Capability> </Channel> <Channel Name="Prism"> <Group Byte="0">Prism</Group> <Capability Min="0" Max="19">Open position/hole (0=default)</Capability> <Capability Min="20" Max="127">3-facet rotating prism</Capability> <Capability Min="128" Max="135">Macro 1</Capability> <Capability Min="136" Max="143">Macro 2</Capability> <Capability Min="144" Max="151">Macro 3</Capability> <Capability Min="152" Max="159">Macro 4</Capability> <Capability Min="160" Max="167">Macro 5</Capability> <Capability Min="168" Max="175">Macro 6</Capability> <Capability Min="176" Max="183">Macro 7</Capability> <Capability Min="184" Max="191">Macro 8</Capability> <Capability Min="192" Max="199">Macro 9</Capability> <Capability Min="200" Max="207">Macro 10</Capability> <Capability Min="208" Max="215">Macro 11</Capability> <Capability Min="216" Max="223">Macro 12</Capability> <Capability Min="224" Max="231">Macro 13</Capability> <Capability Min="232" Max="239">Macro 14</Capability> <Capability Min="240" Max="247">Macro 15</Capability> <Capability Min="248" Max="255">Macro 16</Capability> </Channel> <Channel Name="Prism rotation"> <Group Byte="0">Speed</Group> <Capability Min="0" Max="0">No rotation</Capability> <Capability Min="1" Max="127">Forwards rotation from fast to slow</Capability> <Capability Min="128" Max="128">No rotation (128= default)</Capability> <Capability Min="129" Max="255">Backwards rotation from slow to fast</Capability> </Channel> <Channel Name="Frost"> <Group Byte="0">Beam</Group> <Capability Min="0" Max="0">Open</Capability> <Capability Min="1" Max="179">Frost from 0% to 100%</Capability> <Capability Min="180" Max="189">100% frost</Capability> <Capability Min="190" Max="211">Pulse closing from slow to fast</Capability> <Capability Min="212" Max="233">Pulse opening from fast to slow</Capability> <Capability Min="234" Max="255">Ramping from fast to slow</Capability> </Channel> <Channel Name="Iris"> <Group Byte="0">Beam</Group> <Capability Min="0" Max="0">Open</Capability> <Capability Min="1" Max="179">From max.diameter to min.diameter</Capability> <Capability Min="180" Max="191">Closed</Capability> <Capability Min="192" Max="219">Pulse opening from slow to fast</Capability> <Capability Min="220" Max="247">Pulse closing from fast to slow</Capability> <Capability Min="248" Max="249">Random pulse opening (fast)</Capability> <Capability Min="250" Max="251">Random pulse opening (slow)</Capability> <Capability Min="252" Max="253">Random pulse closing (fast)</Capability> <Capability Min="254" Max="255">Random pulse closing (slow)</Capability> </Channel> <Channel Name="Iris - fine" Preset="ShutterIrisFine"/> <Channel Name="Zoom"> <Group Byte="0">Beam</Group> <Capability Min="0" Max="255">Zoom from max. to min.beam angle (128=default)</Capability> </Channel> <Channel Name="Zoom - fine"> <Group Byte="1">Beam</Group> <Capability Min="0" Max="255">Fine zooming (0=default)</Capability> </Channel> <Channel Name="Focus"> <Group Byte="0">Beam</Group> <Capability Min="0" Max="255">Continuous adjustment from far to near (128=default)</Capability> </Channel> <Channel Name="Focus - fine"> <Group Byte="1">Beam</Group> <Capability Min="0" Max="255">Fine focusing (0=default)</Capability> </Channel> <Channel Name="Reserved"> <Group Byte="0">Nothing</Group> <Capability Min="0" Max="255">Reserved for future functions</Capability> </Channel> <Channel Name="Shutter/ strobe" Default="32"> <Group Byte="0">Shutter</Group> <Capability Min="0" Max="31" Preset="ShutterClose">Shutter closed</Capability> <Capability Min="32" Max="63" Preset="ShutterOpen">Shutter open (32=default)</Capability> <Capability Min="64" Max="95" Preset="StrobeSlowToFast">Strobe-effect from slow to fast</Capability> <Capability Min="96" Max="127" Preset="ShutterOpen">Shutter open</Capability> <Capability Min="128" Max="143" Preset="RampDownSlowToFast">Opening pulse in sequences from slow to fast</Capability> <Capability Min="144" Max="159" Preset="RampDownFastToSlow">Closing pulse in sequences from fast to slow</Capability> <Capability Min="160" Max="191" Preset="ShutterOpen">Shutter open</Capability> <Capability Min="192" Max="223" Preset="StrobeRandomSlowToFast">Random strobe-effect from slow to fast</Capability> <Capability Min="224" Max="255" Preset="ShutterOpen">Shutter open</Capability> </Channel> <Channel Name="Dimmer intensity" Preset="IntensityMasterDimmer"/> <Channel Name="Dimmer intensity - fine" Preset="IntensityMasterDimmerFine"/> <Mode Name="Standard 16 bit"> <Channel Number="0">Pan</Channel> <Channel Number="1">Pan Fine</Channel> <Channel Number="2">Tilt</Channel> <Channel Number="3">Tilt Fine</Channel> <Channel Number="4">Pan/Tilt speed , Pan/Tilt time</Channel> <Channel Number="5">Power/Special functions</Channel> <Channel Number="6">Colour wheel</Channel> <Channel Number="7">Colour wheel - fine positioning</Channel> <Channel Number="8">Cyan</Channel> <Channel Number="9">Magenta</Channel> <Channel Number="10">Yellow</Channel> <Channel Number="11">Virtual colour wheel</Channel> <Channel Number="12">Effect speed</Channel> <Channel Number="13">Colour wheel + CMY time</Channel> <Channel Number="14">Stat. Gobo+Zoom+Focus+Frost+Iris+Prism time</Channel> <Channel Number="15">Static gobo wheel</Channel> <Channel Number="16">Rotating gobo wheel</Channel> <Channel Number="17">Rot. Gobo indexing/rotation</Channel> <Channel Number="18">Rot. Gobo indexing/rotation - fine</Channel> <Channel Number="19">Prism</Channel> <Channel Number="20">Prism rotation</Channel> <Channel Number="21">Frost</Channel> <Channel Number="22">Iris</Channel> <Channel Number="23">Iris - fine</Channel> <Channel Number="24">Zoom</Channel> <Channel Number="25">Zoom - fine</Channel> <Channel Number="26">Focus</Channel> <Channel Number="27">Focus - fine</Channel> <Channel Number="28">Reserved</Channel> <Channel Number="29">Shutter/ strobe</Channel> <Channel Number="30">Dimmer intensity</Channel> <Channel Number="31">Dimmer intensity - fine</Channel> </Mode> <Mode Name="Reduced 8 bit"> <Channel Number="0">Pan</Channel> <Channel Number="1">Pan Fine</Channel> <Channel Number="2">Tilt</Channel> <Channel Number="3">Tilt Fine</Channel> <Channel Number="4">Pan/Tilt speed , Pan/Tilt time</Channel> <Channel Number="5">Power/Special functions</Channel> <Channel Number="6">Colour wheel</Channel> <Channel Number="7">Cyan</Channel> <Channel Number="8">Magenta</Channel> <Channel Number="9">Yellow</Channel> <Channel Number="10">Virtual colour wheel</Channel> <Channel Number="11">Effect speed</Channel> <Channel Number="12">Colour wheel + CMY time</Channel> <Channel Number="13">Stat. Gobo+Zoom+Focus+Frost+Iris+Prism time</Channel> <Channel Number="14">Static gobo wheel</Channel> <Channel Number="15">Rotating gobo wheel</Channel> <Channel Number="16">Rot. Gobo indexing/rotation</Channel> <Channel Number="17">Prism</Channel> <Channel Number="18">Prism rotation</Channel> <Channel Number="19">Frost</Channel> <Channel Number="20">Iris</Channel> <Channel Number="21">Zoom</Channel> <Channel Number="22">Focus</Channel> <Channel Number="23">Reserved</Channel> <Channel Number="24">Shutter/ strobe</Channel> <Channel Number="25">Dimmer intensity</Channel> </Mode> <Physical> <Bulb Type="LED" Lumens="9660" ColourTemperature="6500"/> <Dimensions Weight="19" Width="382" Height="664" Depth="250"/> <Lens Name="Other" DegreesMin="9" DegreesMax="40"/> <Focus Type="Fixed" PanMax="540" TiltMax="270"/> <Technical PowerConsumption="500" DmxConnector="3-pin and 5-pin"/> </Physical> </FixtureDefinition>
{ "pile_set_name": "Github" }
namespace SharpLab.Runtime.Internal { public static class InspectionSettings { public static bool ProfilerActive { get; set; } public static int CurrentProcessId { get; set; } public static ulong StackStart { get; set; } } }
{ "pile_set_name": "Github" }
#Mon Jan 15 14:40:24 CST 2018 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
{ "pile_set_name": "Github" }
define( [ "./deletedIds" ], function( deletedIds ) { return deletedIds.indexOf; } );
{ "pile_set_name": "Github" }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ #pragma once #include <folly/futures/Future.h> #include <atomic> #include <utility> #include "eden/fs/fuse/FuseChannel.h" #include "eden/fs/fuse/FuseTypes.h" #include "eden/fs/inodes/RequestContext.h" #include "eden/fs/store/ImportPriority.h" #include "eden/fs/store/ObjectFetchContext.h" #include "eden/fs/telemetry/EdenStats.h" #include "eden/fs/telemetry/RequestMetricsScope.h" namespace facebook { namespace eden { /** * Each FUSE request has a corresponding FuseRequestContext object that is * allocated at request start and deallocated when it finishes. * * Unless a member function indicates otherwise, FuseRequestContext may be used * from multiple threads, but only by one thread at a time. */ class FuseRequestContext : public RequestContext { FuseChannel* channel_; fuse_in_header fuseHeader_; fuse_in_header stealReq(); public: FuseRequestContext(const FuseRequestContext&) = delete; FuseRequestContext& operator=(const FuseRequestContext&) = delete; FuseRequestContext(FuseRequestContext&&) = delete; FuseRequestContext& operator=(FuseRequestContext&&) = delete; explicit FuseRequestContext( FuseChannel* channel, const fuse_in_header& fuseHeader); // Override of `ObjectFetchContext` std::optional<pid_t> getClientPid() const override { return static_cast<pid_t>(fuseHeader_.pid); } // Returns the underlying fuse request, throwing an error if it has // already been released const fuse_in_header& getReq() const; // Returns the underlying fuse request. Unlike getReq this function doesn't // throw. The caller is responsible to verify that the fuse_in_header is // valid by checking if (fuseHeader.opcode != 0) const fuse_in_header& examineReq() const; /** Append error handling clauses to a future chain * These clauses result in reporting a fuse request error back to the * kernel. */ folly::Future<folly::Unit> catchErrors( folly::Future<folly::Unit>&& fut, Notifications* FOLLY_NULLABLE notifications) { return std::move(fut).thenTryInline([this, notifications]( folly::Try<folly::Unit>&& try_) { SCOPE_EXIT { finishRequest(); }; if (try_.hasException()) { if (auto* err = try_.tryGetExceptionObject<folly::FutureTimeout>()) { timeoutErrorHandler(*err, notifications); } else if ( auto* err = try_.tryGetExceptionObject<std::system_error>()) { systemErrorHandler(*err, notifications); } else if (auto* err = try_.tryGetExceptionObject<std::exception>()) { genericErrorHandler(*err, notifications); } else { genericErrorHandler( std::runtime_error{"unknown exception type"}, notifications); } } }); } void systemErrorHandler( const std::system_error& err, Notifications* FOLLY_NULLABLE notifications); void genericErrorHandler( const std::exception& err, Notifications* FOLLY_NULLABLE notifications); void timeoutErrorHandler( const folly::FutureTimeout& err, Notifications* FOLLY_NULLABLE notifications); template <typename T> void sendReply(const T& payload) { channel_->sendReply(stealReq(), payload); } template <typename T> void sendReply(T&& payload) { channel_->sendReply(stealReq(), std::forward<T>(payload)); } // Reply with a negative errno value or 0 for success void replyError(int err); // Don't send a reply, just release req_ void replyNone(); }; } // namespace eden } // namespace facebook
{ "pile_set_name": "Github" }
-- DISTRIBUTE_RESULT |PARTITIONED| -- ONE_TO_ONE_EXCHANGE |PARTITIONED| -- STREAM_PROJECT |PARTITIONED| -- ONE_TO_ONE_EXCHANGE |PARTITIONED| -- STABLE_SORT [$$25(ASC)] |PARTITIONED| -- RANGE_PARTITION_EXCHANGE [$$25(ASC)] |PARTITIONED| -- FORWARD |PARTITIONED| -- ONE_TO_ONE_EXCHANGE |PARTITIONED| -- REPLICATE |PARTITIONED| -- ONE_TO_ONE_EXCHANGE |PARTITIONED| -- STREAM_SELECT |PARTITIONED| -- ONE_TO_ONE_EXCHANGE |PARTITIONED| -- BTREE_SEARCH |PARTITIONED| -- ONE_TO_ONE_EXCHANGE |PARTITIONED| -- STABLE_SORT [$$29(ASC)] |PARTITIONED| -- ONE_TO_ONE_EXCHANGE |PARTITIONED| -- LENGTH_PARTITIONED_INVERTED_INDEX_SEARCH |PARTITIONED| -- ONE_TO_ONE_EXCHANGE |PARTITIONED| -- ASSIGN |PARTITIONED| -- EMPTY_TUPLE_SOURCE |PARTITIONED| -- BROADCAST_EXCHANGE |PARTITIONED| -- AGGREGATE |UNPARTITIONED| -- RANDOM_MERGE_EXCHANGE |PARTITIONED| -- AGGREGATE |PARTITIONED| -- STREAM_PROJECT |PARTITIONED| -- ONE_TO_ONE_EXCHANGE |PARTITIONED| -- REPLICATE |PARTITIONED| -- ONE_TO_ONE_EXCHANGE |PARTITIONED| -- STREAM_SELECT |PARTITIONED| -- ONE_TO_ONE_EXCHANGE |PARTITIONED| -- BTREE_SEARCH |PARTITIONED| -- ONE_TO_ONE_EXCHANGE |PARTITIONED| -- STABLE_SORT [$$29(ASC)] |PARTITIONED| -- ONE_TO_ONE_EXCHANGE |PARTITIONED| -- LENGTH_PARTITIONED_INVERTED_INDEX_SEARCH |PARTITIONED| -- ONE_TO_ONE_EXCHANGE |PARTITIONED| -- ASSIGN |PARTITIONED| -- EMPTY_TUPLE_SOURCE |PARTITIONED|
{ "pile_set_name": "Github" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Flot Examples</title> <link href="layout.css" rel="stylesheet" type="text/css"> <!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../excanvas.min.js"></script><![endif]--> <script language="javascript" type="text/javascript" src="../jquery.js"></script> <script language="javascript" type="text/javascript" src="../jquery.flot.js"></script> </head> <body> <h1>Flot Examples</h1> <div id="placeholder" style="width:600px;height:300px"></div> <p>One of the goals of Flot is to support user interactions. Try pointing and clicking on the points.</p> <p id="hoverdata">Mouse hovers at (<span id="x">0</span>, <span id="y">0</span>). <span id="clickdata"></span></p> <p>A tooltip is easy to build with a bit of jQuery code and the data returned from the plot.</p> <p><input id="enableTooltip" type="checkbox">Enable tooltip</p> <script type="text/javascript"> $(function () { var sin = [], cos = []; for (var i = 0; i < 14; i += 0.5) { sin.push([i, Math.sin(i)]); cos.push([i, Math.cos(i)]); } var plot = $.plot($("#placeholder"), [ { data: sin, label: "sin(x)"}, { data: cos, label: "cos(x)" } ], { series: { lines: { show: true }, points: { show: true } }, grid: { hoverable: true, clickable: true }, yaxis: { min: -1.2, max: 1.2 } }); function showTooltip(x, y, contents) { $('<div id="tooltip">' + contents + '</div>').css( { position: 'absolute', display: 'none', top: y + 5, left: x + 5, border: '1px solid #fdd', padding: '2px', 'background-color': '#fee', opacity: 0.80 }).appendTo("body").fadeIn(200); } var previousPoint = null; $("#placeholder").bind("plothover", function (event, pos, item) { $("#x").text(pos.x.toFixed(2)); $("#y").text(pos.y.toFixed(2)); if ($("#enableTooltip:checked").length > 0) { if (item) { if (previousPoint != item.dataIndex) { previousPoint = item.dataIndex; $("#tooltip").remove(); var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2); showTooltip(item.pageX, item.pageY, item.series.label + " of " + x + " = " + y); } } else { $("#tooltip").remove(); previousPoint = null; } } }); $("#placeholder").bind("plotclick", function (event, pos, item) { if (item) { $("#clickdata").text("You clicked point " + item.dataIndex + " in " + item.series.label + "."); plot.highlight(item.series, item.datapoint); } }); }); </script> </body> </html>
{ "pile_set_name": "Github" }
<?php /** * This file is audio handler * * PHP version 7 * * @category Media * @package Xpressengine\Media * @author XE Developers <[email protected]> * @copyright 2020 Copyright XEHub Corp. <https://www.xehub.io> * @license http://www.gnu.org/licenses/lgpl-3.0-standalone.html LGPL * @link https://xpressengine.io */ namespace Xpressengine\Media\Handlers; use Xpressengine\Media\Exceptions\NotAvailableException; use Xpressengine\Media\Models\Media; use Xpressengine\Media\Models\Audio; use Xpressengine\Media\Repositories\AudioRepository; use Xpressengine\Storage\TempFileCreator; use Xpressengine\Storage\File; /** * Class AudioHandler * * @category Media * @package Xpressengine\Media * @author XE Developers <[email protected]> * @copyright 2020 Copyright XEHub Corp. <https://www.xehub.io> * @license http://www.gnu.org/licenses/lgpl-3.0-standalone.html LGPL * @link https://xpressengine.io */ class AudioHandler extends AbstractHandler { /** * Media reader instance * * @var \getID3 */ protected $reader; /** * TempFileCreator instance * * @var TempFileCreator */ protected $temp; /** * Constructor * * @param AudioRepository $repo AudioRepository instance * @param \getID3 $reader Media reader instance * @param TempFileCreator $temp TempFileCreator instance */ public function __construct(AudioRepository $repo, \getID3 $reader, TempFileCreator $temp) { parent::__construct($repo); $this->reader = $reader; $this->temp = $temp; } /** * 미디어에서 사진 추출 * * @param Media $media audio instance * @return null */ public function getPicture(Media $media) { return null; } /** * media 객체로 반환 * * @param File $file file instance * @return Audio * @throws NotAvailableException */ public function make(File $file) { if ($this->isAvailable($file->mime) !== true) { throw new NotAvailableException(); } $audio = $this->makeModel($file); if (!$audio->meta) { list($audioData, $playtime, $bitrate) = $this->extractInformation($audio); $meta = $audio->meta()->create([ 'audio' => $audioData, 'playtime' => $playtime, 'bitrate' => $bitrate, ]); $audio->setRelation('meta', $meta); } return $audio; } /** * Extract file meta data * * @param Audio $audio audio file instance * @return array */ protected function extractInformation(Audio $audio) { $tmpFile = $this->temp->create($audio->getContent()); $info = $this->reader->analyze($tmpFile->getPathname()); $tmpFile->destroy(); if (isset($info['audio']['streams'])) { unset($info['audio']['streams']); } return [$info['audio'], $info['playtime_seconds'], $info['bitrate']]; } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="15702" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct"> <dependencies> <deployment identifier="macosx"/> <plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="15702"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <objects> <customObject id="-2" userLabel="File's Owner" customClass="FBLauncherController"> <connections> <outlet property="progressPanel" destination="hEA-LJ-CM5" id="orM-UI-yKC"/> <outlet property="progressPanelBar" destination="CGz-AO-sJG" id="fqP-zG-MPD"/> <outlet property="progressPanelCancelButton" destination="QBI-GE-Mwp" id="iAB-1p-RwW"/> <outlet property="progressPanelLabel" destination="wTx-rb-XUh" id="aBh-BZ-oN9"/> <outlet property="romSetTreeController" destination="IZb-g9-uEr" id="LXG-Ox-P93"/> <outlet property="window" destination="QvC-M9-y7g" id="qj1-RH-US7"/> </connections> </customObject> <customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/> <customObject id="-3" userLabel="Application" customClass="NSObject"/> <window title="FinalBurn Neo Launcher" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" visibleAtLaunch="NO" animationBehavior="default" id="QvC-M9-y7g"> <windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/> <windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/> <rect key="contentRect" x="196" y="240" width="594" height="549"/> <rect key="screenRect" x="0.0" y="0.0" width="2560" height="1417"/> <view key="contentView" wantsLayer="YES" id="EiT-Mj-1SZ"> <rect key="frame" x="0.0" y="0.0" width="594" height="549"/> <autoresizingMask key="autoresizingMask"/> <subviews> <scrollView autohidesScrollers="YES" horizontalLineScroll="19" horizontalPageScroll="10" verticalLineScroll="19" verticalPageScroll="10" usesPredominantAxisScrolling="NO" translatesAutoresizingMaskIntoConstraints="NO" id="uLN-UU-wUx" customClass="FBDropFileScrollView"> <rect key="frame" x="-1" y="-1" width="596" height="551"/> <clipView key="contentView" id="Dhm-mF-Mxw"> <rect key="frame" x="1" y="0.0" width="594" height="550"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <outlineView verticalHuggingPriority="750" allowsExpansionToolTips="YES" columnAutoresizingStyle="lastColumnOnly" multipleSelection="NO" autosaveColumns="NO" headerView="3Ac-aF-wVK" indentationPerLevel="16" outlineTableColumn="SfF-mw-sk3" id="LI1-S9-omw"> <rect key="frame" x="0.0" y="0.0" width="594" height="525"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <size key="intercellSpacing" width="3" height="2"/> <color key="backgroundColor" name="controlBackgroundColor" catalog="System" colorSpace="catalog"/> <color key="gridColor" name="gridColor" catalog="System" colorSpace="catalog"/> <tableColumns> <tableColumn editable="NO" width="73" minWidth="40" maxWidth="1000" id="sYe-77-mxg"> <tableHeaderCell key="headerCell" lineBreakMode="truncatingTail" borderStyle="border" title="Status"> <font key="font" metaFont="message" size="11"/> <color key="textColor" name="headerTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="headerColor" catalog="System" colorSpace="catalog"/> </tableHeaderCell> <imageCell key="dataCell" refusesFirstResponder="YES" alignment="left" imageScaling="proportionallyDown" id="37K-uV-JwN"/> <tableColumnResizingMask key="resizingMask" resizeWithTable="YES" userResizable="YES"/> <connections> <binding destination="IZb-g9-uEr" name="value" keyPath="arrangedObjects.status" id="D1U-05-p70"> <dictionary key="options"> <string key="NSValueTransformerName">FBRomSetStatusAsNSImage</string> </dictionary> </binding> </connections> </tableColumn> <tableColumn editable="NO" width="116" minWidth="40" maxWidth="1000" id="SfF-mw-sk3"> <tableHeaderCell key="headerCell" lineBreakMode="truncatingTail" borderStyle="border" title="Name"> <font key="font" metaFont="message" size="11"/> <color key="textColor" name="headerTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="headerColor" catalog="System" colorSpace="catalog"/> </tableHeaderCell> <textFieldCell key="dataCell" lineBreakMode="truncatingTail" selectable="YES" editable="YES" title="Text Cell" id="AVl-5b-hSg"> <font key="font" metaFont="message" size="11"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <tableColumnResizingMask key="resizingMask" resizeWithTable="YES" userResizable="YES"/> <connections> <binding destination="IZb-g9-uEr" name="value" keyPath="arrangedObjects.name" id="sC4-4h-dIP"/> </connections> </tableColumn> <tableColumn editable="NO" width="396" minWidth="40" maxWidth="1000" id="HLR-VA-LE2"> <tableHeaderCell key="headerCell" lineBreakMode="truncatingTail" borderStyle="border" title="Title"> <font key="font" metaFont="message" size="11"/> <color key="textColor" name="headerTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="headerColor" catalog="System" colorSpace="catalog"/> </tableHeaderCell> <textFieldCell key="dataCell" lineBreakMode="truncatingTail" selectable="YES" editable="YES" title="Text Cell" id="Qf5-Np-ORW"> <font key="font" metaFont="message" size="11"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlBackgroundColor" catalog="System" colorSpace="catalog"/> </textFieldCell> <tableColumnResizingMask key="resizingMask" resizeWithTable="YES" userResizable="YES"/> <connections> <binding destination="IZb-g9-uEr" name="value" keyPath="arrangedObjects.title" id="kha-1D-9gI"/> </connections> </tableColumn> </tableColumns> <connections> <binding destination="-2" name="doubleClickTarget" keyPath="self" id="WLF-Lh-4jC"> <dictionary key="options"> <string key="NSSelectorName">launchSet:</string> </dictionary> </binding> </connections> </outlineView> </subviews> </clipView> <constraints> <constraint firstAttribute="height" relation="greaterThanOrEqual" constant="551" id="idy-SK-Zk5"/> <constraint firstAttribute="width" relation="greaterThanOrEqual" constant="596" id="jy2-Q4-zO9"/> </constraints> <scroller key="horizontalScroller" hidden="YES" wantsLayer="YES" verticalHuggingPriority="750" horizontal="YES" id="GKm-KM-6zH"> <rect key="frame" x="1" y="535" width="594" height="15"/> <autoresizingMask key="autoresizingMask"/> </scroller> <scroller key="verticalScroller" hidden="YES" wantsLayer="YES" verticalHuggingPriority="750" doubleValue="1" horizontal="NO" id="AXN-0R-j49"> <rect key="frame" x="224" y="17" width="15" height="102"/> <autoresizingMask key="autoresizingMask"/> </scroller> <tableHeaderView key="headerView" id="3Ac-aF-wVK"> <rect key="frame" x="0.0" y="0.0" width="594" height="25"/> <autoresizingMask key="autoresizingMask"/> </tableHeaderView> <connections> <outlet property="delegate" destination="-2" id="B47-W5-Vyk"/> </connections> </scrollView> </subviews> <constraints> <constraint firstAttribute="trailing" secondItem="uLN-UU-wUx" secondAttribute="trailing" constant="-1" id="A4j-TA-gK2"/> <constraint firstItem="uLN-UU-wUx" firstAttribute="leading" secondItem="EiT-Mj-1SZ" secondAttribute="leading" constant="-1" id="HiR-f2-iJv"/> <constraint firstAttribute="bottom" secondItem="uLN-UU-wUx" secondAttribute="bottom" constant="-1" id="bUh-HJ-Ps7"/> <constraint firstItem="uLN-UU-wUx" firstAttribute="top" secondItem="EiT-Mj-1SZ" secondAttribute="top" constant="-1" id="riQ-vq-ikW"/> </constraints> </view> <connections> <outlet property="delegate" destination="-2" id="uIo-I6-8Np"/> </connections> <point key="canvasLocation" x="192" y="209.5"/> </window> <treeController objectClassName="FBLauncherItem" editable="NO" childrenKeyPath="subsets" id="IZb-g9-uEr"> <connections> <binding destination="-2" name="contentArray" keyPath="romSets" id="i4j-NI-FYk"/> <binding destination="Mk3-du-Xcu" name="sortDescriptors" keyPath="values.romSetSortDescriptor" id="XzZ-ve-L7D"> <dictionary key="options"> <string key="NSValueTransformerName">NSUnarchiveFromData</string> </dictionary> </binding> </connections> </treeController> <userDefaultsController representsSharedInstance="YES" id="Mk3-du-Xcu"/> <window title="Import in Progress..." allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" hidesOnDeactivate="YES" releasedWhenClosed="NO" visibleAtLaunch="NO" animationBehavior="default" id="hEA-LJ-CM5" customClass="NSPanel"> <windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" utility="YES"/> <windowPositionMask key="initialPositionMask" leftStrut="YES" rightStrut="YES" topStrut="YES" bottomStrut="YES"/> <rect key="contentRect" x="272" y="172" width="407" height="80"/> <rect key="screenRect" x="0.0" y="0.0" width="2560" height="1417"/> <view key="contentView" id="epq-bd-srL"> <rect key="frame" x="0.0" y="0.0" width="407" height="80"/> <autoresizingMask key="autoresizingMask"/> <subviews> <progressIndicator wantsLayer="YES" maxValue="1" style="bar" translatesAutoresizingMaskIntoConstraints="NO" id="CGz-AO-sJG"> <rect key="frame" x="20" y="19" width="307" height="20"/> </progressIndicator> <textField horizontalHuggingPriority="251" verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="wTx-rb-XUh"> <rect key="frame" x="18" y="46" width="371" height="14"/> <textFieldCell key="cell" controlSize="small" scrollable="YES" lineBreakMode="clipping" sendsActionOnEndEditing="YES" title="Label" id="ziH-TJ-CzP"> <font key="font" metaFont="message" size="11"/> <color key="textColor" name="controlTextColor" catalog="System" colorSpace="catalog"/> <color key="backgroundColor" name="controlColor" catalog="System" colorSpace="catalog"/> </textFieldCell> </textField> <button verticalHuggingPriority="750" translatesAutoresizingMaskIntoConstraints="NO" id="QBI-GE-Mwp"> <rect key="frame" x="330" y="14" width="62" height="27"/> <buttonCell key="cell" type="push" title="Cancel" bezelStyle="rounded" alignment="center" controlSize="small" borderStyle="border" imageScaling="proportionallyDown" inset="2" id="ChL-9J-tsE"> <behavior key="behavior" pushIn="YES" lightByBackground="YES" lightByGray="YES"/> <font key="font" metaFont="message" size="11"/> <string key="keyEquivalent" base64-UTF8="YES"> Gw </string> </buttonCell> <connections> <action selector="cancelProgress:" target="-2" id="rdI-OE-fwp"/> </connections> </button> </subviews> <constraints> <constraint firstAttribute="trailing" secondItem="QBI-GE-Mwp" secondAttribute="trailing" constant="20" symbolic="YES" id="0De-ap-gwT"/> <constraint firstItem="QBI-GE-Mwp" firstAttribute="leading" secondItem="CGz-AO-sJG" secondAttribute="trailing" constant="8" symbolic="YES" id="5PE-IS-Kny"/> <constraint firstItem="CGz-AO-sJG" firstAttribute="top" secondItem="wTx-rb-XUh" secondAttribute="bottom" constant="8" symbolic="YES" id="9yC-z6-hAA"/> <constraint firstAttribute="bottom" secondItem="QBI-GE-Mwp" secondAttribute="bottom" constant="20" symbolic="YES" id="Eyb-oA-y8e"/> <constraint firstAttribute="trailing" secondItem="wTx-rb-XUh" secondAttribute="trailing" constant="20" symbolic="YES" id="JZv-12-9FB"/> <constraint firstItem="wTx-rb-XUh" firstAttribute="top" secondItem="epq-bd-srL" secondAttribute="top" constant="20" symbolic="YES" id="OsP-qE-Zdd"/> <constraint firstItem="QBI-GE-Mwp" firstAttribute="top" secondItem="wTx-rb-XUh" secondAttribute="bottom" constant="8" symbolic="YES" id="WNM-57-Qcb"/> <constraint firstItem="wTx-rb-XUh" firstAttribute="leading" secondItem="epq-bd-srL" secondAttribute="leading" constant="20" symbolic="YES" id="cv1-So-faD"/> <constraint firstItem="CGz-AO-sJG" firstAttribute="leading" secondItem="epq-bd-srL" secondAttribute="leading" constant="20" symbolic="YES" id="mhB-B1-C30"/> <constraint firstAttribute="bottom" secondItem="CGz-AO-sJG" secondAttribute="bottom" constant="20" symbolic="YES" id="vXT-nh-W8t"/> </constraints> </view> <point key="canvasLocation" x="146.5" y="679"/> </window> </objects> </document>
{ "pile_set_name": "Github" }
.. warning:: There are known non-determinism issues for RNN functions on some versions of cuDNN and CUDA. You can enforce deterministic behavior by setting the following environment variables: On CUDA 10.1, set environment variable ``CUDA_LAUNCH_BLOCKING=1``. This may affect performance. On CUDA 10.2 or later, set environment variable (note the leading colon symbol) ``CUBLAS_WORKSPACE_CONFIG=:16:8`` or ``CUBLAS_WORKSPACE_CONFIG=:4096:2``. See the `cuDNN 8 Release Notes`_ for more information. .. _cuDNN 8 Release Notes: https://docs.nvidia.com/deeplearning/sdk/cudnn-release-notes/rel_8.html
{ "pile_set_name": "Github" }
# frozen_string_literal: true require 'ostruct' require 'rubygems' RSpec.describe YARD::CLI::Gems do before do @rebuild = false @gem1 = build_mock('gem1') @gem2 = build_mock('gem2') @gem3 = build_mock('gem3') end def build_mock(name, version = '1.0') OpenStruct.new :name => name, :version => version, :full_gem_path => "/path/to/gems/#{name}-#{version}", :yardoc_file => "/path/to/yardoc/#{name}-#{version}" end def build_specs(*specs) specs.each do |themock| allow(Registry).to receive(:yardoc_file_for_gem).with(themock.name, "= #{themock.version}").and_return(themock.yardoc_file) allow(File).to receive(:directory?).with(themock.yardoc_file).and_return(@rebuild) allow(File).to receive(:directory?).with(themock.full_gem_path).and_return(true) allow(Registry).to receive(:yardoc_file_for_gem).with(themock.name, "= #{themock.version}", true).and_return(themock.yardoc_file) expect(Dir).to receive(:chdir).with(themock.full_gem_path).and_yield end expect(Registry).to receive(:clear).exactly(specs.size).times expect(CLI::Yardoc).to receive(:run).exactly(specs.size).times end describe "#run" do it "builds all gem indexes if no gem is specified" do build_specs(@gem1, @gem2) expect(YARD::GemIndex).to receive(:each) {|&b| [@gem1, @gem2].each(&b) } CLI::Gems.run end it "allows gem to be specified" do build_specs(@gem1) expect(YARD::GemIndex).to receive(:find_all_by_name).with(@gem1.name, '>= 0').and_return([@gem1]) CLI::Gems.run(@gem1.name) end it "allows multiple gems to be specified for building" do build_specs(@gem1, @gem2) expect(YARD::GemIndex).to receive(:find_all_by_name).with(@gem1.name, @gem1.version).and_return([@gem1]) expect(YARD::GemIndex).to receive(:find_all_by_name).with(@gem2.name, '>= 0').and_return([@gem2]) CLI::Gems.run(@gem1.name, @gem1.version, @gem2.name) end it "allows version to be specified with gem" do build_specs(@gem1) expect(YARD::GemIndex).to receive(:find_all_by_name).with(@gem1.name, '>= 1.0').and_return([@gem1]) CLI::Gems.run(@gem1.name, '>= 1.0') end it "warns if one of the gems is not found, but it should process others" do build_specs(@gem2) expect(YARD::GemIndex).to receive(:find_all_by_name).with(@gem1.name, '>= 2.0').and_return([]) expect(YARD::GemIndex).to receive(:find_all_by_name).with(@gem2.name, '>= 0').and_return([@gem2]) expect(log).to receive(:warn).with(/#{@gem1.name} >= 2.0 could not be found/) CLI::Gems.run(@gem1.name, '>= 2.0', @gem2.name) end it "fails if specified gem(s) is/are not found" do expect(CLI::Yardoc).not_to receive(:run) expect(YARD::GemIndex).to receive(:find_all_by_name).with(@gem1.name, '>= 2.0').and_return([]) expect(log).to receive(:warn).with(/#{@gem1.name} >= 2.0 could not be found/) expect(log).to receive(:error).with(/No specified gems could be found/) CLI::Gems.run(@gem1.name, '>= 2.0') end it "accepts --rebuild" do @rebuild = true build_specs(@gem1) expect(YARD::GemIndex).to receive(:each) {|&b| [@gem1].each(&b) } CLI::Gems.run('--rebuild') end end end
{ "pile_set_name": "Github" }
package it.eng.spagobi.metadata.metadata; import java.util.HashSet; import java.util.Set; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.NotEmpty; import com.fasterxml.jackson.annotation.JsonIgnore; // Generated 13-apr-2016 14.55.30 by Hibernate Tools 3.4.0.CR1 import it.eng.spagobi.commons.metadata.SbiHibernateModel; import it.eng.spagobi.services.validation.ExtendedAlphanumeric; /** * SbiMetaSource generated by hbm2java */ public class SbiMetaSource extends SbiHibernateModel { private Integer sourceId; @NotEmpty @ExtendedAlphanumeric @Size(max = 100) private String name; @NotEmpty @ExtendedAlphanumeric @Size(max = 100) private String type; @ExtendedAlphanumeric @Size(max = 100) private String url; @ExtendedAlphanumeric @Size(max = 100) private String location; @ExtendedAlphanumeric @Size(max = 100) private String sourceSchema; @ExtendedAlphanumeric @Size(max = 100) private String sourceCatalogue; @ExtendedAlphanumeric @Size(max = 100) private String role; @JsonIgnore private Set sbiMetaJobSources = new HashSet(0); @JsonIgnore private Set sbiMetaTables = new HashSet(0); public SbiMetaSource() { } public SbiMetaSource(String name, String type) { this.name = name; this.type = type; } public SbiMetaSource(String name, String type, String url, String location, String sourceSchema, String sourceCatalogue, String role, Set sbiMetaJobSources, Set sbiMetaTables) { this.name = name; this.type = type; this.url = url; this.location = location; this.sourceSchema = sourceSchema; this.sourceCatalogue = sourceCatalogue; this.role = role; this.sbiMetaJobSources = sbiMetaJobSources; this.sbiMetaTables = sbiMetaTables; } public Integer getSourceId() { return this.sourceId; } public void setSourceId(Integer sourceId) { this.sourceId = sourceId; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getType() { return this.type; } public void setType(String type) { this.type = type; } public String getUrl() { return this.url; } public void setUrl(String url) { this.url = url; } public String getLocation() { return this.location; } public void setLocation(String location) { this.location = location; } public String getSourceSchema() { return this.sourceSchema; } public void setSourceSchema(String sourceSchema) { this.sourceSchema = sourceSchema; } public String getSourceCatalogue() { return this.sourceCatalogue; } public void setSourceCatalogue(String sourceCatalogue) { this.sourceCatalogue = sourceCatalogue; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public Set getSbiMetaJobSources() { return this.sbiMetaJobSources; } public void setSbiMetaJobSources(Set sbiMetaJobSources) { this.sbiMetaJobSources = sbiMetaJobSources; } public Set getSbiMetaTables() { return this.sbiMetaTables; } public void setSbiMetaTables(Set sbiMetaTables) { this.sbiMetaTables = sbiMetaTables; } }
{ "pile_set_name": "Github" }
{ "name": "qcod/laravel-imageup", "description": "Auto Image upload, resize and crop for Laravel eloquent model using Intervention image", "homepage": "https://github.com/qcod/laravel-imageup", "type": "library", "license": "MIT", "keywords": [ "laravel", "image upload", "image crop", "image resize", "intervention image", "eloquent", "model" ], "authors": [ { "name": "Mohd Saqueib Ansari", "email": "[email protected]" } ], "require": { "php": "^7.3", "laravel/framework": "~5.4.0|~5.5.0|~5.6.0|~5.7.0|~5.8.0|^6.0|^7.0|^8.0", "intervention/image": "^2.4" }, "require-dev": { "orchestra/testbench": "^4.0|^5.0", "phpunit/phpunit": "^8.0|^9.0", "dms/phpunit-arraysubset-asserts": "^0.2.0" }, "autoload": { "psr-4": { "QCod\\ImageUp\\": "src/" } }, "autoload-dev": { "psr-4": { "QCod\\ImageUp\\Tests\\": "tests/" } }, "extra": { "laravel": { "providers": [ "QCod\\ImageUp\\ImageUpServiceProvider" ] } }, "scripts": { "test": "vendor/bin/phpunit" } }
{ "pile_set_name": "Github" }
#ifndef SEQ64_MASTERMIDIBUS_PM_HPP #define SEQ64_MASTERMIDIBUS_PM_HPP /* * This file is part of seq24/sequencer64. * * seq24 is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * seq24 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with seq24; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /** * \file mastermidibus_pm.hpp * * This module declares/defines the base class for MIDI I/O for Windows. * * \library sequencer64 application * \author Seq24 team; modifications by Chris Ahlstrom * \date 2015-07-24 * \updates 2017-05-27 * \license GNU GPLv2 or above * * This mastermidibus module is the Windows (and Linux now!) version of the * mastermidibus module using the PortMidi library. */ #include "mastermidibase.hpp" /* seq64::mastermidibase ABC */ #include "portmidi.h" /* PortMIDI API header file */ /* * Do not document the namespace; it breaks Doxygen. */ namespace seq64 { /** * The class that "supervises" all of the midibus objects. This * implementation uses the PortMidi library, which supports Linux and * Windows, but not JACK or Mac OSX. */ class mastermidibus : public mastermidibase { private: /* * All members have been moved into the new base class. */ public: mastermidibus ( int ppqn = SEQ64_USE_DEFAULT_PPQN, midibpm bpm = SEQ64_DEFAULT_BPM /* c_beats_per_minute */ ); virtual ~mastermidibus (); virtual bool activate (); protected: virtual void api_init (int ppqn, midibpm /*bpm*/); virtual bool api_get_midi_event (event * in); virtual void api_set_ppqn (int ppqn); virtual void api_set_beats_per_minute (midibpm bpm); /* * TODO * virtual void api_flush (); virtual void api_start (); virtual void api_stop (); virtual void api_continue_from (midipulse tick); virtual void api_port_start (int client, int port); * */ }; // class mastermidibus } // namespace seq64 #endif // SEQ64_MASTERMIDIBUS_PM_HPP /* * mastermidibus_pm.hpp * * vim: sw=4 ts=4 wm=4 et ft=cpp */
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Reviewed: no --> <sect1 id="zend.layout.quickstart"> <title>Zend_Layout Quick Start</title> <para> There are two primary use cases for <classname>Zend_Layout</classname>: with the Zend Framework <acronym>MVC</acronym>, and without. </para> <sect2 id="zend.layout.quickstart.layouts"> <title>Layout scripts</title> <para> In both cases, however, you'll need to create a layout script. Layout scripts simply utilize <classname>Zend_View</classname> (or whatever view implementation you are using). Layout variables are registered with a <classname>Zend_Layout</classname> <link linkend="zend.view.helpers.initial.placeholder">placeholder</link>, and may be accessed via the placeholder helper or by fetching them as object properties of the layout object via the layout helper. </para> <para> As an example: </para> <programlisting language="php"><![CDATA[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>My Site</title> </head> <body> <?php // fetch 'content' key using layout helper: echo $this->layout()->content; // fetch 'foo' key using placeholder helper: echo $this->placeholder('Zend_Layout')->foo; // fetch layout object and retrieve various keys from it: $layout = $this->layout(); echo $layout->bar; echo $layout->baz; ?> </body> </html> ]]></programlisting> <para> Because <classname>Zend_Layout</classname> utilizes <classname>Zend_View</classname> for rendering, you can also use any view helpers registered, and also have access to any previously assigned view variables. Particularly useful are the various <link linkend="zend.view.helpers.initial.placeholder">placeholder helpers</link>, as they allow you to retrieve content for areas such as the &lt;head&gt; section, navigation, etc.: </para> <programlisting language="php"><![CDATA[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <?php echo $this->headTitle() ?> <?php echo $this->headScript() ?> <?php echo $this->headStyle() ?> </head> <body> <?php echo $this->render('header.phtml') ?> <div id="nav"><?php echo $this->placeholder('nav') ?></div> <div id="content"><?php echo $this->layout()->content ?></div> <?php echo $this->render('footer.phtml') ?> </body> </html> ]]></programlisting> </sect2> <sect2 id="zend.layout.quickstart.mvc"> <title>Using Zend_Layout with the Zend Framework MVC</title> <para> <classname>Zend_Controller</classname> offers a rich set of functionality for extension via its <link linkend="zend.controller.plugins">front controller plugins</link> and <link linkend="zend.controller.actionhelpers">action controller helpers</link>. <classname>Zend_View</classname> also has <link linkend="zend.view.helpers">helpers</link>. <classname>Zend_Layout</classname> takes advantage of these various extension points when used with the <acronym>MVC</acronym> components. </para> <para> <methodname>Zend_Layout::startMvc()</methodname> creates an instance of <classname>Zend_Layout</classname> with any optional configuration you provide it. It then registers a front controller plugin that renders the layout with any application content once the dispatch loop is done, and registers an action helper to allow access to the layout object from your action controllers. Additionally, you may at any time grab the layout instance from within a view script using the <classname>Layout</classname> view helper. </para> <para> First, let's look at how to initialize <classname>Zend_Layout</classname> for use with the <acronym>MVC</acronym>: </para> <programlisting language="php"><![CDATA[ // In your bootstrap: Zend_Layout::startMvc(); ]]></programlisting> <para> <methodname>startMvc()</methodname> can take an optional array of options or <classname>Zend_Config</classname> object to customize the instance; these options are detailed in <link linkend="zend.layout.options">this section</link>. </para> <para> In an action controller, you may then access the layout instance as an action helper: </para> <programlisting language="php"><![CDATA[ class FooController extends Zend_Controller_Action { public function barAction() { // disable layouts for this action: $this->_helper->layout->disableLayout(); } public function bazAction() { // use different layout script with this action: $this->_helper->layout->setLayout('foobaz'); }; } ]]></programlisting> <para> In your view scripts, you can then access the layout object via the <classname>Layout</classname> view helper. This view helper is slightly different than others in that it takes no arguments, and returns an object instead of a string value. This allows you to immediately call methods on the layout object: </para> <programlisting language="php"><![CDATA[ <?php $this->layout()->setLayout('foo'); // set alternate layout ?> ]]></programlisting> <para> At any time, you can fetch the <classname>Zend_Layout</classname> instance registered with the <acronym>MVC</acronym> via the <methodname>getMvcInstance()</methodname> static method: </para> <programlisting language="php"><![CDATA[ // Returns null if startMvc() has not first been called $layout = Zend_Layout::getMvcInstance(); ]]></programlisting> <para> Finally, <classname>Zend_Layout</classname>'s front controller plugin has one important feature in addition to rendering the layout: it retrieves all named segments from the response object and assigns them as layout variables, assigning the 'default' segment to the variable 'content'. This allows you to access your application content and render it in your view scripts. </para> <para> As an example, let's say your code first hits <methodname>FooController::indexAction()</methodname>, which renders some content to the default response segment, and then forwards to <methodname>NavController::menuAction()</methodname>, which renders content to the 'nav' response segment. Finally, you forward to <methodname>CommentController::fetchAction()</methodname> and fetch some comments, but render those to the default response segment as well (which appends content to that segment). Your view script could then render each separately: </para> <programlisting language="php"><![CDATA[ <body> <!-- renders /nav/menu --> <div id="nav"><?php echo $this->layout()->nav ?></div> <!-- renders /foo/index + /comment/fetch --> <div id="content"><?php echo $this->layout()->content ?></div> </body> ]]></programlisting> <para> This feature is particularly useful when used in conjunction with the ActionStack <link linkend="zend.controller.actionhelpers.actionstack">action helper</link> and <link linkend="zend.controller.plugins.standard.actionstack">plugin</link>, which you can use to setup a stack of actions through which to loop, and thus create widgetized pages. </para> </sect2> <sect2 id="zend.layout.quickstart.standalone"> <title>Using Zend_Layout as a Standalone Component</title> <para> As a standalone component, <classname>Zend_Layout</classname> does not offer nearly as many features or as much convenience as when used with the <acronym>MVC</acronym>. However, it still has two chief benefits: </para> <itemizedlist> <listitem><para>Scoping of layout variables.</para></listitem> <listitem> <para>Isolation of layout view script from other view scripts.</para> </listitem> </itemizedlist> <para> When used as a standalone component, simply instantiate the layout object, use the various accessors to set state, set variables as object properties, and render the layout: </para> <programlisting language="php"><![CDATA[ $layout = new Zend_Layout(); // Set a layout script path: $layout->setLayoutPath('/path/to/layouts'); // set some variables: $layout->content = $content; $layout->nav = $nav; // choose a different layout script: $layout->setLayout('foo'); // render final layout echo $layout->render(); ]]></programlisting> </sect2> <sect2 id="zend.layout.quickstart.example"> <title>Sample Layout</title> <para> Sometimes a picture is worth a thousand words. The following is a sample layout script showing how it might all come together. </para> <para> <inlinegraphic align="center" valign="middle" fileref="figures/zend.layout.quickstart.example.png" format="PNG" /> </para> <para> The actual order of elements may vary, depending on the <acronym>CSS</acronym> you've setup; for instance, if you're using absolute positioning, you may be able to have the navigation displayed later in the document, but still show up at the top; the same could be said for the sidebar or header. The actual mechanics of pulling the content remain the same, however. </para> </sect2> </sect1> <!-- vim:se ts=4 sw=4 et: -->
{ "pile_set_name": "Github" }
// // INMessageAttributeResolutionResult.h // Intents // // Copyright (c) 2016-2017 Apple Inc. All rights reserved. // #import <Intents/INIntentResolutionResult.h> #import <Intents/INMessageAttribute.h> NS_ASSUME_NONNULL_BEGIN API_AVAILABLE(ios(10.0), watchos(3.2), macosx(10.12)) @interface INMessageAttributeResolutionResult : INIntentResolutionResult // This resolution result is for when the app extension wants to tell Siri to proceed, with a given INMessageAttribute. The resolvedValue can be different than the original INMessageAttribute. This allows app extensions to apply business logic constraints. // Use +notRequired to continue with a 'nil' value. + (instancetype)successWithResolvedMessageAttribute:(INMessageAttribute)resolvedMessageAttribute NS_SWIFT_NAME(success(with:)); + (instancetype)successWithResolvedValue:(INMessageAttribute)resolvedValue NS_SWIFT_UNAVAILABLE("Please use 'success(with:)' instead.") API_DEPRECATED_WITH_REPLACEMENT("+successWithResolvedMessageAttribute:", ios(10.0, 11.0), watchos(3.2, 4.0), macos(10.12, 10.13)); // This resolution result is to ask Siri to confirm if this is the value with which the user wants to continue. + (instancetype)confirmationRequiredWithMessageAttributeToConfirm:(INMessageAttribute)messageAttributeToConfirm NS_SWIFT_NAME(confirmationRequired(with:)); + (instancetype)confirmationRequiredWithValueToConfirm:(INMessageAttribute)valueToConfirm NS_SWIFT_UNAVAILABLE("Please use 'confirmationRequired(with:)' instead.") API_DEPRECATED_WITH_REPLACEMENT("+confirmationRequiredWithMessageAttributeToConfirm:", ios(10.0, 11.0), watchos(3.2, 4.0), macos(10.12, 10.13)); @end NS_ASSUME_NONNULL_END
{ "pile_set_name": "Github" }
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2014 Communications Engineering Lab, KIT. # # This is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this software; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, gr_unittest from gnuradio import blocks import radar_swig as radar class qa_usrp_echotimer_cc (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def test_001_t (self): # set up fg self.tb.run () # check data if __name__ == '__main__': gr_unittest.run(qa_usrp_echotimer_cc, "qa_usrp_echotimer_cc.xml")
{ "pile_set_name": "Github" }
/* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. * ------------------------------------------------------------------------- * * config_array.h * Configuration item array implementation. * * IDENTIFICATION * src/gausskernel/storage/mot/core/src/infra/config/config_array.h * * ------------------------------------------------------------------------- */ #ifndef CONFIG_ARRAY_H #define CONFIG_ARRAY_H #include "config_item_class.h" #include "config_item_visitor.h" #include "typed_config_value.h" #include "mot_vector.h" namespace MOT { // forward declaration class ConfigSection; class ConfigArray : public ConfigItem { public: /** Constructor. */ ConfigArray(); /** Destructor. */ ~ConfigArray() override; /** * @brief Utility method for creating a configuration array. * @param path The configuration path leading to the item. * @param name The configuration item name. * @return The configuration array if succeeded, otherwise null. */ static ConfigArray* CreateConfigArray(const char* path, const char* name) { return ConfigItem::CreateConfigItem<ConfigArray>(path, name); } /** * @brief Prints the configuration section to the log. * @param logLevel The log level used for printing. * @param fullPrint Specifies whether to print full path names of terminal leaves. */ virtual void Print(LogLevel logLevel, bool fullPrint) const; /** * @brief Builds the array by adding a sub-item. * @param configItem The direct configuration item to add as a child of this * array. It could be another section or a terminal value. * @return True if succeeded, otherwise false. */ inline bool AddConfigItem(ConfigItem* configItem) { return mItemArray.push_back(configItem); } /** * @brief Retrieves the configuration item count held by this item array. * @return The item count. */ inline uint32_t GetConfigItemCount() const { return mItemArray.size(); } /** * @brief Retrieves a configuration sub-section by index. * @param index The index of the sub-section * @return The sub-section, or null pointer if index is out of bounds, or the * configuration item in the specified index is not a section. */ inline const ConfigSection* GetConfigSectionAt(uint32_t index) const; /** * @brief Retrieves a typed configuration sub-value by index. * @param index The index of the sub-value * @return The typed sub-value, or null pointer if index is out of bounds, or * the configuration item in the specified index is not a value. */ template <typename T> inline const TypedConfigValue<T>* GetConfigValueAt(uint32_t index) const { const TypedConfigValue<T>* result = nullptr; const ConfigValue* value = GetTypedItemAt<ConfigValue>(index); if (value != nullptr && value->GetConfigValueType() == ConfigValueTypeMapper<T>::CONFIG_VALUE_TYPE) { result = static_cast<const TypedConfigValue<T>*>(value); } return result; } /** * @brief Retrieves a typed configuration sub-array by index. * @param index The index of the sub-array. * @return The typed sub-array, or null pointer if index is out of bounds, or * the configuration item in the specified index is not an array. */ inline const ConfigArray* GetConfigArrayAt(uint32_t index) const { return GetTypedItemAt<ConfigArray>(index); } /** * @brief Retrieves a configuration item by index. * @param index The index of the sub-item. * @return The resulting configuration item, or null pointer if index is out of bounds, or * the configuration item in the specified index is not a value. */ inline const ConfigItem* GetConfigItemAt(uint32_t index) const { const ConfigItem* result = nullptr; if (index < mItemArray.size()) { result = mItemArray[index]; } return result; } /** * @brief Traverses the section with a visitor applied to each sub-item in the array. This is a * recursive call. * @param visitor The visitor used to visit each sub-item in the array. */ void ForEach(ConfigItemVisitor& visitor) const; /** @typedef Configuration item array type. */ typedef mot_vector<ConfigItem*> ConfigItemVector; private: /** @var Array of all direct sub-sections. */ ConfigItemVector mItemArray; /** * @brief Helper method for get a typed configuration item at a specified index. * @param index The item index. * @return The item if the index in array bounds and the item class matches. */ template <typename T> inline const T* GetTypedItemAt(uint32_t index) const; }; /** @typedef Configuration item array type. */ typedef ConfigArray::ConfigItemVector ConfigItemVector; } // namespace MOT #include "config_section.h" namespace MOT { // specialization template <typename T> inline const T* ConfigArray::GetTypedItemAt(uint32_t index) const { const T* result = nullptr; const ConfigItem* item = GetConfigItemAt(index); if (item != nullptr) { if (item->GetClass() == ConfigItemClassMapper<T>::CONFIG_ITEM_CLASS) { result = static_cast<const T*>(item); } } return result; } inline const ConfigSection* ConfigArray::GetConfigSectionAt(uint32_t index) const { return GetTypedItemAt<ConfigSection>(index); } // specialization template <> struct ConfigItemClassMapper<ConfigArray> { /** @var The configuration item class (array). */ static constexpr const ConfigItemClass CONFIG_ITEM_CLASS = ConfigItemClass::CONFIG_ITEM_ARRAY; /** @var The configuation item class name. */ static constexpr const char* CONFIG_ITEM_CLASS_NAME = "ConfigArray"; }; } // namespace MOT #endif /* CONFIG_ARRAY_H */
{ "pile_set_name": "Github" }
;;; subst.el --- simple substitutions. -*- lexical-binding:t -*- ;;; Commentary: ;; This is some utility code to rewrite SSA names in a compiler ;; instance. The caller provides a map and all the instructions are ;; updated according to the map. ;;; Code: (require 'elcomp) (cl-defgeneric elcomp--rewrite-insn (insn _map) "Rewrite INSN according to MAP. MAP is a hash table mapping old instructions to new ones. Unhandled cases call `error'." (error "unhandled case: %S" insn)) (cl-defmethod elcomp--rewrite-insn ((insn elcomp--set) map) (let ((new-insn (gethash (elcomp--value insn) map))) (when new-insn (setf (elcomp--value insn) new-insn)))) (cl-defmethod elcomp--rewrite-insn ((insn elcomp--call) map) ;; FIXME: the :func slot? (cl-mapl (lambda (cell) (let ((new-insn (gethash (car cell) map))) (when new-insn (setf (car cell) new-insn)))) (elcomp--args insn))) (cl-defmethod elcomp--rewrite-insn ((_insn elcomp--goto) _map) nil) (cl-defmethod elcomp--rewrite-insn ((insn elcomp--if) map) (let ((new-insn (gethash (elcomp--sym insn) map))) (when new-insn (setf (elcomp--sym insn) new-insn)))) (cl-defmethod elcomp--rewrite-insn ((insn elcomp--return) map) (let ((new-insn (gethash (elcomp--sym insn) map))) (when new-insn (setf (elcomp--sym insn) new-insn)))) (cl-defmethod elcomp--rewrite-insn ((insn elcomp--phi) map) ;; Ugh. (let ((new-hash (make-hash-table))) (maphash (lambda (phi _ignore) (let ((subst (gethash phi map))) (puthash ;; It never makes sense to propagate a constant into a phi. (if (elcomp--constant-p subst) phi (or subst phi)) t new-hash))) (elcomp--args insn)) (setf (elcomp--args insn) new-hash))) ;; FIXME `elcomp--catch's :tag? (defun elcomp--rewrite-using-map (compiler map) "Rewrite all the instructions in COMPILER according to MAP. MAP is a hash table that maps old operands to new ones." (elcomp--iterate-over-bbs compiler (lambda (bb) (maphash (lambda (_ignore phi) (elcomp--rewrite-insn phi map)) (elcomp--basic-block-phis bb)) (dolist (insn (elcomp--basic-block-code bb)) (elcomp--rewrite-insn insn map))))) (provide 'elcomp/subst) ;;; subst.el ends here
{ "pile_set_name": "Github" }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.rs.security.oauth2.grants.code; import java.net.URI; import javax.ws.rs.core.MultivaluedMap; import org.apache.cxf.jaxrs.impl.MetadataMap; import org.apache.cxf.rs.security.jose.jwt.JwtClaims; import org.apache.cxf.rs.security.jose.jwt.JwtToken; import org.apache.cxf.rs.security.oauth2.provider.OAuthJoseJwtProducer; /** * Base Authorization Code Grant representation, captures the code * and the redirect URI this code has been returned to, visible to the client */ public class JwtRequestCodeGrant extends AuthorizationCodeGrant { private static final long serialVersionUID = -3738825769770411453L; private OAuthJoseJwtProducer joseProducer = new OAuthJoseJwtProducer(); private String clientSecret; private String issuer; public JwtRequestCodeGrant() { } public JwtRequestCodeGrant(String issuer) { this.issuer = issuer; } public JwtRequestCodeGrant(String code, String issuer) { super(code); this.issuer = issuer; } public JwtRequestCodeGrant(String code, URI uri, String issuer) { super(code, uri); this.issuer = issuer; } public MultivaluedMap<String, String> toMap() { String request = getRequest(); MultivaluedMap<String, String> newMap = new MetadataMap<>(); newMap.putSingle("request", request); return newMap; } public String getRequest() { MultivaluedMap<String, String> map = super.toMap(); JwtClaims claims = new JwtClaims(); if (issuer != null) { claims.setIssuer(issuer); } for (String key : map.keySet()) { claims.setClaim(key, map.getFirst(key)); } return joseProducer.processJwt(new JwtToken(claims), clientSecret); } public void setIssuer(String issuer) { // Can it be a client id ? this.issuer = issuer; } public void setClientSecret(String clientSecret) { this.clientSecret = clientSecret; } public OAuthJoseJwtProducer getJoseProducer() { return joseProducer; } public void setJoseProducer(OAuthJoseJwtProducer joseProducer) { this.joseProducer = joseProducer; } }
{ "pile_set_name": "Github" }
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 2014, Steve Holme, <[email protected]>. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "test.h" #include "memdebug.h" /* * This is the list of basic details you need to tweak to get things right. */ #define TO "<[email protected]>" #define FROM "<[email protected]>" static const char *payload_text[] = { "From: different\r\n", "To: another\r\n", "\r\n", "\r\n", ".\r\n", ".\r\n", "\r\n", ".\r\n", "\r\n", "body", NULL }; struct upload_status { int lines_read; }; static size_t read_callback(void *ptr, size_t size, size_t nmemb, void *userp) { struct upload_status *upload_ctx = (struct upload_status *)userp; const char *data; if((size == 0) || (nmemb == 0) || ((size*nmemb) < 1)) { return 0; } data = payload_text[upload_ctx->lines_read]; if(data) { size_t len = strlen(data); memcpy(ptr, data, len); upload_ctx->lines_read++; return len; } return 0; } int test(char *URL) { CURLcode res; CURL *curl; struct curl_slist *rcpt_list = NULL; struct upload_status upload_ctx = {0}; if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) { fprintf(stderr, "curl_global_init() failed\n"); return TEST_ERR_MAJOR_BAD; } if((curl = curl_easy_init()) == NULL) { fprintf(stderr, "curl_easy_init() failed\n"); curl_global_cleanup(); return TEST_ERR_MAJOR_BAD; } rcpt_list = curl_slist_append(rcpt_list, TO); /* more addresses can be added here rcpt_list = curl_slist_append(rcpt_list, "<[email protected]>"); */ test_setopt(curl, CURLOPT_URL, URL); test_setopt(curl, CURLOPT_UPLOAD, 1L); test_setopt(curl, CURLOPT_READFUNCTION, read_callback); test_setopt(curl, CURLOPT_READDATA, &upload_ctx); test_setopt(curl, CURLOPT_MAIL_FROM, FROM); test_setopt(curl, CURLOPT_MAIL_RCPT, rcpt_list); test_setopt(curl, CURLOPT_VERBOSE, 1L); res = curl_easy_perform(curl); test_cleanup: curl_slist_free_all(rcpt_list); curl_easy_cleanup(curl); curl_global_cleanup(); return (int)res; }
{ "pile_set_name": "Github" }
<?php namespace Laravel\Tinker; use Exception; use Symfony\Component\VarDumper\Caster\Caster; class TinkerCaster { /** * Application methods to include in the presenter. * * @var array */ private static $appProperties = [ 'configurationIsCached', 'environment', 'environmentFile', 'isLocal', 'routesAreCached', 'runningUnitTests', 'version', 'path', 'basePath', 'configPath', 'databasePath', 'langPath', 'publicPath', 'storagePath', 'bootstrapPath', ]; /** * Get an array representing the properties of an application. * * @param \Illuminate\Foundation\Application $app * @return array */ public static function castApplication($app) { $results = []; foreach (self::$appProperties as $property) { try { $val = $app->$property(); if (! is_null($val)) { $results[Caster::PREFIX_VIRTUAL.$property] = $val; } } catch (Exception $e) { // } } return $results; } /** * Get an array representing the properties of a collection. * * @param \Illuminate\Support\Collection $collection * @return array */ public static function castCollection($collection) { return [ Caster::PREFIX_VIRTUAL.'all' => $collection->all(), ]; } /** * Get an array representing the properties of a model. * * @param \Illuminate\Database\Eloquent\Model $model * @return array */ public static function castModel($model) { $attributes = array_merge( $model->getAttributes(), $model->getRelations() ); $visible = array_flip( $model->getVisible() ?: array_diff(array_keys($attributes), $model->getHidden()) ); $results = []; foreach (array_intersect_key($attributes, $visible) as $key => $value) { $results[(isset($visible[$key]) ? Caster::PREFIX_VIRTUAL : Caster::PREFIX_PROTECTED).$key] = $value; } return $results; } }
{ "pile_set_name": "Github" }
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** No Commercial Usage ** ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "rule.h" #include "highlighterexception.h" #include "progressdata.h" #include "highlightdefinition.h" #include "reuse.h" #include <QtCore/QStringList> #include <functional> using namespace TextEditor; using namespace Internal; const QLatin1Char Rule::kBackSlash('\\'); const QLatin1Char Rule::kUnderscore('_'); const QLatin1Char Rule::kDot('.'); const QLatin1Char Rule::kPlus('+'); const QLatin1Char Rule::kMinus('-'); const QLatin1Char Rule::kZero('0'); const QLatin1Char Rule::kQuote('\"'); const QLatin1Char Rule::kSingleQuote('\''); const QLatin1Char Rule::kQuestion('?'); const QLatin1Char Rule::kX('x'); const QLatin1Char Rule::kA('a'); const QLatin1Char Rule::kB('b'); const QLatin1Char Rule::kE('e'); const QLatin1Char Rule::kF('f'); const QLatin1Char Rule::kN('n'); const QLatin1Char Rule::kR('r'); const QLatin1Char Rule::kT('t'); const QLatin1Char Rule::kV('v'); const QLatin1Char Rule::kOpeningBrace('{'); const QLatin1Char Rule::kClosingBrace('}'); Rule::Rule(bool consumesNonSpace) : m_lookAhead(false), m_firstNonSpace(false), m_column(-1), m_consumesNonSpace(consumesNonSpace) {} Rule::~Rule() {} void Rule::setContext(const QString &context) { m_context = context; } const QString &Rule::context() const { return m_context; } void Rule::setItemData(const QString &itemData) { m_itemData = itemData; } const QString &Rule::itemData() const { return m_itemData; } void Rule::setBeginRegion(const QString &begin) { m_beginRegion = begin; } const QString &Rule::beginRegion() const { return m_beginRegion; } void Rule::setEndRegion(const QString &end) { m_endRegion = end; } const QString &Rule::endRegion() const { return m_endRegion; } void Rule::setLookAhead(const QString &lookAhead) { m_lookAhead = toBool(lookAhead); } bool Rule::isLookAhead() const { return m_lookAhead; } void Rule::setFirstNonSpace(const QString &firstNonSpace) { m_firstNonSpace = toBool(firstNonSpace); } bool Rule::isFirstNonSpace() const { return m_firstNonSpace; } void Rule::setColumn(const QString &column) { bool ok; m_column = column.toInt(&ok); if (!ok) m_column = -1; } int Rule::column() const { return m_column; } void Rule::addChild(const QSharedPointer<Rule> &rule) { m_children.append(rule); } bool Rule::hasChildren() const { return !m_children.isEmpty(); } const QList<QSharedPointer<Rule> > &Rule::children() const { return m_children; } void Rule::setDefinition(const QSharedPointer<HighlightDefinition> &definition) { m_definition = definition; } const QSharedPointer<HighlightDefinition> &Rule::definition() const { return m_definition; } template <class predicate_t> bool Rule::predicateMatchSucceed(const QString &text, const int length, ProgressData *progress, const predicate_t &p) const { int original = progress->offset(); while (progress->offset() < length && p(text.at(progress->offset()))) progress->incrementOffset(); if (original != progress->offset()) return true; return false; } bool Rule::charPredicateMatchSucceed(const QString &text, const int length, ProgressData *progress, bool (QChar::* predicate)() const) const { return predicateMatchSucceed(text, length, progress, std::mem_fun_ref(predicate)); } bool Rule::charPredicateMatchSucceed(const QString &text, const int length, ProgressData *progress, bool (*predicate)(const QChar &)) const { return predicateMatchSucceed(text, length, progress, std::ptr_fun(predicate)); } bool Rule::matchSucceed(const QString &text, const int length, ProgressData *progress) { if (m_firstNonSpace && !progress->isOnlySpacesSoFar()) return false; if (m_column != -1 && m_column != progress->offset()) return false; int original = progress->offset(); if (doMatchSucceed(text, length, progress)) { if (progress->isOnlySpacesSoFar() && !m_lookAhead && m_consumesNonSpace) progress->setOnlySpacesSoFar(false); if (m_lookAhead) progress->setOffset(original); return true; } return false; } Rule *Rule::clone() const { return doClone(); } void Rule::progressFinished() { doProgressFinished(); } bool Rule::matchCharacter(const QString &text, const int length, ProgressData *progress, const QChar &c, bool saveRestoreOffset) const { Q_UNUSED(length) Q_ASSERT(progress->offset() < length); if (text.at(progress->offset()) == c) { if (saveRestoreOffset) progress->saveOffset(); progress->incrementOffset(); return true; } return false; } bool Rule::matchEscapeSequence(const QString &text, const int length, ProgressData *progress, bool saveRestoreOffset) const { if (matchCharacter(text, length, progress, kBackSlash, saveRestoreOffset)) { if (progress->offset() < length) { const QChar &c = text.at(progress->offset()); if (c == kA || c == kB || c == kE || c == kF || c == kN || c == kR || c == kT || c == kV || c == kQuestion || c == kSingleQuote || c == kQuote || c == kBackSlash) { progress->incrementOffset(); return true; } else if (saveRestoreOffset) { progress->restoreOffset(); } } else if (saveRestoreOffset) { progress->restoreOffset(); } } return false; } bool Rule::matchOctalSequence(const QString &text, const int length, ProgressData *progress, bool saveRestoreOffset) const { // An octal sequence is identified as in the C++ Standard. // octal-escape-sequence: // \ octal-digit // \ octal-digit octal-digit // \ octal-digit octal-digit octal-digit if (matchCharacter(text, length, progress, kBackSlash, saveRestoreOffset)) { int count = 0; while (progress->offset() < length && count < 3 && isOctalDigit(text.at(progress->offset()))) { ++count; progress->incrementOffset(); } if (count > 0) return true; else if (saveRestoreOffset) progress->restoreOffset(); } return false; } bool Rule::matchHexSequence(const QString &text, const int length, ProgressData *progress, bool saveRestoreOffset) const { // An hex sequence is identified as in the C++ Standard. // hexadecimal-escape-sequence: // \x hexadecimal-digit // hexadecimal-escape-sequence hexadecimal-digit if (matchCharacter(text, length, progress, kBackSlash, saveRestoreOffset)) { if (progress->offset() < length && matchCharacter(text, length, progress, kX, false)) { bool found = false; while (progress->offset() < length && isHexDigit(text.at(progress->offset()))) { if (!found) found = true; progress->incrementOffset(); } if (found) return true; else if (saveRestoreOffset) progress->restoreOffset(); } else if (saveRestoreOffset) { progress->restoreOffset(); } } return false; }
{ "pile_set_name": "Github" }
// // Copyright (c) 2000-2002 // Joerg Walter, Mathias Koch // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // The authors gratefully acknowledge the support of // GeNeSys mbH & Co. KG in producing this work. // #ifndef _BOOST_UBLAS_VECTOR_SPARSE_ #define _BOOST_UBLAS_VECTOR_SPARSE_ #include <boost/config.hpp> // In debug mode, MSCV enables iterator debugging, which additional checks are // executed for consistency. So, when two iterators are compared, it is tested // that they point to elements of the same container. If the check fails, then // the program is aborted. // // When matrices MVOV are traversed by column and then by row, the previous // check fails. // // MVOV::iterator2 iter2 = mvov.begin2(); // for (; iter2 != mvov.end() ; iter2++) { // MVOV::iterator1 iter1 = iter2.begin(); // ..... // } // // These additional checks in iterators are disabled in this file, but their // status are restored at the end of file. // https://msdn.microsoft.com/en-us/library/hh697468.aspx #ifdef BOOST_MSVC #define _BACKUP_ITERATOR_DEBUG_LEVEL _ITERATOR_DEBUG_LEVEL #undef _ITERATOR_DEBUG_LEVEL #define _ITERATOR_DEBUG_LEVEL 0 #endif #include <boost/numeric/ublas/storage_sparse.hpp> #include <boost/numeric/ublas/vector_expression.hpp> #include <boost/numeric/ublas/detail/vector_assign.hpp> #if BOOST_UBLAS_TYPE_CHECK #include <boost/numeric/ublas/vector.hpp> #endif // Iterators based on ideas of Jeremy Siek namespace boost { namespace numeric { namespace ublas { #ifdef BOOST_UBLAS_STRICT_VECTOR_SPARSE template<class V> class sparse_vector_element: public container_reference<V> { public: typedef V vector_type; typedef typename V::size_type size_type; typedef typename V::value_type value_type; typedef const value_type &const_reference; typedef value_type *pointer; private: // Proxied element operations void get_d () const { pointer p = (*this) ().find_element (i_); if (p) d_ = *p; else d_ = value_type/*zero*/(); } void set (const value_type &s) const { pointer p = (*this) ().find_element (i_); if (!p) (*this) ().insert_element (i_, s); else *p = s; } public: // Construction and destruction sparse_vector_element (vector_type &v, size_type i): container_reference<vector_type> (v), i_ (i) { } BOOST_UBLAS_INLINE sparse_vector_element (const sparse_vector_element &p): container_reference<vector_type> (p), i_ (p.i_) {} BOOST_UBLAS_INLINE ~sparse_vector_element () { } // Assignment BOOST_UBLAS_INLINE sparse_vector_element &operator = (const sparse_vector_element &p) { // Overide the implict copy assignment p.get_d (); set (p.d_); return *this; } template<class D> BOOST_UBLAS_INLINE sparse_vector_element &operator = (const D &d) { set (d); return *this; } template<class D> BOOST_UBLAS_INLINE sparse_vector_element &operator += (const D &d) { get_d (); d_ += d; set (d_); return *this; } template<class D> BOOST_UBLAS_INLINE sparse_vector_element &operator -= (const D &d) { get_d (); d_ -= d; set (d_); return *this; } template<class D> BOOST_UBLAS_INLINE sparse_vector_element &operator *= (const D &d) { get_d (); d_ *= d; set (d_); return *this; } template<class D> BOOST_UBLAS_INLINE sparse_vector_element &operator /= (const D &d) { get_d (); d_ /= d; set (d_); return *this; } // Comparison template<class D> BOOST_UBLAS_INLINE bool operator == (const D &d) const { get_d (); return d_ == d; } template<class D> BOOST_UBLAS_INLINE bool operator != (const D &d) const { get_d (); return d_ != d; } // Conversion - weak link in proxy as d_ is not a perfect alias for the element BOOST_UBLAS_INLINE operator const_reference () const { get_d (); return d_; } // Conversion to reference - may be invalidated BOOST_UBLAS_INLINE value_type& ref () const { const pointer p = (*this) ().find_element (i_); if (!p) return (*this) ().insert_element (i_, value_type/*zero*/()); else return *p; } private: size_type i_; mutable value_type d_; }; /* * Generalise explicit reference access */ namespace detail { template <class R> struct element_reference { typedef R& reference; static reference get_reference (reference r) { return r; } }; template <class V> struct element_reference<sparse_vector_element<V> > { typedef typename V::value_type& reference; static reference get_reference (const sparse_vector_element<V>& sve) { return sve.ref (); } }; } template <class VER> typename detail::element_reference<VER>::reference ref (VER& ver) { return detail::element_reference<VER>::get_reference (ver); } template <class VER> typename detail::element_reference<VER>::reference ref (const VER& ver) { return detail::element_reference<VER>::get_reference (ver); } template<class V> struct type_traits<sparse_vector_element<V> > { typedef typename V::value_type element_type; typedef type_traits<sparse_vector_element<V> > self_type; typedef typename type_traits<element_type>::value_type value_type; typedef typename type_traits<element_type>::const_reference const_reference; typedef sparse_vector_element<V> reference; typedef typename type_traits<element_type>::real_type real_type; typedef typename type_traits<element_type>::precision_type precision_type; static const unsigned plus_complexity = type_traits<element_type>::plus_complexity; static const unsigned multiplies_complexity = type_traits<element_type>::multiplies_complexity; static BOOST_UBLAS_INLINE real_type real (const_reference t) { return type_traits<element_type>::real (t); } static BOOST_UBLAS_INLINE real_type imag (const_reference t) { return type_traits<element_type>::imag (t); } static BOOST_UBLAS_INLINE value_type conj (const_reference t) { return type_traits<element_type>::conj (t); } static BOOST_UBLAS_INLINE real_type type_abs (const_reference t) { return type_traits<element_type>::type_abs (t); } static BOOST_UBLAS_INLINE value_type type_sqrt (const_reference t) { return type_traits<element_type>::type_sqrt (t); } static BOOST_UBLAS_INLINE real_type norm_1 (const_reference t) { return type_traits<element_type>::norm_1 (t); } static BOOST_UBLAS_INLINE real_type norm_2 (const_reference t) { return type_traits<element_type>::norm_2 (t); } static BOOST_UBLAS_INLINE real_type norm_inf (const_reference t) { return type_traits<element_type>::norm_inf (t); } static BOOST_UBLAS_INLINE bool equals (const_reference t1, const_reference t2) { return type_traits<element_type>::equals (t1, t2); } }; template<class V1, class T2> struct promote_traits<sparse_vector_element<V1>, T2> { typedef typename promote_traits<typename sparse_vector_element<V1>::value_type, T2>::promote_type promote_type; }; template<class T1, class V2> struct promote_traits<T1, sparse_vector_element<V2> > { typedef typename promote_traits<T1, typename sparse_vector_element<V2>::value_type>::promote_type promote_type; }; template<class V1, class V2> struct promote_traits<sparse_vector_element<V1>, sparse_vector_element<V2> > { typedef typename promote_traits<typename sparse_vector_element<V1>::value_type, typename sparse_vector_element<V2>::value_type>::promote_type promote_type; }; #endif /** \brief Index map based sparse vector * * A sparse vector of values of type T of variable size. The sparse storage type A can be * \c std::map<size_t, T> or \c map_array<size_t, T>. This means that only non-zero elements * are effectively stored. * * For a \f$n\f$-dimensional sparse vector, and 0 <= i < n the non-zero elements \f$v_i\f$ * are mapped to consecutive elements of the associative container, i.e. for elements * \f$k = v_{i_1}\f$ and \f$k + 1 = v_{i_2}\f$ of the container, holds \f$i_1 < i_2\f$. * * Supported parameters for the adapted array are \c map_array<std::size_t, T> and * \c map_std<std::size_t, T>. The latter is equivalent to \c std::map<std::size_t, T>. * * \tparam T the type of object stored in the vector (like double, float, complex, etc...) * \tparam A the type of Storage array */ template<class T, class A> class mapped_vector: public vector_container<mapped_vector<T, A> > { typedef T &true_reference; typedef T *pointer; typedef const T *const_pointer; typedef mapped_vector<T, A> self_type; public: #ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS using vector_container<self_type>::operator (); #endif typedef typename A::size_type size_type; typedef typename A::difference_type difference_type; typedef T value_type; typedef A array_type; typedef const value_type &const_reference; #ifndef BOOST_UBLAS_STRICT_VECTOR_SPARSE typedef typename detail::map_traits<A,T>::reference reference; #else typedef sparse_vector_element<self_type> reference; #endif typedef const vector_reference<const self_type> const_closure_type; typedef vector_reference<self_type> closure_type; typedef self_type vector_temporary_type; typedef sparse_tag storage_category; // Construction and destruction BOOST_UBLAS_INLINE mapped_vector (): vector_container<self_type> (), size_ (0), data_ () {} BOOST_UBLAS_INLINE mapped_vector (size_type size, size_type non_zeros = 0): vector_container<self_type> (), size_ (size), data_ () { detail::map_reserve (data(), restrict_capacity (non_zeros)); } BOOST_UBLAS_INLINE mapped_vector (const mapped_vector &v): vector_container<self_type> (), size_ (v.size_), data_ (v.data_) {} template<class AE> BOOST_UBLAS_INLINE mapped_vector (const vector_expression<AE> &ae, size_type non_zeros = 0): vector_container<self_type> (), size_ (ae ().size ()), data_ () { detail::map_reserve (data(), restrict_capacity (non_zeros)); vector_assign<scalar_assign> (*this, ae); } // Accessors BOOST_UBLAS_INLINE size_type size () const { return size_; } BOOST_UBLAS_INLINE size_type nnz_capacity () const { return detail::map_capacity (data ()); } BOOST_UBLAS_INLINE size_type nnz () const { return data (). size (); } // Storage accessors BOOST_UBLAS_INLINE const array_type &data () const { return data_; } BOOST_UBLAS_INLINE array_type &data () { return data_; } // Resizing private: BOOST_UBLAS_INLINE size_type restrict_capacity (size_type non_zeros) const { non_zeros = (std::min) (non_zeros, size_); return non_zeros; } public: BOOST_UBLAS_INLINE void resize (size_type size, bool preserve = true) { size_ = size; if (preserve) { data ().erase (data ().lower_bound(size_), data ().end()); } else { data ().clear (); } } // Reserving BOOST_UBLAS_INLINE void reserve (size_type non_zeros, bool /*preserve*/ = true) { detail::map_reserve (data (), restrict_capacity (non_zeros)); } // Element support BOOST_UBLAS_INLINE pointer find_element (size_type i) { return const_cast<pointer> (const_cast<const self_type&>(*this).find_element (i)); } BOOST_UBLAS_INLINE const_pointer find_element (size_type i) const { const_subiterator_type it (data ().find (i)); if (it == data ().end ()) return 0; BOOST_UBLAS_CHECK ((*it).first == i, internal_logic ()); // broken map return &(*it).second; } // Element access BOOST_UBLAS_INLINE const_reference operator () (size_type i) const { BOOST_UBLAS_CHECK (i < size_, bad_index ()); const_subiterator_type it (data ().find (i)); if (it == data ().end ()) return zero_; BOOST_UBLAS_CHECK ((*it).first == i, internal_logic ()); // broken map return (*it).second; } BOOST_UBLAS_INLINE true_reference ref (size_type i) { BOOST_UBLAS_CHECK (i < size_, bad_index ()); std::pair<subiterator_type, bool> ii (data ().insert (typename array_type::value_type (i, value_type/*zero*/()))); BOOST_UBLAS_CHECK ((ii.first)->first == i, internal_logic ()); // broken map return (ii.first)->second; } BOOST_UBLAS_INLINE reference operator () (size_type i) { #ifndef BOOST_UBLAS_STRICT_VECTOR_SPARSE return ref (i); #else BOOST_UBLAS_CHECK (i < size_, bad_index ()); return reference (*this, i); #endif } BOOST_UBLAS_INLINE const_reference operator [] (size_type i) const { return (*this) (i); } BOOST_UBLAS_INLINE reference operator [] (size_type i) { return (*this) (i); } // Element assignment BOOST_UBLAS_INLINE true_reference insert_element (size_type i, const_reference t) { std::pair<subiterator_type, bool> ii = data ().insert (typename array_type::value_type (i, t)); BOOST_UBLAS_CHECK (ii.second, bad_index ()); // duplicate element BOOST_UBLAS_CHECK ((ii.first)->first == i, internal_logic ()); // broken map if (!ii.second) // existing element (ii.first)->second = t; return (ii.first)->second; } BOOST_UBLAS_INLINE void erase_element (size_type i) { subiterator_type it = data ().find (i); if (it == data ().end ()) return; data ().erase (it); } // Zeroing BOOST_UBLAS_INLINE void clear () { data ().clear (); } // Assignment BOOST_UBLAS_INLINE mapped_vector &operator = (const mapped_vector &v) { if (this != &v) { size_ = v.size_; data () = v.data (); } return *this; } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE mapped_vector &operator = (const vector_container<C> &v) { resize (v ().size (), false); assign (v); return *this; } BOOST_UBLAS_INLINE mapped_vector &assign_temporary (mapped_vector &v) { swap (v); return *this; } template<class AE> BOOST_UBLAS_INLINE mapped_vector &operator = (const vector_expression<AE> &ae) { self_type temporary (ae, detail::map_capacity (data())); return assign_temporary (temporary); } template<class AE> BOOST_UBLAS_INLINE mapped_vector &assign (const vector_expression<AE> &ae) { vector_assign<scalar_assign> (*this, ae); return *this; } // Computed assignment template<class AE> BOOST_UBLAS_INLINE mapped_vector &operator += (const vector_expression<AE> &ae) { self_type temporary (*this + ae, detail::map_capacity (data())); return assign_temporary (temporary); } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE mapped_vector &operator += (const vector_container<C> &v) { plus_assign (v); return *this; } template<class AE> BOOST_UBLAS_INLINE mapped_vector &plus_assign (const vector_expression<AE> &ae) { vector_assign<scalar_plus_assign> (*this, ae); return *this; } template<class AE> BOOST_UBLAS_INLINE mapped_vector &operator -= (const vector_expression<AE> &ae) { self_type temporary (*this - ae, detail::map_capacity (data())); return assign_temporary (temporary); } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE mapped_vector &operator -= (const vector_container<C> &v) { minus_assign (v); return *this; } template<class AE> BOOST_UBLAS_INLINE mapped_vector &minus_assign (const vector_expression<AE> &ae) { vector_assign<scalar_minus_assign> (*this, ae); return *this; } template<class AT> BOOST_UBLAS_INLINE mapped_vector &operator *= (const AT &at) { vector_assign_scalar<scalar_multiplies_assign> (*this, at); return *this; } template<class AT> BOOST_UBLAS_INLINE mapped_vector &operator /= (const AT &at) { vector_assign_scalar<scalar_divides_assign> (*this, at); return *this; } // Swapping BOOST_UBLAS_INLINE void swap (mapped_vector &v) { if (this != &v) { std::swap (size_, v.size_); data ().swap (v.data ()); } } BOOST_UBLAS_INLINE friend void swap (mapped_vector &v1, mapped_vector &v2) { v1.swap (v2); } // Iterator types private: // Use storage iterator typedef typename A::const_iterator const_subiterator_type; typedef typename A::iterator subiterator_type; BOOST_UBLAS_INLINE true_reference at_element (size_type i) { BOOST_UBLAS_CHECK (i < size_, bad_index ()); subiterator_type it (data ().find (i)); BOOST_UBLAS_CHECK (it != data ().end(), bad_index ()); BOOST_UBLAS_CHECK ((*it).first == i, internal_logic ()); // broken map return it->second; } public: class const_iterator; class iterator; // Element lookup // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. const_iterator find (size_type i) const { return const_iterator (*this, data ().lower_bound (i)); } // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. iterator find (size_type i) { return iterator (*this, data ().lower_bound (i)); } class const_iterator: public container_const_reference<mapped_vector>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, const_iterator, value_type> { public: typedef typename mapped_vector::value_type value_type; typedef typename mapped_vector::difference_type difference_type; typedef typename mapped_vector::const_reference reference; typedef const typename mapped_vector::pointer pointer; // Construction and destruction BOOST_UBLAS_INLINE const_iterator (): container_const_reference<self_type> (), it_ () {} BOOST_UBLAS_INLINE const_iterator (const self_type &v, const const_subiterator_type &it): container_const_reference<self_type> (v), it_ (it) {} BOOST_UBLAS_INLINE const_iterator (const typename self_type::iterator &it): // ISSUE self_type:: stops VC8 using std::iterator here container_const_reference<self_type> (it ()), it_ (it.it_) {} // Arithmetic BOOST_UBLAS_INLINE const_iterator &operator ++ () { ++ it_; return *this; } BOOST_UBLAS_INLINE const_iterator &operator -- () { -- it_; return *this; } // Dereference BOOST_UBLAS_INLINE const_reference operator * () const { BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ()); return (*it_).second; } // Index BOOST_UBLAS_INLINE size_type index () const { BOOST_UBLAS_CHECK (*this != (*this) ().end (), bad_index ()); BOOST_UBLAS_CHECK ((*it_).first < (*this) ().size (), bad_index ()); return (*it_).first; } // Assignment BOOST_UBLAS_INLINE const_iterator &operator = (const const_iterator &it) { container_const_reference<self_type>::assign (&it ()); it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const const_iterator &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); return it_ == it.it_; } private: const_subiterator_type it_; }; BOOST_UBLAS_INLINE const_iterator begin () const { return const_iterator (*this, data ().begin ()); } BOOST_UBLAS_INLINE const_iterator cbegin () const { return begin (); } BOOST_UBLAS_INLINE const_iterator end () const { return const_iterator (*this, data ().end ()); } BOOST_UBLAS_INLINE const_iterator cend () const { return end (); } class iterator: public container_reference<mapped_vector>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, iterator, value_type> { public: typedef typename mapped_vector::value_type value_type; typedef typename mapped_vector::difference_type difference_type; typedef typename mapped_vector::true_reference reference; typedef typename mapped_vector::pointer pointer; // Construction and destruction BOOST_UBLAS_INLINE iterator (): container_reference<self_type> (), it_ () {} BOOST_UBLAS_INLINE iterator (self_type &v, const subiterator_type &it): container_reference<self_type> (v), it_ (it) {} // Arithmetic BOOST_UBLAS_INLINE iterator &operator ++ () { ++ it_; return *this; } BOOST_UBLAS_INLINE iterator &operator -- () { -- it_; return *this; } // Dereference BOOST_UBLAS_INLINE reference operator * () const { BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ()); return (*it_).second; } // Index BOOST_UBLAS_INLINE size_type index () const { BOOST_UBLAS_CHECK (*this != (*this) ().end (), bad_index ()); BOOST_UBLAS_CHECK ((*it_).first < (*this) ().size (), bad_index ()); return (*it_).first; } // Assignment BOOST_UBLAS_INLINE iterator &operator = (const iterator &it) { container_reference<self_type>::assign (&it ()); it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const iterator &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); return it_ == it.it_; } private: subiterator_type it_; friend class const_iterator; }; BOOST_UBLAS_INLINE iterator begin () { return iterator (*this, data ().begin ()); } BOOST_UBLAS_INLINE iterator end () { return iterator (*this, data ().end ()); } // Reverse iterator typedef reverse_iterator_base<const_iterator> const_reverse_iterator; typedef reverse_iterator_base<iterator> reverse_iterator; BOOST_UBLAS_INLINE const_reverse_iterator rbegin () const { return const_reverse_iterator (end ()); } BOOST_UBLAS_INLINE const_reverse_iterator crbegin () const { return rbegin (); } BOOST_UBLAS_INLINE const_reverse_iterator rend () const { return const_reverse_iterator (begin ()); } BOOST_UBLAS_INLINE const_reverse_iterator crend () const { return rend (); } BOOST_UBLAS_INLINE reverse_iterator rbegin () { return reverse_iterator (end ()); } BOOST_UBLAS_INLINE reverse_iterator rend () { return reverse_iterator (begin ()); } // Serialization template<class Archive> void serialize(Archive & ar, const unsigned int /* file_version */){ serialization::collection_size_type s (size_); ar & serialization::make_nvp("size",s); if (Archive::is_loading::value) { size_ = s; } ar & serialization::make_nvp("data", data_); } private: size_type size_; array_type data_; static const value_type zero_; }; template<class T, class A> const typename mapped_vector<T, A>::value_type mapped_vector<T, A>::zero_ = value_type/*zero*/(); // Thanks to Kresimir Fresl for extending this to cover different index bases. /** \brief Compressed array based sparse vector * * a sparse vector of values of type T of variable size. The non zero values are stored as * two seperate arrays: an index array and a value array. The index array is always sorted * and there is at most one entry for each index. Inserting an element can be time consuming. * If the vector contains a few zero entries, then it is better to have a normal vector. * If the vector has a very high dimension with a few non-zero values, then this vector is * very memory efficient (at the cost of a few more computations). * * For a \f$n\f$-dimensional compressed vector and \f$0 \leq i < n\f$ the non-zero elements * \f$v_i\f$ are mapped to consecutive elements of the index and value container, i.e. for * elements \f$k = v_{i_1}\f$ and \f$k + 1 = v_{i_2}\f$ of these containers holds \f$i_1 < i_2\f$. * * Supported parameters for the adapted array (indices and values) are \c unbounded_array<> , * \c bounded_array<> and \c std::vector<>. * * \tparam T the type of object stored in the vector (like double, float, complex, etc...) * \tparam IB the index base of the compressed vector. Default is 0. Other supported value is 1 * \tparam IA the type of adapted array for indices. Default is \c unbounded_array<std::size_t> * \tparam TA the type of adapted array for values. Default is unbounded_array<T> */ template<class T, std::size_t IB, class IA, class TA> class compressed_vector: public vector_container<compressed_vector<T, IB, IA, TA> > { typedef T &true_reference; typedef T *pointer; typedef const T *const_pointer; typedef compressed_vector<T, IB, IA, TA> self_type; public: #ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS using vector_container<self_type>::operator (); #endif // ISSUE require type consistency check // is_convertable (IA::size_type, TA::size_type) typedef typename IA::value_type size_type; typedef typename IA::difference_type difference_type; typedef T value_type; typedef const T &const_reference; #ifndef BOOST_UBLAS_STRICT_VECTOR_SPARSE typedef T &reference; #else typedef sparse_vector_element<self_type> reference; #endif typedef IA index_array_type; typedef TA value_array_type; typedef const vector_reference<const self_type> const_closure_type; typedef vector_reference<self_type> closure_type; typedef self_type vector_temporary_type; typedef sparse_tag storage_category; // Construction and destruction BOOST_UBLAS_INLINE compressed_vector (): vector_container<self_type> (), size_ (0), capacity_ (restrict_capacity (0)), filled_ (0), index_data_ (capacity_), value_data_ (capacity_) { storage_invariants (); } explicit BOOST_UBLAS_INLINE compressed_vector (size_type size, size_type non_zeros = 0): vector_container<self_type> (), size_ (size), capacity_ (restrict_capacity (non_zeros)), filled_ (0), index_data_ (capacity_), value_data_ (capacity_) { storage_invariants (); } BOOST_UBLAS_INLINE compressed_vector (const compressed_vector &v): vector_container<self_type> (), size_ (v.size_), capacity_ (v.capacity_), filled_ (v.filled_), index_data_ (v.index_data_), value_data_ (v.value_data_) { storage_invariants (); } template<class AE> BOOST_UBLAS_INLINE compressed_vector (const vector_expression<AE> &ae, size_type non_zeros = 0): vector_container<self_type> (), size_ (ae ().size ()), capacity_ (restrict_capacity (non_zeros)), filled_ (0), index_data_ (capacity_), value_data_ (capacity_) { storage_invariants (); vector_assign<scalar_assign> (*this, ae); } // Accessors BOOST_UBLAS_INLINE size_type size () const { return size_; } BOOST_UBLAS_INLINE size_type nnz_capacity () const { return capacity_; } BOOST_UBLAS_INLINE size_type nnz () const { return filled_; } // Storage accessors BOOST_UBLAS_INLINE static size_type index_base () { return IB; } BOOST_UBLAS_INLINE typename index_array_type::size_type filled () const { return filled_; } BOOST_UBLAS_INLINE const index_array_type &index_data () const { return index_data_; } BOOST_UBLAS_INLINE const value_array_type &value_data () const { return value_data_; } BOOST_UBLAS_INLINE void set_filled (const typename index_array_type::size_type & filled) { filled_ = filled; storage_invariants (); } BOOST_UBLAS_INLINE index_array_type &index_data () { return index_data_; } BOOST_UBLAS_INLINE value_array_type &value_data () { return value_data_; } // Resizing private: BOOST_UBLAS_INLINE size_type restrict_capacity (size_type non_zeros) const { non_zeros = (std::max) (non_zeros, size_type (1)); non_zeros = (std::min) (non_zeros, size_); return non_zeros; } public: BOOST_UBLAS_INLINE void resize (size_type size, bool preserve = true) { size_ = size; capacity_ = restrict_capacity (capacity_); if (preserve) { index_data_. resize (capacity_, size_type ()); value_data_. resize (capacity_, value_type ()); filled_ = (std::min) (capacity_, filled_); while ((filled_ > 0) && (zero_based(index_data_[filled_ - 1]) >= size)) { --filled_; } } else { index_data_. resize (capacity_); value_data_. resize (capacity_); filled_ = 0; } storage_invariants (); } // Reserving BOOST_UBLAS_INLINE void reserve (size_type non_zeros, bool preserve = true) { capacity_ = restrict_capacity (non_zeros); if (preserve) { index_data_. resize (capacity_, size_type ()); value_data_. resize (capacity_, value_type ()); filled_ = (std::min) (capacity_, filled_); } else { index_data_. resize (capacity_); value_data_. resize (capacity_); filled_ = 0; } storage_invariants (); } // Element support BOOST_UBLAS_INLINE pointer find_element (size_type i) { return const_cast<pointer> (const_cast<const self_type&>(*this).find_element (i)); } BOOST_UBLAS_INLINE const_pointer find_element (size_type i) const { const_subiterator_type it (detail::lower_bound (index_data_.begin (), index_data_.begin () + filled_, k_based (i), std::less<size_type> ())); if (it == index_data_.begin () + filled_ || *it != k_based (i)) return 0; return &value_data_ [it - index_data_.begin ()]; } // Element access BOOST_UBLAS_INLINE const_reference operator () (size_type i) const { BOOST_UBLAS_CHECK (i < size_, bad_index ()); const_subiterator_type it (detail::lower_bound (index_data_.begin (), index_data_.begin () + filled_, k_based (i), std::less<size_type> ())); if (it == index_data_.begin () + filled_ || *it != k_based (i)) return zero_; return value_data_ [it - index_data_.begin ()]; } BOOST_UBLAS_INLINE true_reference ref (size_type i) { BOOST_UBLAS_CHECK (i < size_, bad_index ()); subiterator_type it (detail::lower_bound (index_data_.begin (), index_data_.begin () + filled_, k_based (i), std::less<size_type> ())); if (it == index_data_.begin () + filled_ || *it != k_based (i)) return insert_element (i, value_type/*zero*/()); else return value_data_ [it - index_data_.begin ()]; } BOOST_UBLAS_INLINE reference operator () (size_type i) { #ifndef BOOST_UBLAS_STRICT_VECTOR_SPARSE return ref (i) ; #else BOOST_UBLAS_CHECK (i < size_, bad_index ()); return reference (*this, i); #endif } BOOST_UBLAS_INLINE const_reference operator [] (size_type i) const { return (*this) (i); } BOOST_UBLAS_INLINE reference operator [] (size_type i) { return (*this) (i); } // Element assignment BOOST_UBLAS_INLINE true_reference insert_element (size_type i, const_reference t) { BOOST_UBLAS_CHECK (!find_element (i), bad_index ()); // duplicate element if (filled_ >= capacity_) reserve (2 * capacity_, true); subiterator_type it (detail::lower_bound (index_data_.begin (), index_data_.begin () + filled_, k_based (i), std::less<size_type> ())); // ISSUE max_capacity limit due to difference_type typename std::iterator_traits<subiterator_type>::difference_type n = it - index_data_.begin (); BOOST_UBLAS_CHECK (filled_ == 0 || filled_ == typename index_array_type::size_type (n) || *it != k_based (i), internal_logic ()); // duplicate found by lower_bound ++ filled_; it = index_data_.begin () + n; std::copy_backward (it, index_data_.begin () + filled_ - 1, index_data_.begin () + filled_); *it = k_based (i); typename value_array_type::iterator itt (value_data_.begin () + n); std::copy_backward (itt, value_data_.begin () + filled_ - 1, value_data_.begin () + filled_); *itt = t; storage_invariants (); return *itt; } BOOST_UBLAS_INLINE void erase_element (size_type i) { subiterator_type it (detail::lower_bound (index_data_.begin (), index_data_.begin () + filled_, k_based (i), std::less<size_type> ())); typename std::iterator_traits<subiterator_type>::difference_type n = it - index_data_.begin (); if (filled_ > typename index_array_type::size_type (n) && *it == k_based (i)) { std::copy (it + 1, index_data_.begin () + filled_, it); typename value_array_type::iterator itt (value_data_.begin () + n); std::copy (itt + 1, value_data_.begin () + filled_, itt); -- filled_; } storage_invariants (); } // Zeroing BOOST_UBLAS_INLINE void clear () { filled_ = 0; storage_invariants (); } // Assignment BOOST_UBLAS_INLINE compressed_vector &operator = (const compressed_vector &v) { if (this != &v) { size_ = v.size_; capacity_ = v.capacity_; filled_ = v.filled_; index_data_ = v.index_data_; value_data_ = v.value_data_; } storage_invariants (); return *this; } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE compressed_vector &operator = (const vector_container<C> &v) { resize (v ().size (), false); assign (v); return *this; } BOOST_UBLAS_INLINE compressed_vector &assign_temporary (compressed_vector &v) { swap (v); return *this; } template<class AE> BOOST_UBLAS_INLINE compressed_vector &operator = (const vector_expression<AE> &ae) { self_type temporary (ae, capacity_); return assign_temporary (temporary); } template<class AE> BOOST_UBLAS_INLINE compressed_vector &assign (const vector_expression<AE> &ae) { vector_assign<scalar_assign> (*this, ae); return *this; } // Computed assignment template<class AE> BOOST_UBLAS_INLINE compressed_vector &operator += (const vector_expression<AE> &ae) { self_type temporary (*this + ae, capacity_); return assign_temporary (temporary); } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE compressed_vector &operator += (const vector_container<C> &v) { plus_assign (v); return *this; } template<class AE> BOOST_UBLAS_INLINE compressed_vector &plus_assign (const vector_expression<AE> &ae) { vector_assign<scalar_plus_assign> (*this, ae); return *this; } template<class AE> BOOST_UBLAS_INLINE compressed_vector &operator -= (const vector_expression<AE> &ae) { self_type temporary (*this - ae, capacity_); return assign_temporary (temporary); } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE compressed_vector &operator -= (const vector_container<C> &v) { minus_assign (v); return *this; } template<class AE> BOOST_UBLAS_INLINE compressed_vector &minus_assign (const vector_expression<AE> &ae) { vector_assign<scalar_minus_assign> (*this, ae); return *this; } template<class AT> BOOST_UBLAS_INLINE compressed_vector &operator *= (const AT &at) { vector_assign_scalar<scalar_multiplies_assign> (*this, at); return *this; } template<class AT> BOOST_UBLAS_INLINE compressed_vector &operator /= (const AT &at) { vector_assign_scalar<scalar_divides_assign> (*this, at); return *this; } // Swapping BOOST_UBLAS_INLINE void swap (compressed_vector &v) { if (this != &v) { std::swap (size_, v.size_); std::swap (capacity_, v.capacity_); std::swap (filled_, v.filled_); index_data_.swap (v.index_data_); value_data_.swap (v.value_data_); } storage_invariants (); } BOOST_UBLAS_INLINE friend void swap (compressed_vector &v1, compressed_vector &v2) { v1.swap (v2); } // Back element insertion and erasure BOOST_UBLAS_INLINE void push_back (size_type i, const_reference t) { BOOST_UBLAS_CHECK (filled_ == 0 || index_data_ [filled_ - 1] < k_based (i), external_logic ()); if (filled_ >= capacity_) reserve (2 * capacity_, true); BOOST_UBLAS_CHECK (filled_ < capacity_, internal_logic ()); index_data_ [filled_] = k_based (i); value_data_ [filled_] = t; ++ filled_; storage_invariants (); } BOOST_UBLAS_INLINE void pop_back () { BOOST_UBLAS_CHECK (filled_ > 0, external_logic ()); -- filled_; storage_invariants (); } // Iterator types private: // Use index array iterator typedef typename IA::const_iterator const_subiterator_type; typedef typename IA::iterator subiterator_type; BOOST_UBLAS_INLINE true_reference at_element (size_type i) { BOOST_UBLAS_CHECK (i < size_, bad_index ()); subiterator_type it (detail::lower_bound (index_data_.begin (), index_data_.begin () + filled_, k_based (i), std::less<size_type> ())); BOOST_UBLAS_CHECK (it != index_data_.begin () + filled_ && *it == k_based (i), bad_index ()); return value_data_ [it - index_data_.begin ()]; } public: class const_iterator; class iterator; // Element lookup // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. const_iterator find (size_type i) const { return const_iterator (*this, detail::lower_bound (index_data_.begin (), index_data_.begin () + filled_, k_based (i), std::less<size_type> ())); } // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. iterator find (size_type i) { return iterator (*this, detail::lower_bound (index_data_.begin (), index_data_.begin () + filled_, k_based (i), std::less<size_type> ())); } class const_iterator: public container_const_reference<compressed_vector>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, const_iterator, value_type> { public: typedef typename compressed_vector::value_type value_type; typedef typename compressed_vector::difference_type difference_type; typedef typename compressed_vector::const_reference reference; typedef const typename compressed_vector::pointer pointer; // Construction and destruction BOOST_UBLAS_INLINE const_iterator (): container_const_reference<self_type> (), it_ () {} BOOST_UBLAS_INLINE const_iterator (const self_type &v, const const_subiterator_type &it): container_const_reference<self_type> (v), it_ (it) {} BOOST_UBLAS_INLINE const_iterator (const typename self_type::iterator &it): // ISSUE self_type:: stops VC8 using std::iterator here container_const_reference<self_type> (it ()), it_ (it.it_) {} // Arithmetic BOOST_UBLAS_INLINE const_iterator &operator ++ () { ++ it_; return *this; } BOOST_UBLAS_INLINE const_iterator &operator -- () { -- it_; return *this; } // Dereference BOOST_UBLAS_INLINE const_reference operator * () const { BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ()); return (*this) ().value_data_ [it_ - (*this) ().index_data_.begin ()]; } // Index BOOST_UBLAS_INLINE size_type index () const { BOOST_UBLAS_CHECK (*this != (*this) ().end (), bad_index ()); BOOST_UBLAS_CHECK ((*this) ().zero_based (*it_) < (*this) ().size (), bad_index ()); return (*this) ().zero_based (*it_); } // Assignment BOOST_UBLAS_INLINE const_iterator &operator = (const const_iterator &it) { container_const_reference<self_type>::assign (&it ()); it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const const_iterator &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); return it_ == it.it_; } private: const_subiterator_type it_; }; BOOST_UBLAS_INLINE const_iterator begin () const { return find (0); } BOOST_UBLAS_INLINE const_iterator cbegin () const { return begin (); } BOOST_UBLAS_INLINE const_iterator end () const { return find (size_); } BOOST_UBLAS_INLINE const_iterator cend () const { return end (); } class iterator: public container_reference<compressed_vector>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, iterator, value_type> { public: typedef typename compressed_vector::value_type value_type; typedef typename compressed_vector::difference_type difference_type; typedef typename compressed_vector::true_reference reference; typedef typename compressed_vector::pointer pointer; // Construction and destruction BOOST_UBLAS_INLINE iterator (): container_reference<self_type> (), it_ () {} BOOST_UBLAS_INLINE iterator (self_type &v, const subiterator_type &it): container_reference<self_type> (v), it_ (it) {} // Arithmetic BOOST_UBLAS_INLINE iterator &operator ++ () { ++ it_; return *this; } BOOST_UBLAS_INLINE iterator &operator -- () { -- it_; return *this; } // Dereference BOOST_UBLAS_INLINE reference operator * () const { BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ()); return (*this) ().value_data_ [it_ - (*this) ().index_data_.begin ()]; } // Index BOOST_UBLAS_INLINE size_type index () const { BOOST_UBLAS_CHECK (*this != (*this) ().end (), bad_index ()); BOOST_UBLAS_CHECK ((*this) ().zero_based (*it_) < (*this) ().size (), bad_index ()); return (*this) ().zero_based (*it_); } // Assignment BOOST_UBLAS_INLINE iterator &operator = (const iterator &it) { container_reference<self_type>::assign (&it ()); it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const iterator &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); return it_ == it.it_; } private: subiterator_type it_; friend class const_iterator; }; BOOST_UBLAS_INLINE iterator begin () { return find (0); } BOOST_UBLAS_INLINE iterator end () { return find (size_); } // Reverse iterator typedef reverse_iterator_base<const_iterator> const_reverse_iterator; typedef reverse_iterator_base<iterator> reverse_iterator; BOOST_UBLAS_INLINE const_reverse_iterator rbegin () const { return const_reverse_iterator (end ()); } BOOST_UBLAS_INLINE const_reverse_iterator crbegin () const { return rbegin (); } BOOST_UBLAS_INLINE const_reverse_iterator rend () const { return const_reverse_iterator (begin ()); } BOOST_UBLAS_INLINE const_reverse_iterator crend () const { return rend (); } BOOST_UBLAS_INLINE reverse_iterator rbegin () { return reverse_iterator (end ()); } BOOST_UBLAS_INLINE reverse_iterator rend () { return reverse_iterator (begin ()); } // Serialization template<class Archive> void serialize(Archive & ar, const unsigned int /* file_version */){ serialization::collection_size_type s (size_); ar & serialization::make_nvp("size",s); if (Archive::is_loading::value) { size_ = s; } // ISSUE: filled may be much less than capacity // ISSUE: index_data_ and value_data_ are undefined between filled and capacity (trouble with 'nan'-values) ar & serialization::make_nvp("capacity", capacity_); ar & serialization::make_nvp("filled", filled_); ar & serialization::make_nvp("index_data", index_data_); ar & serialization::make_nvp("value_data", value_data_); storage_invariants(); } private: void storage_invariants () const { BOOST_UBLAS_CHECK (capacity_ == index_data_.size (), internal_logic ()); BOOST_UBLAS_CHECK (capacity_ == value_data_.size (), internal_logic ()); BOOST_UBLAS_CHECK (filled_ <= capacity_, internal_logic ()); BOOST_UBLAS_CHECK ((0 == filled_) || (zero_based(index_data_[filled_ - 1]) < size_), internal_logic ()); } size_type size_; typename index_array_type::size_type capacity_; typename index_array_type::size_type filled_; index_array_type index_data_; value_array_type value_data_; static const value_type zero_; BOOST_UBLAS_INLINE static size_type zero_based (size_type k_based_index) { return k_based_index - IB; } BOOST_UBLAS_INLINE static size_type k_based (size_type zero_based_index) { return zero_based_index + IB; } friend class iterator; friend class const_iterator; }; template<class T, std::size_t IB, class IA, class TA> const typename compressed_vector<T, IB, IA, TA>::value_type compressed_vector<T, IB, IA, TA>::zero_ = value_type/*zero*/(); // Thanks to Kresimir Fresl for extending this to cover different index bases. /** \brief Coordimate array based sparse vector * * a sparse vector of values of type \c T of variable size. The non zero values are stored * as two seperate arrays: an index array and a value array. The arrays may be out of order * with multiple entries for each vector element. If there are multiple values for the same * index the sum of these values is the real value. It is way more efficient for inserting values * than a \c compressed_vector but less memory efficient. Also linearly parsing a vector can * be longer in specific cases than a \c compressed_vector. * * For a n-dimensional sorted coordinate vector and \f$ 0 \leq i < n\f$ the non-zero elements * \f$v_i\f$ are mapped to consecutive elements of the index and value container, i.e. for * elements \f$k = v_{i_1}\f$ and \f$k + 1 = v_{i_2}\f$ of these containers holds \f$i_1 < i_2\f$. * * Supported parameters for the adapted array (indices and values) are \c unbounded_array<> , * \c bounded_array<> and \c std::vector<>. * * \tparam T the type of object stored in the vector (like double, float, complex, etc...) * \tparam IB the index base of the compressed vector. Default is 0. Other supported value is 1 * \tparam IA the type of adapted array for indices. Default is \c unbounded_array<std::size_t> * \tparam TA the type of adapted array for values. Default is unbounded_array<T> */ template<class T, std::size_t IB, class IA, class TA> class coordinate_vector: public vector_container<coordinate_vector<T, IB, IA, TA> > { typedef T &true_reference; typedef T *pointer; typedef const T *const_pointer; typedef coordinate_vector<T, IB, IA, TA> self_type; public: #ifdef BOOST_UBLAS_ENABLE_PROXY_SHORTCUTS using vector_container<self_type>::operator (); #endif // ISSUE require type consistency check // is_convertable (IA::size_type, TA::size_type) typedef typename IA::value_type size_type; typedef typename IA::difference_type difference_type; typedef T value_type; typedef const T &const_reference; #ifndef BOOST_UBLAS_STRICT_VECTOR_SPARSE typedef T &reference; #else typedef sparse_vector_element<self_type> reference; #endif typedef IA index_array_type; typedef TA value_array_type; typedef const vector_reference<const self_type> const_closure_type; typedef vector_reference<self_type> closure_type; typedef self_type vector_temporary_type; typedef sparse_tag storage_category; // Construction and destruction BOOST_UBLAS_INLINE coordinate_vector (): vector_container<self_type> (), size_ (0), capacity_ (restrict_capacity (0)), filled_ (0), sorted_filled_ (filled_), sorted_ (true), index_data_ (capacity_), value_data_ (capacity_) { storage_invariants (); } explicit BOOST_UBLAS_INLINE coordinate_vector (size_type size, size_type non_zeros = 0): vector_container<self_type> (), size_ (size), capacity_ (restrict_capacity (non_zeros)), filled_ (0), sorted_filled_ (filled_), sorted_ (true), index_data_ (capacity_), value_data_ (capacity_) { storage_invariants (); } BOOST_UBLAS_INLINE coordinate_vector (const coordinate_vector &v): vector_container<self_type> (), size_ (v.size_), capacity_ (v.capacity_), filled_ (v.filled_), sorted_filled_ (v.sorted_filled_), sorted_ (v.sorted_), index_data_ (v.index_data_), value_data_ (v.value_data_) { storage_invariants (); } template<class AE> BOOST_UBLAS_INLINE coordinate_vector (const vector_expression<AE> &ae, size_type non_zeros = 0): vector_container<self_type> (), size_ (ae ().size ()), capacity_ (restrict_capacity (non_zeros)), filled_ (0), sorted_filled_ (filled_), sorted_ (true), index_data_ (capacity_), value_data_ (capacity_) { storage_invariants (); vector_assign<scalar_assign> (*this, ae); } // Accessors BOOST_UBLAS_INLINE size_type size () const { return size_; } BOOST_UBLAS_INLINE size_type nnz_capacity () const { return capacity_; } BOOST_UBLAS_INLINE size_type nnz () const { return filled_; } // Storage accessors BOOST_UBLAS_INLINE static size_type index_base () { return IB; } BOOST_UBLAS_INLINE typename index_array_type::size_type filled () const { return filled_; } BOOST_UBLAS_INLINE const index_array_type &index_data () const { return index_data_; } BOOST_UBLAS_INLINE const value_array_type &value_data () const { return value_data_; } BOOST_UBLAS_INLINE void set_filled (const typename index_array_type::size_type &sorted, const typename index_array_type::size_type &filled) { sorted_filled_ = sorted; filled_ = filled; storage_invariants (); } BOOST_UBLAS_INLINE index_array_type &index_data () { return index_data_; } BOOST_UBLAS_INLINE value_array_type &value_data () { return value_data_; } // Resizing private: BOOST_UBLAS_INLINE size_type restrict_capacity (size_type non_zeros) const { // minimum non_zeros non_zeros = (std::max) (non_zeros, size_type (1)); // ISSUE no maximum as coordinate may contain inserted duplicates return non_zeros; } public: BOOST_UBLAS_INLINE void resize (size_type size, bool preserve = true) { if (preserve) sort (); // remove duplicate elements. size_ = size; capacity_ = restrict_capacity (capacity_); if (preserve) { index_data_. resize (capacity_, size_type ()); value_data_. resize (capacity_, value_type ()); filled_ = (std::min) (capacity_, filled_); while ((filled_ > 0) && (zero_based(index_data_[filled_ - 1]) >= size)) { --filled_; } } else { index_data_. resize (capacity_); value_data_. resize (capacity_); filled_ = 0; } sorted_filled_ = filled_; storage_invariants (); } // Reserving BOOST_UBLAS_INLINE void reserve (size_type non_zeros, bool preserve = true) { if (preserve) sort (); // remove duplicate elements. capacity_ = restrict_capacity (non_zeros); if (preserve) { index_data_. resize (capacity_, size_type ()); value_data_. resize (capacity_, value_type ()); filled_ = (std::min) (capacity_, filled_); } else { index_data_. resize (capacity_); value_data_. resize (capacity_); filled_ = 0; } sorted_filled_ = filled_; storage_invariants (); } // Element support BOOST_UBLAS_INLINE pointer find_element (size_type i) { return const_cast<pointer> (const_cast<const self_type&>(*this).find_element (i)); } BOOST_UBLAS_INLINE const_pointer find_element (size_type i) const { sort (); const_subiterator_type it (detail::lower_bound (index_data_.begin (), index_data_.begin () + filled_, k_based (i), std::less<size_type> ())); if (it == index_data_.begin () + filled_ || *it != k_based (i)) return 0; return &value_data_ [it - index_data_.begin ()]; } // Element access BOOST_UBLAS_INLINE const_reference operator () (size_type i) const { BOOST_UBLAS_CHECK (i < size_, bad_index ()); sort (); const_subiterator_type it (detail::lower_bound (index_data_.begin (), index_data_.begin () + filled_, k_based (i), std::less<size_type> ())); if (it == index_data_.begin () + filled_ || *it != k_based (i)) return zero_; return value_data_ [it - index_data_.begin ()]; } BOOST_UBLAS_INLINE true_reference ref (size_type i) { BOOST_UBLAS_CHECK (i < size_, bad_index ()); sort (); subiterator_type it (detail::lower_bound (index_data_.begin (), index_data_.begin () + filled_, k_based (i), std::less<size_type> ())); if (it == index_data_.begin () + filled_ || *it != k_based (i)) return insert_element (i, value_type/*zero*/()); else return value_data_ [it - index_data_.begin ()]; } BOOST_UBLAS_INLINE reference operator () (size_type i) { #ifndef BOOST_UBLAS_STRICT_VECTOR_SPARSE return ref (i); #else BOOST_UBLAS_CHECK (i < size_, bad_index ()); return reference (*this, i); #endif } BOOST_UBLAS_INLINE const_reference operator [] (size_type i) const { return (*this) (i); } BOOST_UBLAS_INLINE reference operator [] (size_type i) { return (*this) (i); } // Element assignment BOOST_UBLAS_INLINE void append_element (size_type i, const_reference t) { if (filled_ >= capacity_) reserve (2 * filled_, true); BOOST_UBLAS_CHECK (filled_ < capacity_, internal_logic ()); index_data_ [filled_] = k_based (i); value_data_ [filled_] = t; ++ filled_; sorted_ = false; storage_invariants (); } BOOST_UBLAS_INLINE true_reference insert_element (size_type i, const_reference t) { BOOST_UBLAS_CHECK (!find_element (i), bad_index ()); // duplicate element append_element (i, t); return value_data_ [filled_ - 1]; } BOOST_UBLAS_INLINE void erase_element (size_type i) { sort (); subiterator_type it (detail::lower_bound (index_data_.begin (), index_data_.begin () + filled_, k_based (i), std::less<size_type> ())); typename std::iterator_traits<subiterator_type>::difference_type n = it - index_data_.begin (); if (filled_ > typename index_array_type::size_type (n) && *it == k_based (i)) { std::copy (it + 1, index_data_.begin () + filled_, it); typename value_array_type::iterator itt (value_data_.begin () + n); std::copy (itt + 1, value_data_.begin () + filled_, itt); -- filled_; sorted_filled_ = filled_; } storage_invariants (); } // Zeroing BOOST_UBLAS_INLINE void clear () { filled_ = 0; sorted_filled_ = filled_; sorted_ = true; storage_invariants (); } // Assignment BOOST_UBLAS_INLINE coordinate_vector &operator = (const coordinate_vector &v) { if (this != &v) { size_ = v.size_; capacity_ = v.capacity_; filled_ = v.filled_; sorted_filled_ = v.sorted_filled_; sorted_ = v.sorted_; index_data_ = v.index_data_; value_data_ = v.value_data_; } storage_invariants (); return *this; } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE coordinate_vector &operator = (const vector_container<C> &v) { resize (v ().size (), false); assign (v); return *this; } BOOST_UBLAS_INLINE coordinate_vector &assign_temporary (coordinate_vector &v) { swap (v); return *this; } template<class AE> BOOST_UBLAS_INLINE coordinate_vector &operator = (const vector_expression<AE> &ae) { self_type temporary (ae, capacity_); return assign_temporary (temporary); } template<class AE> BOOST_UBLAS_INLINE coordinate_vector &assign (const vector_expression<AE> &ae) { vector_assign<scalar_assign> (*this, ae); return *this; } // Computed assignment template<class AE> BOOST_UBLAS_INLINE coordinate_vector &operator += (const vector_expression<AE> &ae) { self_type temporary (*this + ae, capacity_); return assign_temporary (temporary); } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE coordinate_vector &operator += (const vector_container<C> &v) { plus_assign (v); return *this; } template<class AE> BOOST_UBLAS_INLINE coordinate_vector &plus_assign (const vector_expression<AE> &ae) { vector_assign<scalar_plus_assign> (*this, ae); return *this; } template<class AE> BOOST_UBLAS_INLINE coordinate_vector &operator -= (const vector_expression<AE> &ae) { self_type temporary (*this - ae, capacity_); return assign_temporary (temporary); } template<class C> // Container assignment without temporary BOOST_UBLAS_INLINE coordinate_vector &operator -= (const vector_container<C> &v) { minus_assign (v); return *this; } template<class AE> BOOST_UBLAS_INLINE coordinate_vector &minus_assign (const vector_expression<AE> &ae) { vector_assign<scalar_minus_assign> (*this, ae); return *this; } template<class AT> BOOST_UBLAS_INLINE coordinate_vector &operator *= (const AT &at) { vector_assign_scalar<scalar_multiplies_assign> (*this, at); return *this; } template<class AT> BOOST_UBLAS_INLINE coordinate_vector &operator /= (const AT &at) { vector_assign_scalar<scalar_divides_assign> (*this, at); return *this; } // Swapping BOOST_UBLAS_INLINE void swap (coordinate_vector &v) { if (this != &v) { std::swap (size_, v.size_); std::swap (capacity_, v.capacity_); std::swap (filled_, v.filled_); std::swap (sorted_filled_, v.sorted_filled_); std::swap (sorted_, v.sorted_); index_data_.swap (v.index_data_); value_data_.swap (v.value_data_); } storage_invariants (); } BOOST_UBLAS_INLINE friend void swap (coordinate_vector &v1, coordinate_vector &v2) { v1.swap (v2); } // replacement if STL lower bound algorithm for use of inplace_merge size_type lower_bound (size_type beg, size_type end, size_type target) const { while (end > beg) { size_type mid = (beg + end) / 2; if (index_data_[mid] < index_data_[target]) { beg = mid + 1; } else { end = mid; } } return beg; } // specialized replacement of STL inplace_merge to avoid compilation // problems with respect to the array_triple iterator void inplace_merge (size_type beg, size_type mid, size_type end) const { size_type len_lef = mid - beg; size_type len_rig = end - mid; if (len_lef == 1 && len_rig == 1) { if (index_data_[mid] < index_data_[beg]) { std::swap(index_data_[beg], index_data_[mid]); std::swap(value_data_[beg], value_data_[mid]); } } else if (len_lef > 0 && len_rig > 0) { size_type lef_mid, rig_mid; if (len_lef >= len_rig) { lef_mid = (beg + mid) / 2; rig_mid = lower_bound(mid, end, lef_mid); } else { rig_mid = (mid + end) / 2; lef_mid = lower_bound(beg, mid, rig_mid); } std::rotate(&index_data_[0] + lef_mid, &index_data_[0] + mid, &index_data_[0] + rig_mid); std::rotate(&value_data_[0] + lef_mid, &value_data_[0] + mid, &value_data_[0] + rig_mid); size_type new_mid = lef_mid + rig_mid - mid; inplace_merge(beg, lef_mid, new_mid); inplace_merge(new_mid, rig_mid, end); } } // Sorting and summation of duplicates BOOST_UBLAS_INLINE void sort () const { if (! sorted_ && filled_ > 0) { typedef index_pair_array<index_array_type, value_array_type> array_pair; array_pair ipa (filled_, index_data_, value_data_); #ifndef BOOST_UBLAS_COO_ALWAYS_DO_FULL_SORT const typename array_pair::iterator iunsorted = ipa.begin () + sorted_filled_; // sort new elements and merge std::sort (iunsorted, ipa.end ()); inplace_merge(0, sorted_filled_, filled_); #else const typename array_pair::iterator iunsorted = ipa.begin (); std::sort (iunsorted, ipa.end ()); #endif // sum duplicates with += and remove size_type filled = 0; for (size_type i = 1; i < filled_; ++ i) { if (index_data_ [filled] != index_data_ [i]) { ++ filled; if (filled != i) { index_data_ [filled] = index_data_ [i]; value_data_ [filled] = value_data_ [i]; } } else { value_data_ [filled] += value_data_ [i]; } } filled_ = filled + 1; sorted_filled_ = filled_; sorted_ = true; storage_invariants (); } } // Back element insertion and erasure BOOST_UBLAS_INLINE void push_back (size_type i, const_reference t) { // must maintain sort order BOOST_UBLAS_CHECK (sorted_ && (filled_ == 0 || index_data_ [filled_ - 1] < k_based (i)), external_logic ()); if (filled_ >= capacity_) reserve (2 * filled_, true); BOOST_UBLAS_CHECK (filled_ < capacity_, internal_logic ()); index_data_ [filled_] = k_based (i); value_data_ [filled_] = t; ++ filled_; sorted_filled_ = filled_; storage_invariants (); } BOOST_UBLAS_INLINE void pop_back () { // ISSUE invariants could be simpilfied if sorted required as precondition BOOST_UBLAS_CHECK (filled_ > 0, external_logic ()); -- filled_; sorted_filled_ = (std::min) (sorted_filled_, filled_); sorted_ = sorted_filled_ = filled_; storage_invariants (); } // Iterator types private: // Use index array iterator typedef typename IA::const_iterator const_subiterator_type; typedef typename IA::iterator subiterator_type; BOOST_UBLAS_INLINE true_reference at_element (size_type i) { BOOST_UBLAS_CHECK (i < size_, bad_index ()); sort (); subiterator_type it (detail::lower_bound (index_data_.begin (), index_data_.begin () + filled_, k_based (i), std::less<size_type> ())); BOOST_UBLAS_CHECK (it != index_data_.begin () + filled_ && *it == k_based (i), bad_index ()); return value_data_ [it - index_data_.begin ()]; } public: class const_iterator; class iterator; // Element lookup // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. const_iterator find (size_type i) const { sort (); return const_iterator (*this, detail::lower_bound (index_data_.begin (), index_data_.begin () + filled_, k_based (i), std::less<size_type> ())); } // BOOST_UBLAS_INLINE This function seems to be big. So we do not let the compiler inline it. iterator find (size_type i) { sort (); return iterator (*this, detail::lower_bound (index_data_.begin (), index_data_.begin () + filled_, k_based (i), std::less<size_type> ())); } class const_iterator: public container_const_reference<coordinate_vector>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, const_iterator, value_type> { public: typedef typename coordinate_vector::value_type value_type; typedef typename coordinate_vector::difference_type difference_type; typedef typename coordinate_vector::const_reference reference; typedef const typename coordinate_vector::pointer pointer; // Construction and destruction BOOST_UBLAS_INLINE const_iterator (): container_const_reference<self_type> (), it_ () {} BOOST_UBLAS_INLINE const_iterator (const self_type &v, const const_subiterator_type &it): container_const_reference<self_type> (v), it_ (it) {} BOOST_UBLAS_INLINE const_iterator (const typename self_type::iterator &it): // ISSUE self_type:: stops VC8 using std::iterator here container_const_reference<self_type> (it ()), it_ (it.it_) {} // Arithmetic BOOST_UBLAS_INLINE const_iterator &operator ++ () { ++ it_; return *this; } BOOST_UBLAS_INLINE const_iterator &operator -- () { -- it_; return *this; } // Dereference BOOST_UBLAS_INLINE const_reference operator * () const { BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ()); return (*this) ().value_data_ [it_ - (*this) ().index_data_.begin ()]; } // Index BOOST_UBLAS_INLINE size_type index () const { BOOST_UBLAS_CHECK (*this != (*this) ().end (), bad_index ()); BOOST_UBLAS_CHECK ((*this) ().zero_based (*it_) < (*this) ().size (), bad_index ()); return (*this) ().zero_based (*it_); } // Assignment BOOST_UBLAS_INLINE const_iterator &operator = (const const_iterator &it) { container_const_reference<self_type>::assign (&it ()); it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const const_iterator &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); return it_ == it.it_; } private: const_subiterator_type it_; }; BOOST_UBLAS_INLINE const_iterator begin () const { return find (0); } BOOST_UBLAS_INLINE const_iterator cbegin () const { return begin(); } BOOST_UBLAS_INLINE const_iterator end () const { return find (size_); } BOOST_UBLAS_INLINE const_iterator cend () const { return end(); } class iterator: public container_reference<coordinate_vector>, public bidirectional_iterator_base<sparse_bidirectional_iterator_tag, iterator, value_type> { public: typedef typename coordinate_vector::value_type value_type; typedef typename coordinate_vector::difference_type difference_type; typedef typename coordinate_vector::true_reference reference; typedef typename coordinate_vector::pointer pointer; // Construction and destruction BOOST_UBLAS_INLINE iterator (): container_reference<self_type> (), it_ () {} BOOST_UBLAS_INLINE iterator (self_type &v, const subiterator_type &it): container_reference<self_type> (v), it_ (it) {} // Arithmetic BOOST_UBLAS_INLINE iterator &operator ++ () { ++ it_; return *this; } BOOST_UBLAS_INLINE iterator &operator -- () { -- it_; return *this; } // Dereference BOOST_UBLAS_INLINE reference operator * () const { BOOST_UBLAS_CHECK (index () < (*this) ().size (), bad_index ()); return (*this) ().value_data_ [it_ - (*this) ().index_data_.begin ()]; } // Index BOOST_UBLAS_INLINE size_type index () const { BOOST_UBLAS_CHECK (*this != (*this) ().end (), bad_index ()); BOOST_UBLAS_CHECK ((*this) ().zero_based (*it_) < (*this) ().size (), bad_index ()); return (*this) ().zero_based (*it_); } // Assignment BOOST_UBLAS_INLINE iterator &operator = (const iterator &it) { container_reference<self_type>::assign (&it ()); it_ = it.it_; return *this; } // Comparison BOOST_UBLAS_INLINE bool operator == (const iterator &it) const { BOOST_UBLAS_CHECK (&(*this) () == &it (), external_logic ()); return it_ == it.it_; } private: subiterator_type it_; friend class const_iterator; }; BOOST_UBLAS_INLINE iterator begin () { return find (0); } BOOST_UBLAS_INLINE iterator end () { return find (size_); } // Reverse iterator typedef reverse_iterator_base<const_iterator> const_reverse_iterator; typedef reverse_iterator_base<iterator> reverse_iterator; BOOST_UBLAS_INLINE const_reverse_iterator rbegin () const { return const_reverse_iterator (end ()); } BOOST_UBLAS_INLINE const_reverse_iterator crbegin () const { return rbegin (); } BOOST_UBLAS_INLINE const_reverse_iterator rend () const { return const_reverse_iterator (begin ()); } BOOST_UBLAS_INLINE const_reverse_iterator crend () const { return rend (); } BOOST_UBLAS_INLINE reverse_iterator rbegin () { return reverse_iterator (end ()); } BOOST_UBLAS_INLINE reverse_iterator rend () { return reverse_iterator (begin ()); } // Serialization template<class Archive> void serialize(Archive & ar, const unsigned int /* file_version */){ serialization::collection_size_type s (size_); ar & serialization::make_nvp("size",s); if (Archive::is_loading::value) { size_ = s; } // ISSUE: filled may be much less than capacity // ISSUE: index_data_ and value_data_ are undefined between filled and capacity (trouble with 'nan'-values) ar & serialization::make_nvp("capacity", capacity_); ar & serialization::make_nvp("filled", filled_); ar & serialization::make_nvp("sorted_filled", sorted_filled_); ar & serialization::make_nvp("sorted", sorted_); ar & serialization::make_nvp("index_data", index_data_); ar & serialization::make_nvp("value_data", value_data_); storage_invariants(); } private: void storage_invariants () const { BOOST_UBLAS_CHECK (capacity_ == index_data_.size (), internal_logic ()); BOOST_UBLAS_CHECK (capacity_ == value_data_.size (), internal_logic ()); BOOST_UBLAS_CHECK (filled_ <= capacity_, internal_logic ()); BOOST_UBLAS_CHECK (sorted_filled_ <= filled_, internal_logic ()); BOOST_UBLAS_CHECK (sorted_ == (sorted_filled_ == filled_), internal_logic ()); BOOST_UBLAS_CHECK ((0 == filled_) || (zero_based(index_data_[filled_ - 1]) < size_), internal_logic ()); } size_type size_; size_type capacity_; mutable typename index_array_type::size_type filled_; mutable typename index_array_type::size_type sorted_filled_; mutable bool sorted_; mutable index_array_type index_data_; mutable value_array_type value_data_; static const value_type zero_; BOOST_UBLAS_INLINE static size_type zero_based (size_type k_based_index) { return k_based_index - IB; } BOOST_UBLAS_INLINE static size_type k_based (size_type zero_based_index) { return zero_based_index + IB; } friend class iterator; friend class const_iterator; }; template<class T, std::size_t IB, class IA, class TA> const typename coordinate_vector<T, IB, IA, TA>::value_type coordinate_vector<T, IB, IA, TA>::zero_ = value_type/*zero*/(); }}} #ifdef BOOST_MSVC #undef _ITERATOR_DEBUG_LEVEL #define _ITERATOR_DEBUG_LEVEL _BACKUP_ITERATOR_DEBUG_LEVEL #undef _BACKUP_ITERATOR_DEBUG_LEVEL #endif #endif
{ "pile_set_name": "Github" }
package cli import ( "flag" "fmt" "strconv" ) // IntFlag is a flag with type int type IntFlag struct { Name string Usage string EnvVar string FilePath string Required bool Hidden bool Value int Destination *int } // String returns a readable representation of this value // (for usage defaults) func (f IntFlag) String() string { return FlagStringer(f) } // GetName returns the name of the flag func (f IntFlag) GetName() string { return f.Name } // IsRequired returns whether or not the flag is required func (f IntFlag) IsRequired() bool { return f.Required } // TakesValue returns true of the flag takes a value, otherwise false func (f IntFlag) TakesValue() bool { return true } // GetUsage returns the usage string for the flag func (f IntFlag) GetUsage() string { return f.Usage } // GetValue returns the flags value as string representation and an empty // string if the flag takes no value at all. func (f IntFlag) GetValue() string { return fmt.Sprintf("%d", f.Value) } // Apply populates the flag given the flag set and environment // Ignores errors func (f IntFlag) Apply(set *flag.FlagSet) { _ = f.ApplyWithError(set) } // ApplyWithError populates the flag given the flag set and environment func (f IntFlag) ApplyWithError(set *flag.FlagSet) error { if envVal, ok := flagFromFileEnv(f.FilePath, f.EnvVar); ok { envValInt, err := strconv.ParseInt(envVal, 0, 64) if err != nil { return fmt.Errorf("could not parse %s as int value for flag %s: %s", envVal, f.Name, err) } f.Value = int(envValInt) } eachName(f.Name, func(name string) { if f.Destination != nil { set.IntVar(f.Destination, name, f.Value, f.Usage) return } set.Int(name, f.Value, f.Usage) }) return nil } // Int looks up the value of a local IntFlag, returns // 0 if not found func (c *Context) Int(name string) int { return lookupInt(name, c.flagSet) } // GlobalInt looks up the value of a global IntFlag, returns // 0 if not found func (c *Context) GlobalInt(name string) int { if fs := lookupGlobalFlagSet(name, c); fs != nil { return lookupInt(name, fs) } return 0 } func lookupInt(name string, set *flag.FlagSet) int { f := set.Lookup(name) if f != nil { parsed, err := strconv.ParseInt(f.Value.String(), 0, 64) if err != nil { return 0 } return int(parsed) } return 0 }
{ "pile_set_name": "Github" }
# Copyright (C) 2010-2013 marco riccardi. # This file is part of Dorothy - http://www.honeynet.it/ # See the file 'LICENSE' for copying permission. module Dorothy #Dorothy module-class for managig the virtual sandboxes class Doro_VSM #ESX vSphere5 interface class ESX #Creates a new instance for communicating with ESX through the vSpere5's API def initialize(server,user,pass,vmname,guestuser,guestpass) begin vim = RbVmomi::VIM.connect(:host => server , :user => user, :password=> pass, :insecure => true) rescue Timeout::Error raise "Fail to connect to the ESXi server #{server} - TimeOut (Are you sure that is the right address?)" end @server = server dc = vim.serviceInstance.find_datacenter @vm = dc.find_vm(vmname) raise "Virtual Machine #{vmname} not present within ESX!!" if @vm.nil? om = vim.serviceContent.guestOperationsManager am = om.authManager @pm = om.processManager @fm = om.fileManager #AUTHENTICATION guestauth = {:interactiveSession => false, :username => guestuser, :password => guestpass} r = 0 begin @auth=RbVmomi::VIM::NamePasswordAuthentication(guestauth) abort if am.ValidateCredentialsInGuest(:vm => @vm, :auth => @auth) != nil rescue RbVmomi::Fault => e if e.inspect =~ /InvalidPowerState/ if r <= 5 r = r+1 LOGGER.debug "VSM", "VM busy (maybe still revertig, retrying.." sleep 2 retry end LOGGER.error "VSM", "Error, can't connect to VM #{@vm[:name]}" LOGGER.debug "VSM", e raise "VSM Error" end end end def revert_vm @vm.RevertToCurrentSnapshot_Task end def copy_file(filename,file) filepath = "C:\\#{filename}" #put md5 hash begin url = @fm.InitiateFileTransferToGuest(:vm => @vm, :auth=> @auth, :guestFilePath=> filepath, :fileSize => file.size, :fileAttributes => '', :overwrite => true).sub('*:443', @server) RestClient.put(url, file) rescue RbVmomi::Fault LOGGER.error "VSM", "Fail to copy the file #{file} to #{@vm}: #{$!}" abort end end def exec_file(filename, program) program["prog_args"].nil? ? args = "" : args = program["prog_args"] args += " #{filename}" cmd = { :programPath => program["prog_path"], :arguments => args } pid = @pm.StartProgramInGuest(:vm => @vm , :auth => @auth, :spec => cmd ) pid.to_i end def exec_file_raw(filename, arguments="") filepath = "C:\\#{filename}" cmd = { :programPath => filepath, :arguments => arguments } pid = @pm.StartProgramInGuest(:vm => @vm , :auth => @auth, :spec => cmd ) pid.to_i end def check_internet exec_file_raw("windows\\system32\\ping.exe", "-n 1 www.google.com") #make www.google.com customizable, move to doroconf end def get_status(pid) p = get_running_procs(pid) p["exitCode"] end def get_running_procs(pid=nil, save_tofile=false, filename="#{DoroSettings.env[:home]}/etc/baseline_processes.yml") pid = Array(pid) unless pid.nil? @pp2 = Hash.new procs = @pm.ListProcessesInGuest(:vm => @vm , :auth => @auth, :pids => pid ) procs.each {|pp2| @pp2.merge! Hash[pp2.pid, Hash["pname", pp2.name, "owner", pp2.owner, "cmdLine", pp2.cmdLine, "startTime", pp2.startTime, "endTime", pp2.endTime, "exitCode", pp2.exitCode]]} if save_tofile Util.write(filename, @pp2.to_yaml) LOGGER.info "VSM", "Current running processes saved to #{filename}" end @pp2 end def get_new_procs(current_procs, original_procs_file) original_procs = YAML.load_file(original_procs_file) @new_procs = Hash.new current_procs.each_key {|pid| @new_procs.merge!(Hash[pid, current_procs[pid]]) unless original_procs.has_key?(pid) } @new_procs end def get_files(path) fm_files = @fm.ListFilesInGuest(:vm => @vm, :auth=> @auth, :filePath=> path).files @files = Hash.new fm_files.each {|file| @files.merge!(Hash[file.path, Hash[:size, file.size, :type, file.type, :attrs, file.attributes]]) } @files end def screenshot a = @vm.CreateScreenshot_Task.wait_for_completion.split(" ") screenpath = "/vmfs/volumes/" + a[0].delete("[]") + "/" + a[1] return screenpath end end #Empty method for showing how it could be easy to extend the dorothy's VSM with another virtual manager. class VirtualBox def initialize end def revert_vm end def copy_file end def exec_file end def check_internet end def get_status end def screenshot end end end end
{ "pile_set_name": "Github" }
/* * Software License Agreement (BSD License) * * Copyright (c) 2009, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id: fpfh_omp.h 35361 2011-01-20 04:34:49Z rusu $ * */ #ifndef PCL_ROS_FPFH_OMP_H_ #define PCL_ROS_FPFH_OMP_H_ #include <pcl/features/fpfh_omp.h> #include "pcl_ros/features/fpfh.h" namespace pcl_ros { /** \brief @b FPFHEstimationOMP estimates the Fast Point Feature Histogram (FPFH) descriptor for a given point cloud * dataset containing points and normals, in parallel, using the OpenMP standard. * * @note If you use this code in any academic work, please cite: * * <ul> * <li> R.B. Rusu, N. Blodow, M. Beetz. * Fast Point Feature Histograms (FPFH) for 3D Registration. * In Proceedings of the IEEE International Conference on Robotics and Automation (ICRA), * Kobe, Japan, May 12-17 2009. * </li> * <li> R.B. Rusu, A. Holzbach, N. Blodow, M. Beetz. * Fast Geometric Point Labeling using Conditional Random Fields. * In Proceedings of the 22nd IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS), * St. Louis, MO, USA, October 11-15 2009. * </li> * </ul> * \author Radu Bogdan Rusu */ class FPFHEstimationOMP : public FeatureFromNormals { private: pcl::FPFHEstimationOMP<pcl::PointXYZ, pcl::Normal, pcl::FPFHSignature33> impl_; typedef pcl::PointCloud<pcl::FPFHSignature33> PointCloudOut; /** \brief Child initialization routine. Internal method. */ inline bool childInit (ros::NodeHandle &nh) { // Create the output publisher pub_output_ = nh.advertise<PointCloudOut> ("output", max_queue_size_); return (true); } /** \brief Publish an empty point cloud of the feature output type. */ void emptyPublish (const PointCloudInConstPtr &cloud); /** \brief Compute the feature and publish it. */ void computePublish (const PointCloudInConstPtr &cloud, const PointCloudNConstPtr &normals, const PointCloudInConstPtr &surface, const IndicesPtr &indices); public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; } #endif //#ifndef PCL_ROS_FPFH_OMP_H_
{ "pile_set_name": "Github" }
// Horizontal dividers // // Dividers (basically an hr) within dropdowns and nav lists .nav-divider(@color: #e5e5e5) { height: 1px; margin: ((@line-height-computed / 2) - 1) 0; overflow: hidden; background-color: @color; }
{ "pile_set_name": "Github" }
require 'test_helper' class PaymentNotificationsControllerTest < ActionController::TestCase def test_create_invalid PaymentNotification.any_instance.stubs(:valid?).returns(false) post :create assert_template 'new' end def test_create_valid PaymentNotification.any_instance.stubs(:valid?).returns(true) post :create assert_redirected_to payment_notifications_url end end
{ "pile_set_name": "Github" }
using Nitra.Model; using Nitra.Typing.RuleMethod; using Nemerle; using System; using G = NitraSyntaxParseTree; namespace Nitra.Typing { [Record, ExportableSymbol] public abstract class RegularRuleSymbol : RuleDefSymbol, IRuleDeclarationSite { public sealed override Type : RuleType { get { RuleType.Chars(None()) } } public sealed override IsToken : bool { get { true } } public abstract Rule : RegularRule { get; } public abstract CanParseEmptyString : bool { get; } public abstract FirstCharLowerBound : char { get; } public abstract FirstCharUpperBound : char { get; } public Fsm : FSM { [Memoize] get { assert(Node != null); FSMTransform.MakeDeterministic(this.Rule.ConvertRegularRuleToFsm(Node.Project)) } } public override Description : string { get { "regular rule" } } } public sealed class ParsedRegularRuleSymbol : RegularRuleSymbol { public this(node : G.RegexRule, declarationSite : IRuleDeclarationSite) { base(node.Name); _node = node; DeclarationSite = declarationSite; } private _node : G.RegexRule; public override DeclarationSite : IRuleDeclarationSite { get; } public override Options : RuleDefinitionOptions { [Memoize] get { _node.RuleAttributes.Options(DeclarationSite.GetDefaultRuleDefinitionOptions()) } } public override Rule : RegularRule { get { _node.Regex() } } public override LastLocation : option[Location] { [Memoize] get { Some(_node.RuleBody.GetLastLocation()) } } public override IdInGrammar : int { [Memoize] get { DeclaringModule.GetNewRuleId() } } public override CanParseEmptyString : bool { [Memoize] get { Fsm.OkStates.Contains(Fsm.StartState) } } public override FirstCharLowerBound : char { get { FirstCharBounds[0] } } public override FirstCharUpperBound : char { get { FirstCharBounds[1] } } private FirstCharBounds : char * char { [Memoize] get { mutable totalRange = RangeSet(); foreach (Symbol(Chars = range, From = from) when from == Fsm.StartState in Fsm.Transitions) totalRange = totalRange.Sum(range); match (totalRange.GetBounds()) { | None => (char.MinValue, char.MaxValue) | Some(bounds) => bounds } } } } }
{ "pile_set_name": "Github" }
package com.trackray.base.handle; import com.trackray.base.bean.Task; import com.trackray.base.utils.SysLog; import java.util.Map; import java.util.concurrent.ThreadPoolExecutor; /** * 任务线程监控 * @author 浅蓝 * @email [email protected] * @since 2019/1/8 12:28 */ public class ThreadMonitor { private int maxTime; private int sleepTime; private CoreThreadMap coreThreadPool; public void save(Task task , int status){}; public void monitor() throws InterruptedException { new Thread(){ @Override public void run() { while (true) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { e.printStackTrace(); } if (coreThreadPool.size() > 0){ for (Map.Entry<String, Map<String, Object>> entry : coreThreadPool.entrySet()) { Task task = (Task) entry.getValue().get("task"); Long taskTime = (Long) entry.getValue().get("create_time"); ThreadPoolExecutor value = (ThreadPoolExecutor) entry.getValue().get("thread_pool"); long currenTime = System.currentTimeMillis(); long temp = currenTime - taskTime; if ( temp > maxTime){ SysLog.info(String.format("Task=%s 线程共启动%d毫秒,已超过设定最大时间%d,已结束该线程",entry.getKey(),temp,maxTime)); save(task , 2); value.shutdownNow(); coreThreadPool.remove(entry.getKey()); }else{ if (value.isShutdown() || ((value.getTaskCount())==(value.getCompletedTaskCount()) && value.getPoolSize()>0) ){ SysLog.info(String.format("Task=%s 该任务已完成",entry.getKey())); value.shutdownNow(); coreThreadPool.remove(entry.getKey()); save(task , 2); continue; } SysLog.info(String.format("Task=%s 线程共启动%d毫秒 任务数=%d 已完成=%d ",entry.getKey(),temp,value.getTaskCount(),value.getCompletedTaskCount())); save(task , 1); } } System.gc(); //垃圾回收 } } } }.start(); } public void setCoreThreadPool(CoreThreadMap coreThreadPool) { this.coreThreadPool = coreThreadPool; } public void setMaxTime(int maxTime) { this.maxTime = maxTime; } public void setSleepTime(int sleepTime) { this.sleepTime = sleepTime; } }
{ "pile_set_name": "Github" }
// megafunction wizard: %ALTFP_MULT% // GENERATION: STANDARD // VERSION: WM1.0 // MODULE: ALTFP_MULT // ============================================================ // File Name: altfp_multiplier.v // Megafunction Name(s): // ALTFP_MULT // // Simulation Library Files(s): // // ============================================================ // ************************************************************ // THIS IS A WIZARD-GENERATED FILE. DO NOT EDIT THIS FILE! // // 12.0 Build 178 05/31/2012 SJ Full Version // ************************************************************ //Copyright (C) 1991-2012 Altera Corporation //Your use of Altera Corporation's design tools, logic functions //and other software and tools, and its AMPP partner logic //functions, and any output files from any of the foregoing //(including device programming or simulation files), and any //associated documentation or information are expressly subject //to the terms and conditions of the Altera Program License //Subscription Agreement, Altera MegaCore Function License //Agreement, or other applicable license agreement, including, //without limitation, that your use is for the sole purpose of //programming logic devices manufactured by Altera and sold by //Altera or its authorized distributors. Please refer to the //applicable agreement for further details. //altfp_mult CBX_AUTO_BLACKBOX="ALL" DEDICATED_MULTIPLIER_CIRCUITRY="YES" DENORMAL_SUPPORT="NO" DEVICE_FAMILY="Cyclone II" EXCEPTION_HANDLING="NO" PIPELINE=11 REDUCED_FUNCTIONALITY="NO" ROUNDING="TO_NEAREST" WIDTH_EXP=8 WIDTH_MAN=23 clk_en clock dataa datab result //VERSION_BEGIN 12.0 cbx_alt_ded_mult_y 2012:05:31:20:23:38:SJ cbx_altbarrel_shift 2012:05:31:20:23:38:SJ cbx_altera_mult_add 2012:05:31:20:23:38:SJ cbx_altfp_mult 2012:05:31:20:23:38:SJ cbx_altmult_add 2012:05:31:20:23:38:SJ cbx_cycloneii 2012:05:31:20:23:38:SJ cbx_lpm_add_sub 2012:05:31:20:23:38:SJ cbx_lpm_compare 2012:05:31:20:23:38:SJ cbx_lpm_mult 2012:05:31:20:23:38:SJ cbx_mgl 2012:05:31:20:24:43:SJ cbx_padd 2012:05:31:20:23:38:SJ cbx_parallel_add 2012:05:31:20:23:38:SJ cbx_stratix 2012:05:31:20:23:38:SJ cbx_stratixii 2012:05:31:20:23:38:SJ cbx_util_mgl 2012:05:31:20:23:38:SJ VERSION_END // synthesis VERILOG_INPUT_VERSION VERILOG_2001 // altera message_off 10463 //synthesis_resources = lpm_add_sub 4 lpm_mult 1 reg 293 //synopsys translate_off `timescale 1 ps / 1 ps //synopsys translate_on module altfp_multiplier_altfp_mult_4do ( clk_en, clock, dataa, datab, result) ; input clk_en; input clock; input [31:0] dataa; input [31:0] datab; output [31:0] result; `ifndef ALTERA_RESERVED_QIS // synopsys translate_off `endif tri1 clk_en; `ifndef ALTERA_RESERVED_QIS // synopsys translate_on `endif reg dataa_exp_all_one_ff_p1; reg dataa_exp_not_zero_ff_p1; reg dataa_man_not_zero_ff_p1; reg dataa_man_not_zero_ff_p2; reg datab_exp_all_one_ff_p1; reg datab_exp_not_zero_ff_p1; reg datab_man_not_zero_ff_p1; reg datab_man_not_zero_ff_p2; reg [9:0] delay_exp2_bias; reg [9:0] delay_exp3_bias; reg [9:0] delay_exp_bias; reg delay_man_product_msb; reg delay_man_product_msb2; reg delay_man_product_msb_p0; reg delay_man_product_msb_p1; reg [23:0] delay_round; reg [8:0] exp_add_p1; reg [9:0] exp_adj_p1; reg [9:0] exp_adj_p2; reg [8:0] exp_bias_p1; reg [8:0] exp_bias_p2; reg [8:0] exp_bias_p3; reg [7:0] exp_result_ff; reg input_is_infinity_dffe_0; reg input_is_infinity_dffe_1; reg input_is_infinity_dffe_2; reg input_is_infinity_dffe_3; reg input_is_infinity_ff1; reg input_is_infinity_ff2; reg input_is_infinity_ff3; reg input_is_infinity_ff4; reg input_is_infinity_ff5; reg input_is_nan_dffe_0; reg input_is_nan_dffe_1; reg input_is_nan_dffe_2; reg input_is_nan_dffe_3; reg input_is_nan_ff1; reg input_is_nan_ff2; reg input_is_nan_ff3; reg input_is_nan_ff4; reg input_is_nan_ff5; reg input_not_zero_dffe_0; reg input_not_zero_dffe_1; reg input_not_zero_dffe_2; reg input_not_zero_dffe_3; reg input_not_zero_ff1; reg input_not_zero_ff2; reg input_not_zero_ff3; reg input_not_zero_ff4; reg input_not_zero_ff5; reg lsb_dffe; reg [22:0] man_result_ff; reg man_round_carry; reg man_round_carry_p0; reg [23:0] man_round_p; reg [23:0] man_round_p0; reg [23:0] man_round_p1; reg [24:0] man_round_p2; reg round_dffe; reg [0:0] sign_node_ff0; reg [0:0] sign_node_ff1; reg [0:0] sign_node_ff2; reg [0:0] sign_node_ff3; reg [0:0] sign_node_ff4; reg [0:0] sign_node_ff5; reg [0:0] sign_node_ff6; reg [0:0] sign_node_ff7; reg [0:0] sign_node_ff8; reg [0:0] sign_node_ff9; reg [0:0] sign_node_ff10; reg sticky_dffe; wire [8:0] wire_exp_add_adder_result; wire [9:0] wire_exp_adj_adder_result; wire [9:0] wire_exp_bias_subtr_result; wire [24:0] wire_man_round_adder_result; wire [47:0] wire_man_product2_mult_result; wire aclr; wire [9:0] bias; wire [7:0] dataa_exp_all_one; wire [7:0] dataa_exp_not_zero; wire [22:0] dataa_man_not_zero; wire [7:0] datab_exp_all_one; wire [7:0] datab_exp_not_zero; wire [22:0] datab_man_not_zero; wire exp_is_inf; wire exp_is_zero; wire [9:0] expmod; wire [7:0] inf_num; wire lsb_bit; wire [24:0] man_shift_full; wire [7:0] result_exp_all_one; wire [8:0] result_exp_not_zero; wire round_bit; wire round_carry; wire [22:0] sticky_bit; // synopsys translate_off initial dataa_exp_all_one_ff_p1 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) dataa_exp_all_one_ff_p1 <= 1'b0; else if (clk_en == 1'b1) dataa_exp_all_one_ff_p1 <= dataa_exp_all_one[7]; // synopsys translate_off initial dataa_exp_not_zero_ff_p1 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) dataa_exp_not_zero_ff_p1 <= 1'b0; else if (clk_en == 1'b1) dataa_exp_not_zero_ff_p1 <= dataa_exp_not_zero[7]; // synopsys translate_off initial dataa_man_not_zero_ff_p1 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) dataa_man_not_zero_ff_p1 <= 1'b0; else if (clk_en == 1'b1) dataa_man_not_zero_ff_p1 <= dataa_man_not_zero[10]; // synopsys translate_off initial dataa_man_not_zero_ff_p2 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) dataa_man_not_zero_ff_p2 <= 1'b0; else if (clk_en == 1'b1) dataa_man_not_zero_ff_p2 <= dataa_man_not_zero[22]; // synopsys translate_off initial datab_exp_all_one_ff_p1 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) datab_exp_all_one_ff_p1 <= 1'b0; else if (clk_en == 1'b1) datab_exp_all_one_ff_p1 <= datab_exp_all_one[7]; // synopsys translate_off initial datab_exp_not_zero_ff_p1 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) datab_exp_not_zero_ff_p1 <= 1'b0; else if (clk_en == 1'b1) datab_exp_not_zero_ff_p1 <= datab_exp_not_zero[7]; // synopsys translate_off initial datab_man_not_zero_ff_p1 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) datab_man_not_zero_ff_p1 <= 1'b0; else if (clk_en == 1'b1) datab_man_not_zero_ff_p1 <= datab_man_not_zero[10]; // synopsys translate_off initial datab_man_not_zero_ff_p2 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) datab_man_not_zero_ff_p2 <= 1'b0; else if (clk_en == 1'b1) datab_man_not_zero_ff_p2 <= datab_man_not_zero[22]; // synopsys translate_off initial delay_exp2_bias = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) delay_exp2_bias <= 10'b0; else if (clk_en == 1'b1) delay_exp2_bias <= delay_exp_bias; // synopsys translate_off initial delay_exp3_bias = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) delay_exp3_bias <= 10'b0; else if (clk_en == 1'b1) delay_exp3_bias <= delay_exp2_bias; // synopsys translate_off initial delay_exp_bias = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) delay_exp_bias <= 10'b0; else if (clk_en == 1'b1) delay_exp_bias <= wire_exp_bias_subtr_result; // synopsys translate_off initial delay_man_product_msb = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) delay_man_product_msb <= 1'b0; else if (clk_en == 1'b1) delay_man_product_msb <= delay_man_product_msb_p1; // synopsys translate_off initial delay_man_product_msb2 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) delay_man_product_msb2 <= 1'b0; else if (clk_en == 1'b1) delay_man_product_msb2 <= delay_man_product_msb; // synopsys translate_off initial delay_man_product_msb_p0 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) delay_man_product_msb_p0 <= 1'b0; else if (clk_en == 1'b1) delay_man_product_msb_p0 <= wire_man_product2_mult_result[47]; // synopsys translate_off initial delay_man_product_msb_p1 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) delay_man_product_msb_p1 <= 1'b0; else if (clk_en == 1'b1) delay_man_product_msb_p1 <= delay_man_product_msb_p0; // synopsys translate_off initial delay_round = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) delay_round <= 24'b0; else if (clk_en == 1'b1) delay_round <= ((man_round_p2[23:0] & {24{(~ man_round_p2[24])}}) | (man_round_p2[24:1] & {24{man_round_p2[24]}})); // synopsys translate_off initial exp_add_p1 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) exp_add_p1 <= 9'b0; else if (clk_en == 1'b1) exp_add_p1 <= wire_exp_add_adder_result; // synopsys translate_off initial exp_adj_p1 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) exp_adj_p1 <= 10'b0; else if (clk_en == 1'b1) exp_adj_p1 <= delay_exp3_bias; // synopsys translate_off initial exp_adj_p2 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) exp_adj_p2 <= 10'b0; else if (clk_en == 1'b1) exp_adj_p2 <= wire_exp_adj_adder_result; // synopsys translate_off initial exp_bias_p1 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) exp_bias_p1 <= 9'b0; else if (clk_en == 1'b1) exp_bias_p1 <= exp_add_p1[8:0]; // synopsys translate_off initial exp_bias_p2 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) exp_bias_p2 <= 9'b0; else if (clk_en == 1'b1) exp_bias_p2 <= exp_bias_p1; // synopsys translate_off initial exp_bias_p3 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) exp_bias_p3 <= 9'b0; else if (clk_en == 1'b1) exp_bias_p3 <= exp_bias_p2; // synopsys translate_off initial exp_result_ff = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) exp_result_ff <= 8'b0; else if (clk_en == 1'b1) exp_result_ff <= ((inf_num & {8{((exp_is_inf | input_is_infinity_ff5) | input_is_nan_ff5)}}) | ((exp_adj_p2[7:0] & {8{(~ exp_is_zero)}}) & {8{input_not_zero_ff5}})); // synopsys translate_off initial input_is_infinity_dffe_0 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_is_infinity_dffe_0 <= 1'b0; else if (clk_en == 1'b1) input_is_infinity_dffe_0 <= ((dataa_exp_all_one_ff_p1 & (~ (dataa_man_not_zero_ff_p1 | dataa_man_not_zero_ff_p2))) | (datab_exp_all_one_ff_p1 & (~ (datab_man_not_zero_ff_p1 | datab_man_not_zero_ff_p2)))); // synopsys translate_off initial input_is_infinity_dffe_1 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_is_infinity_dffe_1 <= 1'b0; else if (clk_en == 1'b1) input_is_infinity_dffe_1 <= input_is_infinity_dffe_0; // synopsys translate_off initial input_is_infinity_dffe_2 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_is_infinity_dffe_2 <= 1'b0; else if (clk_en == 1'b1) input_is_infinity_dffe_2 <= input_is_infinity_dffe_1; // synopsys translate_off initial input_is_infinity_dffe_3 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_is_infinity_dffe_3 <= 1'b0; else if (clk_en == 1'b1) input_is_infinity_dffe_3 <= input_is_infinity_dffe_2; // synopsys translate_off initial input_is_infinity_ff1 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_is_infinity_ff1 <= 1'b0; else if (clk_en == 1'b1) input_is_infinity_ff1 <= input_is_infinity_dffe_3; // synopsys translate_off initial input_is_infinity_ff2 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_is_infinity_ff2 <= 1'b0; else if (clk_en == 1'b1) input_is_infinity_ff2 <= input_is_infinity_ff1; // synopsys translate_off initial input_is_infinity_ff3 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_is_infinity_ff3 <= 1'b0; else if (clk_en == 1'b1) input_is_infinity_ff3 <= input_is_infinity_ff2; // synopsys translate_off initial input_is_infinity_ff4 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_is_infinity_ff4 <= 1'b0; else if (clk_en == 1'b1) input_is_infinity_ff4 <= input_is_infinity_ff3; // synopsys translate_off initial input_is_infinity_ff5 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_is_infinity_ff5 <= 1'b0; else if (clk_en == 1'b1) input_is_infinity_ff5 <= input_is_infinity_ff4; // synopsys translate_off initial input_is_nan_dffe_0 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_is_nan_dffe_0 <= 1'b0; else if (clk_en == 1'b1) input_is_nan_dffe_0 <= ((dataa_exp_all_one_ff_p1 & (dataa_man_not_zero_ff_p1 | dataa_man_not_zero_ff_p2)) | (datab_exp_all_one_ff_p1 & (datab_man_not_zero_ff_p1 | datab_man_not_zero_ff_p2))); // synopsys translate_off initial input_is_nan_dffe_1 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_is_nan_dffe_1 <= 1'b0; else if (clk_en == 1'b1) input_is_nan_dffe_1 <= input_is_nan_dffe_0; // synopsys translate_off initial input_is_nan_dffe_2 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_is_nan_dffe_2 <= 1'b0; else if (clk_en == 1'b1) input_is_nan_dffe_2 <= input_is_nan_dffe_1; // synopsys translate_off initial input_is_nan_dffe_3 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_is_nan_dffe_3 <= 1'b0; else if (clk_en == 1'b1) input_is_nan_dffe_3 <= input_is_nan_dffe_2; // synopsys translate_off initial input_is_nan_ff1 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_is_nan_ff1 <= 1'b0; else if (clk_en == 1'b1) input_is_nan_ff1 <= input_is_nan_dffe_3; // synopsys translate_off initial input_is_nan_ff2 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_is_nan_ff2 <= 1'b0; else if (clk_en == 1'b1) input_is_nan_ff2 <= input_is_nan_ff1; // synopsys translate_off initial input_is_nan_ff3 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_is_nan_ff3 <= 1'b0; else if (clk_en == 1'b1) input_is_nan_ff3 <= input_is_nan_ff2; // synopsys translate_off initial input_is_nan_ff4 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_is_nan_ff4 <= 1'b0; else if (clk_en == 1'b1) input_is_nan_ff4 <= input_is_nan_ff3; // synopsys translate_off initial input_is_nan_ff5 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_is_nan_ff5 <= 1'b0; else if (clk_en == 1'b1) input_is_nan_ff5 <= input_is_nan_ff4; // synopsys translate_off initial input_not_zero_dffe_0 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_not_zero_dffe_0 <= 1'b0; else if (clk_en == 1'b1) input_not_zero_dffe_0 <= (dataa_exp_not_zero_ff_p1 & datab_exp_not_zero_ff_p1); // synopsys translate_off initial input_not_zero_dffe_1 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_not_zero_dffe_1 <= 1'b0; else if (clk_en == 1'b1) input_not_zero_dffe_1 <= input_not_zero_dffe_0; // synopsys translate_off initial input_not_zero_dffe_2 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_not_zero_dffe_2 <= 1'b0; else if (clk_en == 1'b1) input_not_zero_dffe_2 <= input_not_zero_dffe_1; // synopsys translate_off initial input_not_zero_dffe_3 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_not_zero_dffe_3 <= 1'b0; else if (clk_en == 1'b1) input_not_zero_dffe_3 <= input_not_zero_dffe_2; // synopsys translate_off initial input_not_zero_ff1 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_not_zero_ff1 <= 1'b0; else if (clk_en == 1'b1) input_not_zero_ff1 <= input_not_zero_dffe_3; // synopsys translate_off initial input_not_zero_ff2 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_not_zero_ff2 <= 1'b0; else if (clk_en == 1'b1) input_not_zero_ff2 <= input_not_zero_ff1; // synopsys translate_off initial input_not_zero_ff3 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_not_zero_ff3 <= 1'b0; else if (clk_en == 1'b1) input_not_zero_ff3 <= input_not_zero_ff2; // synopsys translate_off initial input_not_zero_ff4 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_not_zero_ff4 <= 1'b0; else if (clk_en == 1'b1) input_not_zero_ff4 <= input_not_zero_ff3; // synopsys translate_off initial input_not_zero_ff5 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) input_not_zero_ff5 <= 1'b0; else if (clk_en == 1'b1) input_not_zero_ff5 <= input_not_zero_ff4; // synopsys translate_off initial lsb_dffe = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) lsb_dffe <= 1'b0; else if (clk_en == 1'b1) lsb_dffe <= lsb_bit; // synopsys translate_off initial man_result_ff = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) man_result_ff <= 23'b0; else if (clk_en == 1'b1) man_result_ff <= {((((((delay_round[22] & input_not_zero_ff5) & (~ input_is_infinity_ff5)) & (~ exp_is_inf)) & (~ exp_is_zero)) | (input_is_infinity_ff5 & (~ input_not_zero_ff5))) | input_is_nan_ff5), (((((delay_round[21:0] & {22{input_not_zero_ff5}}) & {22{(~ input_is_infinity_ff5)}}) & {22{(~ exp_is_inf)}}) & {22{(~ exp_is_zero)}}) & {22{(~ input_is_nan_ff5)}})}; // synopsys translate_off initial man_round_carry = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) man_round_carry <= 1'b0; else if (clk_en == 1'b1) man_round_carry <= man_round_carry_p0; // synopsys translate_off initial man_round_carry_p0 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) man_round_carry_p0 <= 1'b0; else if (clk_en == 1'b1) man_round_carry_p0 <= round_carry; // synopsys translate_off initial man_round_p = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) man_round_p <= 24'b0; else if (clk_en == 1'b1) man_round_p <= man_shift_full[24:1]; // synopsys translate_off initial man_round_p0 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) man_round_p0 <= 24'b0; else if (clk_en == 1'b1) man_round_p0 <= man_round_p; // synopsys translate_off initial man_round_p1 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) man_round_p1 <= 24'b0; else if (clk_en == 1'b1) man_round_p1 <= man_round_p0; // synopsys translate_off initial man_round_p2 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) man_round_p2 <= 25'b0; else if (clk_en == 1'b1) man_round_p2 <= wire_man_round_adder_result; // synopsys translate_off initial round_dffe = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) round_dffe <= 1'b0; else if (clk_en == 1'b1) round_dffe <= round_bit; // synopsys translate_off initial sign_node_ff0 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) sign_node_ff0 <= 1'b0; else if (clk_en == 1'b1) sign_node_ff0 <= (dataa[31] ^ datab[31]); // synopsys translate_off initial sign_node_ff1 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) sign_node_ff1 <= 1'b0; else if (clk_en == 1'b1) sign_node_ff1 <= sign_node_ff0[0:0]; // synopsys translate_off initial sign_node_ff2 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) sign_node_ff2 <= 1'b0; else if (clk_en == 1'b1) sign_node_ff2 <= sign_node_ff1[0:0]; // synopsys translate_off initial sign_node_ff3 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) sign_node_ff3 <= 1'b0; else if (clk_en == 1'b1) sign_node_ff3 <= sign_node_ff2[0:0]; // synopsys translate_off initial sign_node_ff4 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) sign_node_ff4 <= 1'b0; else if (clk_en == 1'b1) sign_node_ff4 <= sign_node_ff3[0:0]; // synopsys translate_off initial sign_node_ff5 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) sign_node_ff5 <= 1'b0; else if (clk_en == 1'b1) sign_node_ff5 <= sign_node_ff4[0:0]; // synopsys translate_off initial sign_node_ff6 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) sign_node_ff6 <= 1'b0; else if (clk_en == 1'b1) sign_node_ff6 <= sign_node_ff5[0:0]; // synopsys translate_off initial sign_node_ff7 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) sign_node_ff7 <= 1'b0; else if (clk_en == 1'b1) sign_node_ff7 <= sign_node_ff6[0:0]; // synopsys translate_off initial sign_node_ff8 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) sign_node_ff8 <= 1'b0; else if (clk_en == 1'b1) sign_node_ff8 <= sign_node_ff7[0:0]; // synopsys translate_off initial sign_node_ff9 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) sign_node_ff9 <= 1'b0; else if (clk_en == 1'b1) sign_node_ff9 <= sign_node_ff8[0:0]; // synopsys translate_off initial sign_node_ff10 = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) sign_node_ff10 <= 1'b0; else if (clk_en == 1'b1) sign_node_ff10 <= sign_node_ff9[0:0]; // synopsys translate_off initial sticky_dffe = 0; // synopsys translate_on always @ ( posedge clock or posedge aclr) if (aclr == 1'b1) sticky_dffe <= 1'b0; else if (clk_en == 1'b1) sticky_dffe <= sticky_bit[22]; lpm_add_sub exp_add_adder ( .aclr(aclr), .cin(1'b0), .clken(clk_en), .clock(clock), .cout(), .dataa({1'b0, dataa[30:23]}), .datab({1'b0, datab[30:23]}), .overflow(), .result(wire_exp_add_adder_result) `ifndef FORMAL_VERIFICATION // synopsys translate_off `endif , .add_sub(1'b1) `ifndef FORMAL_VERIFICATION // synopsys translate_on `endif ); defparam exp_add_adder.lpm_pipeline = 1, exp_add_adder.lpm_width = 9, exp_add_adder.lpm_type = "lpm_add_sub"; lpm_add_sub exp_adj_adder ( .cin(1'b0), .cout(), .dataa(exp_adj_p1), .datab({expmod[9:0]}), .overflow(), .result(wire_exp_adj_adder_result) `ifndef FORMAL_VERIFICATION // synopsys translate_off `endif , .aclr(1'b0), .add_sub(1'b1), .clken(1'b1), .clock(1'b0) `ifndef FORMAL_VERIFICATION // synopsys translate_on `endif ); defparam exp_adj_adder.lpm_pipeline = 0, exp_adj_adder.lpm_width = 10, exp_adj_adder.lpm_type = "lpm_add_sub"; lpm_add_sub exp_bias_subtr ( .cout(), .dataa({1'b0, exp_bias_p3}), .datab({bias[9:0]}), .overflow(), .result(wire_exp_bias_subtr_result) `ifndef FORMAL_VERIFICATION // synopsys translate_off `endif , .aclr(1'b0), .add_sub(1'b1), .cin(), .clken(1'b1), .clock(1'b0) `ifndef FORMAL_VERIFICATION // synopsys translate_on `endif ); defparam exp_bias_subtr.lpm_direction = "SUB", exp_bias_subtr.lpm_pipeline = 0, exp_bias_subtr.lpm_representation = "UNSIGNED", exp_bias_subtr.lpm_width = 10, exp_bias_subtr.lpm_type = "lpm_add_sub"; lpm_add_sub man_round_adder ( .cout(), .dataa({1'b0, man_round_p1}), .datab({{24{1'b0}}, man_round_carry}), .overflow(), .result(wire_man_round_adder_result) `ifndef FORMAL_VERIFICATION // synopsys translate_off `endif , .aclr(1'b0), .add_sub(1'b1), .cin(), .clken(1'b1), .clock(1'b0) `ifndef FORMAL_VERIFICATION // synopsys translate_on `endif ); defparam man_round_adder.lpm_pipeline = 0, man_round_adder.lpm_width = 25, man_round_adder.lpm_type = "lpm_add_sub"; lpm_mult man_product2_mult ( .aclr(aclr), .clken(clk_en), .clock(clock), .dataa({1'b1, dataa[22:0]}), .datab({1'b1, datab[22:0]}), .result(wire_man_product2_mult_result) `ifndef FORMAL_VERIFICATION // synopsys translate_off `endif , .sum({1{1'b0}}) `ifndef FORMAL_VERIFICATION // synopsys translate_on `endif ); defparam man_product2_mult.lpm_pipeline = 5, man_product2_mult.lpm_representation = "UNSIGNED", man_product2_mult.lpm_widtha = 24, man_product2_mult.lpm_widthb = 24, man_product2_mult.lpm_widthp = 48, man_product2_mult.lpm_widths = 1, man_product2_mult.lpm_type = "lpm_mult", man_product2_mult.lpm_hint = "DEDICATED_MULTIPLIER_CIRCUITRY=YES"; assign aclr = 1'b0, bias = {{3{1'b0}}, {7{1'b1}}}, dataa_exp_all_one = {(dataa[30] & dataa_exp_all_one[6]), (dataa[29] & dataa_exp_all_one[5]), (dataa[28] & dataa_exp_all_one[4]), (dataa[27] & dataa_exp_all_one[3]), (dataa[26] & dataa_exp_all_one[2]), (dataa[25] & dataa_exp_all_one[1]), (dataa[24] & dataa_exp_all_one[0]), dataa[23]}, dataa_exp_not_zero = {(dataa[30] | dataa_exp_not_zero[6]), (dataa[29] | dataa_exp_not_zero[5]), (dataa[28] | dataa_exp_not_zero[4]), (dataa[27] | dataa_exp_not_zero[3]), (dataa[26] | dataa_exp_not_zero[2]), (dataa[25] | dataa_exp_not_zero[1]), (dataa[24] | dataa_exp_not_zero[0]), dataa[23]}, dataa_man_not_zero = {(dataa[22] | dataa_man_not_zero[21]), (dataa[21] | dataa_man_not_zero[20]), (dataa[20] | dataa_man_not_zero[19]), (dataa[19] | dataa_man_not_zero[18]), (dataa[18] | dataa_man_not_zero[17]), (dataa[17] | dataa_man_not_zero[16]), (dataa[16] | dataa_man_not_zero[15]), (dataa[15] | dataa_man_not_zero[14]), (dataa[14] | dataa_man_not_zero[13]), (dataa[13] | dataa_man_not_zero[12]), (dataa[12] | dataa_man_not_zero[11]), dataa[11], (dataa[10] | dataa_man_not_zero[9]), (dataa[9] | dataa_man_not_zero[8]), (dataa[8] | dataa_man_not_zero[7]), (dataa[7] | dataa_man_not_zero[6]), (dataa[6] | dataa_man_not_zero[5]), (dataa[5] | dataa_man_not_zero[4]), (dataa[4] | dataa_man_not_zero[3]), (dataa[3] | dataa_man_not_zero[2]), (dataa[2] | dataa_man_not_zero[1]), (dataa[1] | dataa_man_not_zero[0]), dataa[0]}, datab_exp_all_one = {(datab[30] & datab_exp_all_one[6]), (datab[29] & datab_exp_all_one[5]), (datab[28] & datab_exp_all_one[4]), (datab[27] & datab_exp_all_one[3]), (datab[26] & datab_exp_all_one[2]), (datab[25] & datab_exp_all_one[1]), (datab[24] & datab_exp_all_one[0]), datab[23]}, datab_exp_not_zero = {(datab[30] | datab_exp_not_zero[6]), (datab[29] | datab_exp_not_zero[5]), (datab[28] | datab_exp_not_zero[4]), (datab[27] | datab_exp_not_zero[3]), (datab[26] | datab_exp_not_zero[2]), (datab[25] | datab_exp_not_zero[1]), (datab[24] | datab_exp_not_zero[0]), datab[23]}, datab_man_not_zero = {(datab[22] | datab_man_not_zero[21]), (datab[21] | datab_man_not_zero[20]), (datab[20] | datab_man_not_zero[19]), (datab[19] | datab_man_not_zero[18]), (datab[18] | datab_man_not_zero[17]), (datab[17] | datab_man_not_zero[16]), (datab[16] | datab_man_not_zero[15]), (datab[15] | datab_man_not_zero[14]), (datab[14] | datab_man_not_zero[13]), (datab[13] | datab_man_not_zero[12]), (datab[12] | datab_man_not_zero[11]), datab[11], (datab[10] | datab_man_not_zero[9]), (datab[9] | datab_man_not_zero[8]), (datab[8] | datab_man_not_zero[7]), (datab[7] | datab_man_not_zero[6]), (datab[6] | datab_man_not_zero[5]), (datab[5] | datab_man_not_zero[4]), (datab[4] | datab_man_not_zero[3]), (datab[3] | datab_man_not_zero[2]), (datab[2] | datab_man_not_zero[1]), (datab[1] | datab_man_not_zero[0]), datab[0]}, exp_is_inf = (((~ exp_adj_p2[9]) & exp_adj_p2[8]) | ((~ exp_adj_p2[8]) & result_exp_all_one[7])), exp_is_zero = (exp_adj_p2[9] | (~ result_exp_not_zero[8])), expmod = {{8{1'b0}}, (delay_man_product_msb2 & man_round_p2[24]), (delay_man_product_msb2 ^ man_round_p2[24])}, inf_num = {8{1'b1}}, lsb_bit = man_shift_full[1], man_shift_full = ((wire_man_product2_mult_result[46:22] & {25{(~ wire_man_product2_mult_result[47])}}) | (wire_man_product2_mult_result[47:23] & {25{wire_man_product2_mult_result[47]}})), result = {sign_node_ff10[0:0], exp_result_ff[7:0], man_result_ff[22:0]}, result_exp_all_one = {(result_exp_all_one[6] & exp_adj_p2[7]), (result_exp_all_one[5] & exp_adj_p2[6]), (result_exp_all_one[4] & exp_adj_p2[5]), (result_exp_all_one[3] & exp_adj_p2[4]), (result_exp_all_one[2] & exp_adj_p2[3]), (result_exp_all_one[1] & exp_adj_p2[2]), (result_exp_all_one[0] & exp_adj_p2[1]), exp_adj_p2[0]}, result_exp_not_zero = {(result_exp_not_zero[7] | exp_adj_p2[8]), (result_exp_not_zero[6] | exp_adj_p2[7]), (result_exp_not_zero[5] | exp_adj_p2[6]), (result_exp_not_zero[4] | exp_adj_p2[5]), (result_exp_not_zero[3] | exp_adj_p2[4]), (result_exp_not_zero[2] | exp_adj_p2[3]), (result_exp_not_zero[1] | exp_adj_p2[2]), (result_exp_not_zero[0] | exp_adj_p2[1]), exp_adj_p2[0]}, round_bit = man_shift_full[0], round_carry = (round_dffe & (lsb_dffe | sticky_dffe)), sticky_bit = {(sticky_bit[21] | (wire_man_product2_mult_result[47] & wire_man_product2_mult_result[22])), (sticky_bit[20] | wire_man_product2_mult_result[21]), (sticky_bit[19] | wire_man_product2_mult_result[20]), (sticky_bit[18] | wire_man_product2_mult_result[19]), (sticky_bit[17] | wire_man_product2_mult_result[18]), (sticky_bit[16] | wire_man_product2_mult_result[17]), (sticky_bit[15] | wire_man_product2_mult_result[16]), (sticky_bit[14] | wire_man_product2_mult_result[15]), (sticky_bit[13] | wire_man_product2_mult_result[14]), (sticky_bit[12] | wire_man_product2_mult_result[13]), (sticky_bit[11] | wire_man_product2_mult_result[12]), (sticky_bit[10] | wire_man_product2_mult_result[11]), (sticky_bit[9] | wire_man_product2_mult_result[10]), (sticky_bit[8] | wire_man_product2_mult_result[9]), (sticky_bit[7] | wire_man_product2_mult_result[8]), (sticky_bit[6] | wire_man_product2_mult_result[7]), (sticky_bit[5] | wire_man_product2_mult_result[6]), (sticky_bit[4] | wire_man_product2_mult_result[5]), (sticky_bit[3] | wire_man_product2_mult_result[4]), (sticky_bit[2] | wire_man_product2_mult_result[3]), (sticky_bit[1] | wire_man_product2_mult_result[2]), (sticky_bit[0] | wire_man_product2_mult_result[1]), wire_man_product2_mult_result[0]}; endmodule //altfp_multiplier_altfp_mult_4do //VALID FILE // synopsys translate_off `timescale 1 ps / 1 ps // synopsys translate_on module altfp_multiplier_11 ( clk_en, clock, dataa, datab, result); input clk_en; input clock; input [31:0] dataa; input [31:0] datab; output [31:0] result; wire [31:0] sub_wire0; wire [31:0] result = sub_wire0[31:0]; altfp_multiplier_altfp_mult_4do altfp_multiplier_altfp_mult_4do_component ( .clk_en (clk_en), .clock (clock), .datab (datab), .dataa (dataa), .result (sub_wire0)); endmodule // ============================================================ // CNX file retrieval info // ============================================================ // Retrieval info: LIBRARY: altera_mf altera_mf.altera_mf_components.all // Retrieval info: PRIVATE: FPM_FORMAT STRING "Single" // Retrieval info: PRIVATE: INTENDED_DEVICE_FAMILY STRING "Cyclone II" // Retrieval info: CONSTANT: DEDICATED_MULTIPLIER_CIRCUITRY STRING "YES" // Retrieval info: CONSTANT: DENORMAL_SUPPORT STRING "NO" // Retrieval info: CONSTANT: EXCEPTION_HANDLING STRING "NO" // Retrieval info: CONSTANT: INTENDED_DEVICE_FAMILY STRING "UNUSED" // Retrieval info: CONSTANT: LPM_HINT STRING "UNUSED" // Retrieval info: CONSTANT: LPM_TYPE STRING "altfp_mult" // Retrieval info: CONSTANT: PIPELINE NUMERIC "11" // Retrieval info: CONSTANT: REDUCED_FUNCTIONALITY STRING "NO" // Retrieval info: CONSTANT: ROUNDING STRING "TO_NEAREST" // Retrieval info: CONSTANT: WIDTH_EXP NUMERIC "8" // Retrieval info: CONSTANT: WIDTH_MAN NUMERIC "23" // Retrieval info: USED_PORT: clk_en 0 0 0 0 INPUT NODEFVAL "clk_en" // Retrieval info: CONNECT: @clk_en 0 0 0 0 clk_en 0 0 0 0 // Retrieval info: USED_PORT: clock 0 0 0 0 INPUT NODEFVAL "clock" // Retrieval info: CONNECT: @clock 0 0 0 0 clock 0 0 0 0 // Retrieval info: USED_PORT: dataa 0 0 32 0 INPUT NODEFVAL "dataa[31..0]" // Retrieval info: CONNECT: @dataa 0 0 32 0 dataa 0 0 32 0 // Retrieval info: USED_PORT: datab 0 0 32 0 INPUT NODEFVAL "datab[31..0]" // Retrieval info: CONNECT: @datab 0 0 32 0 datab 0 0 32 0 // Retrieval info: USED_PORT: result 0 0 32 0 OUTPUT NODEFVAL "result[31..0]" // Retrieval info: CONNECT: result 0 0 32 0 @result 0 0 32 0 // Retrieval info: GEN_FILE: TYPE_NORMAL altfp_multiplier.v TRUE FALSE // Retrieval info: GEN_FILE: TYPE_NORMAL altfp_multiplier.qip TRUE FALSE // Retrieval info: GEN_FILE: TYPE_NORMAL altfp_multiplier.bsf FALSE TRUE // Retrieval info: GEN_FILE: TYPE_NORMAL altfp_multiplier_inst.v FALSE TRUE // Retrieval info: GEN_FILE: TYPE_NORMAL altfp_multiplier_bb.v FALSE TRUE // Retrieval info: GEN_FILE: TYPE_NORMAL altfp_multiplier.inc FALSE TRUE // Retrieval info: GEN_FILE: TYPE_NORMAL altfp_multiplier.cmp FALSE TRUE
{ "pile_set_name": "Github" }
// Copyright 2019 The Prometheus 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 procfs import ( "bufio" "bytes" "errors" "fmt" "io" "strings" "github.com/prometheus/procfs/internal/util" ) // A NetSockstat contains the output of /proc/net/sockstat{,6} for IPv4 or IPv6, // respectively. type NetSockstat struct { // Used is non-nil for IPv4 sockstat results, but nil for IPv6. Used *int Protocols []NetSockstatProtocol } // A NetSockstatProtocol contains statistics about a given socket protocol. // Pointer fields indicate that the value may or may not be present on any // given protocol. type NetSockstatProtocol struct { Protocol string InUse int Orphan *int TW *int Alloc *int Mem *int Memory *int } // NetSockstat retrieves IPv4 socket statistics. func (fs FS) NetSockstat() (*NetSockstat, error) { return readSockstat(fs.proc.Path("net", "sockstat")) } // NetSockstat6 retrieves IPv6 socket statistics. // // If IPv6 is disabled on this kernel, the returned error can be checked with // os.IsNotExist. func (fs FS) NetSockstat6() (*NetSockstat, error) { return readSockstat(fs.proc.Path("net", "sockstat6")) } // readSockstat opens and parses a NetSockstat from the input file. func readSockstat(name string) (*NetSockstat, error) { // This file is small and can be read with one syscall. b, err := util.ReadFileNoStat(name) if err != nil { // Do not wrap this error so the caller can detect os.IsNotExist and // similar conditions. return nil, err } stat, err := parseSockstat(bytes.NewReader(b)) if err != nil { return nil, fmt.Errorf("failed to read sockstats from %q: %v", name, err) } return stat, nil } // parseSockstat reads the contents of a sockstat file and parses a NetSockstat. func parseSockstat(r io.Reader) (*NetSockstat, error) { var stat NetSockstat s := bufio.NewScanner(r) for s.Scan() { // Expect a minimum of a protocol and one key/value pair. fields := strings.Split(s.Text(), " ") if len(fields) < 3 { return nil, fmt.Errorf("malformed sockstat line: %q", s.Text()) } // The remaining fields are key/value pairs. kvs, err := parseSockstatKVs(fields[1:]) if err != nil { return nil, fmt.Errorf("error parsing sockstat key/value pairs from %q: %v", s.Text(), err) } // The first field is the protocol. We must trim its colon suffix. proto := strings.TrimSuffix(fields[0], ":") switch proto { case "sockets": // Special case: IPv4 has a sockets "used" key/value pair that we // embed at the top level of the structure. used := kvs["used"] stat.Used = &used default: // Parse all other lines as individual protocols. nsp := parseSockstatProtocol(kvs) nsp.Protocol = proto stat.Protocols = append(stat.Protocols, nsp) } } if err := s.Err(); err != nil { return nil, err } return &stat, nil } // parseSockstatKVs parses a string slice into a map of key/value pairs. func parseSockstatKVs(kvs []string) (map[string]int, error) { if len(kvs)%2 != 0 { return nil, errors.New("odd number of fields in key/value pairs") } // Iterate two values at a time to gather key/value pairs. out := make(map[string]int, len(kvs)/2) for i := 0; i < len(kvs); i += 2 { vp := util.NewValueParser(kvs[i+1]) out[kvs[i]] = vp.Int() if err := vp.Err(); err != nil { return nil, err } } return out, nil } // parseSockstatProtocol parses a NetSockstatProtocol from the input kvs map. func parseSockstatProtocol(kvs map[string]int) NetSockstatProtocol { var nsp NetSockstatProtocol for k, v := range kvs { // Capture the range variable to ensure we get unique pointers for // each of the optional fields. v := v switch k { case "inuse": nsp.InUse = v case "orphan": nsp.Orphan = &v case "tw": nsp.TW = &v case "alloc": nsp.Alloc = &v case "mem": nsp.Mem = &v case "memory": nsp.Memory = &v } } return nsp }
{ "pile_set_name": "Github" }
/***************************************************************************** * Copyright (C) jparsec.org * * ------------------------------------------------------------------------- * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * *****************************************************************************/ package org.jparsec; import org.junit.Test; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; /** * Unit test for {@link Operators}. * * @author Ben Yu */ public class OperatorsTest { @Test public void testSort() { Asserts.assertArrayEquals(Operators.sort()); Asserts.assertArrayEquals(Operators.sort("="), "="); Asserts.assertArrayEquals(Operators.sort("+", "+=", "+", ""), "+=", "+"); Asserts.assertArrayEquals(Operators.sort("+", "+=", "+++", "-"), "-", "+=", "+++", "+"); Asserts.assertArrayEquals(Operators.sort("+", "+=", "+++", "-", "-="), "-=", "-", "+=", "+++", "+"); } @Test public void testLexicon() { List<String> ops = Arrays.asList( "++", "--", "+", "-", "+=", "-=", "+++", "=", "==", "===", "!", "!=", "<", "<=", ">", ">=", "<>"); Lexicon lexicon = Operators.lexicon(ops); for (String op : ops) { assertEquals(Tokens.reserved(op), lexicon.word(op)); } for (String op : ops) { assertEquals(Tokens.reserved(op), lexicon.tokenizer.parse(op)); } } }
{ "pile_set_name": "Github" }
-----BEGIN PRIVATE KEY----- MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgQ+pQkN5g6rEGUSiB x2VKmuRWyEl5eXd8xS0wHCheYguhRANCAARZQw4l9TScJkpubx62YPYnRj/k3okm h8Ag0d+aJXCfa1zmjWvDA6TZqzpy4vVLGC3ctzorT3C2SlbcmMdB8SeR -----END PRIVATE KEY-----
{ "pile_set_name": "Github" }
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import com.adobe.test.Assert; var gTestfile = 'regress-483103.js'; //----------------------------------------------------------------------------- var BUGNUMBER = 483103; var summary = 'TM: Do not assert: p->isQuad()'; var actual = ''; var expect = ''; //----------------------------------------------------------------------------- addtestcases(); //----------------------------------------------------------------------------- function addtestcases() { //printBugNumber(BUGNUMBER); //printStatus (summary); var t = new String(""); for (var j = 0; j < 3; ++j) { var e = t.charAt("-1"); } Assert.expectEq(summary, expect, actual); }
{ "pile_set_name": "Github" }
package spoon.test.position.testclasses; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(value={}) @Retention(RetentionPolicy.RUNTIME) public abstract @interface FooAnnotation { String value(); }
{ "pile_set_name": "Github" }
import { Test, TestingModule } from '@nestjs/testing'; import { Controller, Get, UseFilters, INestApplication } from '@nestjs/common'; import { FlubErrorHandler } from './../flub-error-handler'; import * as request from 'supertest'; let flubModule: TestingModule; let app: INestApplication; @Controller('test') @UseFilters(new FlubErrorHandler()) class TestController { @Get('') testMe() { return 'test'; throw new Error('standard error'); } @Get('no') noError() { return { success: true }; } } beforeAll(async () => { flubModule = await Test.createTestingModule({ controllers: [TestController], }).compile(); app = flubModule.createNestApplication(); await app.init(); }); describe('FlubErrorHandler', () => { it('No Error', async () => { return await request(app.getHttpServer()) .get('/test/no') .set('Accept', 'application/json') .expect(200, { success: true }) .expect('Content-Type', /json/); }); }); afterAll(async () => { await app.close(); });
{ "pile_set_name": "Github" }
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. #include "env-inl.h" #include "node_constants.h" #include "node_internals.h" #include "util-inl.h" #include "zlib.h" #if !defined(_MSC_VER) #include <unistd.h> #endif #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #if HAVE_OPENSSL #include <openssl/ec.h> #include <openssl/ssl.h> #ifndef OPENSSL_NO_ENGINE #include <openssl/engine.h> #endif // !OPENSSL_NO_ENGINE #endif // HAVE_OPENSSL #if defined(__POSIX__) #include <dlfcn.h> #endif #include <cerrno> #include <csignal> #include <limits> namespace node { using v8::Local; using v8::Object; namespace { void DefineErrnoConstants(Local<Object> target) { #ifdef E2BIG NODE_DEFINE_CONSTANT(target, E2BIG); #endif #ifdef EACCES NODE_DEFINE_CONSTANT(target, EACCES); #endif #ifdef EADDRINUSE NODE_DEFINE_CONSTANT(target, EADDRINUSE); #endif #ifdef EADDRNOTAVAIL NODE_DEFINE_CONSTANT(target, EADDRNOTAVAIL); #endif #ifdef EAFNOSUPPORT NODE_DEFINE_CONSTANT(target, EAFNOSUPPORT); #endif #ifdef EAGAIN NODE_DEFINE_CONSTANT(target, EAGAIN); #endif #ifdef EALREADY NODE_DEFINE_CONSTANT(target, EALREADY); #endif #ifdef EBADF NODE_DEFINE_CONSTANT(target, EBADF); #endif #ifdef EBADMSG NODE_DEFINE_CONSTANT(target, EBADMSG); #endif #ifdef EBUSY NODE_DEFINE_CONSTANT(target, EBUSY); #endif #ifdef ECANCELED NODE_DEFINE_CONSTANT(target, ECANCELED); #endif #ifdef ECHILD NODE_DEFINE_CONSTANT(target, ECHILD); #endif #ifdef ECONNABORTED NODE_DEFINE_CONSTANT(target, ECONNABORTED); #endif #ifdef ECONNREFUSED NODE_DEFINE_CONSTANT(target, ECONNREFUSED); #endif #ifdef ECONNRESET NODE_DEFINE_CONSTANT(target, ECONNRESET); #endif #ifdef EDEADLK NODE_DEFINE_CONSTANT(target, EDEADLK); #endif #ifdef EDESTADDRREQ NODE_DEFINE_CONSTANT(target, EDESTADDRREQ); #endif #ifdef EDOM NODE_DEFINE_CONSTANT(target, EDOM); #endif #ifdef EDQUOT NODE_DEFINE_CONSTANT(target, EDQUOT); #endif #ifdef EEXIST NODE_DEFINE_CONSTANT(target, EEXIST); #endif #ifdef EFAULT NODE_DEFINE_CONSTANT(target, EFAULT); #endif #ifdef EFBIG NODE_DEFINE_CONSTANT(target, EFBIG); #endif #ifdef EHOSTUNREACH NODE_DEFINE_CONSTANT(target, EHOSTUNREACH); #endif #ifdef EIDRM NODE_DEFINE_CONSTANT(target, EIDRM); #endif #ifdef EILSEQ NODE_DEFINE_CONSTANT(target, EILSEQ); #endif #ifdef EINPROGRESS NODE_DEFINE_CONSTANT(target, EINPROGRESS); #endif #ifdef EINTR NODE_DEFINE_CONSTANT(target, EINTR); #endif #ifdef EINVAL NODE_DEFINE_CONSTANT(target, EINVAL); #endif #ifdef EIO NODE_DEFINE_CONSTANT(target, EIO); #endif #ifdef EISCONN NODE_DEFINE_CONSTANT(target, EISCONN); #endif #ifdef EISDIR NODE_DEFINE_CONSTANT(target, EISDIR); #endif #ifdef ELOOP NODE_DEFINE_CONSTANT(target, ELOOP); #endif #ifdef EMFILE NODE_DEFINE_CONSTANT(target, EMFILE); #endif #ifdef EMLINK NODE_DEFINE_CONSTANT(target, EMLINK); #endif #ifdef EMSGSIZE NODE_DEFINE_CONSTANT(target, EMSGSIZE); #endif #ifdef EMULTIHOP NODE_DEFINE_CONSTANT(target, EMULTIHOP); #endif #ifdef ENAMETOOLONG NODE_DEFINE_CONSTANT(target, ENAMETOOLONG); #endif #ifdef ENETDOWN NODE_DEFINE_CONSTANT(target, ENETDOWN); #endif #ifdef ENETRESET NODE_DEFINE_CONSTANT(target, ENETRESET); #endif #ifdef ENETUNREACH NODE_DEFINE_CONSTANT(target, ENETUNREACH); #endif #ifdef ENFILE NODE_DEFINE_CONSTANT(target, ENFILE); #endif #ifdef ENOBUFS NODE_DEFINE_CONSTANT(target, ENOBUFS); #endif #ifdef ENODATA NODE_DEFINE_CONSTANT(target, ENODATA); #endif #ifdef ENODEV NODE_DEFINE_CONSTANT(target, ENODEV); #endif #ifdef ENOENT NODE_DEFINE_CONSTANT(target, ENOENT); #endif #ifdef ENOEXEC NODE_DEFINE_CONSTANT(target, ENOEXEC); #endif #ifdef ENOLCK NODE_DEFINE_CONSTANT(target, ENOLCK); #endif #ifdef ENOLINK NODE_DEFINE_CONSTANT(target, ENOLINK); #endif #ifdef ENOMEM NODE_DEFINE_CONSTANT(target, ENOMEM); #endif #ifdef ENOMSG NODE_DEFINE_CONSTANT(target, ENOMSG); #endif #ifdef ENOPROTOOPT NODE_DEFINE_CONSTANT(target, ENOPROTOOPT); #endif #ifdef ENOSPC NODE_DEFINE_CONSTANT(target, ENOSPC); #endif #ifdef ENOSR NODE_DEFINE_CONSTANT(target, ENOSR); #endif #ifdef ENOSTR NODE_DEFINE_CONSTANT(target, ENOSTR); #endif #ifdef ENOSYS NODE_DEFINE_CONSTANT(target, ENOSYS); #endif #ifdef ENOTCONN NODE_DEFINE_CONSTANT(target, ENOTCONN); #endif #ifdef ENOTDIR NODE_DEFINE_CONSTANT(target, ENOTDIR); #endif #ifdef ENOTEMPTY NODE_DEFINE_CONSTANT(target, ENOTEMPTY); #endif #ifdef ENOTSOCK NODE_DEFINE_CONSTANT(target, ENOTSOCK); #endif #ifdef ENOTSUP NODE_DEFINE_CONSTANT(target, ENOTSUP); #endif #ifdef ENOTTY NODE_DEFINE_CONSTANT(target, ENOTTY); #endif #ifdef ENXIO NODE_DEFINE_CONSTANT(target, ENXIO); #endif #ifdef EOPNOTSUPP NODE_DEFINE_CONSTANT(target, EOPNOTSUPP); #endif #ifdef EOVERFLOW NODE_DEFINE_CONSTANT(target, EOVERFLOW); #endif #ifdef EPERM NODE_DEFINE_CONSTANT(target, EPERM); #endif #ifdef EPIPE NODE_DEFINE_CONSTANT(target, EPIPE); #endif #ifdef EPROTO NODE_DEFINE_CONSTANT(target, EPROTO); #endif #ifdef EPROTONOSUPPORT NODE_DEFINE_CONSTANT(target, EPROTONOSUPPORT); #endif #ifdef EPROTOTYPE NODE_DEFINE_CONSTANT(target, EPROTOTYPE); #endif #ifdef ERANGE NODE_DEFINE_CONSTANT(target, ERANGE); #endif #ifdef EROFS NODE_DEFINE_CONSTANT(target, EROFS); #endif #ifdef ESPIPE NODE_DEFINE_CONSTANT(target, ESPIPE); #endif #ifdef ESRCH NODE_DEFINE_CONSTANT(target, ESRCH); #endif #ifdef ESTALE NODE_DEFINE_CONSTANT(target, ESTALE); #endif #ifdef ETIME NODE_DEFINE_CONSTANT(target, ETIME); #endif #ifdef ETIMEDOUT NODE_DEFINE_CONSTANT(target, ETIMEDOUT); #endif #ifdef ETXTBSY NODE_DEFINE_CONSTANT(target, ETXTBSY); #endif #ifdef EWOULDBLOCK NODE_DEFINE_CONSTANT(target, EWOULDBLOCK); #endif #ifdef EXDEV NODE_DEFINE_CONSTANT(target, EXDEV); #endif } void DefineWindowsErrorConstants(Local<Object> target) { #ifdef WSAEINTR NODE_DEFINE_CONSTANT(target, WSAEINTR); #endif #ifdef WSAEBADF NODE_DEFINE_CONSTANT(target, WSAEBADF); #endif #ifdef WSAEACCES NODE_DEFINE_CONSTANT(target, WSAEACCES); #endif #ifdef WSAEFAULT NODE_DEFINE_CONSTANT(target, WSAEFAULT); #endif #ifdef WSAEINVAL NODE_DEFINE_CONSTANT(target, WSAEINVAL); #endif #ifdef WSAEMFILE NODE_DEFINE_CONSTANT(target, WSAEMFILE); #endif #ifdef WSAEWOULDBLOCK NODE_DEFINE_CONSTANT(target, WSAEWOULDBLOCK); #endif #ifdef WSAEINPROGRESS NODE_DEFINE_CONSTANT(target, WSAEINPROGRESS); #endif #ifdef WSAEALREADY NODE_DEFINE_CONSTANT(target, WSAEALREADY); #endif #ifdef WSAENOTSOCK NODE_DEFINE_CONSTANT(target, WSAENOTSOCK); #endif #ifdef WSAEDESTADDRREQ NODE_DEFINE_CONSTANT(target, WSAEDESTADDRREQ); #endif #ifdef WSAEMSGSIZE NODE_DEFINE_CONSTANT(target, WSAEMSGSIZE); #endif #ifdef WSAEPROTOTYPE NODE_DEFINE_CONSTANT(target, WSAEPROTOTYPE); #endif #ifdef WSAENOPROTOOPT NODE_DEFINE_CONSTANT(target, WSAENOPROTOOPT); #endif #ifdef WSAEPROTONOSUPPORT NODE_DEFINE_CONSTANT(target, WSAEPROTONOSUPPORT); #endif #ifdef WSAESOCKTNOSUPPORT NODE_DEFINE_CONSTANT(target, WSAESOCKTNOSUPPORT); #endif #ifdef WSAEOPNOTSUPP NODE_DEFINE_CONSTANT(target, WSAEOPNOTSUPP); #endif #ifdef WSAEPFNOSUPPORT NODE_DEFINE_CONSTANT(target, WSAEPFNOSUPPORT); #endif #ifdef WSAEAFNOSUPPORT NODE_DEFINE_CONSTANT(target, WSAEAFNOSUPPORT); #endif #ifdef WSAEADDRINUSE NODE_DEFINE_CONSTANT(target, WSAEADDRINUSE); #endif #ifdef WSAEADDRNOTAVAIL NODE_DEFINE_CONSTANT(target, WSAEADDRNOTAVAIL); #endif #ifdef WSAENETDOWN NODE_DEFINE_CONSTANT(target, WSAENETDOWN); #endif #ifdef WSAENETUNREACH NODE_DEFINE_CONSTANT(target, WSAENETUNREACH); #endif #ifdef WSAENETRESET NODE_DEFINE_CONSTANT(target, WSAENETRESET); #endif #ifdef WSAECONNABORTED NODE_DEFINE_CONSTANT(target, WSAECONNABORTED); #endif #ifdef WSAECONNRESET NODE_DEFINE_CONSTANT(target, WSAECONNRESET); #endif #ifdef WSAENOBUFS NODE_DEFINE_CONSTANT(target, WSAENOBUFS); #endif #ifdef WSAEISCONN NODE_DEFINE_CONSTANT(target, WSAEISCONN); #endif #ifdef WSAENOTCONN NODE_DEFINE_CONSTANT(target, WSAENOTCONN); #endif #ifdef WSAESHUTDOWN NODE_DEFINE_CONSTANT(target, WSAESHUTDOWN); #endif #ifdef WSAETOOMANYREFS NODE_DEFINE_CONSTANT(target, WSAETOOMANYREFS); #endif #ifdef WSAETIMEDOUT NODE_DEFINE_CONSTANT(target, WSAETIMEDOUT); #endif #ifdef WSAECONNREFUSED NODE_DEFINE_CONSTANT(target, WSAECONNREFUSED); #endif #ifdef WSAELOOP NODE_DEFINE_CONSTANT(target, WSAELOOP); #endif #ifdef WSAENAMETOOLONG NODE_DEFINE_CONSTANT(target, WSAENAMETOOLONG); #endif #ifdef WSAEHOSTDOWN NODE_DEFINE_CONSTANT(target, WSAEHOSTDOWN); #endif #ifdef WSAEHOSTUNREACH NODE_DEFINE_CONSTANT(target, WSAEHOSTUNREACH); #endif #ifdef WSAENOTEMPTY NODE_DEFINE_CONSTANT(target, WSAENOTEMPTY); #endif #ifdef WSAEPROCLIM NODE_DEFINE_CONSTANT(target, WSAEPROCLIM); #endif #ifdef WSAEUSERS NODE_DEFINE_CONSTANT(target, WSAEUSERS); #endif #ifdef WSAEDQUOT NODE_DEFINE_CONSTANT(target, WSAEDQUOT); #endif #ifdef WSAESTALE NODE_DEFINE_CONSTANT(target, WSAESTALE); #endif #ifdef WSAEREMOTE NODE_DEFINE_CONSTANT(target, WSAEREMOTE); #endif #ifdef WSASYSNOTREADY NODE_DEFINE_CONSTANT(target, WSASYSNOTREADY); #endif #ifdef WSAVERNOTSUPPORTED NODE_DEFINE_CONSTANT(target, WSAVERNOTSUPPORTED); #endif #ifdef WSANOTINITIALISED NODE_DEFINE_CONSTANT(target, WSANOTINITIALISED); #endif #ifdef WSAEDISCON NODE_DEFINE_CONSTANT(target, WSAEDISCON); #endif #ifdef WSAENOMORE NODE_DEFINE_CONSTANT(target, WSAENOMORE); #endif #ifdef WSAECANCELLED NODE_DEFINE_CONSTANT(target, WSAECANCELLED); #endif #ifdef WSAEINVALIDPROCTABLE NODE_DEFINE_CONSTANT(target, WSAEINVALIDPROCTABLE); #endif #ifdef WSAEINVALIDPROVIDER NODE_DEFINE_CONSTANT(target, WSAEINVALIDPROVIDER); #endif #ifdef WSAEPROVIDERFAILEDINIT NODE_DEFINE_CONSTANT(target, WSAEPROVIDERFAILEDINIT); #endif #ifdef WSASYSCALLFAILURE NODE_DEFINE_CONSTANT(target, WSASYSCALLFAILURE); #endif #ifdef WSASERVICE_NOT_FOUND NODE_DEFINE_CONSTANT(target, WSASERVICE_NOT_FOUND); #endif #ifdef WSATYPE_NOT_FOUND NODE_DEFINE_CONSTANT(target, WSATYPE_NOT_FOUND); #endif #ifdef WSA_E_NO_MORE NODE_DEFINE_CONSTANT(target, WSA_E_NO_MORE); #endif #ifdef WSA_E_CANCELLED NODE_DEFINE_CONSTANT(target, WSA_E_CANCELLED); #endif #ifdef WSAEREFUSED NODE_DEFINE_CONSTANT(target, WSAEREFUSED); #endif } void DefineSignalConstants(Local<Object> target) { #ifdef SIGHUP NODE_DEFINE_CONSTANT(target, SIGHUP); #endif #ifdef SIGINT NODE_DEFINE_CONSTANT(target, SIGINT); #endif #ifdef SIGQUIT NODE_DEFINE_CONSTANT(target, SIGQUIT); #endif #ifdef SIGILL NODE_DEFINE_CONSTANT(target, SIGILL); #endif #ifdef SIGTRAP NODE_DEFINE_CONSTANT(target, SIGTRAP); #endif #ifdef SIGABRT NODE_DEFINE_CONSTANT(target, SIGABRT); #endif #ifdef SIGIOT NODE_DEFINE_CONSTANT(target, SIGIOT); #endif #ifdef SIGBUS NODE_DEFINE_CONSTANT(target, SIGBUS); #endif #ifdef SIGFPE NODE_DEFINE_CONSTANT(target, SIGFPE); #endif #ifdef SIGKILL NODE_DEFINE_CONSTANT(target, SIGKILL); #endif #ifdef SIGUSR1 NODE_DEFINE_CONSTANT(target, SIGUSR1); #endif #ifdef SIGSEGV NODE_DEFINE_CONSTANT(target, SIGSEGV); #endif #ifdef SIGUSR2 NODE_DEFINE_CONSTANT(target, SIGUSR2); #endif #ifdef SIGPIPE NODE_DEFINE_CONSTANT(target, SIGPIPE); #endif #ifdef SIGALRM NODE_DEFINE_CONSTANT(target, SIGALRM); #endif NODE_DEFINE_CONSTANT(target, SIGTERM); #ifdef SIGCHLD NODE_DEFINE_CONSTANT(target, SIGCHLD); #endif #ifdef SIGSTKFLT NODE_DEFINE_CONSTANT(target, SIGSTKFLT); #endif #ifdef SIGCONT NODE_DEFINE_CONSTANT(target, SIGCONT); #endif #ifdef SIGSTOP NODE_DEFINE_CONSTANT(target, SIGSTOP); #endif #ifdef SIGTSTP NODE_DEFINE_CONSTANT(target, SIGTSTP); #endif #ifdef SIGBREAK NODE_DEFINE_CONSTANT(target, SIGBREAK); #endif #ifdef SIGTTIN NODE_DEFINE_CONSTANT(target, SIGTTIN); #endif #ifdef SIGTTOU NODE_DEFINE_CONSTANT(target, SIGTTOU); #endif #ifdef SIGURG NODE_DEFINE_CONSTANT(target, SIGURG); #endif #ifdef SIGXCPU NODE_DEFINE_CONSTANT(target, SIGXCPU); #endif #ifdef SIGXFSZ NODE_DEFINE_CONSTANT(target, SIGXFSZ); #endif #ifdef SIGVTALRM NODE_DEFINE_CONSTANT(target, SIGVTALRM); #endif #ifdef SIGPROF NODE_DEFINE_CONSTANT(target, SIGPROF); #endif #ifdef SIGWINCH NODE_DEFINE_CONSTANT(target, SIGWINCH); #endif #ifdef SIGIO NODE_DEFINE_CONSTANT(target, SIGIO); #endif #ifdef SIGPOLL NODE_DEFINE_CONSTANT(target, SIGPOLL); #endif #ifdef SIGLOST NODE_DEFINE_CONSTANT(target, SIGLOST); #endif #ifdef SIGPWR NODE_DEFINE_CONSTANT(target, SIGPWR); #endif #ifdef SIGINFO NODE_DEFINE_CONSTANT(target, SIGINFO); #endif #ifdef SIGSYS NODE_DEFINE_CONSTANT(target, SIGSYS); #endif #ifdef SIGUNUSED NODE_DEFINE_CONSTANT(target, SIGUNUSED); #endif } void DefinePriorityConstants(Local<Object> target) { #ifdef UV_PRIORITY_LOW # define PRIORITY_LOW UV_PRIORITY_LOW NODE_DEFINE_CONSTANT(target, PRIORITY_LOW); # undef PRIORITY_LOW #endif #ifdef UV_PRIORITY_BELOW_NORMAL # define PRIORITY_BELOW_NORMAL UV_PRIORITY_BELOW_NORMAL NODE_DEFINE_CONSTANT(target, PRIORITY_BELOW_NORMAL); # undef PRIORITY_BELOW_NORMAL #endif #ifdef UV_PRIORITY_NORMAL # define PRIORITY_NORMAL UV_PRIORITY_NORMAL NODE_DEFINE_CONSTANT(target, PRIORITY_NORMAL); # undef PRIORITY_NORMAL #endif #ifdef UV_PRIORITY_ABOVE_NORMAL # define PRIORITY_ABOVE_NORMAL UV_PRIORITY_ABOVE_NORMAL NODE_DEFINE_CONSTANT(target, PRIORITY_ABOVE_NORMAL); # undef PRIORITY_ABOVE_NORMAL #endif #ifdef UV_PRIORITY_HIGH # define PRIORITY_HIGH UV_PRIORITY_HIGH NODE_DEFINE_CONSTANT(target, PRIORITY_HIGH); # undef PRIORITY_HIGH #endif #ifdef UV_PRIORITY_HIGHEST # define PRIORITY_HIGHEST UV_PRIORITY_HIGHEST NODE_DEFINE_CONSTANT(target, PRIORITY_HIGHEST); # undef PRIORITY_HIGHEST #endif } void DefineCryptoConstants(Local<Object> target) { #ifdef OPENSSL_VERSION_NUMBER NODE_DEFINE_CONSTANT(target, OPENSSL_VERSION_NUMBER); #endif #ifdef SSL_OP_ALL NODE_DEFINE_CONSTANT(target, SSL_OP_ALL); #endif #ifdef SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION NODE_DEFINE_CONSTANT(target, SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); #endif #ifdef SSL_OP_CIPHER_SERVER_PREFERENCE NODE_DEFINE_CONSTANT(target, SSL_OP_CIPHER_SERVER_PREFERENCE); #endif #ifdef SSL_OP_CISCO_ANYCONNECT NODE_DEFINE_CONSTANT(target, SSL_OP_CISCO_ANYCONNECT); #endif #ifdef SSL_OP_COOKIE_EXCHANGE NODE_DEFINE_CONSTANT(target, SSL_OP_COOKIE_EXCHANGE); #endif #ifdef SSL_OP_CRYPTOPRO_TLSEXT_BUG NODE_DEFINE_CONSTANT(target, SSL_OP_CRYPTOPRO_TLSEXT_BUG); #endif #ifdef SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS NODE_DEFINE_CONSTANT(target, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS); #endif #ifdef SSL_OP_EPHEMERAL_RSA NODE_DEFINE_CONSTANT(target, SSL_OP_EPHEMERAL_RSA); #endif #ifdef SSL_OP_LEGACY_SERVER_CONNECT NODE_DEFINE_CONSTANT(target, SSL_OP_LEGACY_SERVER_CONNECT); #endif #ifdef SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER NODE_DEFINE_CONSTANT(target, SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER); #endif #ifdef SSL_OP_MICROSOFT_SESS_ID_BUG NODE_DEFINE_CONSTANT(target, SSL_OP_MICROSOFT_SESS_ID_BUG); #endif #ifdef SSL_OP_MSIE_SSLV2_RSA_PADDING NODE_DEFINE_CONSTANT(target, SSL_OP_MSIE_SSLV2_RSA_PADDING); #endif #ifdef SSL_OP_NETSCAPE_CA_DN_BUG NODE_DEFINE_CONSTANT(target, SSL_OP_NETSCAPE_CA_DN_BUG); #endif #ifdef SSL_OP_NETSCAPE_CHALLENGE_BUG NODE_DEFINE_CONSTANT(target, SSL_OP_NETSCAPE_CHALLENGE_BUG); #endif #ifdef SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG NODE_DEFINE_CONSTANT(target, SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG); #endif #ifdef SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG NODE_DEFINE_CONSTANT(target, SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG); #endif #ifdef SSL_OP_NO_COMPRESSION NODE_DEFINE_CONSTANT(target, SSL_OP_NO_COMPRESSION); #endif #ifdef SSL_OP_NO_QUERY_MTU NODE_DEFINE_CONSTANT(target, SSL_OP_NO_QUERY_MTU); #endif #ifdef SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION NODE_DEFINE_CONSTANT(target, SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); #endif #ifdef SSL_OP_NO_SSLv2 NODE_DEFINE_CONSTANT(target, SSL_OP_NO_SSLv2); #endif #ifdef SSL_OP_NO_SSLv3 NODE_DEFINE_CONSTANT(target, SSL_OP_NO_SSLv3); #endif #ifdef SSL_OP_NO_TICKET NODE_DEFINE_CONSTANT(target, SSL_OP_NO_TICKET); #endif #ifdef SSL_OP_NO_TLSv1 NODE_DEFINE_CONSTANT(target, SSL_OP_NO_TLSv1); #endif #ifdef SSL_OP_NO_TLSv1_1 NODE_DEFINE_CONSTANT(target, SSL_OP_NO_TLSv1_1); #endif #ifdef SSL_OP_NO_TLSv1_2 NODE_DEFINE_CONSTANT(target, SSL_OP_NO_TLSv1_2); #endif #ifdef SSL_OP_PKCS1_CHECK_1 NODE_DEFINE_CONSTANT(target, SSL_OP_PKCS1_CHECK_1); #endif #ifdef SSL_OP_PKCS1_CHECK_2 NODE_DEFINE_CONSTANT(target, SSL_OP_PKCS1_CHECK_2); #endif #ifdef SSL_OP_SINGLE_DH_USE NODE_DEFINE_CONSTANT(target, SSL_OP_SINGLE_DH_USE); #endif #ifdef SSL_OP_SINGLE_ECDH_USE NODE_DEFINE_CONSTANT(target, SSL_OP_SINGLE_ECDH_USE); #endif #ifdef SSL_OP_SSLEAY_080_CLIENT_DH_BUG NODE_DEFINE_CONSTANT(target, SSL_OP_SSLEAY_080_CLIENT_DH_BUG); #endif #ifdef SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG NODE_DEFINE_CONSTANT(target, SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG); #endif #ifdef SSL_OP_TLS_BLOCK_PADDING_BUG NODE_DEFINE_CONSTANT(target, SSL_OP_TLS_BLOCK_PADDING_BUG); #endif #ifdef SSL_OP_TLS_D5_BUG NODE_DEFINE_CONSTANT(target, SSL_OP_TLS_D5_BUG); #endif #ifdef SSL_OP_TLS_ROLLBACK_BUG NODE_DEFINE_CONSTANT(target, SSL_OP_TLS_ROLLBACK_BUG); #endif # ifndef OPENSSL_NO_ENGINE # ifdef ENGINE_METHOD_RSA NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_RSA); # endif # ifdef ENGINE_METHOD_DSA NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_DSA); # endif # ifdef ENGINE_METHOD_DH NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_DH); # endif # ifdef ENGINE_METHOD_RAND NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_RAND); # endif # ifdef ENGINE_METHOD_EC NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_EC); # endif # ifdef ENGINE_METHOD_CIPHERS NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_CIPHERS); # endif # ifdef ENGINE_METHOD_DIGESTS NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_DIGESTS); # endif # ifdef ENGINE_METHOD_PKEY_METHS NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_PKEY_METHS); # endif # ifdef ENGINE_METHOD_PKEY_ASN1_METHS NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_PKEY_ASN1_METHS); # endif # ifdef ENGINE_METHOD_ALL NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_ALL); # endif # ifdef ENGINE_METHOD_NONE NODE_DEFINE_CONSTANT(target, ENGINE_METHOD_NONE); # endif # endif // !OPENSSL_NO_ENGINE #ifdef DH_CHECK_P_NOT_SAFE_PRIME NODE_DEFINE_CONSTANT(target, DH_CHECK_P_NOT_SAFE_PRIME); #endif #ifdef DH_CHECK_P_NOT_PRIME NODE_DEFINE_CONSTANT(target, DH_CHECK_P_NOT_PRIME); #endif #ifdef DH_UNABLE_TO_CHECK_GENERATOR NODE_DEFINE_CONSTANT(target, DH_UNABLE_TO_CHECK_GENERATOR); #endif #ifdef DH_NOT_SUITABLE_GENERATOR NODE_DEFINE_CONSTANT(target, DH_NOT_SUITABLE_GENERATOR); #endif #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation #define ALPN_ENABLED 1 NODE_DEFINE_CONSTANT(target, ALPN_ENABLED); #endif #ifdef RSA_PKCS1_PADDING NODE_DEFINE_CONSTANT(target, RSA_PKCS1_PADDING); #endif #ifdef RSA_SSLV23_PADDING NODE_DEFINE_CONSTANT(target, RSA_SSLV23_PADDING); #endif #ifdef RSA_NO_PADDING NODE_DEFINE_CONSTANT(target, RSA_NO_PADDING); #endif #ifdef RSA_PKCS1_OAEP_PADDING NODE_DEFINE_CONSTANT(target, RSA_PKCS1_OAEP_PADDING); #endif #ifdef RSA_X931_PADDING NODE_DEFINE_CONSTANT(target, RSA_X931_PADDING); #endif #ifdef RSA_PKCS1_PSS_PADDING NODE_DEFINE_CONSTANT(target, RSA_PKCS1_PSS_PADDING); #endif #ifdef RSA_PSS_SALTLEN_DIGEST NODE_DEFINE_CONSTANT(target, RSA_PSS_SALTLEN_DIGEST); #endif #ifdef RSA_PSS_SALTLEN_MAX_SIGN NODE_DEFINE_CONSTANT(target, RSA_PSS_SALTLEN_MAX_SIGN); #endif #ifdef RSA_PSS_SALTLEN_AUTO NODE_DEFINE_CONSTANT(target, RSA_PSS_SALTLEN_AUTO); #endif #ifdef DEFAULT_CIPHER_LIST_CORE NODE_DEFINE_STRING_CONSTANT(target, "defaultCoreCipherList", DEFAULT_CIPHER_LIST_CORE); #endif #ifdef TLS1_VERSION NODE_DEFINE_CONSTANT(target, TLS1_VERSION); #endif #ifdef TLS1_1_VERSION NODE_DEFINE_CONSTANT(target, TLS1_1_VERSION); #endif #ifdef TLS1_2_VERSION NODE_DEFINE_CONSTANT(target, TLS1_2_VERSION); #endif #ifdef TLS1_3_VERSION NODE_DEFINE_CONSTANT(target, TLS1_3_VERSION); #endif #if HAVE_OPENSSL // NOTE: These are not defines NODE_DEFINE_CONSTANT(target, POINT_CONVERSION_COMPRESSED); NODE_DEFINE_CONSTANT(target, POINT_CONVERSION_UNCOMPRESSED); NODE_DEFINE_CONSTANT(target, POINT_CONVERSION_HYBRID); #endif } void DefineSystemConstants(Local<Object> target) { NODE_DEFINE_CONSTANT(target, UV_FS_SYMLINK_DIR); NODE_DEFINE_CONSTANT(target, UV_FS_SYMLINK_JUNCTION); // file access modes NODE_DEFINE_CONSTANT(target, O_RDONLY); NODE_DEFINE_CONSTANT(target, O_WRONLY); NODE_DEFINE_CONSTANT(target, O_RDWR); // file types from readdir NODE_DEFINE_CONSTANT(target, UV_DIRENT_UNKNOWN); NODE_DEFINE_CONSTANT(target, UV_DIRENT_FILE); NODE_DEFINE_CONSTANT(target, UV_DIRENT_DIR); NODE_DEFINE_CONSTANT(target, UV_DIRENT_LINK); NODE_DEFINE_CONSTANT(target, UV_DIRENT_FIFO); NODE_DEFINE_CONSTANT(target, UV_DIRENT_SOCKET); NODE_DEFINE_CONSTANT(target, UV_DIRENT_CHAR); NODE_DEFINE_CONSTANT(target, UV_DIRENT_BLOCK); NODE_DEFINE_CONSTANT(target, S_IFMT); NODE_DEFINE_CONSTANT(target, S_IFREG); NODE_DEFINE_CONSTANT(target, S_IFDIR); NODE_DEFINE_CONSTANT(target, S_IFCHR); #ifdef S_IFBLK NODE_DEFINE_CONSTANT(target, S_IFBLK); #endif #ifdef S_IFIFO NODE_DEFINE_CONSTANT(target, S_IFIFO); #endif #ifdef S_IFLNK NODE_DEFINE_CONSTANT(target, S_IFLNK); #endif #ifdef S_IFSOCK NODE_DEFINE_CONSTANT(target, S_IFSOCK); #endif #ifdef O_CREAT NODE_DEFINE_CONSTANT(target, O_CREAT); #endif #ifdef O_EXCL NODE_DEFINE_CONSTANT(target, O_EXCL); #endif NODE_DEFINE_CONSTANT(target, UV_FS_O_FILEMAP); #ifdef O_NOCTTY NODE_DEFINE_CONSTANT(target, O_NOCTTY); #endif #ifdef O_TRUNC NODE_DEFINE_CONSTANT(target, O_TRUNC); #endif #ifdef O_APPEND NODE_DEFINE_CONSTANT(target, O_APPEND); #endif #ifdef O_DIRECTORY NODE_DEFINE_CONSTANT(target, O_DIRECTORY); #endif #ifdef O_EXCL NODE_DEFINE_CONSTANT(target, O_EXCL); #endif #ifdef O_NOATIME NODE_DEFINE_CONSTANT(target, O_NOATIME); #endif #ifdef O_NOFOLLOW NODE_DEFINE_CONSTANT(target, O_NOFOLLOW); #endif #ifdef O_SYNC NODE_DEFINE_CONSTANT(target, O_SYNC); #endif #ifdef O_DSYNC NODE_DEFINE_CONSTANT(target, O_DSYNC); #endif #ifdef O_SYMLINK NODE_DEFINE_CONSTANT(target, O_SYMLINK); #endif #ifdef O_DIRECT NODE_DEFINE_CONSTANT(target, O_DIRECT); #endif #ifdef O_NONBLOCK NODE_DEFINE_CONSTANT(target, O_NONBLOCK); #endif #ifdef S_IRWXU NODE_DEFINE_CONSTANT(target, S_IRWXU); #endif #ifdef S_IRUSR NODE_DEFINE_CONSTANT(target, S_IRUSR); #endif #ifdef S_IWUSR NODE_DEFINE_CONSTANT(target, S_IWUSR); #endif #ifdef S_IXUSR NODE_DEFINE_CONSTANT(target, S_IXUSR); #endif #ifdef S_IRWXG NODE_DEFINE_CONSTANT(target, S_IRWXG); #endif #ifdef S_IRGRP NODE_DEFINE_CONSTANT(target, S_IRGRP); #endif #ifdef S_IWGRP NODE_DEFINE_CONSTANT(target, S_IWGRP); #endif #ifdef S_IXGRP NODE_DEFINE_CONSTANT(target, S_IXGRP); #endif #ifdef S_IRWXO NODE_DEFINE_CONSTANT(target, S_IRWXO); #endif #ifdef S_IROTH NODE_DEFINE_CONSTANT(target, S_IROTH); #endif #ifdef S_IWOTH NODE_DEFINE_CONSTANT(target, S_IWOTH); #endif #ifdef S_IXOTH NODE_DEFINE_CONSTANT(target, S_IXOTH); #endif #ifdef F_OK NODE_DEFINE_CONSTANT(target, F_OK); #endif #ifdef R_OK NODE_DEFINE_CONSTANT(target, R_OK); #endif #ifdef W_OK NODE_DEFINE_CONSTANT(target, W_OK); #endif #ifdef X_OK NODE_DEFINE_CONSTANT(target, X_OK); #endif #ifdef UV_FS_COPYFILE_EXCL # define COPYFILE_EXCL UV_FS_COPYFILE_EXCL NODE_DEFINE_CONSTANT(target, UV_FS_COPYFILE_EXCL); NODE_DEFINE_CONSTANT(target, COPYFILE_EXCL); # undef COPYFILE_EXCL #endif #ifdef UV_FS_COPYFILE_FICLONE # define COPYFILE_FICLONE UV_FS_COPYFILE_FICLONE NODE_DEFINE_CONSTANT(target, UV_FS_COPYFILE_FICLONE); NODE_DEFINE_CONSTANT(target, COPYFILE_FICLONE); # undef COPYFILE_FICLONE #endif #ifdef UV_FS_COPYFILE_FICLONE_FORCE # define COPYFILE_FICLONE_FORCE UV_FS_COPYFILE_FICLONE_FORCE NODE_DEFINE_CONSTANT(target, UV_FS_COPYFILE_FICLONE_FORCE); NODE_DEFINE_CONSTANT(target, COPYFILE_FICLONE_FORCE); # undef COPYFILE_FICLONE_FORCE #endif } void DefineDLOpenConstants(Local<Object> target) { #ifdef RTLD_LAZY NODE_DEFINE_CONSTANT(target, RTLD_LAZY); #endif #ifdef RTLD_NOW NODE_DEFINE_CONSTANT(target, RTLD_NOW); #endif #ifdef RTLD_GLOBAL NODE_DEFINE_CONSTANT(target, RTLD_GLOBAL); #endif #ifdef RTLD_LOCAL NODE_DEFINE_CONSTANT(target, RTLD_LOCAL); #endif #ifdef RTLD_DEEPBIND NODE_DEFINE_CONSTANT(target, RTLD_DEEPBIND); #endif } void DefineTraceConstants(Local<Object> target) { NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_BEGIN); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_END); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_COMPLETE); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_INSTANT); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_ASYNC_BEGIN); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_ASYNC_STEP_INTO); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_ASYNC_STEP_PAST); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_ASYNC_END); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_NESTABLE_ASYNC_BEGIN); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_NESTABLE_ASYNC_END); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_NESTABLE_ASYNC_INSTANT); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_FLOW_BEGIN); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_FLOW_STEP); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_FLOW_END); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_METADATA); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_COUNTER); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_SAMPLE); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_CREATE_OBJECT); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_SNAPSHOT_OBJECT); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_DELETE_OBJECT); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_MEMORY_DUMP); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_MARK); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_CLOCK_SYNC); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_ENTER_CONTEXT); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_LEAVE_CONTEXT); NODE_DEFINE_CONSTANT(target, TRACE_EVENT_PHASE_LINK_IDS); } } // anonymous namespace void DefineConstants(v8::Isolate* isolate, Local<Object> target) { Environment* env = Environment::GetCurrent(isolate); Local<Object> os_constants = Object::New(isolate); CHECK(os_constants->SetPrototype(env->context(), Null(env->isolate())).FromJust()); Local<Object> err_constants = Object::New(isolate); CHECK(err_constants->SetPrototype(env->context(), Null(env->isolate())).FromJust()); Local<Object> sig_constants = Object::New(isolate); CHECK(sig_constants->SetPrototype(env->context(), Null(env->isolate())).FromJust()); Local<Object> priority_constants = Object::New(isolate); CHECK(priority_constants->SetPrototype(env->context(), Null(env->isolate())).FromJust()); Local<Object> fs_constants = Object::New(isolate); CHECK(fs_constants->SetPrototype(env->context(), Null(env->isolate())).FromJust()); Local<Object> crypto_constants = Object::New(isolate); CHECK(crypto_constants->SetPrototype(env->context(), Null(env->isolate())).FromJust()); Local<Object> zlib_constants = Object::New(isolate); CHECK(zlib_constants->SetPrototype(env->context(), Null(env->isolate())).FromJust()); Local<Object> dlopen_constants = Object::New(isolate); CHECK(dlopen_constants->SetPrototype(env->context(), Null(env->isolate())).FromJust()); Local<Object> trace_constants = Object::New(isolate); CHECK(trace_constants->SetPrototype(env->context(), Null(env->isolate())).FromJust()); DefineErrnoConstants(err_constants); DefineWindowsErrorConstants(err_constants); DefineSignalConstants(sig_constants); DefinePriorityConstants(priority_constants); DefineSystemConstants(fs_constants); DefineCryptoConstants(crypto_constants); DefineZlibConstants(zlib_constants); DefineDLOpenConstants(dlopen_constants); DefineTraceConstants(trace_constants); // Define libuv constants. NODE_DEFINE_CONSTANT(os_constants, UV_UDP_REUSEADDR); os_constants->Set(env->context(), OneByteString(isolate, "dlopen"), dlopen_constants).Check(); os_constants->Set(env->context(), OneByteString(isolate, "errno"), err_constants).Check(); os_constants->Set(env->context(), OneByteString(isolate, "signals"), sig_constants).Check(); os_constants->Set(env->context(), OneByteString(isolate, "priority"), priority_constants).Check(); target->Set(env->context(), OneByteString(isolate, "os"), os_constants).Check(); target->Set(env->context(), OneByteString(isolate, "fs"), fs_constants).Check(); target->Set(env->context(), OneByteString(isolate, "crypto"), crypto_constants).Check(); target->Set(env->context(), OneByteString(isolate, "zlib"), zlib_constants).Check(); target->Set(env->context(), OneByteString(isolate, "trace"), trace_constants).Check(); } } // namespace node
{ "pile_set_name": "Github" }
*> \brief \b SPPT01 * * =========== DOCUMENTATION =========== * * Online html documentation available at * http://www.netlib.org/lapack/explore-html/ * * Definition: * =========== * * SUBROUTINE SPPT01( UPLO, N, A, AFAC, RWORK, RESID ) * * .. Scalar Arguments .. * CHARACTER UPLO * INTEGER N * REAL RESID * .. * .. Array Arguments .. * REAL A( * ), AFAC( * ), RWORK( * ) * .. * * *> \par Purpose: * ============= *> *> \verbatim *> *> SPPT01 reconstructs a symmetric positive definite packed matrix A *> from its L*L' or U'*U factorization and computes the residual *> norm( L*L' - A ) / ( N * norm(A) * EPS ) or *> norm( U'*U - A ) / ( N * norm(A) * EPS ), *> where EPS is the machine epsilon. *> \endverbatim * * Arguments: * ========== * *> \param[in] UPLO *> \verbatim *> UPLO is CHARACTER*1 *> Specifies whether the upper or lower triangular part of the *> symmetric matrix A is stored: *> = 'U': Upper triangular *> = 'L': Lower triangular *> \endverbatim *> *> \param[in] N *> \verbatim *> N is INTEGER *> The number of rows and columns of the matrix A. N >= 0. *> \endverbatim *> *> \param[in] A *> \verbatim *> A is REAL array, dimension (N*(N+1)/2) *> The original symmetric matrix A, stored as a packed *> triangular matrix. *> \endverbatim *> *> \param[in,out] AFAC *> \verbatim *> AFAC is REAL array, dimension (N*(N+1)/2) *> On entry, the factor L or U from the L*L' or U'*U *> factorization of A, stored as a packed triangular matrix. *> Overwritten with the reconstructed matrix, and then with the *> difference L*L' - A (or U'*U - A). *> \endverbatim *> *> \param[out] RWORK *> \verbatim *> RWORK is REAL array, dimension (N) *> \endverbatim *> *> \param[out] RESID *> \verbatim *> RESID is REAL *> If UPLO = 'L', norm(L*L' - A) / ( N * norm(A) * EPS ) *> If UPLO = 'U', norm(U'*U - A) / ( N * norm(A) * EPS ) *> \endverbatim * * Authors: * ======== * *> \author Univ. of Tennessee *> \author Univ. of California Berkeley *> \author Univ. of Colorado Denver *> \author NAG Ltd. * *> \date November 2011 * *> \ingroup single_lin * * ===================================================================== SUBROUTINE SPPT01( UPLO, N, A, AFAC, RWORK, RESID ) * * -- LAPACK test routine (version 3.4.0) -- * -- LAPACK is a software package provided by Univ. of Tennessee, -- * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- * November 2011 * * .. Scalar Arguments .. CHARACTER UPLO INTEGER N REAL RESID * .. * .. Array Arguments .. REAL A( * ), AFAC( * ), RWORK( * ) * .. * * ===================================================================== * * .. Parameters .. REAL ZERO, ONE PARAMETER ( ZERO = 0.0E+0, ONE = 1.0E+0 ) * .. * .. Local Scalars .. INTEGER I, K, KC, NPP REAL ANORM, EPS, T * .. * .. External Functions .. LOGICAL LSAME REAL SDOT, SLAMCH, SLANSP EXTERNAL LSAME, SDOT, SLAMCH, SLANSP * .. * .. External Subroutines .. EXTERNAL SSCAL, SSPR, STPMV * .. * .. Intrinsic Functions .. INTRINSIC REAL * .. * .. Executable Statements .. * * Quick exit if N = 0 * IF( N.LE.0 ) THEN RESID = ZERO RETURN END IF * * Exit with RESID = 1/EPS if ANORM = 0. * EPS = SLAMCH( 'Epsilon' ) ANORM = SLANSP( '1', UPLO, N, A, RWORK ) IF( ANORM.LE.ZERO ) THEN RESID = ONE / EPS RETURN END IF * * Compute the product U'*U, overwriting U. * IF( LSAME( UPLO, 'U' ) ) THEN KC = ( N*( N-1 ) ) / 2 + 1 DO 10 K = N, 1, -1 * * Compute the (K,K) element of the result. * T = SDOT( K, AFAC( KC ), 1, AFAC( KC ), 1 ) AFAC( KC+K-1 ) = T * * Compute the rest of column K. * IF( K.GT.1 ) THEN CALL STPMV( 'Upper', 'Transpose', 'Non-unit', K-1, AFAC, $ AFAC( KC ), 1 ) KC = KC - ( K-1 ) END IF 10 CONTINUE * * Compute the product L*L', overwriting L. * ELSE KC = ( N*( N+1 ) ) / 2 DO 20 K = N, 1, -1 * * Add a multiple of column K of the factor L to each of * columns K+1 through N. * IF( K.LT.N ) $ CALL SSPR( 'Lower', N-K, ONE, AFAC( KC+1 ), 1, $ AFAC( KC+N-K+1 ) ) * * Scale column K by the diagonal element. * T = AFAC( KC ) CALL SSCAL( N-K+1, T, AFAC( KC ), 1 ) * KC = KC - ( N-K+2 ) 20 CONTINUE END IF * * Compute the difference L*L' - A (or U'*U - A). * NPP = N*( N+1 ) / 2 DO 30 I = 1, NPP AFAC( I ) = AFAC( I ) - A( I ) 30 CONTINUE * * Compute norm( L*U - A ) / ( N * norm(A) * EPS ) * RESID = SLANSP( '1', UPLO, N, AFAC, RWORK ) * RESID = ( ( RESID / REAL( N ) ) / ANORM ) / EPS * RETURN * * End of SPPT01 * END
{ "pile_set_name": "Github" }
using System; namespace Octgn.Sdk.Packaging { public interface IDependency { string Id { get; } string Version { get; } } }
{ "pile_set_name": "Github" }
Sitemap: https://developers.steem.io/sitemap.xml
{ "pile_set_name": "Github" }
# Copyright 2019 The Amber 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. [vertex shader passthrough] [fragment shader] #version 430 layout(set = 0, binding = 0) uniform Uniform { float uniform_value; }; layout(location = 0) out vec4 outColor; void main() { outColor = vec4(uniform_value, 0.0, 0.0, uniform_value); } [test] uniform ubo 0:0 float 0 1.0 clear draw rect -1 -1 2 2 probe rect rgba (0, 0, 250, 250) (1.0 0.0 0.0 1.0)
{ "pile_set_name": "Github" }
// Telegrammer - Telegram Bot Swift SDK. // This file is autogenerated by API/generate_wrappers.rb script. /** Represents a result of an inline query that was chosen by the user and sent to their chat partner. SeeAlso Telegram Bot API Reference: [ChosenInlineResult](https://core.telegram.org/bots/api#choseninlineresult) */ public final class ChosenInlineResult: Codable { /// Custom keys for coding/decoding `ChosenInlineResult` struct enum CodingKeys: String, CodingKey { case resultId = "result_id" case from = "from" case location = "location" case inlineMessageId = "inline_message_id" case query = "query" } /// The unique identifier for the result that was chosen public var resultId: String /// The user that chose the result public var from: User /// Optional. Sender location, only for bots that require user location public var location: Location? /// Optional. Identifier of the sent inline message. Available only if there is an inline keyboard attached to the message. Will be also received in callback queries and can be used to edit the message. public var inlineMessageId: String? /// The query that was used to obtain the result public var query: String public init (resultId: String, from: User, location: Location? = nil, inlineMessageId: String? = nil, query: String) { self.resultId = resultId self.from = from self.location = location self.inlineMessageId = inlineMessageId self.query = query } }
{ "pile_set_name": "Github" }
{ "types": { "EIP712Domain": [ { "name": "name", "type": "string" }, { "name": "version", "type": "string" }, { "name": "chainId", "type": "uint256" }, { "name": "verifyingContract", "type": "address" } ], "Foo": [ { "name": "addys", "type": "address[]" }, { "name": "stringies", "type": "string[]" }, { "name": "inties", "type": "uint[]" } ] }, "primaryType": "Foo", "domain": { "name": "Lorem", "version": "1", "chainId": "1", "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC" }, "message": { "addys": [ "0x0000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000003" ], "stringies": [ "lorem", "ipsum", "dolores" ], "inties": [ "0x0000000000000000000000000000000000000001", "3", 4.0 ] } }
{ "pile_set_name": "Github" }
// // SynchronizedSubscribeType.swift // RxSwift // // Created by Krunoslav Zaher on 10/25/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // protocol SynchronizedSubscribeType : class, ObservableType, Lock { func _synchronized_subscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E } extension SynchronizedSubscribeType { func synchronizedSubscribe<O: ObserverType>(_ observer: O) -> Disposable where O.E == E { lock(); defer { unlock() } return _synchronized_subscribe(observer) } }
{ "pile_set_name": "Github" }
class CreateImpressionJob < ApplicationJob queue_as :impression def perform(id, campaign_id, property_id, creative_id, ad_template, ad_theme, ip_address, country_code, user_agent, displayed_at_string) ScoutApm::Transaction.ignore! if rand > (ENV["SCOUT_SAMPLE_RATE"] || 1).to_f return unless user_agent campaign = Campaign.find_by(id: campaign_id) return unless campaign&.standard? property = Property.find_by(id: property_id) return unless property displayed_at = Time.parse(displayed_at_string) ip_info = Mmdb.lookup(ip_address) subdivision = ip_info&.subdivisions&.first&.iso_code province_code = Province.find("#{country_code}-#{subdivision}")&.iso_code impression = Impression.create!( id: id, advertiser_id: campaign.user_id, publisher_id: property.user_id, organization_id: campaign.organization_id, campaign: campaign, creative_id: creative_id, property: property, ad_template: ad_template, ad_theme: ad_theme, ip_address: ip_address, # NOTE: obfuscated via an Impression model callback user_agent: user_agent, displayed_at: displayed_at, displayed_at_date: displayed_at.to_date, fallback_campaign: campaign.fallback?, country_code: country_code, province_code: province_code, postal_code: ip_info&.postal&.code, latitude: ip_info&.location&.latitude, longitude: ip_info&.location&.longitude ) campaign.increment_hourly_consumed_budget_fractional_cents impression.estimated_gross_revenue_fractional_cents impression.track_event :impression_created rescue ActiveRecord::RecordNotUnique, ActiveRecord::NotNullViolation => e # prevent reattempts when a race condition attempts to write the same record # prevent reattempts when data is invalid Rollbar.error e end end
{ "pile_set_name": "Github" }
;- v0.3.1 ;********************* ;* * ;* * ;* MCI * ;* * ;* * ;********************* /* Each MCI function is documented separately. The following is general information that relates to the entire library. Notes ===== MCI Reference Guide: http://msdn.microsoft.com/en-us/library/ms709461(VS.85).aspx Devices referenced within the function documentation: Driver Type Description ------ ---- ----------- MCIAVI avivideo MCICDA cdaudio CD audio dat Digital-audio tape player digitalvideo Digital video in a window (not GDI-based) MPEGVideo General-purpose media player other Undefined MCI device overlay Overlay device (analog video in a window) scanner Image scanner MCISEQ sequencer MIDI sequencer vcr Video-cassette recorder or player MCIPIONR videodisc Videodisc (Pioneer LaserDisc) MCIWAVE waveaudio Audio device that plays digitized waveform files Programming Notes ================= OutputDebug statements in the core of some of the functions that only execute on condition are permanent and are provided to help the developer find and eliminate programming errors. Under normal conditions, these debugging statements should not slow down the operation of the functions because they "should" only execute when the developer has made a programming/logic error or if there are unusual conditions. Credit ====== - Original library released by Fincs as the "Sound_*" library and then as the "Media_*" library. The orginal libraries are a conversion-to-AutoHotkey from the AutoIt "Sound.au3" standard library written by RazerM. This library would not be possible without the significant effort by Fincs to translate and enhance the original library and RazerM for providing the original AutoIt library. Some of the code and documentation are from the libraries provided by Fincs: Post 1: http://www.autohotkey.com/forum/viewtopic.php?t=20666 Post 2: http://www.autohotkey.com/forum/viewtopic.php?t=22662 - Notify idea and code from Sean: Post: http://www.autohotkey.com/forum/viewtopic.php?p=132331#132331 - mciGetErrorString DLL function code from PhiLho: Post: http://www.autohotkey.com/forum/viewtopic.php?p=116011#116011 */ ;---------- ; ; Function: MCI_Open ; ; ; Description: ; ; Opens an MCI device and loads the specified file (p_MediaFile). ; ; ; Parameters: ; ; p_MediaFile - A multimedia file. [Required] ; ; p_Alias - Alias [Optional]. A name such as media1. If blank, an ; alias will automatically be generated. ; ; p_Flags - Flags that determine how the device is opened. [Optional] ; ; Some commonly used flags include the following: ; ; type {device_type} ; sharable ; ; If more than one flag is used, separate each flag/flag value with a ; space. For example: ; ; type MPEGVideo sharable ; ; Notes ; ----- ; - The "wait" flag is automatically added to the end of the ; command string. This flag directs the device to complete the ; "open" request before returning. ; ; ; - By default, the MCI device that is opened is determined by the ; file's extension. The "type" flag can be used to 1) override ; the default device that is registered for the file extension or ; to 2) open a media file with a file extension that is not ; registered as a MCI file extension. ; ; To see a list of MCI devices that have been registered for your ; computer, go the following registry locations: ; ; Windows NT4/2000/XP/2003/Vista/etc.: ; ; 16-bit: ; HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\MCI ; ; 32-bit: ; HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\MCI32 ; ; ; Windows 95/98/ME: ; ; HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\MediaResources\MCI ; ; ; To see a list of registered file extensions and the MCI device ; that has been assigned to each extension, go the following ; locations: ; ; For Windows NT4/2000/XP/2003/Vista, this information is ; stored in the registry at the following location: ; ; HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\MCI Extensions ; ; ; For Windows 95/98/ME, this information is stored in the ; %windir%\win.ini file in the "MCI Extensions" section. ; ; ; - Use the "shareable" flag with care. Per msdn, the "shareable" ; flag "initializes the device or file as shareable. Subsequent ; attempts to open the device or file fail unless you specify ; "shareable" in both the original and subsequent open commands. ; MCI returns an invalid device error if the device is already ; open and not shareable. The MCISEQ sequencer and MCIWAVE ; devices do not support shared files." ; ; ; - For a complete list of flags and descriptions for the "open" ; command string, see the "MCI Reference Guide" (link at the top ; of this library). ; ; ; Return value: ; ; Returns the multimedia handle (alias) or a 0 to indicate failure. ; Failure will occur with any of the following conditions: ; ; - The media file does not exist. ; ; - The media file's extension is not a regisitered MCI extension. ; Note: This test is only performed if the "type" flag is not ; specified. ; ; - Non-zero return code from the MCI_SendString function. ; ; ; Remarks: ; ; - Use the MCI_OpenCDAudio function to open a CDAudio device. ; ; - After the device has been successfully opened, this function sets the ; time format to milliseconds. This time format will remain in effect ; until it is manually set to another value or until the device is ; closed. ; ;------------------------------------------------------------------------------ MCI_Open(p_MediaFile,p_Alias="",p_Flags="") { Static s_Seq=0 ;[==============] ;[ Parameters ] ;[==============] ;-- p_MediaFile if p_MediaFile<>new { ;-- Media file exist? IfNotExist %p_MediaFile% { outputdebug, (ltrim join`s End Func: %A_ThisFunc%: The media file can't be found. Return=0 ) return false } ;-- "Type" flag not defined? if InStr(A_Space . p_Flags . A_Space," type ")=0 { ;-- Registered file extension? SplitPath p_MediaFile,,,l_Extension ;-- Which OS type? if A_OSType=WIN32_NT ;-- Windows NT4/2000/XP/2003/Vista RegRead ,l_Dummy ,HKEY_LOCAL_MACHINE ,SOFTWARE\Microsoft\Windows NT\CurrentVersion\MCI Extensions ,%l_Extension% else { ;-- Windows 95/98/ME iniRead ,l_Value ,%A_WinDir%\win.ini ,MCI Extensions ,%l_Extension% if l_Value=ERROR ErrorLevel=1 } ;-- Not found? if ErrorLevel { outputdebug, (ltrim join`s End Func: %A_ThisFunc%: The file extension for this media file is not registered as a valid MCI extension. Return=0 ) return false } } ;-- Enclose in DQ p_MediaFile="%p_MediaFile%" } ;-- Alias if p_Alias is Space { s_Seq++ p_Alias=MCIFile%s_Seq% } ;[===============] ;[ Open device ] ;[===============] l_CmdString=open %p_MediaFile% alias %p_Alias% %p_Flags% wait l_Return:=MCI_SendString(l_CmdString,Dummy) if l_Return l_Return:=0 else l_Return:=p_Alias ;-- Set time format to milliseconds if l_Return { l_CmdString=set %p_Alias% time format milliseconds wait MCI_SendString(l_CmdString,Dummy) } ;-- Return to sender return l_Return } ;---------- ; ; Function: MCI_OpenCDAudio ; ; ; Description: ; ; Opens a CDAudio device. ; ; ; Parameters: ; ; p_Drive - CDROM drive letter. [Optional] If blank, the first CDROM ; drive found is used. ; ; p_Alias - Alias. [optional] A name such as media1. If blank, an ; alias will automatically be generated. ; ; p_CheckForMedia - Check for media [Optional]. The default is TRUE. ; ; ; Return value: ; ; Returns the multimedia handle (alias) or a 0 to indicate failure. ; Failure will occur with any of the following conditions: ; - The computer does not have a CDROM drive. ; - The specified drive is not CDROM drive. ; - Non-zero return code from the MCI_SendString function. ; ; If p_CheckForMedia is TRUE (the default), failure will also occur with ; any of the following conditions: ; - No media was found in the device. ; - Media does not contain audio tracks. ; ; ; Remarks: ; ; After the device has been successfully opened, this function sets ; the time format to milliseconds. This time format will remain in effect ; until it is manually set to another value or until the device is closed. ; ;------------------------------------------------------------------------------ MCI_OpenCDAudio(p_Drive="",p_Alias="",p_CheckForMedia=true) { Static s_Seq=0 ;-- Parameters p_Drive=%p_Drive% ;-- Autotrim p_Drive:=SubStr(p_Drive,1,1) if p_Drive is not Alpha p_Drive:="" ;-- Drive not specified if p_Drive is Space { ;-- Collect list of CDROM drives DriveGet l_ListOfCDROMDrives,List,CDROM if l_ListOfCDROMDrives is Space { outputdebug, (ltrim join`s End Func: %A_ThisFunc%: This PC does not have functioning CDROM drive. Return=0 ) return false } ;-- Assign the first CDROM drive p_Drive:=SubStr(l_ListOfCDROMDrives,1,1) } ;-- Is this a CDROM drive? DriveGet l_DriveType,Type,%p_Drive%: if l_DriveType<>CDROM { outputdebug, (ltrim join`s End Func: %A_ThisFunc%: The specified drive (%p_Drive%:) is not a CDROM drive. Return=0 ) return false } ;-- Alias if p_Alias is Space { s_Seq++ p_Alias=MCICDAudio%s_Seq% } ;-- Open device l_CmdString=open %p_Drive%: alias %p_Alias% type cdaudio shareable wait l_Return:=MCI_SendString(l_CmdString,Dummy) if l_Return l_Return:=0 else l_Return:=p_Alias ;-- Device is open if l_Return { ;-- Set time format to milliseconds l_CmdString=set %p_Alias% time format milliseconds wait MCI_SendString(l_CmdString,Dummy) ;-- Check for media? if p_CheckForMedia { if not MCI_MediaIsPresent(p_Alias) { MCI_Close(p_Alias) outputdebug, (ltrim join`s End Func: %A_ThisFunc%: Media is not present in the specified drive (%p_Drive%:). Return=0 ) return false } ;-- 1st track an audio track? if not MCI_TrackIsAudio(p_Alias,1) { MCI_Close(p_Alias) outputdebug, (ltrim join`s End Func: %A_ThisFunc%: Media in drive %p_Drive%: does not contain CD Audio tracks. Return=0 ) return false } } } return l_Return } ;---------- ; ; Function: MCI_Close ; ; ; Description: ; ; Closes the device and any associated resources. ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; ; Return value: ; ; Returns the return code from the MCI_SendString function which is 0 ; if the command completed successfully. ; ; ; Remarks: ; ; Closing a device usually stops playback but not always. Consider ; stopping the device before closing it. ; ; ; ;------------------------------------------------------------------------------ MCI_Close(p_lpszDeviceID) { Static MM_MCINOTIFY:=0x03B9 ;-- Close device l_Return:=MCI_SendString("close " . p_lpszDeviceID . " wait",Dummy) ;-- Turn off monitoring of MM_MCINOTIFY message? if OnMessage(MM_MCINOTIFY)="MCI_Notify" { ;-- Don't proceed unless all MCI devices are closed MCI_SendString("sysinfo all quantity open",l_OpenMCIDevices) if l_OpenMCIDevices=0 { ;-- Disable monitoring OnMessage(MM_MCINOTIFY,"") } } return l_Return } ;---------- ; ; Function: MCI_Play ; ; ; Description: ; ; Starts playing a device. ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; p_Flags - Flags that determine how the device is played. [Optional] ; If blank, no flags are used. ; ; Some commonly used flags include the following: ; ; from {position} ; to {position} ; wait ; ; If more than one flag is used, separate each flag/flag value with a ; space. For example: ; ; from 10144 to 95455 wait ; ; Notes ; ----- ; - With the exception of very short sound files (<300 ms), the ; "wait" flag is not recommended. The entire application will be ; non-responsive while the media is being played. ; ; - Do not add the "notify" flag unless you plan to have your ; script trap the MM_MCINOTIFY message outside of this function. ; The "notify" flag is automatically added if the p_Callback ; parameter contains a value. ; ; - For a complete list of flags and descriptions for the "play" ; command string, see the "MCI Reference Guide" (link at the top ; of this library). ; ; ; p_Callback - Function name that is called when the MM_MCINOTIFY message ; is sent. [Optional]. If defined, the "notify" flag is automatically ; added. ; ; Important: The syntax of this parameter and the associated function ; is critical. If not defined correctly, the script may crash. ; ; The function must have at least one parameter. For example: ; ; MyNotifyFunction(NotifyFlag) ; ; Additional parameters are allowed but they must be optional (contain ; a default value). For example: ; ; MyNotifyFunction(NotifyFlag,FirstCall=false,Parm3="ABC") ; ; When a notify message is sent, the approriate MM_MCINOTIFY flag is ; sent to the developer-defined function as the first parameter. See ; the MCI_Notify function for a description and a list of MM_MCINOTIFY ; flag values. ; ; ; p_hWndCallback - Handle to a callback window if the p_Callback ; parameter contains a value and/or if the "notify" flag is defined ; [Optional]. If undefined but needed, the handle to default ; Autohotkey window is used. ; ; ; Return value: ; ; Returns the return code from the MCI_SendString function which is 0 ; if the command completed successfully. ; ;------------------------------------------------------------------------------ MCI_Play(p_lpszDeviceID,p_Flags="",p_Callback="",p_hwndCallback=0) { Static MM_MCINOTIFY:=0x03B9 ;-- Build command string l_CmdString:="play " . p_lpszDeviceID if p_Flags l_CmdString:=l_CmdString . A_Space . p_Flags ;-- Notify p_Callback=%p_Callback% ;-- AutoTrim if StrLen(p_Callback) { l_CmdString:=l_CmdString . " notify" ;-- Attach p_Callback to MCI_Notify function MCI_Notify(p_Callback,"","","") ;-- Monitor for MM_MCINOTIFY message OnMessage(MM_MCINOTIFY,"MCI_Notify") ;-- Note: If the MM_MCINOTIFY message was monitored elsewhere, ; this statement will override it. } ;-- Callback handle if not p_hwndCallback { if InStr(A_Space . l_CmdString . A_Space," notify ") or StrLen(p_Callback) { l_DetectHiddenWindows:=A_DetectHiddenWindows DetectHiddenWindows On Process Exist p_hwndCallback:=WinExist("ahk_pid " . ErrorLevel . " ahk_class AutoHotkey") DetectHiddenWindows %l_DetectHiddenWindows% } } ;-- Send it! l_return:=MCI_SendString(l_CmdString,Dummy,p_hwndCallback) return l_Return } ;---------- ; ; Function: MCI_Notify (Internal function. Do not call directly). ;-- Experimental ; ; ; Description: ; ; This function has 2 responsibilties: ; ; 1) If called by the MCI_Play function, wParam contains the name of the ; developer-defined function. This value is assigned to the ; s_Callback static variable for future use. ; ; 2) When called as a result of MM_MCINOTIFY message, this function will ; call the developer-defined function (name stored in the s_Callback ; static variable) sending the MM_MCINOTIFY status flag as the first ; parameter. ; ; ; Parameters: ; ; wParam - Function name or a MM_MCINOTIFY flag. MM_MCINOTIFY flag ; values are as follows: ; ; MCI_NOTIFY_SUCCESSFUL=0x1 ; The conditions initiating the callback function have been ; met. ; ; MCI_NOTIFY_SUPERSEDED=0x2 ; The device received another command with the "notify" flag ; set and the current conditions for initiating the callback ; function have been superseded. ; ; MCI_NOTIFY_ABORTED=0x4 ; The device received a command that prevented the current ; conditions for initiating the callback function from being ; met. If a new command interrupts the current command and ; it also requests notification, the device sends this ; message only and not MCI_NOTIFY_SUPERSEDED. ; ; MCI_NOTIFY_FAILURE=0x8 ; A device error occurred while the device was executing the ; command. ; ; lParam - lDevID. This is the identifier of the device initiating the ; callback function. This information is only useful if operating ; more than one MCI device at a time. ; ; ; Return value: ; ; Per msdn, returns 0 to indicate a successful call. ; ; ; Remarks: ; ; This function does not complete until the call to the developer-defined ; function has completed. If a MM_MCINOTIFY message is issued while this ; function is running, the message will be treated as unmonitored. ; ;------------------------------------------------------------------------------ MCI_Notify(wParam,lParam,msg,hWnd) { ;;;;; Critical ;-- This will cause MM_MCINOTIFY messages to be buffered rather than ; discared if this function is still running when another MM_MCINOTIFY ; message is sent. Static s_Callback ;-- Internal call? if lParam is Space { s_Callback:=wParam return } ;-- Call developer function if s_Callback is not Space %s_Callback%(wParam) return 0 } ;---------- ; ; Function: MCI_Stop ; ; ; Description: ; ; Stops playback or recording. ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; ; Return value: ; ; Returns the return code from the MCI_SendString function which is 0 ; if the command completed successfully. ; ; ; Remarks: ; ; - After close, a "seek to start" is not done because 1) it slows down the ; the stop request and 2) it may be unwanted. If you need to set the ; media position back to the beginning after a stop, call the MCI_Seek ; function and set the p_Position parameter to 0. ; ; - For (some) CD audio devices, the stop command stops playback and resets ; the current track position to zero. ; ;------------------------------------------------------------------------------ MCI_Stop(p_lpszDeviceID) { l_Return:=MCI_SendString("stop " . p_lpszDeviceID . " wait",Dummy) return l_Return } ;---------- ; ; Function: MCI_Pause ; ; ; Description: ; ; Pauses playback or recording. ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; ; Return value: ; ; Returns the return code from the MCI_SendString function which is 0 ; if the command completed successfully. ; ; ; Remarks: ; ; msdn: With the MCICDA, MCISEQ, and MCIPIONR drivers, the pause command ; works the same as the stop command. ; ; Observation: For MCISEQ devices, pause works OK for me. ; ;------------------------------------------------------------------------------ MCI_Pause(p_lpszDeviceID) { l_Return:=MCI_SendString("pause " . p_lpszDeviceID . " wait",Dummy) return l_Return } ;---------- ; ; Function: MCI_Resume ; ; ; Description: ; ; Resumes playback or recording after the device has been paused (see the ; MCI_Pause function). ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; ; Return value: ; ; Returns the return code from the MCI_SendString function which is 0 ; if the command completed successfully. ; ; ; Remarks: ; ; msdn: Digital-video, VCR, and waveform-audio devices recognize this ; command. Although CD audio, MIDI sequencer, and videodisc devices ; also recognize this command, the MCICDA, MCISEQ, and MCIPIONR device ; drivers do not support it. ; ; ; Programming notes: ; ; An alternative to this command is the MCI_Play command. Many devices ; will begin to play where they were last paused. If the device does not ; begin playback correctly, try specifying an appropriate "From" ; and "To" value (if needed) in the p_Flags parameter. ; ;------------------------------------------------------------------------------ MCI_Resume(p_lpszDeviceID) { l_Return:=MCI_SendString("resume " . p_lpszDeviceID . " wait",Dummy) return l_Return } ;---------- ; ; Function: MCI_Record ; ; ; Description: ; ; Starts recording. ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; p_Flags - Flags that determine how the device operates for ; recording. [Optional] If blank, no flags are used. ; ; Some commonly used flags include the following: ; ; from {position} ; to {position} ; insert ; overwrite ; ; If more than one flag is used, separate each flag/flag value with a ; space. For example: ; ; overwrite from 18122 to 26427 ; ; ; Notes ; ----- ; - The "wait" flag is not recommended. The entire application will ; be non-responsive until recording is stopped with a Stop or ; Pause command. ; ; - For a complete list of flags and descriptions for the "record" ; command string, see the "MCI Reference Guide" (link at the top ; of this library). ; ; ; Return value: ; ; Returns the return code from the MCI_SendString function which is 0 ; if the command completed successfully. ; ; ; Remarks: ; ; msdn: Recording stops when a Stop or Pause command is issued. For the ; MCIWAVE driver, all data recorded after a file is opened is discarded if ; the file is closed without saving it. ; ; ; Credit: ; ; Original function and examples by heresy. ; ;------------------------------------------------------------------------------ MCI_Record(p_lpszDeviceID,p_Flags="") { l_CmdString=record %p_lpszDeviceID% %p_Flags% l_Return:=MCI_SendString(l_CmdString,Dummy) return l_Return } ;---------- ; ; Function: MCI_Save ; ; ; Description: ; ; Saves an MCI file. ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; p_FileName - File name to store a MCI file. [Required] If the file ; does not exist, a new file will be created. If the file exists, it ; will be overwritten. ; ; ; Return value: ; ; Returns the return code from the MCI_SendString function which is 0 ; if the command completed successfully. ; ; ; Remarks: ; ; This command can overwrite existing files. Use with care. ; ; ; Credit: ; ; Original function and examples by heresy. ; ;------------------------------------------------------------------------------ MCI_Save(p_lpszDeviceID,p_FileName) { l_CmdString=save %p_lpszDeviceID% "%p_FileName%" l_Return:=MCI_SendString(l_CmdString,Dummy) return l_Return } ;---------- ; ; Function: MCI_Seek ; ; ; Description: ; ; Move to a specified position. ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; p_Position - Position to stop the seek. [Required] Value must be ; "start", "end", or an integer. ; ; ; Return value: ; ; Returns the return code from the MCI_SendString function which is 0 ; if the command completed successfully. ; ;------------------------------------------------------------------------------ /* Usage and Programming notes: MCI Bug?: For some reason, seek for cdaudio doesn't work correctly on the first attempt. Second and susequent attempts work fine. */ MCI_Seek(p_lpszDeviceID,p_Position) { ;-- Get current status l_Status:=MCI_Status(p_lpszDeviceID) ;-- Adjust p_Position if necessary if p_Position not in start,end { if p_Position is not Number p_Position=0 p_Position:=Round(p_Position) ;-- Integer values only if (p_Position>MCI_Length(p_lpszDeviceID)) p_Position:="end" else if p_Position<1 p_Position:="start" ;-- This is necessary because some devices don't like a "0" ; position. } ;-- Seek l_CmdString=seek %p_lpszDeviceID% to %p_Position% wait l_Return:=MCI_SendString(l_CmdString,Dummy) ;-- Return to mode before seek if l_Status in paused,playing { MCI_Play(p_lpszDeviceID) ;-- Re-pause if l_Status=paused MCI_Pause(p_lpszDeviceID) } l_CurrentPos:=MCI_Position(p_lpszDeviceID) ;-- Return to sender return l_Return } ;---------- ; ; Function: MCI_Length ; ; ; Description: ; ; Returns the total length of the media in the current time format. ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; p_Track - Track number. [Optional] The default is 0 (no track number). ; ; ; Return value: ; ; If a track number is not specified (the default), the length of the ; entire media is returned. If a track number is specified, only the ; the length of the specified track is returned. ; ;------------------------------------------------------------------------------ MCI_Length(p_lpszDeviceID,p_Track=0) { ;-- Build command string l_CmdString:="status " . p_lpszDeviceID . " length" if p_Track l_CmdString:=l_CmdString . " track " . p_Track ;-- Send it! MCI_SendString(l_CmdString,l_lpszReturnString) return l_lpszReturnString } ;---------- ; ; Function: MCI_Status ; ; ; Description: ; ; Identifies the current mode of the device. ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; ; Return value: ; ; Returns the current mode of the device. ; ; msdn: All devices can return the "not ready", "paused", "playing", and ; "stopped" values. Some devices can return the additional "open", ; "parked", "recording", and "seeking" values. ; ;------------------------------------------------------------------------------ MCI_Status(p_lpszDeviceID) { MCI_SendString("status " . p_lpszDeviceID . " mode",l_lpszReturnString) return l_lpszReturnString } ;---------- ; ; Function: MCI_Position ; ; ; Description: ; ; Identifies the current playback or recording position. ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; p_Track - Track number. [Optional] The default is 0 (no track number). ; ; ; Return value: ; ; Returns the current playback or recording position in the current time ; format. If the p_Track parameter contains a non-zero value, returns the ; start position of the track relative to entire media. ; ;------------------------------------------------------------------------------ MCI_Position(p_lpszDeviceID,p_Track=0) { ;-- Build command string l_CmdString:="status " . p_lpszDeviceID . " position" if p_Track l_CmdString:=l_CmdString . " track " . p_Track ;-- Send it! MCI_SendString(l_CmdString,l_lpszReturnString) return l_lpszReturnString } ;---------- ; ; Function: MCI_DeviceType ; ; ; Description: ; ; Identifies the device type name. ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; ; Return value: ; ; Returns a device type name, which can be one of the following: ; ; cdaudio ; dat ; digitalvideo ; other ; overlay ; scanner ; sequencer ; vcr ; videodisc ; waveaudio ; ;------------------------------------------------------------------------------ MCI_DeviceType(p_lpszDeviceID) { l_CmdString=capability %p_lpszDeviceID% device type MCI_SendString(l_CmdString,l_lpszReturnString) return l_lpszReturnString } ;---------- ; ; Function: MCI_MediaIsPresent ; ; ; Description: ; ; Checks to see if media is present in the device. ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; ; Return value: ; ; Returns TRUE if the media is inserted in the device or FALSE otherwise. ; ; msdn: Sequencer, video-overlay, digital-video, and waveform-audio ; devices (always) return TRUE. ; ;------------------------------------------------------------------------------ MCI_MediaIsPresent(p_lpszDeviceID) { l_CmdString=status %p_lpszDeviceID% media present l_RC:=MCI_SendString(l_CmdString,l_lpszReturnString) if l_RC ;-- Probably invalid command for the device l_Return:=false else if (l_lpszReturnString="true") l_Return:=true else l_Return:=false return l_Return } ;---------- ; ; Function: MCI_TrackIsAudio ; ; Description: ; ; Determines if the specified track is an audio track. ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; p_Track - Track number. [Optional] The default is 1. ; ; ; Return value: ; ; Returns TRUE if the specified track is an audio track otherwise returns ; FALSE. ; ; ; Remarks: ; ; This command will only work on a device that supports multiple tracks. ; ;------------------------------------------------------------------------------ MCI_TrackIsAudio(p_lpszDeviceID,p_Track=1) { if p_Track is not Integer p_Track=1 l_CmdString=status %p_lpszDeviceID% type track %p_Track% l_RC:=MCI_SendString(l_CmdString,l_lpszReturnString) if l_RC ;-- Probably invalid command for the device l_Return:=false else if l_lpszReturnString=audio l_Return:=true else l_Return:=false return l_Return } ;---------- ; ; Function: MCI_CurrentTrack ; ; ; Description: ; ; Identifies the current track. ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; ; Return value: ; ; Returns the current track. The MCISEQ sequencer returns 1. ; ;------------------------------------------------------------------------------ MCI_CurrentTrack(p_lpszDeviceID) { l_CmdString:="status " . p_lpszDeviceID . " current track" l_Return:=MCI_SendString(l_CmdString,l_lpszReturnString) return l_lpszReturnString } ;---------- ; ; Function: MCI_NumberOfTracks ; ; ; Description: ; ; Identifies the number of tracks on the media. ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; ; Return value: ; ; Returns the number of tracks on the media. ; ; ; Remarks: ; ; msdn: The MCISEQ and MCIWAVE devices return 1, as do most VCR devices. ; The MCIPIONR device does not support this flag. ; ;------------------------------------------------------------------------------ MCI_NumberOfTracks(p_lpszDeviceID) { l_CmdString:="status " . p_lpszDeviceID . " number of tracks" l_Return:=MCI_SendString(l_CmdString,l_lpszReturnString) return l_lpszReturnString } ;---------- ; ; Function: MCI_SetVolume ; ; ; Description: ; ; Sets the average audio volume for both audio channels. If the left and ; right volumes have been set to different values, then the ratio of ; left-to-right volume is approximately unchanged. ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; p_Factor - Volume factor [Required] ; ; ; Return value: ; ; Returns the return code from the MCI_SendString function which is 0 ; if the command completed successfully. ; ; ; Observations: ; ; - Factor range appears to be from 0 to 1000. ; - Most MCI devices do not support this command. ; ;------------------------------------------------------------------------------ MCI_SetVolume(p_lpszDeviceID,p_Factor) { l_CmdString:="setaudio " . p_lpszDeviceID . " volume to " . p_Factor l_Return:=MCI_SendString(l_CmdString,Dummy) return l_Return } ;---------- ; ; Function: MCI_SetBass ; ; ; Description: ; ; Sets the audio low frequency level. ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; p_Factor - Bass factor [Require] ; ; ; Return value: ; ; Returns the return code from the MCI_SendString function which is 0 ; if the command completed successfully. ; ; ; Observations: ; ; - Factor range appears to be from 0 to ?????. ; - Most MCI devices do not support this command. ; ;------------------------------------------------------------------------------ MCI_SetBass(p_lpszDeviceID,p_Factor) { l_CmdString:="setaudio " . p_lpszDeviceID . " bass to " . p_Factor l_Return:=MCI_SendString(l_CmdString,Dummy) return l_lpszReturnString } ;---------- ; ; Function: MCI_SetTreble ; ; Description: ; ; Sets the audio high-frequency level. ; ; ; Parameters: ; ; p_lpszDeviceID - Device name or alias. [Required] ; ; p_Factor - Treble factor [Required] ; ; ; Return value: ; ; Returns the return code from the MCI_SendString function which is 0 ; if the command completed successfully. ; ; ; Observations: ; ; - Factor range appears to be from 0 to ?????. ; - Most MCI devices do not support this command. ; ;------------------------------------------------------------------------------ MCI_SetTreble(p_lpszDeviceID,p_Factor) { l_CmdString:="setaudio " . p_lpszDeviceID . " treble to " . p_Factor l_Return:=MCI_SendString(l_CmdString,Dummy) return l_lpszReturnString } ;---------- ; ; Function: MCI_ToMilliseconds ; ; ; Description: ; ; Converts the specified hour, minute and second into a valid milliseconds ; timestamp. ; ; ; Parameters: ; ; Hour, Min, Sec - Position to convert to milliseconds ; ; ; Return value: ; ; The specified position converted to milliseconds. ; ;------------------------------------------------------------------------------ MCI_ToMilliseconds(Hour,Min,Sec) { milli:=Sec*1000 milli += (Min*60)*1000 milli += (Hour*3600)*1000 return milli } ;---------- ; ; Function: MCI_ToHHMMSS ; ; ; Description: ; ; Converts the specified number of milliseconds to hh:mm:ss format. ; ; ; Parameters: ; ; p_ms - Number of milliseconds. [Required] ; ; p_MinimumSize - Minimum size. [Optional] The default is 4. This is ; the minimum size in characters (not significant digits) that you ; want returned. Unless you want a ":" character to show as the ; leading character, don't set this value to 3 or 6. ; ; ; Return value: ; ; Returns the amount of time in hh:mm:ss format with leading zero and ":" ; characters suppressed unless the length is less than p_MinimumSize. ; ; Note: If the number of hours is greater than 99, the size of hour ; ("hh") will increase as needed. ; ; ; Usage Notes: ; ; To use this function to create separate variables for the number of ; hours, minutes, and seconds, set the p_MinimumSize parameter to 8 and ; use simple SubStr commands to create these variables. For example: ; ; x:=MCI_ToHHMMSS(NumberOfMilliseconds,8) ; HH:=SubStr(x,1,2) ; MM:=SubStr(x,4,2) ; SS:=SubStr(x,6,2) ; ; To remove leading zeros from these variables, simply add 0 to the ; extracted value. For example: ; ; MM:=SubStr(x,4,2)+0 ; ; ; Credit: ; ; This function is a customized version of an example that was extracted ; from the AutoHotkey documenation. ; ;------------------------------------------------------------------------------ MCI_ToHHMMSS(p_ms,p_MinimumSize=4) { ;-- Convert p_ms to whole seconds if p_ms is not Number l_Seconds=0 else if p_ms<0 l_Seconds=0 else l_Seconds:=floor(p_ms/1000) ;-- Initialize and format l_Time=20121212 ;-- Midnight of an arbitrary date EnvAdd l_Time,l_Seconds,Seconds FormatTime l_mmss,%l_Time%,mm:ss l_FormattedTime:="0" . l_Seconds//3600 . ":" . l_mmss ;-- Allows support for more than 24 hours. ;-- Trim insignificant leading characters loop if StrLen(l_FormattedTime)<=p_MinimumSize break else if SubStr(l_FormattedTime,1,1)="0" StringTrimLeft l_FormattedTime,l_FormattedTime,1 else if SubStr(l_FormattedTime,1,1)=":" StringTrimLeft l_FormattedTime,l_FormattedTime,1 else break ;-- Return to sender return l_FormattedTime } ;---------- ; ; Function: MCI_SendString ; ; ; Description: ; ; This is the primary function that controls MCI operations. With the ; exception of the formatting functions, all of the functions in this ; library call this function. ; ; ; Parameters: ; ; p_lpszCommand - MCI command string. [Required] ; ; p_lpszReturnString - Variable name that receives return information. ; [Required] ; ; p_hwndCallback - Handle to a callback window if the "notify" flag was ; specified in the command string. [Optional] The default is 0 ; (No callback window). ; ; ; Return value: ; ; Two values are returned: ; ; 1) The function returns zero if successful or an error number ; otherwise. See the "Debugging" section for more information. ; ; 2) If the MCI command string was a request for information, the ; variable named in the p_lpszReturnString parameter will contain the ; requested information. ; ; ; Debugging: ; ; If a non-zero value is returned from the call to the mciSendString ; function, a call to the mciGetErrorString function is made to convert ; the error number into a developer-friendly error message. All of this ; information is sent to the debugger in an easy-to-read format. ; ;------------------------------------------------------------------------------ MCI_SendString(p_lpszCommand,ByRef p_lpszReturnString,p_hwndCallback=0) { VarSetCapacity(p_lpszReturnString,100,0) l_Return:=DllCall("winmm.dll\mciSendStringA" ,"str",p_lpszCommand ;-- lpszCommand ,"str",p_lpszReturnString ;-- lpszReturnString ,"uint",100 ;-- cchReturn ,"uint",p_hwndCallback ;-- hwndCallback ,"Cdecl int") ;-- Return type if ErrorLevel MsgBox ,262160 ;-- 262160=0 (OK button) + 16 (Error icon) + 262144 (AOT) ,%A_ThisFunc% Function Error, (ltrim join`s Unexpected ErrorLevel from DllCall to the "winmm.dll\mciSendStringA" function. ErrorLevel=%ErrorLevel% %A_Space% `nSee the AutoHotkey documentation (Keyword: DLLCall) for more information. %A_Space% ) ;-- Return code? if l_Return { VarSetCapacity(l_MCIErrorString,1024) DllCall("winmm\mciGetErrorStringA" ,"uint",l_Return ;-- MCI error number ,"str",l_MCIErrorString ;-- MCI error text ,"uint",1024) ;-- This is provided to help debug MCI calls outputdebug, (ltrim join`s End Func: %A_ThisFunc%: Unexpected return code from command string: "%p_lpszCommand%" `n--------- Return code=%l_Return% - %l_MCIErrorString% ) } return l_Return }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: c3da7902c633f184dae4130069be1575 timeCreated: 1517675872 licenseType: Free TextureImporter: fileIDToRecycleName: {} serializedVersion: 4 mipmaps: mipMapMode: 0 enableMipMap: 1 sRGBTexture: 1 linearTexture: 0 fadeOut: 0 borderMipMap: 0 mipMapsPreserveCoverage: 0 alphaTestReferenceValue: 0.5 mipMapFadeDistanceStart: 1 mipMapFadeDistanceEnd: 3 bumpmap: convertToNormalMap: 0 externalNormalMap: 0 heightScale: 0.25 normalMapFilter: 0 isReadable: 0 grayScaleToAlpha: 0 generateCubemap: 6 cubemapConvolution: 0 seamlessCubemap: 0 textureFormat: 1 maxTextureSize: 2048 textureSettings: serializedVersion: 2 filterMode: -1 aniso: -1 mipBias: -1 wrapU: -1 wrapV: -1 wrapW: -1 nPOTScale: 1 lightmap: 0 compressionQuality: 50 spriteMode: 0 spriteExtrude: 1 spriteMeshType: 1 alignment: 0 spritePivot: {x: 0.5, y: 0.5} spriteBorder: {x: 0, y: 0, z: 0, w: 0} spritePixelsToUnits: 100 alphaUsage: 1 alphaIsTransparency: 0 spriteTessellationDetail: -1 textureType: 0 textureShape: 1 maxTextureSizeSet: 0 compressionQualitySet: 0 textureFormatSet: 0 platformSettings: - buildTarget: DefaultTexturePlatform maxTextureSize: 2048 textureFormat: -1 textureCompression: 1 compressionQuality: 50 crunchedCompression: 0 allowsAlphaSplitting: 0 overridden: 0 spriteSheet: serializedVersion: 2 sprites: [] outline: [] physicsShape: [] spritePackingTag: userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
--- layout: default title: installation --- # Installation cvui is a header-only lib, so there is no real need to install it. All you have to do is place the `cvui.h` (or `cvui.py`) file along with the rest of your source code and compile/run your project. Check the [usage page]({{ site.url }}/usage) to learn how to use cvui. ## Note to Python users The Python version of cvui, i.e. `cvui.py`, can be conveniently installed using `pip`: ``` pip install cvui ```
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 1378a33cdd085d64c9da863d2484ff21 timeCreated: 1485107928 licenseType: Pro TextureImporter: fileIDToRecycleName: {} serializedVersion: 4 mipmaps: mipMapMode: 0 enableMipMap: 0 sRGBTexture: 0 linearTexture: 0 fadeOut: 0 borderMipMap: 0 mipMapFadeDistanceStart: 1 mipMapFadeDistanceEnd: 3 bumpmap: convertToNormalMap: 0 externalNormalMap: 0 heightScale: 0.25 normalMapFilter: 0 isReadable: 0 grayScaleToAlpha: 0 generateCubemap: 6 cubemapConvolution: 0 seamlessCubemap: 0 textureFormat: 1 maxTextureSize: 2048 textureSettings: filterMode: 0 aniso: -1 mipBias: -1 wrapMode: 0 nPOTScale: 1 lightmap: 0 compressionQuality: 50 spriteMode: 0 spriteExtrude: 1 spriteMeshType: 1 alignment: 0 spritePivot: {x: 0.5, y: 0.5} spriteBorder: {x: 0, y: 0, z: 0, w: 0} spritePixelsToUnits: 100 alphaUsage: 2 alphaIsTransparency: 0 spriteTessellationDetail: -1 textureType: 10 textureShape: 1 maxTextureSizeSet: 0 compressionQualitySet: 0 textureFormatSet: 0 platformSettings: - buildTarget: DefaultTexturePlatform maxTextureSize: 64 textureFormat: -1 textureCompression: 0 compressionQuality: 50 crunchedCompression: 0 allowsAlphaSplitting: 0 overridden: 0 - buildTarget: Standalone maxTextureSize: 64 textureFormat: -1 textureCompression: 0 compressionQuality: 50 crunchedCompression: 0 allowsAlphaSplitting: 0 overridden: 0 spriteSheet: serializedVersion: 2 sprites: [] outline: [] spritePackingTag: userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Format: //devtools/kokoro/config/proto/build.proto # Build logs will be here action { define_artifacts { regex: "**/*sponge_log.xml" } } # Download secrets from Cloud Storage. gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/cloud-code-samples" # Download trampoline resources. gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" # Use the trampoline script to run in docker. build_file: "cloud-code-samples/.kokoro/trampoline.sh" # Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" value: "gcr.io/cloud-devrel-kokoro-resources/java8" } env_vars: { key: "TRAMPOLINE_BUILD_FILE" value: "github/cloud-code-samples/.kokoro/test.sh" }
{ "pile_set_name": "Github" }
# frozen_string_literal: true require 'spec_helper' describe 'show.html.erb' do include_context 'action view' let(:assigns) { {model: Model1.new(field: 'foo')} } it { is_expected.to include 'foo' } end
{ "pile_set_name": "Github" }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #import <React/RCTViewManager.h> NS_ASSUME_NONNULL_BEGIN @interface RCTSafeAreaViewManager : RCTViewManager @end NS_ASSUME_NONNULL_END
{ "pile_set_name": "Github" }
// +build !arm,!ppc64 package netlink func ifrDataByte(b byte) int8 { return int8(b) }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2012-2018 Red Hat, Inc. * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.selenium.pageobject.dashboard; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toMap; import static org.eclipse.che.selenium.core.constant.TestTimeoutsConstants.LOAD_PAGE_TIMEOUT_SEC; import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.ADD_BUTTON_ID; import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.ADD_OR_CANCEL_BUTTON_XPATH_TEMPLATE; import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.ADD_OR_IMPORT_PROJECT_BUTTON_ID; import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.BLANK_BUTTON_ID; import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.BLANK_FORM_DESCRIPTION_FIELD_XPATH; import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.BLANK_FORM_NAME_ERROR_MESSAGE_XPATH; import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.BLANK_FORM_NAME_FIELD_XPATH; import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.CANCEL_BUTTON_ID; import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.CHECKBOX_BY_SAMPLE_NAME_ID_TEMPLATE; import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.GITHUG_BUTTON_ID; import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.GIT_BUTTON_ID; import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.SAMPLES_BUTTON_ID; import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.TOOLTIP_XPATH_TEMPLATE; import static org.eclipse.che.selenium.pageobject.dashboard.AddOrImportForm.Locators.ZIP_BUTTON_ID; import com.google.inject.Inject; import com.google.inject.Singleton; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.che.selenium.core.SeleniumWebDriver; import org.eclipse.che.selenium.core.webdriver.SeleniumWebDriverHelper; import org.eclipse.che.selenium.core.webdriver.WebDriverWaitFactory; import org.openqa.selenium.By; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedCondition; /** @author Ihor Okhrimenko */ @Singleton public class AddOrImportForm { private final SeleniumWebDriver seleniumWebDriver; private final SeleniumWebDriverHelper seleniumWebDriverHelper; private final WebDriverWaitFactory webDriverWaitFactory; private static final int DEFAULT_TIMEOUT = LOAD_PAGE_TIMEOUT_SEC; @Inject AddOrImportForm( SeleniumWebDriver seleniumWebDriver, SeleniumWebDriverHelper seleniumWebDriverHelper, WebDriverWaitFactory webDriverWaitFactory) { this.seleniumWebDriver = seleniumWebDriver; this.seleniumWebDriverHelper = seleniumWebDriverHelper; this.webDriverWaitFactory = webDriverWaitFactory; PageFactory.initElements(seleniumWebDriver, this); } public interface Locators { String ADD_OR_IMPORT_PROJECT_BUTTON_ID = "ADD_PROJECT"; String ADD_OR_CANCEL_BUTTON_XPATH_TEMPLATE = "//*[@id='%s']/button"; // "Add or Import Project" form buttons String SAMPLES_BUTTON_ID = "samples-button"; String BLANK_BUTTON_ID = "blank-button"; String GIT_BUTTON_ID = "git-button"; String GITHUG_BUTTON_ID = "github-button"; String ZIP_BUTTON_ID = "zip-button"; String ADD_BUTTON_ID = "add-project-button"; String CANCEL_BUTTON_ID = "cancel-button"; String CHECKBOX_BY_SAMPLE_NAME_ID_TEMPLATE = "sample-%s"; String PROJECT_TAB_XPATH_TEMPLATE = "//toggle-single-button[@id='%s']/div/button/div"; String PROJECT_TAB_BY_NAME_XPATH_TEMPLATE = "//div[@class='%s']//span[text()='console-java-simple']"; // Blank tab fields String BLANK_FORM_NAME_FIELD_XPATH = "//input[@name='name']"; String BLANK_FORM_DESCRIPTION_FIELD_XPATH = "//input[@name='description']"; String BLANK_FORM_NAME_ERROR_MESSAGE_XPATH = "//div[@id='project-source-selector']//div[@id='new-workspace-error-message']/div"; String TOOLTIP_XPATH_TEMPLATE = "//*[contains(@class, 'tooltip') and @content='%s']"; } public WebElement waitAddOrImportProjectButton(int timeout) { return seleniumWebDriverHelper.waitVisibility(By.id(ADD_OR_IMPORT_PROJECT_BUTTON_ID), timeout); } public WebElement waitAddOrImportProjectButton() { return waitAddOrImportProjectButton(DEFAULT_TIMEOUT); } public void clickOnAddOrImportProjectButton() { waitAddOrImportProjectButton().click(); } public void clickOnSamplesButton() { seleniumWebDriverHelper.waitAndClick(By.id(SAMPLES_BUTTON_ID)); } public void clickOnBlankButton() { seleniumWebDriverHelper.waitAndClick(By.id(BLANK_BUTTON_ID)); } public void clickOnGitButton() { seleniumWebDriverHelper.waitAndClick(By.id(GIT_BUTTON_ID)); } public void clickOnGitHubButton() { seleniumWebDriverHelper.waitAndClick(By.id(GITHUG_BUTTON_ID)); } public void clickOnZipButton() { seleniumWebDriverHelper.waitAndClick(By.id(ZIP_BUTTON_ID)); } public void clickOnAddButton() { seleniumWebDriverHelper.waitAndClick(By.id(ADD_BUTTON_ID)); } public void addSampleToWorkspace(String sampleName) { waitAddOrImportFormOpened(); if (!isSampleCheckboxEnabled(sampleName)) { clickOnSampleCheckbox(sampleName); } waitSampleCheckboxEnabled(sampleName); clickOnAddButton(); waitProjectTabAppearance(sampleName); } public void clickOnCancelButton() { seleniumWebDriverHelper.waitAndClick(By.id(CANCEL_BUTTON_ID)); } public void waitAddOrImportFormOpened() { seleniumWebDriverHelper.waitAllVisibilityBy( asList( By.id(SAMPLES_BUTTON_ID), By.id(BLANK_BUTTON_ID), By.id(GIT_BUTTON_ID), By.id(GITHUG_BUTTON_ID), By.id(ZIP_BUTTON_ID), By.id(ADD_BUTTON_ID), By.id(CANCEL_BUTTON_ID))); } public void waitAddOrImportFormClosed() { seleniumWebDriverHelper.waitAllInvisibilityBy( asList( By.id(SAMPLES_BUTTON_ID), By.id(BLANK_BUTTON_ID), By.id(GIT_BUTTON_ID), By.id(GITHUG_BUTTON_ID), By.id(ZIP_BUTTON_ID), By.id(ADD_BUTTON_ID), By.id(CANCEL_BUTTON_ID))); } private void waitSelectionOfHeaderButton(String buttonId) { String locator = format("//che-toggle-joined-button[@id='%s']/button", buttonId); seleniumWebDriverHelper.waitAttributeContainsValue( By.xpath(locator), "class", "che-toggle-button-enabled"); } public void waitSamplesButtonSelected() { waitSelectionOfHeaderButton(SAMPLES_BUTTON_ID); } public void waitBlankButtonSelected() { waitSelectionOfHeaderButton(BLANK_BUTTON_ID); } public void waitGitButtonSelected() { waitSelectionOfHeaderButton(GIT_BUTTON_ID); } public void waitGitHubButtonSelected() { waitSelectionOfHeaderButton(GITHUG_BUTTON_ID); } public void waitZipButtonSelected() { waitSelectionOfHeaderButton(ZIP_BUTTON_ID); } private void waitButtonDisableState(WebElement button, boolean state) { seleniumWebDriverHelper.waitAttributeEqualsTo(button, "aria-disabled", Boolean.toString(state)); } private WebElement waitAddButton() { return seleniumWebDriverHelper.waitVisibility( By.xpath(format(ADD_OR_CANCEL_BUTTON_XPATH_TEMPLATE, ADD_BUTTON_ID))); } private WebElement waitCancelButton() { return seleniumWebDriverHelper.waitVisibility( By.xpath(format(ADD_OR_CANCEL_BUTTON_XPATH_TEMPLATE, CANCEL_BUTTON_ID))); } public void waitAddButtonDisabled() { waitButtonDisableState(waitAddButton(), true); } public void waitCancelButtonDisabled() { waitButtonDisableState(waitCancelButton(), true); } public void waitAddButtonEnabled() { waitButtonDisableState(waitAddButton(), false); } public void waitCancelButtonEnabled() { waitButtonDisableState(waitCancelButton(), false); } public void waitGitTabOpened() { waitGitButtonSelected(); waitGitUrlField(); } public WebElement waitGitUrlField() { return seleniumWebDriverHelper.waitVisibility(waitElementByNameAttribute("remoteGitURL")); } public void typeToGitUrlField(String text) { seleniumWebDriverHelper.setValue(waitGitUrlField(), text); } public WebElement waitConnectYourGithubAccountButton() { return seleniumWebDriverHelper.waitVisibility( By.xpath("//*[@id='import-github-project-button']/*[contains(@class, 'che-button')]")); } public void clickConnectYourGithubAccountButton() { seleniumWebDriverHelper.waitAndClick(waitConnectYourGithubAccountButton()); } private WebElement waitElementByNameAttribute(String nameAttribute) { return seleniumWebDriverHelper.waitVisibility( By.xpath(format("//input[@name='%s']", nameAttribute))); } private void waitTextInTooltip(String expectedText) { seleniumWebDriverHelper.waitTextEqualsTo( By.xpath(format(TOOLTIP_XPATH_TEMPLATE, expectedText)), expectedText); } public void clickOnProjectTab(String tabName) { waitProjectTabAppearance(tabName); seleniumWebDriverHelper.moveCursorTo(By.id(tabName)); try { waitTextInTooltip(tabName); } catch (TimeoutException ex) { // sometimes the tooltip does not display on the CI } seleniumWebDriverHelper.waitAndClick(By.id(tabName)); } private List<WebElement> getSamples() { return seleniumWebDriverHelper.waitVisibilityOfAllElements( By.xpath("//div[@class='add-import-project-sources']//md-item")); } private String getSampleName(WebElement samplesItem) { return asList(seleniumWebDriverHelper.waitVisibilityAndGetText(samplesItem).split("\n")).get(0); } private String getSampleDescription(WebElement samplesItem) { return asList(seleniumWebDriverHelper.waitVisibilityAndGetText(samplesItem).split("\n")).get(1); } private Map<String, String> getSamplesNamesAndDescriptions() { return getSamples() .stream() .collect( toMap(element -> getSampleName(element), element -> getSampleDescription(element))); } public Set<String> getSamplesNames() { return getSamplesNamesAndDescriptions().keySet(); } public String getSampleDescription(String sampleName) { return getSamplesNamesAndDescriptions().get(sampleName); } public void waitSamplesWithDescriptions(Map<String, String> expectedSamplesWithDescriptions) { webDriverWaitFactory .get() .until( (ExpectedCondition<Boolean>) driver -> expectedSamplesWithDescriptions.equals(getSamplesNamesAndDescriptions())); } public void clickOnSampleCheckbox(String sampleName) { String checkboxId = format(CHECKBOX_BY_SAMPLE_NAME_ID_TEMPLATE, sampleName); seleniumWebDriverHelper.waitAndClick( By.xpath(format("//*[@id='%s']/md-checkbox/div", checkboxId))); } public boolean isSampleCheckboxEnabled(String sampleName) { String checkboxId = format(CHECKBOX_BY_SAMPLE_NAME_ID_TEMPLATE, sampleName); String checkboxLocator = format("//div[@id='%s']/md-checkbox", checkboxId); return seleniumWebDriverHelper .waitVisibilityAndGetAttribute(By.xpath(checkboxLocator), "aria-checked") .equals("true"); } private void waitSampleCheckboxState(String sampleName, boolean state) { String checkboxId = format(CHECKBOX_BY_SAMPLE_NAME_ID_TEMPLATE, sampleName); String locator = format("//div[@id='%s']/md-checkbox", checkboxId); seleniumWebDriverHelper.waitAttributeEqualsTo( By.xpath(locator), "aria-checked", Boolean.toString(state)); } public void waitSampleCheckboxEnabled(String sampleName) { waitSampleCheckboxState(sampleName, true); } public void waitSampleCheckboxDisabled(String sampleName) { waitSampleCheckboxState(sampleName, false); } public void waitProjectTabAppearance(String tabName) { seleniumWebDriverHelper.waitVisibility(By.id(tabName)); } public void waitProjectTabDisappearance(String tabName) { seleniumWebDriverHelper.waitInvisibility(By.id(tabName)); } public void waitTextInBlankNameField(String expectedText) { seleniumWebDriverHelper.waitAttributeEqualsTo( By.xpath(BLANK_FORM_NAME_FIELD_XPATH), "value", expectedText); } public void typeToBlankNameField(String text) { seleniumWebDriverHelper.setValue(By.xpath(BLANK_FORM_NAME_FIELD_XPATH), text); } public void waitNameFieldErrorMessageInBlankForm(String errorMessage) { seleniumWebDriverHelper.waitTextEqualsTo( By.xpath(BLANK_FORM_NAME_ERROR_MESSAGE_XPATH), errorMessage); } public void waitErrorMessageDissappearanceInBlankNameField() { seleniumWebDriverHelper.waitInvisibility(By.xpath(BLANK_FORM_NAME_ERROR_MESSAGE_XPATH)); } public void waitTextInBlankDescriptionField(String expectedText) { seleniumWebDriverHelper.waitAttributeEqualsTo( By.xpath(BLANK_FORM_DESCRIPTION_FIELD_XPATH), "value", expectedText); } public void typeToBlankDescriptionField(String text) { seleniumWebDriverHelper.setValue(By.xpath(BLANK_FORM_DESCRIPTION_FIELD_XPATH), text); } }
{ "pile_set_name": "Github" }
title: State and Count of Processes agents: linux, windows, aix, solaris, openvms catalog: os/ps license: GPL distribution: check_mk description: This check looks into the list of then current running processes for those matching a certain name or regular expression and optionally being owned by a certain user. The number of matching processes is matched against warning and critical levels. item: A user definable service description for Nagios. That description must be unique within each host. Changing the description will make Nagios think that it is another service. inventory: One service is created for each configured process on the monitored system. Since Checkmk cannot know which processes are of relevance to you, some configuration is needed. The configuration is done via the ruleset {inventory_processes_rules}. During inventory Checkmk tries to match all entries on each process found on the target host. If an entry matches, one new service will be created according to the entry (if it's not already existing). cluster: On a cluster all processes are accumulated, along with the information on which node they are running.
{ "pile_set_name": "Github" }
/* * linux/fs/hpfs/dir.c * * Mikulas Patocka ([email protected]), 1998-1999 * * directory VFS functions */ #include <linux/slab.h> #include "hpfs_fn.h" static int hpfs_dir_release(struct inode *inode, struct file *filp) { hpfs_lock(inode->i_sb); hpfs_del_pos(inode, &filp->f_pos); /*hpfs_write_if_changed(inode);*/ hpfs_unlock(inode->i_sb); return 0; } /* This is slow, but it's not used often */ static loff_t hpfs_dir_lseek(struct file *filp, loff_t off, int whence) { loff_t new_off = off + (whence == 1 ? filp->f_pos : 0); loff_t pos; struct quad_buffer_head qbh; struct inode *i = file_inode(filp); struct hpfs_inode_info *hpfs_inode = hpfs_i(i); struct super_block *s = i->i_sb; /* Somebody else will have to figure out what to do here */ if (whence == SEEK_DATA || whence == SEEK_HOLE) return -EINVAL; mutex_lock(&i->i_mutex); hpfs_lock(s); /*printk("dir lseek\n");*/ if (new_off == 0 || new_off == 1 || new_off == 11 || new_off == 12 || new_off == 13) goto ok; pos = ((loff_t) hpfs_de_as_down_as_possible(s, hpfs_inode->i_dno) << 4) + 1; while (pos != new_off) { if (map_pos_dirent(i, &pos, &qbh)) hpfs_brelse4(&qbh); else goto fail; if (pos == 12) goto fail; } hpfs_add_pos(i, &filp->f_pos); ok: filp->f_pos = new_off; hpfs_unlock(s); mutex_unlock(&i->i_mutex); return new_off; fail: /*printk("illegal lseek: %016llx\n", new_off);*/ hpfs_unlock(s); mutex_unlock(&i->i_mutex); return -ESPIPE; } static int hpfs_readdir(struct file *filp, void *dirent, filldir_t filldir) { struct inode *inode = file_inode(filp); struct hpfs_inode_info *hpfs_inode = hpfs_i(inode); struct quad_buffer_head qbh; struct hpfs_dirent *de; int lc; long old_pos; unsigned char *tempname; int c1, c2 = 0; int ret = 0; hpfs_lock(inode->i_sb); if (hpfs_sb(inode->i_sb)->sb_chk) { if (hpfs_chk_sectors(inode->i_sb, inode->i_ino, 1, "dir_fnode")) { ret = -EFSERROR; goto out; } if (hpfs_chk_sectors(inode->i_sb, hpfs_inode->i_dno, 4, "dir_dnode")) { ret = -EFSERROR; goto out; } } if (hpfs_sb(inode->i_sb)->sb_chk >= 2) { struct buffer_head *bh; struct fnode *fno; int e = 0; if (!(fno = hpfs_map_fnode(inode->i_sb, inode->i_ino, &bh))) { ret = -EIOERROR; goto out; } if (!fnode_is_dir(fno)) { e = 1; hpfs_error(inode->i_sb, "not a directory, fnode %08lx", (unsigned long)inode->i_ino); } if (hpfs_inode->i_dno != le32_to_cpu(fno->u.external[0].disk_secno)) { e = 1; hpfs_error(inode->i_sb, "corrupted inode: i_dno == %08x, fnode -> dnode == %08x", hpfs_inode->i_dno, le32_to_cpu(fno->u.external[0].disk_secno)); } brelse(bh); if (e) { ret = -EFSERROR; goto out; } } lc = hpfs_sb(inode->i_sb)->sb_lowercase; if (filp->f_pos == 12) { /* diff -r requires this (note, that diff -r */ filp->f_pos = 13; /* also fails on msdos filesystem in 2.0) */ goto out; } if (filp->f_pos == 13) { ret = -ENOENT; goto out; } while (1) { again: /* This won't work when cycle is longer than number of dirents accepted by filldir, but what can I do? maybe killall -9 ls helps */ if (hpfs_sb(inode->i_sb)->sb_chk) if (hpfs_stop_cycles(inode->i_sb, filp->f_pos, &c1, &c2, "hpfs_readdir")) { ret = -EFSERROR; goto out; } if (filp->f_pos == 12) goto out; if (filp->f_pos == 3 || filp->f_pos == 4 || filp->f_pos == 5) { printk("HPFS: warning: pos==%d\n",(int)filp->f_pos); goto out; } if (filp->f_pos == 0) { if (filldir(dirent, ".", 1, filp->f_pos, inode->i_ino, DT_DIR) < 0) goto out; filp->f_pos = 11; } if (filp->f_pos == 11) { if (filldir(dirent, "..", 2, filp->f_pos, hpfs_inode->i_parent_dir, DT_DIR) < 0) goto out; filp->f_pos = 1; } if (filp->f_pos == 1) { filp->f_pos = ((loff_t) hpfs_de_as_down_as_possible(inode->i_sb, hpfs_inode->i_dno) << 4) + 1; hpfs_add_pos(inode, &filp->f_pos); filp->f_version = inode->i_version; } old_pos = filp->f_pos; if (!(de = map_pos_dirent(inode, &filp->f_pos, &qbh))) { ret = -EIOERROR; goto out; } if (de->first || de->last) { if (hpfs_sb(inode->i_sb)->sb_chk) { if (de->first && !de->last && (de->namelen != 2 || de ->name[0] != 1 || de->name[1] != 1)) hpfs_error(inode->i_sb, "hpfs_readdir: bad ^A^A entry; pos = %08lx", old_pos); if (de->last && (de->namelen != 1 || de ->name[0] != 255)) hpfs_error(inode->i_sb, "hpfs_readdir: bad \\377 entry; pos = %08lx", old_pos); } hpfs_brelse4(&qbh); goto again; } tempname = hpfs_translate_name(inode->i_sb, de->name, de->namelen, lc, de->not_8x3); if (filldir(dirent, tempname, de->namelen, old_pos, le32_to_cpu(de->fnode), DT_UNKNOWN) < 0) { filp->f_pos = old_pos; if (tempname != de->name) kfree(tempname); hpfs_brelse4(&qbh); goto out; } if (tempname != de->name) kfree(tempname); hpfs_brelse4(&qbh); } out: hpfs_unlock(inode->i_sb); return ret; } /* * lookup. Search the specified directory for the specified name, set * *result to the corresponding inode. * * lookup uses the inode number to tell read_inode whether it is reading * the inode of a directory or a file -- file ino's are odd, directory * ino's are even. read_inode avoids i/o for file inodes; everything * needed is up here in the directory. (And file fnodes are out in * the boondocks.) * * - M.P.: this is over, sometimes we've got to read file's fnode for eas * inode numbers are just fnode sector numbers; iget lock is used * to tell read_inode to read fnode or not. */ struct dentry *hpfs_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags) { const unsigned char *name = dentry->d_name.name; unsigned len = dentry->d_name.len; struct quad_buffer_head qbh; struct hpfs_dirent *de; ino_t ino; int err; struct inode *result = NULL; struct hpfs_inode_info *hpfs_result; hpfs_lock(dir->i_sb); if ((err = hpfs_chk_name(name, &len))) { if (err == -ENAMETOOLONG) { hpfs_unlock(dir->i_sb); return ERR_PTR(-ENAMETOOLONG); } goto end_add; } /* * '.' and '..' will never be passed here. */ de = map_dirent(dir, hpfs_i(dir)->i_dno, name, len, NULL, &qbh); /* * This is not really a bailout, just means file not found. */ if (!de) goto end; /* * Get inode number, what we're after. */ ino = le32_to_cpu(de->fnode); /* * Go find or make an inode. */ result = iget_locked(dir->i_sb, ino); if (!result) { hpfs_error(dir->i_sb, "hpfs_lookup: can't get inode"); goto bail1; } if (result->i_state & I_NEW) { hpfs_init_inode(result); if (de->directory) hpfs_read_inode(result); else if (le32_to_cpu(de->ea_size) && hpfs_sb(dir->i_sb)->sb_eas) hpfs_read_inode(result); else { result->i_mode |= S_IFREG; result->i_mode &= ~0111; result->i_op = &hpfs_file_iops; result->i_fop = &hpfs_file_ops; set_nlink(result, 1); } unlock_new_inode(result); } hpfs_result = hpfs_i(result); if (!de->directory) hpfs_result->i_parent_dir = dir->i_ino; if (de->has_acl || de->has_xtd_perm) if (!(dir->i_sb->s_flags & MS_RDONLY)) { hpfs_error(result->i_sb, "ACLs or XPERM found. This is probably HPFS386. This driver doesn't support it now. Send me some info on these structures"); goto bail1; } /* * Fill in the info from the directory if this is a newly created * inode. */ if (!result->i_ctime.tv_sec) { if (!(result->i_ctime.tv_sec = local_to_gmt(dir->i_sb, le32_to_cpu(de->creation_date)))) result->i_ctime.tv_sec = 1; result->i_ctime.tv_nsec = 0; result->i_mtime.tv_sec = local_to_gmt(dir->i_sb, le32_to_cpu(de->write_date)); result->i_mtime.tv_nsec = 0; result->i_atime.tv_sec = local_to_gmt(dir->i_sb, le32_to_cpu(de->read_date)); result->i_atime.tv_nsec = 0; hpfs_result->i_ea_size = le32_to_cpu(de->ea_size); if (!hpfs_result->i_ea_mode && de->read_only) result->i_mode &= ~0222; if (!de->directory) { if (result->i_size == -1) { result->i_size = le32_to_cpu(de->file_size); result->i_data.a_ops = &hpfs_aops; hpfs_i(result)->mmu_private = result->i_size; /* * i_blocks should count the fnode and any anodes. * We count 1 for the fnode and don't bother about * anodes -- the disk heads are on the directory band * and we want them to stay there. */ result->i_blocks = 1 + ((result->i_size + 511) >> 9); } } } hpfs_brelse4(&qbh); /* * Made it. */ end: end_add: hpfs_unlock(dir->i_sb); d_add(dentry, result); return NULL; /* * Didn't. */ bail1: hpfs_brelse4(&qbh); /*bail:*/ hpfs_unlock(dir->i_sb); return ERR_PTR(-ENOENT); } const struct file_operations hpfs_dir_ops = { .llseek = hpfs_dir_lseek, .read = generic_read_dir, .readdir = hpfs_readdir, .release = hpfs_dir_release, .fsync = hpfs_file_fsync, };
{ "pile_set_name": "Github" }
package com.alibaba.excel.cache.selector; import java.io.IOException; import org.apache.poi.openxml4j.opc.PackagePart; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.excel.cache.Ehcache; import com.alibaba.excel.cache.MapCache; import com.alibaba.excel.cache.ReadCache; /** * Simple cache selector * * @author Jiaju Zhuang **/ public class SimpleReadCacheSelector implements ReadCacheSelector { private static final Logger LOGGER = LoggerFactory.getLogger(SimpleReadCacheSelector.class); /** * Convert bytes to megabytes */ private static final long B2M = 1000 * 1000L; /** * If it's less than 5M, use map cache, or use ehcache.unit MB. */ private static final int DEFAULT_MAX_USE_MAP_CACHE_SIZE = 5; /** * Maximum size of cache activation.unit MB. */ private static final int DEFAULT_MAX_EHCACHE_ACTIVATE_SIZE = 20; /** * Shared strings exceeding this value will use {@link Ehcache},or use {@link MapCache}.unit MB. */ private long maxUseMapCacheSize; /** * Maximum size of cache activation.unit MB. */ private int maxCacheActivateSize; public SimpleReadCacheSelector() { this(DEFAULT_MAX_USE_MAP_CACHE_SIZE, DEFAULT_MAX_EHCACHE_ACTIVATE_SIZE); } public SimpleReadCacheSelector(long maxUseMapCacheSize, int maxCacheActivateSize) { if (maxUseMapCacheSize <= 0) { this.maxUseMapCacheSize = DEFAULT_MAX_USE_MAP_CACHE_SIZE; } else { this.maxUseMapCacheSize = maxUseMapCacheSize; } if (maxCacheActivateSize <= 0) { this.maxCacheActivateSize = DEFAULT_MAX_EHCACHE_ACTIVATE_SIZE; } else { this.maxCacheActivateSize = maxCacheActivateSize; } } @Override public ReadCache readCache(PackagePart sharedStringsTablePackagePart) { long size = sharedStringsTablePackagePart.getSize(); if (size < 0) { try { size = sharedStringsTablePackagePart.getInputStream().available(); } catch (IOException e) { LOGGER.warn("Unable to get file size, default used MapCache"); return new MapCache(); } } if (size < maxUseMapCacheSize * B2M) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Use map cache.size:{}", size); } return new MapCache(); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Use ehcache.size:{}", size); } return new Ehcache(maxCacheActivateSize); } }
{ "pile_set_name": "Github" }
.t.e.s.t. Comments <% for i in 1..1000 %> fix_<%= i %>: id: <%= i %> name: guy_<%= 1 %> <% end %> .e.o.f.
{ "pile_set_name": "Github" }
/*- * Copyright (c) 2011-2012 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Christos Zoulas. * * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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. */ /* * NPF variables are used to build the intermediate representation (IR) * of the configuration grammar. They represent primitive types (strings, * numbers, etc) as well as complex types (address and mask, table, etc). */ #include <sys/cdefs.h> __RCSID("$NetBSD$"); #include <stdlib.h> #include <string.h> #include <unistd.h> #define _NPFVAR_PRIVATE #include "npfctl.h" typedef struct npf_element { void * e_data; unsigned e_type; struct npf_element *e_next; } npf_element_t; struct npfvar { char * v_key; npf_element_t * v_elements; npf_element_t * v_last; size_t v_count; void * v_next; }; static npfvar_t * var_list = NULL; static size_t var_num = 0; npfvar_t * npfvar_create(void) { npfvar_t *vp = ecalloc(1, sizeof(*vp)); var_num++; return vp; } npfvar_t * npfvar_lookup(const char *key) { for (npfvar_t *it = var_list; it != NULL; it = it->v_next) if (strcmp(it->v_key, key) == 0) return it; return NULL; } const char * npfvar_type(size_t t) { if (t >= __arraycount(npfvar_types)) { return "unknown"; } return npfvar_types[t]; } void npfvar_add(npfvar_t *vp, const char *name) { vp->v_key = estrdup(name); vp->v_next = var_list; var_list = vp; } npfvar_t * npfvar_create_element(unsigned type, const void *data, size_t len) { npfvar_t *vp = npfvar_create(); return npfvar_add_element(vp, type, data, len); } npfvar_t * npfvar_create_from_string(unsigned type, const char *string) { return npfvar_create_element(type, string, strlen(string) + 1); } npfvar_t * npfvar_add_element(npfvar_t *vp, unsigned type, const void *data, size_t len) { npf_element_t *el; el = ecalloc(1, sizeof(*el)); el->e_data = ecalloc(1, len); el->e_type = type; memcpy(el->e_data, data, len); /* Preserve the order of insertion. */ if (vp->v_elements == NULL) { vp->v_elements = el; } else { vp->v_last->e_next = el; } vp->v_last = el; vp->v_count++; return vp; } npfvar_t * npfvar_add_elements(npfvar_t *vp, npfvar_t *vp2) { if (vp2 == NULL) return vp; if (vp == NULL) return vp2; if (vp->v_elements == NULL) { if (vp2->v_elements) { vp->v_elements = vp2->v_elements; } } else if (vp2->v_elements) { vp->v_last->e_next = vp2->v_elements; } if (vp2->v_elements) { vp->v_last = vp2->v_last; vp->v_count += vp2->v_count; vp2->v_elements = NULL; vp2->v_count = 0; vp2->v_last = NULL; } npfvar_destroy(vp2); return vp; } static void npfvar_free_elements(npf_element_t *el) { if (el == NULL) return; npfvar_free_elements(el->e_next); free(el->e_data); free(el); } void npfvar_destroy(npfvar_t *vp) { npfvar_free_elements(vp->v_elements); free(vp->v_key); free(vp); var_num--; } char * npfvar_expand_string(const npfvar_t *vp) { if (npfvar_get_count(vp) != 1) { yyerror("variable '%s' has multiple elements", vp->v_key); return NULL; } return npfvar_get_data(vp, NPFVAR_STRING, 0); } size_t npfvar_get_count(const npfvar_t *vp) { return vp ? vp->v_count : 0; } static npf_element_t * npfvar_get_element(const npfvar_t *vp, size_t idx, size_t level) { npf_element_t *el; /* * Verify the parameters. */ if (vp == NULL) { return NULL; } if (level >= var_num) { yyerror("circular dependency for variable '%s'", vp->v_key); return NULL; } if (vp->v_count <= idx) { yyerror("variable '%s' has only %zu elements, requested %zu", vp->v_key, vp->v_count, idx); return NULL; } /* * Get the element at the given index. */ el = vp->v_elements; while (idx--) { el = el->e_next; } /* * Resolve if it is a reference to another variable. */ if (el->e_type == NPFVAR_VAR_ID) { const npfvar_t *rvp = npfvar_lookup(el->e_data); return npfvar_get_element(rvp, 0, level + 1); } return el; } int npfvar_get_type(const npfvar_t *vp, size_t idx) { npf_element_t *el = npfvar_get_element(vp, idx, 0); return el ? (int)el->e_type : -1; } void * npfvar_get_data(const npfvar_t *vp, unsigned type, size_t idx) { npf_element_t *el = npfvar_get_element(vp, idx, 0); if (el && NPFVAR_TYPE(el->e_type) != NPFVAR_TYPE(type)) { yyerror("variable '%s' element %zu " "is of type '%s' rather than '%s'", vp->v_key, idx, npfvar_type(el->e_type), npfvar_type(type)); return NULL; } return el->e_data; }
{ "pile_set_name": "Github" }
/* *Copyright 2018 T Mobile, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or * implied. See the License for the specific language governing permissions and * limitations under the License. */ /** * Created by adityaagarwal on 18/10/17. */ import { Injectable } from '@angular/core'; import 'rxjs/add/operator/toPromise'; @Injectable() export class AutorefreshService { durationParams: any; autoRefresh: boolean; getDuration(): Promise<AutorefreshService[]> { const absUrl = window.location.href; const sURLVariables = absUrl.split('?'); const urlObj = {}; if (sURLVariables[1] !== undefined) { const valuesParams = sURLVariables[1].split('&'); for (let i = 0; i < valuesParams.length; i++) { const paramsName = valuesParams[i].split('='); urlObj[paramsName[0]] = paramsName[1]; } if (urlObj.hasOwnProperty('autorefresh') ) { if (urlObj['autorefresh'] === true || urlObj['autorefresh'] === 'true' || urlObj['autorefresh'] === '' || urlObj['autorefresh'] == null || urlObj['autorefresh'] === ' ') { this.autoRefresh = true; } } if (urlObj.hasOwnProperty('interval') ) { if (urlObj['interval'] === '' || urlObj['interval'] == null || urlObj['interval'] === undefined || urlObj['interval'] === ' ') { urlObj['interval'] = 1; } } else { urlObj['interval'] = 1; } this.durationParams = urlObj['interval'] * 60000; return this.durationParams; } } }
{ "pile_set_name": "Github" }
/** * Simple in memory cache to store bio and form data for representatives. */ var NodeCache = require('node-cache'); var isUndefined = require('lodash.isundefined'); /** * The defautl TTL for all cache keys, in seconds. * @type {number} */ var DEFAULT_TTL = 60 * 60 * 24 * 7; var repCache = new NodeCache(); /** * * @param slug */ var getLegislatorByURLSlug = function(slug, cb) { repCache.get(slug, function(err, val) { if (err) { cb(err, null); } if (isUndefined(val)) { // ?? } else { cb(null, val); } }); }; /** * Caches a legislator object. * @param legislator */ var cacheLegislator = function(legislator) { repCache.set(legislator.slug(), legislator); repCache.set(legislator.bioguideId, legislator); }; /** * Returns legislator form elements for legislators matching the supplied bioguideIds. * @param bioguideIds {Array.<String>} */ var getFormElementsByBioguideIds = function(bioguideIds) { }; module.exports.getLegislatorByURLSlug = getLegislatorByURLSlug; module.exports.getFormElementsByBioguideIds = getFormElementsByBioguideIds;
{ "pile_set_name": "Github" }
/* * (C) 2010,2011 Thomas Renninger <[email protected]>, Novell Inc. * * Licensed under the terms of the GNU GPL License version 2. * */ #ifndef __CPUIDLE_INFO_HW__ #define __CPUIDLE_INFO_HW__ #include <stdarg.h> #include <time.h> #include "idle_monitor/idle_monitors.h" #define MONITORS_MAX 20 #define MONITOR_NAME_LEN 20 #define CSTATE_NAME_LEN 5 #define CSTATE_DESC_LEN 60 extern int cpu_count; /* Hard to define the right names ...: */ enum power_range_e { RANGE_THREAD, /* Lowest in topology hierarcy, AMD: core, Intel: thread kernel sysfs: cpu */ RANGE_CORE, /* AMD: unit, Intel: core, kernel_sysfs: core_id */ RANGE_PACKAGE, /* Package, processor socket */ RANGE_MACHINE, /* Machine, platform wide */ RANGE_MAX }; typedef struct cstate { int id; enum power_range_e range; char name[CSTATE_NAME_LEN]; char desc[CSTATE_DESC_LEN]; /* either provide a percentage or a general count */ int (*get_count_percent)(unsigned int self_id, double *percent, unsigned int cpu); int (*get_count)(unsigned int self_id, unsigned long long *count, unsigned int cpu); } cstate_t; struct cpuidle_monitor { /* Name must not contain whitespaces */ char name[MONITOR_NAME_LEN]; int name_len; int hw_states_num; cstate_t *hw_states; int (*start) (void); int (*stop) (void); struct cpuidle_monitor* (*do_register) (void); void (*unregister)(void); unsigned int overflow_s; int needs_root; }; extern long long timespec_diff_us(struct timespec start, struct timespec end); #define print_overflow_err(mes, ov) \ { \ fprintf(stderr, gettext("Measure took %u seconds, but registers could " \ "overflow at %u seconds, results " \ "could be inaccurate\n"), mes, ov); \ } /* Taken over from x86info project sources -> return 0 on success */ #include <sched.h> #include <sys/types.h> #include <unistd.h> static inline int bind_cpu(int cpu) { cpu_set_t set; if (sched_getaffinity(getpid(), sizeof(set), &set) == 0) { CPU_ZERO(&set); CPU_SET(cpu, &set); return sched_setaffinity(getpid(), sizeof(set), &set); } return 1; } #endif /* __CPUIDLE_INFO_HW__ */
{ "pile_set_name": "Github" }
# 0.25.0 [2020-09-09] - Update to `yamux-0.8.0`. Upgrade step 4 of 4. This version always implements the additive meaning w.r.t. initial window updates. The configuration option `lazy_open` is removed. Yamux will automatically send an initial window update if the receive window is configured to be larger than the default. # 0.24.0 [2020-09-09] - Update to `yamux-0.7.0`. Upgrade step 3 of 4. This version sets the flag but will always interpret initial window updates as additive. # 0.23.0 [2020-09-09] - Update to `yamux-0.6.0`. As explain below, this is step 2 of 4 in a multi-release upgrade. This version recognises and sets the flag that causes the new semantics for the initial window update. # 0.22.0 [2020-09-09] - Update to `yamux-0.5.0`. *This is the start of a multi-release transition* to a different behaviour w.r.t. the initial window update frame. Tracked in [[1]], this will change the initial window update to mean "in addition to the default receive window" rather than "the total receive window". This version recognises a temporary flag, that will cause the new meaning. The next version `0.23.0` will also set the flag. Version `0.24.0` will still set the flag but will always implement the new meaning, and (finally) version `0.25.0` will no longer set the flag and always use the additive semantics. If current code uses the default Yamux configuration, all upgrades need to be performed in order because each version is only compatible with its immediate predecessor. Alternatively, if the default configuration is deployed with `lazy_open` set to `true`, one can directly upgrade from version `0.21.0` to `0.25.0` without any intermediate upgrades. - Bump `libp2p-core` dependency. [1]: https://github.com/paritytech/yamux/issues/92 # 0.21.0 [2020-08-18] - Bump `libp2p-core` dependency. - Allow overriding the mode (client/server), e.g. in the context of TCP hole punching. [PR 1691](https://github.com/libp2p/rust-libp2p/pull/1691). # 0.20.0 [2020-07-01] - Update `libp2p-core`, i.e. `StreamMuxer::poll_inbound` has been renamed to `poll_event` and returns a `StreamMuxerEvent`. # 0.19.1 [2020-06-22] - Deprecated method `Yamux::is_remote_acknowledged` has been removed as part of [PR 1616](https://github.com/libp2p/rust-libp2p/pull/1616).
{ "pile_set_name": "Github" }
package de.fuberlin.wiwiss.d2rq.algebra; import java.util.List; import java.util.Set; import de.fuberlin.wiwiss.d2rq.expr.Expression; /** * Wraps a relation and allows it to be modified by relational * operators. Normally, applying an operator to a relation * results in a new object. This is impractical in some places. * The MutableRelation solves this problem. * * @author Richard Cyganiak ([email protected]) */ public class MutableRelation implements RelationalOperators { private Relation relation; public MutableRelation(Relation initialState) { this.relation = initialState; } public Relation immutableSnapshot() { return this.relation; } public Relation renameColumns(ColumnRenamer renamer) { return this.relation = this.relation.renameColumns(renamer); } public Relation empty() { return this.relation = Relation.EMPTY; } public Relation select(Expression condition) { if (condition.isFalse()) { return empty(); } return this.relation = this.relation.select(condition); } public Relation orderBy(List<OrderSpec> orderSpecs) { return relation = new RelationImpl( relation.database(), relation.aliases(), relation.condition(), relation.softCondition(), relation.joinConditions(), relation.projections(), relation.isUnique(), orderSpecs, relation.limit(), relation.limitInverse()); } public Relation swapLimits() { return relation = new RelationImpl( relation.database(), relation.aliases(), relation.condition(), relation.softCondition(), relation.joinConditions(), relation.projections(), relation.isUnique(), relation.orderSpecs(), relation.limitInverse(), relation.limit()); } public Relation project(Set<? extends ProjectionSpec> projectionSpecs) { return relation = relation.project(projectionSpecs); } public Relation limit(int limit) { return relation = new RelationImpl( relation.database(), relation.aliases(), relation.condition(), relation.softCondition(), relation.joinConditions(), relation.projections(), relation.isUnique(), relation.orderSpecs(), Relation.combineLimits(relation.limit(), limit), relation.limitInverse()); } }
{ "pile_set_name": "Github" }
// Copyright (C) 2009-2012 Lorenzo Caminiti // Distributed under the Boost Software License, Version 1.0 // (see accompanying file LICENSE_1_0.txt or a copy at // http://www.boost.org/LICENSE_1_0.txt) // Home at http://www.boost.org/libs/utility/identity_type /** @file Wrap type expressions with round parenthesis so they can be passed to macros even if they contain commas. */ #ifndef BOOST_IDENTITY_TYPE_HPP_ #define BOOST_IDENTITY_TYPE_HPP_ #include <boost/type_traits/function_traits.hpp> /** @brief This macro allows to wrap the specified type expression within extra round parenthesis so the type can be passed as a single macro parameter even if it contains commas (not already wrapped within round parenthesis). @Params @Param{parenthesized_type, The type expression to be passed as macro parameter wrapped by a single set of round parenthesis <c>(...)</c>. This type expression can contain an arbitrary number of commas. } @EndParams This macro works on any C++03 compiler (it does not use variadic macros). This macro must be prefixed by <c>typename</c> when used within templates. Note that the compiler will not be able to automatically determine function template parameters when they are wrapped with this macro (these parameters need to be explicitly specified when calling the function template). On some compilers (like GCC), using this macro on abstract types requires to add and remove a reference to the specified type. */ #define BOOST_IDENTITY_TYPE(parenthesized_type) \ /* must NOT prefix this with `::` to work with parenthesized syntax */ \ boost::function_traits< void parenthesized_type >::arg1_type #endif // #include guard
{ "pile_set_name": "Github" }
[% WRAPPER "layout.tt" full_width=1 title=l('Edit Types') no_icons=1 -%] <div id="content" class="wikicontent"> <h1>[%- l('Edit Types') -%]</h1> [% FOR category=by_category.pairs %] [% NEXT IF category.key == l('Historic') %] <h2>[% category.key %]</h2> <ul> [% FOR edit_type=category.value %] [% USE class = Class(edit_type) %] <li> <a href="[% c.uri_for_action('/edit/edit_type', class.edit_type) %]"> [% class.l_edit_name %] </a> </li> [% END %] </ul> [% END %] [%- category_name = l('Historic') -%] [%- category = by_category.$category_name -%] <h2>[% l('Historic') %]</h2> <ul> [% FOR edit_type IN category %] [% USE class = Class(edit_type) %] <li> <a href="[% c.uri_for_action('/edit/edit_type', class.edit_type) %]"> [% class.l_edit_name %] </a> </li> [% END %] </ul> </div> [% END %]
{ "pile_set_name": "Github" }
trackray.version=3.2.1 #TrackRay Account trackray.account=blue trackray.password=trackray #trackray Server port server.port=80 #trackray public network host trackray.host=127.0.0.1 #trackray URL (http/https) trackray.url=http://${trackray.host}:${server.port}/ # 依赖资源文件存放目录 trackray.resource.dir=${user.dir}/resources trackray.release.dir=release trackray.plugin.include.dir=${trackray.resource.dir}/plugin/include/ #HSQLDB database.dir=${user.dir}/data/trackray spring.datasource.url=jdbc:hsqldb:file:${database.dir} spring.datasource.username=sa spring.datasource.password=123456 spring.datasource.driverClassName=org.hsqldb.jdbcDriver spring.datasource.sqlScriptEncoding=utf-8 spring.jpa.hibernate.ddl-auto=update #spring MVC spring.devtools.restart.enabled=true #freemarker spring.freemarker.suffix=.html spring.freemarker.template-loader-path=classpath:/templates/ logging.file=trackray.log server.use-forward-headers=true server.tomcat.remote-ip-header=X-Real-IP server.tomcat.protocol-header=X-Forwarded-Proto ########### #burpsuite# ########### # 是否在控制台中输出 burpsuite 的日志 burp.console.log=true burp.remote.host=127.0.0.1 burp.remote.port=8090 # 是否使用 burp loader-keygen 加载器 burp.local.loader=true # 是否使用无头模式(不显示burp窗口) burp.local.headless=true ########### ####xray### ########### xray.remote.host=127.0.0.1 xray.remote.port=7777 # 是否在控制台输出 xray 日志 xray.console.log=true ########### #crawlergo# ########### # chrome 主程序绝对路径 crawlergo.chrome.path=C:/Program Files (x86)/Google/Chrome/Application/chrome.exe # crawlergo 默认代理推送地址 crawlergo.push.proxy=http://${burp.remote.host}:8080/ # 爬虫过滤模式 crawlergo.filter.mode=smart # 是否在控制台中输出crawlergo 日志 crawlergo.console.log=true # crawlergo 最大标签数 crawlergo.max.tab=20 ########### ###msfrpc## ########### metasploit.host=192.168.91.143:55553 metasploit.user=msf metasploit.pass=msf ########### ####AWVS### ########### awvs.host=https://127.0.0.1:3443 awvs.key=1986ad8c0a5b3df4d7028d5f3c06e936cd5dc7d29f6024e01969935a5096e03f7 ########### ###sqlmap## ########### sqlmap.host=http://127.0.0.1:8775/ ########### ####ceye### ########### ceye.io.token=601db116c2a926704952249af21a2951 ceye.io.identifier=spn7ez.ceye.io #jython plugin python插件目录 python.script.path=${trackray.resource.dir}/python/ #python library python第三方库目录 python.package.path=D:\\Software\\Python\\Lib\\site-packages #maven repository maven仓库目录 (jython插件需要) maven.repository.path=D:/Development/maven/repository #system temp path 临时文件存放目录 temp.dir=${java.io.tmpdir}/trackray/ #quartz spring.quartz.scheduler-name=scanTask
{ "pile_set_name": "Github" }
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/AirPlaySupport.framework/AirPlaySupport */ @interface APSAWDAirPlaySlideshowSessionEndedOnServer : PBCodable <NSCopying> { unsigned int _duration; struct { unsigned int timestamp : 1; unsigned int duration : 1; unsigned int maxBPS : 1; unsigned int maxPhotoBytes : 1; unsigned int minBPS : 1; unsigned int minPhotoBytes : 1; unsigned int pauses : 1; unsigned int reason : 1; unsigned int skipAheads : 1; unsigned int skipBacks : 1; unsigned int totalPhotos : 1; } _has; unsigned int _maxBPS; unsigned int _maxPhotoBytes; unsigned int _minBPS; unsigned int _minPhotoBytes; unsigned int _pauses; int _reason; NSString * _sessionUUID; unsigned int _skipAheads; unsigned int _skipBacks; unsigned long long _timestamp; unsigned int _totalPhotos; } @property (nonatomic) unsigned int duration; @property (nonatomic) bool hasDuration; @property (nonatomic) bool hasMaxBPS; @property (nonatomic) bool hasMaxPhotoBytes; @property (nonatomic) bool hasMinBPS; @property (nonatomic) bool hasMinPhotoBytes; @property (nonatomic) bool hasPauses; @property (nonatomic) bool hasReason; @property (nonatomic, readonly) bool hasSessionUUID; @property (nonatomic) bool hasSkipAheads; @property (nonatomic) bool hasSkipBacks; @property (nonatomic) bool hasTimestamp; @property (nonatomic) bool hasTotalPhotos; @property (nonatomic) unsigned int maxBPS; @property (nonatomic) unsigned int maxPhotoBytes; @property (nonatomic) unsigned int minBPS; @property (nonatomic) unsigned int minPhotoBytes; @property (nonatomic) unsigned int pauses; @property (nonatomic) int reason; @property (nonatomic, retain) NSString *sessionUUID; @property (nonatomic) unsigned int skipAheads; @property (nonatomic) unsigned int skipBacks; @property (nonatomic) unsigned long long timestamp; @property (nonatomic) unsigned int totalPhotos; - (void)copyTo:(id)arg1; - (id)copyWithZone:(struct _NSZone { }*)arg1; - (void)dealloc; - (id)description; - (id)dictionaryRepresentation; - (unsigned int)duration; - (bool)hasDuration; - (bool)hasMaxBPS; - (bool)hasMaxPhotoBytes; - (bool)hasMinBPS; - (bool)hasMinPhotoBytes; - (bool)hasPauses; - (bool)hasReason; - (bool)hasSessionUUID; - (bool)hasSkipAheads; - (bool)hasSkipBacks; - (bool)hasTimestamp; - (bool)hasTotalPhotos; - (unsigned long long)hash; - (bool)isEqual:(id)arg1; - (unsigned int)maxBPS; - (unsigned int)maxPhotoBytes; - (void)mergeFrom:(id)arg1; - (unsigned int)minBPS; - (unsigned int)minPhotoBytes; - (unsigned int)pauses; - (bool)readFrom:(id)arg1; - (int)reason; - (id)sessionUUID; - (void)setDuration:(unsigned int)arg1; - (void)setHasDuration:(bool)arg1; - (void)setHasMaxBPS:(bool)arg1; - (void)setHasMaxPhotoBytes:(bool)arg1; - (void)setHasMinBPS:(bool)arg1; - (void)setHasMinPhotoBytes:(bool)arg1; - (void)setHasPauses:(bool)arg1; - (void)setHasReason:(bool)arg1; - (void)setHasSkipAheads:(bool)arg1; - (void)setHasSkipBacks:(bool)arg1; - (void)setHasTimestamp:(bool)arg1; - (void)setHasTotalPhotos:(bool)arg1; - (void)setMaxBPS:(unsigned int)arg1; - (void)setMaxPhotoBytes:(unsigned int)arg1; - (void)setMinBPS:(unsigned int)arg1; - (void)setMinPhotoBytes:(unsigned int)arg1; - (void)setPauses:(unsigned int)arg1; - (void)setReason:(int)arg1; - (void)setSessionUUID:(id)arg1; - (void)setSkipAheads:(unsigned int)arg1; - (void)setSkipBacks:(unsigned int)arg1; - (void)setTimestamp:(unsigned long long)arg1; - (void)setTotalPhotos:(unsigned int)arg1; - (unsigned int)skipAheads; - (unsigned int)skipBacks; - (unsigned long long)timestamp; - (unsigned int)totalPhotos; - (void)writeTo:(id)arg1; @end
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE ldml SYSTEM "../../common/dtd/ldml.dtd"> <!-- Copyright © 1991-2013 Unicode, Inc. CLDR data files are interpreted according to the LDML specification (http://unicode.org/reports/tr35/) For terms of use, see http://www.unicode.org/copyright.html --> <ldml> <identity> <version number="$Revision: 9170 $"/> <generation date="$Date: 2013-08-07 23:47:50 -0500 (Wed, 07 Aug 2013) $"/> <language type="en"/> <territory type="SB"/> </identity> <numbers> <currencies> <currency type="SBD"> <symbol>$</symbol> </currency> </currencies> </numbers> </ldml>
{ "pile_set_name": "Github" }
[![Build Status](https://travis-ci.org/NYTimes/Store.svg?branch=master)](https://travis-ci.org/NYTimes/Store) # Store Store — это легкая в использовании библиотека для реактивной загрузки данных под Android. ### Проблемы: + Современные Android-приложения нуждаются в удобном и всегда доступном представлении данных. + Пользователи ожидают, что загрузка данных не будет мешать их взаимодействию с приложением. И от социальных, и от новостных, и от business-to-business приложений, пользователи ожидают бесшовного взаимодействия как при подключении к сети, так и в автономном режиме. + В международном роуминге большой объем загружаемых данных может привести к астрономическим счетам за связь. Store представляет собой класс, который упрощает загрузку, парсинг, хранение и извлечение данных в вашем приложении. Store похож на паттерн «репозиторий» [[https://msdn.microsoft.com/en-us/library/ff649690.aspx](https://msdn.microsoft.com/en-us/library/ff649690.aspx)], в дополнение предоставляя реактивный API, реализованный с помощью RxJava, который придерживается однонаправленного потока данных. Store обеспечивает уровень абстракции между элементами UI и операциями с данными. ### Обзор Store отвечает за управление загрузкой конкретного запроса данных. Когда вы создаёте новую реализацию Store, вы предоставляете ему `Fetcher` — функцию, которая определяет, как будет происходить загрузка данных из сети. Также вы можете настроить, как Store будет кэшировать данные в памяти и на диске, а так же то, как будет происходить их парсинг. Store возвращает данные в виде `Observable`, обеспечивая удобную работу с потоками. Созданный Store управляет логикой обработки потока данных, позволяя элементам пользовательского интерфейса использовать наиболее подходящий их источник, и гарантирует, что новейшие данные будут доступны для последующего использования в автономном режиме. Store может использовать классы для промежуточной обработки данных (парсинг и кэширование), идущие в комплекте, или же использовать ваши собственные реализации. Store использует RxJava и «склеивание» множественных запросов, чтобы минимизировать количество обращений к источнику данных в сети и кэшу на диске. Используя Store, с помощью двух уровней кэширования (память и диск), вы исключите ситуации, когда один и тот же сетевой запрос будет выполняться избыточное количество раз. ### Полностью сконфигурированный Store Для начала рассмотрим, как выглядит полностью сконфигурированный Store. Затем последуют более простые примеры, демонстрирующие каждую деталь в отдельности. ```java Store<ArticleAsset, Integer> articleStore = StoreBuilder.<Integer, BufferedSource, ArticleAsset>parsedWithKey() .fetcher(articleId -> api.getArticleAsBufferedSource(articleId)) //OkHttp responseBody.source() .persister(FileSystemPersister.create(FileSystemFactory.create(context.getFilesDir()),pathResolver)) .parser(GsonParserFactory.createSourceParser(gson, ArticleAsset.Article.class)) .open(); ``` Используя указанную выше конфигурацию вы получите: + Кэш в памяти, использующийся при смене конфигурации (например, при повороте экрана) + Кэш на диске для использования в автономном режиме + Парсинг через потоковый API, чтобы ограничить использование памяти + Многофункциональный API для запроса данных: получение кэшированных/новых данных или подписка на их будущие обновления. А теперь более подробно: ### Создание Store Для создания Store используется паттерн builder (строитель). Единственный обязательный параметр — это `.Fetcher<ReturnType,KeyType>`, который содержит единственный метод `fetch(key)`, возвращающий `Observable<ReturnType>`. ``` java Store<ArticleAsset, Integer> store = StoreBuilder.<ArticleAsset,Integer>key() .fetcher(articleId -> api.getArticle(articleId)) //OkHttp responseBody.source() .open(); ``` Store использует типизированные ключи в качестве идентификаторов для данных. Ключом может быть любой объект-значение (value object), который должным образом реализует методы `toString()`, `equals()` и `hashCode()`. При вызове вашей `Fetcher`-функции, ей будет передан конкретный экземпляр ключа. Аналогичным образом, ключ будет использоваться в качестве основного идентификатора в кэше (убедитесь, что ваш ключ правильно реализует `hashCode()`!) ### Наша реализация ключа — BarCode Для удобства мы включили в библиотеку нашу собственную реализацию ключа, называемую BarCode (штрихкод). Barcode имеет два поля: ключ `String key` и тип `String type`. ``` java BarCode barcode = new BarCode("Article", "42"); ``` При использовании BarCode в качестве ключа, удобно использовать соответсвующий метод StoreBuilder: ``` java Store<ArticleAsset, Integer> store = StoreBuilder.<ArticleAsset>barcode() .fetcher(articleBarcode -> api.getAsset(articleBarcode.getKey(),articleBarcode.getType())) .open(); ``` ### Публичный интерфейс: Get, Fetch, Stream, GetRefreshing ```java Observable<Article> article = store.get(barCode); ``` В первый раз, когда вы подпишитесь на `store.get(barCode)`, ответ будет сохранён в кэше в памяти. Все последующие вызовы `store.get(barCode)` с тем же ключом будут возвращать кэшированную версию данных, минимизируя ненужные запросы. Это позволяет предотвратить загрузку свежих данных из сети (или другого внешнего источника), чтобы уменьшить расход трафика и экономить заряд батареи. Хороший пример использования: пересоздание пользовательского интерфейса (activity или fragment) после поворота устройства — будут загружены кэшированные данные из Store. Использование Store поможет вам избежать необходимости реализовывать эту логику на уровне представления. Поток данных, которым управляет Store, на данный момент будет выглядеть следующим образом: ![Simple Store Flow](https://github.com/nytm/Store/blob/feature/rx2/Images/store-1.jpg) По умолчанию, 100 элементов будут сохранены в памяти на 24 часа. Вы можете передать свой экземпляр Guava Cache, чтобы переопределить стандартную политику. ### Запрос свежих данных В качестве альтернативы, вы можете вызвать `store.fetch(barCode)`, чтобы получить `Observable`, игнорируя кэш в памяти (и кэш на диске, если он используется). Получение свежих данных выглядит следующим образом: `store.fetch()` ![Simple Store Flow](https://github.com/nytm/Store/blob/feature/rx2/Images/store-2.jpg) В приложении The New York Times фоновое обновление, выполняемое ночью, использует `fetch()`, чтобы во время обычного использования приложения вызов `store.get()` не приводил к сетевым запросам. Другой хороший пример использования `fetch()` — обработка жеста pull-to-refresh, когда пользователь сам запрашивает обновление данных. Методы `fetch()` и `get()` порождают одно значение и затем вызывают `onCompleted()` или выбрасывают исключение в случае ошибки. ### Поток Для обновлений в реальном времени вы также можете вызвать метод `store.stream()`, который возвращает `Observable`, который порождает событие при сохранении нового объекта в Store. Вы можете рассматривать этот поток как шину событий (Event Bus), позволяющую узнавать, когда происходят новые удачные обращения к сети для определённого Store. Вы можете использовать оператор RxJava `filter()`, чтобы подписаться только на определенные события. ### Получение обновляющихся данных Существует еще один специальный способ подписаться на Store: `getRefreshing(key)`. `getRefreshing()` подпишется на `get()`, который возвращает один результат, но в отличие от `get()`, `getRefreshing()` останется подписанным. Каждый раз после вызова `store.clear(key)` все подписчики `getRefreshing(key)` подпишутся заново и принудительно создадут новый сетевой запрос данных. ### Оптимизация запросов Store предлагает дополнительные механизмы для предотвращения дублирующихся запросов одних и тех же данных. Если некий запрос выполняется в течение минуты после предыдущего точно такого же запроса, возвращается тот же ответ. Это полезно в ситуациях, когда вашему приложению во время запуска требуется сделать много асинхронных вызовов для одних и тех же данных или когда пользователь интенсивно запрашивает обновление данных. Например, новостное приложение The New York Times при запуске вызывает `ConfigStore.get()` из 12 разных мест. Первый из запросов выполняется, а остальные ожидают поступления данных. Мы увидели значительное сокращение объема использованных данных приложением после реализации этой логики. ### Добавление парсера Поскольку данные из сети редко поступают в нужном формате, Store может делегировать их обработку парсеру с помощью `StoreBuilder.<BarCode, BufferedSource, Article>parsedWithKey()` ```java Store<Article,Integer> store = StoreBuilder.<Integer, BufferedSource, Article>parsedWithKey() .fetcher(articleId -> api.getArticle(articleId)) .parser(source -> { try (InputStreamReader reader = new InputStreamReader(source.inputStream())) { return gson.fromJson(reader, Article.class); } catch (IOException e) { throw new RuntimeException(e); } }) .open(); ``` Теперь обновленный поток данных будет выглядеть следующим образом: `store.get()` -> ![Simple Store Flow](https://github.com/nytm/Store/blob/feature/rx2/Images/store-3.jpg) ### Промежуточная обработка данных — GsonSourceParser Отдельный артефакт предоставляет парсеры, использующие Gson, которые могут быть полезны, если `Fethcer` возвращает Reader, BufferedSource или String: - GsonReaderParser - GsonSourceParser - GsonStringParser Они доступны через класс фабрики (GsonParserFactory). Наш пример можно переписать так: ```java Store<Article,Integer> store = StoreBuilder.<Integer, BufferedSource, Article>parsedWithKey() .fetcher(articleId -> api.getArticle(articleId)) .parser(GsonParserFactory.createSourceParser(gson, Article.class)) .open(); ``` В некоторых случаях вам может потребоваться проанализировать JSONArray верхнего уровня, в этом случае вы можете передать TypeToken. ```java Store<List<Article>,Integer> store = StoreBuilder.<Integer, BufferedSource, List<Article>>parsedWithKey() .fetcher(articleId -> api.getArticles()) .parser(GsonParserFactory.createSourceParser(gson, new TypeToken<List<Article>>() {})) .open(); ``` Также существуют артефакты парсеров для Moshi и Jackson! ### Кэширование на диске Можно включить кэширование данных на диске, используя экземпляр класса `Persister` при создании Store. Всякий раз после выполнения сетевого запроса Store будет сохранять данные на диск, а затем считывать их. Поток данных будет выглядеть так: `store.get()` -> ![Simple Store Flow](https://github.com/nytm/Store/blob/feature/rx2/Images/store-5.jpg) Идеальным вариантом будет, если данные будут передаваться из сети на диск с использованием BufferedSource или Reader в качестве типа данных (а не String). ```java Store<Article,Integer> store = StoreBuilder.<Integer, BufferedSource, Article>parsedWithKey() .fetcher(articleId -> api.getArticles()) .persister(new Persister<BufferedSource>() { @Override public Observable<BufferedSource> read(Integer key) { if (dataIsCached) { return Observable.fromCallable(() -> userImplementedCache.get(key)); } else { return Observable.empty(); } } @Override public Observable<Boolean> write(BarCode barCode, BufferedSource source) { userImplementedCache.save(key, source); return Observable.just(true); } }) .parser(GsonParserFactory.createSourceParser(gson, Article.class)) .open(); ``` Stores не заботятся о том, как вы сохраняете или извлекаете данные с диска. В результате вы можете использовать Store с хранилищем объектов или любой базой данных (Realm, SQLite, CouchDB, Firebase etc). Единственное требование заключается в том, что данные должны быть одного и того же типа при сохранении/получении, что и возвращаемое функцией Fetcher значение. Теоретически, ничто не мешает вам реализовать свою версию класса `Persister`, который будет использовать для кэширования данных только память устройства. В таком случае в памяти будут храниться не один а два уровня кэша: первый с оригинальными данными, а второй с распарсенными, что позволит делиться кэшем `Persister` между разными экземплярами Store **Примечание**: При использовании парсера и кэша на диске, парсер будет вызван ПОСЛЕ получения данных с диска, а не между успешным сетевым вызовом и сохранением на диск. Это позволяет классу `Persister` работать непосредственно с сетевым потоком. При использовании SQLite мы рекомендуем библиотеку SqlBrite. Если вы не используете SqlBrite, вы можете создать `Observable` с помощью `Observable.fromCallable(() -> getDBValue())` ### Промежуточный слой — SourcePersister и FileSystem Мы установили, что наибольшей скорости сохранения можно добиться, выполняя потоковое сохранение данных из сети. Поэтому мы включили отдельную библиотеку, предлагающую реактивную файловую систему, использующую `BufferedSource` из библиотеки Okio. Также артефакт этот включает в себя `FileSystemPersister`, реализующий дисковый кэш для Store и прекрасно работающий с `GsonSourceParser`. При использовании `FileSystemPersister` нужно передать ему реализацию `PathResolver`, определяющую пути к элементам кэша в файловой системе. Вернемся к первому примеру: ```java Store<Article,Integer> store = StoreBuilder.<Integer, BufferedSource, Article>parsedWithKey() .fetcher(articleId -> api.getArticles(articleId)) .persister(FileSystemPersister.create(FileSystemFactory.create(context.getFilesDir()),pathResolver)) .parser(GsonParserFactory.createSourceParser(gson, String.class)) .open(); ``` Как уже упоминалось, это то, как мы работаем с сетевыми операциями в The New York Times. Используя конфигурацию, указанную выше, вы получаете: + Кэширование в памяти с помощью Guava Cache + Кэширование на диске с помощью FileSystem (вы можете переиспользовать одну и ту же файловую систему для всех Store) + Парсинг данных из `BufferedSource` в `<T>` (Класс Article в нашем примере) с помошью Gson + Оптимизация запросов + Возможность использовать кэшированные данные или запросить свежие (методы `get()` и `fresh()`) + Возможность подписаться на все новые элементы, полученные из сети (метод `stream()`) + Возможность получить уведомление об очистке кэша, а также переподписаться после этого (метод `getRefreshing()`). Полезно, если нужно выполнить запрос типа POST, после чего другой обновить экран) Мы рекомендуем использовать эту конфигурацию для большинства хранилищ Store. Благодаря передаче данных из сети на диск и с диска в парсер в формате потока байтов, `SourcePersister` потребляет малое количество памяти. Это позволяет нам загружать десятки ответов в формате json размером более 1mb и не беспокоиться об исключениях OutOfMemory на устройствах с малым объемом памяти. Как упоминалось выше, использование Store позволяет нам делать такие вещи, как вызов `configStore.get()` множествно раз асинхронно, прежде чем наша MainActivity закончит загрузку, не блокируя основной поток и не загружая сеть. ### RecordProvider Если вы хотите, чтобы ваш Store знал об устаревании данных на диске, ваш `Persister` должер реализовывать интерфейс `RecordProvider`. После этого, вы можете настроить работу Store одним из двух способов: ```java store = StoreBuilder.<BufferedSource>barcode() .fetcher(fetcher) .persister(persister) .refreshOnStale() .open(); ``` `refreshOnStale` инвалидирует дисковый кэш, каждый раз когда данные устареют. Пользователь получит устаревшие данные. Или же: ```java store = StoreBuilder.<BufferedSource>barcode() .fetcher(fetcher) .persister(persister) .networkBeforeStale() .open(); ``` `networkBeforeStale` — Store попытается использовать сетевой источник, если данные устарели. Если сетевой источник данных выбрасывает исключение или возвращает пустой ответ, Store будет использовать устаревшие данные. ### Создание подклассов Store Можно отнаследоваться от класса реализации Store (`RealStore<T>`): ```java public class SampleStore extends RealStore<String, BarCode> { public SampleStore(Fetcher<String, BarCode> fetcher, Persister<String, BarCode> persister) { super(fetcher, persister); } } ``` Это может быть полезно, если вы хотите внедрить зависимость Store или добавить несколько вспомогательных методов: ```java public class SampleStore extends RealStore<String, BarCode> { @Inject public SampleStore(Fetcher<String, BarCode> fetcher, Persister<String, BarCode> persister) { super(fetcher, persister); } } ``` ### Артефакты Примечание: релизы синхронизированы с состоянием ветки master (а не develop). + **Cache** Кэш, извлеченный из библиотеки Guava (чтобы сократить количество методов) ```groovy implementation 'com.nytimes.android:cache:CurrentVersion' ``` + **Store** Содержит только классы Store, зависит от RxJava и артефакта кэша ```groovy implementation 'com.nytimes.android:store:CurrentVersion' ``` + **Middleware** Парсеры Gson (не стесняйтесь создавать новые и предлагать PR) ```groovy implementation 'com.nytimes.android:middleware:CurrentVersion' ``` + **Middleware-Jackson** Парсеры Jackson (не стесняйтесь создавать новые и предлагать PR) ```groovy implementation 'com.nytimes.android:middleware-jackson:CurrentVersion' ``` + **Middleware-Moshi** Парсеры Moshi (не стесняйтесь создавать новые и предлагать PR) ```groovy implementation 'com.nytimes.android:middleware-moshi:CurrentVersion' ``` + **File System** библиотека, использующая Okio Source/Sink + Middleware для сохранения потока данных из сети в файловую систему ```groovy implementation 'com.nytimes.android:filesystem:CurrentVersion' ``` ### Пример проекта Директория app содержит тестовое приложение, демонстрирующее использование Store. Кроме того, вики этого репозитория содержит некоторые рецепты для распространенных сценариев использования: + Простой пример: Retrofit + Store + Сложный пример: BufferedSource и Retrofit (или OkHTTP) + кэш на диске с FileSystem + GsonSourceParser
{ "pile_set_name": "Github" }
package org.omg.PortableInterceptor; /** * org/omg/PortableInterceptor/ClientRequestInfo.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from c:/workspace/9-2-build-windows-amd64-cygwin-phase2/jdk9/6725/corba/src/java.corba/share/classes/org/omg/PortableInterceptor/Interceptors.idl * Wednesday, August 2, 2017 9:29:17 PM PDT */ /** * Request Information, accessible to client-side request interceptors. * <p> * Some attributes and operations on <code>ClientRequestInfo</code> are * not valid at all interception points. The following table shows the * validity of each attribute or operation. If it is not valid, attempting * to access it will result in a <code>BAD_INV_ORDER</code> being thrown * with a standard minor code of 14. * * <table class="plain"> * <caption style="display:none">Shows the validity of each attribute or operation</caption> * <thead> * <tr> * <th>&nbsp;</th> * <th id="send_req">send_request</th> * <th id="send_poll">send_poll</th> * <th id="rec_reply">receive_reply</th> * <th id="rec_ex">receive_exception</th> * <th id="rec_oth">receive_other</th> * </tr> * </thead> * <tbody> * * <tr> * <td id="ri" colspan=6><i>Inherited from RequestInfo:</i></td> * </tr> * * <tr><th id="req_id"><p style="text-align:left">request_id</p></th> * <td headers="ri req_id send_req">yes</td> * <td headers="ri req_id send_poll">yes</td> * <td headers="ri req_id rec_reply">yes</td> * <td headers="ri req_id rec_ex">yes</td> * <td headers="ri req_id rec_oth">yes</td></tr> * * <tr><th id="op"><p style="text-align:left">operation</p></th> * <td headers="ri op send_req">yes</td> * <td headers="ri op send_poll">yes</td> * <td headers="ri op rec_reply">yes</td> * <td headers="ri op rec_ex">yes</td> * <td headers="ri op rec_oth">yes</td></tr> * * <tr><th id="arg"><p style="text-align:left">arguments</p></th> * <td headers="ri arg send_req">yes<sub>1</sub></td> * <td headers="ri arg send_poll">no </td> * <td headers="ri arg rec_reply">yes</td> * <td headers="ri arg rec_ex">no </td> * <td headers="ri arg rec_oth">no </td></tr> * * <tr><th id="exc"><p style="text-align:left">exceptions</p></th> * <td headers="ri exc send_req">yes</td> * <td headers="ri exc send_poll">no </td> * <td headers="ri exc rec_reply">yes</td> * <td headers="ri exc rec_ex">yes</td> * <td headers="ri exc rec_oth">yes</td></tr> * * <tr><th id="con"><p style="text-align:left">contexts</p></th> * <td headers="ri con send_req">yes</td> * <td headers="ri con send_poll">no </td> * <td headers="ri con rec_reply">yes</td> * <td headers="ri con rec_ex">yes</td> * <td headers="ri con rec_oth">yes</td></tr> * * <tr><th id="op_con"><p style="text-align:left">operation_context</p></th> * <td headers="ri op_con send_req">yes</td> * <td headers="ri op_con send_poll">no </td> * <td headers="ri op_con rec_reply">yes</td> * <td headers="ri op_con rec_ex">yes</td> * <td headers="ri op_con rec_oth">yes</td> * </tr> * * <tr><th id="result"><p style="text-align:left">result</p></th> * <td headers="ri result send_req">no </td> * <td headers="ri result send_poll">no </td> * <td headers="ri result rec_reply">yes</td> * <td headers="ri result rec_ex">no </td> * <td headers="ri result rec_oth">no </td> * </tr> * * <tr><th id="res_exp"><p style="text-align:left">response_expected</p></th> * <td headers="ri res_exp send_req">yes</td> * <td headers="ri res_exp send_poll">yes</td> * <td headers="ri res_exp rec_reply">yes</td> * <td headers="ri res_exp rec_ex">yes</td> * <td headers="ri res_exp rec_oth">yes</td></tr> * * <tr><th id="sync_sco"><p style="text-align:left">sync_scope</p></th> * <td headers="ri sync_sco send_req">yes</td> * <td headers="ri sync_sco send_poll">no </td> * <td headers="ri sync_sco rec_reply">yes</td> * <td headers="ri sync_sco rec_ex">yes</td> * <td headers="ri sync_sco rec_oth">yes</td> * </tr> * * <tr><th id="rep_stat"><p style="text-align:left">reply_status</p></th> * <td headers="ri rep_stat send_req">no </td> * <td headers="ri rep_stat send_poll">no </td> * <td headers="ri rep_stat rec_reply">yes</td> * <td headers="ri rep_stat rec_ex">yes</td> * <td headers="ri rep_stat rec_oth">yes</td></tr> * * <tr><th id="for_ref"><p style="text-align:left">forward_reference</p></th> * <td headers="ri for_ref send_req">no </td> * <td headers="ri for_ref send_poll">no </td> * <td headers="ri for_ref rec_reply">no </td> * <td headers="ri for_ref rec_ex">no </td> * <td headers="ri for_ref rec_oth">yes<sub>2</sub> * </td></tr> * * <tr><th id="get_slot"><p style="text-align:left">get_slot</p></th> * <td headers="ri get_slot send_req">yes</td> * <td headers="ri get_slot send_poll">yes</td> * <td headers="ri get_slot rec_reply">yes</td> * <td headers="ri get_slot rec_ex">yes</td> * <td headers="ri get_slot rec_oth">yes</td></tr> * * <tr><th id="grsc"><p style="text-align:left">get_request_service_context</p></th> * <td headers="ri grsc send_req">yes</td> * <td headers="ri grsc send_poll">no </td> * <td headers="ri grsc rec_reply">yes</td> * <td headers="ri grsc rec_ex">yes</td> * <td headers="ri grsc rec_oth">yes</td></tr> * * <tr><th id="gpsc"><p style="text-align:left">get_reply_service_context</p></th> * <td headers="ri gpsc send_req">no </td> * <td headers="ri gpsc send_poll">no </td> * <td headers="ri gpsc rec_reply">yes</td> * <td headers="ri gpsc rec_ex">yes</td> * <td headers="ri gpsc rec_oth">yes</td> * </tr> * * <tr> * <td id="cri" colspan=6><i>ClientRequestInfo-specific:</i></td> * </tr> * * <tr><th id="target"><p style="text-align:left">target</p></th> * <td headers="cri target send_req">yes</td> * <td headers="cri target send_poll">yes</td> * <td headers="cri target rec_reply">yes</td> * <td headers="cri target rec_ex">yes</td> * <td headers="cri target rec_oth">yes</td></tr> * * <tr><th id="eftarget"><p style="text-align:left">effective_target</p></th> * <td headers="cri eftarget send_req">yes</td> * <td headers="cri eftarget send_poll">yes</td> * <td headers="cri eftarget rec_reply">yes</td> * <td headers="cri eftarget rec_ex">yes</td> * <td headers="cri eftarget rec_oth">yes</td> * </tr> * * <tr><th id="efprof"><p style="text-align:left">effective_profile</p></th> * <td headers="cri efprof send_req">yes</td> * <td headers="cri efprof send_poll">yes</td> * <td headers="cri efprof rec_reply">yes</td> * <td headers="cri efprof rec_ex">yes</td> * <td headers="cri efprof rec_oth">yes</td></tr> * * <tr><th id="rxp"><p style="text-align:left">received_exception</p></th> * <td headers="cri rxp send_req">no </td> * <td headers="cri rxp send_poll">no </td> * <td headers="cri rxp rec_reply">no </td> * <td headers="cri rxp rec_ex">yes</td> * <td headers="cri rxp rec_oth">no </td></tr> * * <tr><th id="rei"><p style="text-align:left">received_exception_id</p></th> * <td headers="cri rei send_req">no </td> * <td headers="cri rei send_poll">no </td> * <td headers="cri rei rec_reply">no </td> * <td headers="cri rei rec_ex">yes</td> * <td headers="cri rei rec_oth">no </td></tr> * * <tr><th id="gec"><p style="text-align:left">get_effective_component</p></th> * <td headers="cri gec send_req">yes</td> * <td headers="cri gec send_poll">no </td> * <td headers="cri gec rec_reply">yes</td> * <td headers="cri gec rec_ex">yes</td> * <td headers="cri gec rec_oth">yes</td></tr> * * <tr><th id="gecs"><p style="text-align:left">get_effective_components</p></th> * <td headers="cri gecs send_req">yes</td> * <td headers="cri gecs send_poll">no </td> * <td headers="cri gecs rec_reply">yes</td> * <td headers="cri gecs rec_ex">yes</td> * <td headers="cri gecs rec_oth">yes</td></tr> * * <tr><th id="grpcy"><p style="text-align:left">get_request_policy</p></th> * <td headers="cri grpcy send_req">yes</td> * <td headers="cri grpcy send_poll">no </td> * <td headers="cri grpcy rec_reply">yes</td> * <td headers="cri grpcy rec_ex">yes</td> * <td headers="cri grpcy rec_oth">yes</td></tr> * * <tr><th id="arsc"><p style="text-align:left">add_request_service_context</p></th> * <td headers="cri arsc send_req">yes</td> * <td headers="cri arsc send_poll">no </td> * <td headers="cri arsc rec_reply">no </td> * <td headers="cri arsc rec_ex">no </td> * <td headers="cri arsc rec_oth">no </td></tr> * * </tbody> * </table> * * <ol> * <li>When <code>ClientRequestInfo</code> is passed to * <code>send_request</code>, there is an entry in the list for every * argument, whether in, inout, or out. But only the in and inout * arguments will be available.</li> * <li>If the <code>reply_status</code> atribute is not * <code>LOCATION_FORWARD</code>, accessing this attribute will * throw <code>BAD_INV_ORDER</code> with a standard minor code of * 14.</li> * </ol> * * @see ClientRequestInterceptor */ public interface ClientRequestInfo extends ClientRequestInfoOperations, org.omg.PortableInterceptor.RequestInfo, org.omg.CORBA.portable.IDLEntity { } // interface ClientRequestInfo
{ "pile_set_name": "Github" }