code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/*
* Copyright (c) 2011 Tamas Cservenak. All rights reserved.
*
* <tamas@cservenak.com>
* http://www.cservenak.com/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.speakeasy.skyengine.resources.io.lzma.streams.cs;
import java.io.IOException;
import java.io.OutputStream;
public class CoderOutputStream
extends OutputStream {
private final CoderThread ct;
private OutputStream out;
protected CoderOutputStream(final OutputStream out, final Coder coder)
throws IOException {
this.ct = new CoderThread(coder, out);
this.out = ct.getOutputStreamSink();
this.ct.start();
}
public void write(int b)
throws IOException {
out.write(b);
}
public void write(byte b[])
throws IOException {
write(b, 0, b.length);
}
public void write(byte b[], int off, int len)
throws IOException {
if ((off | len | (b.length - (len + off)) | (off + len)) < 0) {
throw new IndexOutOfBoundsException();
}
out.write(b, off, len);
}
public void flush()
throws IOException {
out.flush();
}
public void close()
throws IOException {
try {
flush();
} catch (IOException ignored) {
// why do we swallow exception here?!
}
out.close();
try {
ct.join();
} catch (InterruptedException e) {
throw new IOException(e);
}
ct.checkForException();
}
}
|
speakeasy/SKYEngine
|
src/com/speakeasy/skyengine/resources/io/lzma/streams/cs/CoderOutputStream.java
|
Java
|
artistic-2.0
| 2,095 |
"""
hmmer module
"""
from __future__ import print_function
from mungo.mungoCore import *
import blast, sequence
from mungo.useful import smartopen, extractRootName, ClassFromDict, warnDeprecated
import sys, re, warnings
hmmer2frame = {0: 1, 1: 2, 2: 3, 3: -1, 4: -2, 5: -3}
frame2hmmer = dict([(v,k) for k,v in hmmer2frame.iteritems()])
def HmmerFile(iFileHandle, **kw):
"Factory function returning a HmmerFileReader"
return HmmerReader(iFileHandle, **kw)
class HmmerReader(AbstractDataReader):
def __init__(self, iFileHandle, seqType=None, eValueCutoff=None, scoreCutoff=None):
super(HmmerReader, self).__init__(iFileHandle)
self.seqType = seqType
self.eValueCutoff = eValueCutoff
self.scoreCutoff = scoreCutoff
def _generator(self):
"""Return an iterator to a HMMer file."""
if self.seqType in [Domain, SixFrameDomain, BlockSixFrameDomain, OrfDomain, OrfDomain2]:
_Domain = self.seqType
elif self.seqType=='SixFrame':
_Domain = SixFrameDomain
elif self.seqType=='BlockSixFrame':
_Domain = BlockSixFrameDomain
elif self.seqType=='ORFs':
_Domain = OrfDomain
else:
_Domain = Domain
startToken = '^Parsed for domains'
endToken = '^Alignments of top-scoring domains'
abortToken = '\[no hits above thresholds\]'
startRegex = re.compile(startToken)
if not jumpToMatch(self.iFile, startRegex):
raise Exception('No match found. File may be empty.')
# 3. Parse domain details
line = self.iFile.next()
line = self.iFile.next()
endRegex = re.compile(endToken)
abortRegex = re.compile(abortToken)
domains = []
for line in self.iFile:
line = line.strip()
if endRegex.match(line) or abortRegex.match(line):
break
elif not line:
continue
tokens = line.split()
d = _Domain(dict(zip(Domain.attributes[1:], tokens)))
if (self.eValueCutoff and d.eValue>self.eValueCutoff) or \
(self.scoreCutoff and d.score<self.scoreCutoff): continue
yield d
class PfamReader(AbstractDataReader):
def __init__(self, iFileHandle, eValueCutoff=None, scoreCutoff=None):
super(PfamReader, self).__init__(iFileHandle)
self.eValueCutoff = eValueCutoff
self.scoreCutoff = scoreCutoff
def _generator(self):
pass
class Domain(AbstractFeature):
"""Domain feature class"""
attributes = ['domain', 'accession', 'count', 'sStart', 'sEnd',
'sCode', 'qStart', 'qEnd', 'qCode', 'score', 'eValue']
converters = zip(
['qStart','qEnd','sStart','sEnd','score','eValue'],
[int,int,int,int,float,float])
format = attributesToFormat(attributes)
def __init__(self, *args, **kw):
"""Constructor:
@param args: HMMer field values
@type args: list, dict, Domain
Optional keywords:
@keyword domain: Domain name
@keyword accession: Subject name
@keyword count: Id/total hits on subject
@keyword sStart:
@keyword sEnd:
@keyword sCode:
@keyword qStart:
@keyword qEnd:
@keyword qCode:
@keyword score: Bit score
@keyword eValue:
"""
super(Domain, self).__init__(*args, **kw)
self.genomic = False
def __repr__(self):
d = {}
for k,v in self.__dict__.iteritems():
d[k] = v
return self.format % d
def getTokens(self):
return [self.__dict__[key] for key in self.attributes]
def addAttribute(self, attribute, default=None):
self.attributes.append(attribute)
self.format = self.format + '\t%%(%s)s' % attribute
self.__dict__[attribute] = default
def addStrandAttribute(self, strand=None):
self.addAttribute('strand', strand)
def swapStartEnd(self):
if self.sStart>self.sEnd:
self.sStart,self.sEnd = self.sEnd,self.sStart
def getSequence(self, blastdb, getAll=False, convertAccession=lambda x: x):
if getAll:
start = 0
end = 0
else:
start = self.sStart
end = self.sEnd
accession = convertAccession(self.accession)
h,s = blast.getSequence(blastdb, accession, start, end)
return h,s
@staticmethod
def fromGenomic(tokens):
strand = tokens[-1]
d = Domain(tokens[0:-1])
d.genomic = True
d.addStrandAttribute(strand)
return d
class OrfDomain(Domain):
def toGenomic(self, orfStart, orfStrand, doSwapStartEnd=True):
"""Convert from ORF to genomic coordinates."""
self.genomic = True
self.sStart,self.sEnd = convertOrfToGenomic(
self.sStart, self.sEnd, orfStrand, orfStart)
self.addStrandAttribute(orfStrand)
if doSwapStartEnd:
self.swapStartEnd()
class OrfDomain2(Domain):
"ORF domain class for use with my ORF files"
def toGenomic(self, doSwapStartEnd=True):
"""Convert from ORF to genomic coordinates."""
self.genomic = True
o = parseOrfHeader(self.accession)
self.sStart,self.sEnd = convertOrfToGenomic(
self.sStart, self.sEnd, o.strand, o.start)
self.addStrandAttribute(o.strand)
if doSwapStartEnd:
self.swapStartEnd()
class SixFrameDomain(Domain):
def toGenomic(self, L, doSwapStartEnd=True):
"""Convert from 6 frame to genomic coordinates.
@param L: Length of DNA sequence.
"""
self.genomic = True
o = parseSixFrameHeader(self.accession)
self.sStart,self.sEnd = convertSixFrameToGenomic(
self.sStart, self.sEnd, o.frame, L)
self.accession = o.name
self.strand = o.strand
self.addStrandAttribute(o.strand)
if doSwapStartEnd:
self.swapStartEnd()
def toBlockCoords(self, L=1e99, blockSize=5000000, delimiter='.'):
self.accession, self.sStart, self.sEnd = \
blast.genomeToBlock(
self.accession, self.sStart, self.sEnd, L=L,
blockSize=blockSize, delimiter=delimiter)
def getSequenceFromString(self, seq):
s = seq[self.sStart-1:self.sEnd]
if self.strand=='-':
s = sequence.reverseComplement(s)
return s
def getSequence(self, blastDb, padFivePrime=0, padThreePrime=0):
if self.genomic:
start = max(1,self.sStart-padFivePrime)
end = self.sEnd+padThreePrime
h,s = blast.getSequence(blastDb, self.accession, start, end, self.strand)
else:
raise Exception('You must call the toGenomic method first.')
return h,s
class BlockSixFrameDomain(Domain):
def toGenomic(self, relative=False, doSwapStartEnd=True, relDelimiter=':'):
"""Convert from 6 frame to genomic coordinates."""
self.genomic = True
chrom,blockStart,blockEnd,gStart,gEnd,strand = \
convertBlockSixFrameToGenomic(
self.accession, self.sStart, self.sEnd)
if relative:
self.accession = '%s%s%i-%i' % (chrom,relDelimiter,blockStart,blockEnd)
self.sStart = gStart
self.sEnd = gEnd
else:
self.accession = chrom
self.sStart = blockStart + gStart - 1
self.sEnd = blockStart + gEnd - 1
self.addStrandAttribute(strand)
if doSwapStartEnd:
self.swapStartEnd()
class GenomicDomain(AbstractFeature):
"""GenomicDomain feature class"""
attributes = ['domain', 'accession', 'count', 'sStart', 'sEnd',
'sCode', 'qStart', 'qEnd', 'qCode', 'score', 'eValue']
converters = zip(
['qStart','qEnd','sStart','sEnd','score','eValue'],
[int,int,int,int,float,float])
format = attributesToFormat(attributes)
def __init__(self, *args, **kw):
"""Constructor:
@param args: HMMer field values
@type args: list, dict, Domain
Optional keywords:
@keyword domain: Domain name
@keyword accession: Subject name
@keyword count: Id/total hits on subject
@keyword sStart:
@keyword sEnd:
@keyword sCode:
@keyword qStart:
@keyword qEnd:
@keyword qCode:
@keyword score: Bit score
@keyword eValue:
@keyword strand:
"""
super(GenomicDomain, self).__init__(*args, **kw)
def toDict(self):
return self.__dict__
def toList(self):
return self.__dict__.items()
def __repr__(self):
try:
d = {}
for k,v in self.__dict__.iteritems():
d[k] = v
return self.format % d
except:
return str(self.__dict__)
def toBlockCoords(self, L=1e99, blockSize=5000000, delimiter='.'):
self.accession, self.sStart, self.sEnd = \
blast.genomeToBlock(
self.accession, self.sStart, self.sEnd, L=L,
blockSize=blockSize, delimiter=delimiter)
def getSequence(self, blastDb, padFivePrime=0, padThreePrime=0):
start = max(1,self.sStart-padFivePrime)
end = self.sEnd+padThreePrime
h,s = blast.getSequence(blastDb, self.accession, start, end, self.strand)
return h,s
def loadGenomicDomains(filename):
data = []
gene = []
for line in open(filename):
line = line.strip()
if not line:
continue
elif line[0] in ['#', '>']:
if gene:
data.append(gene)
gene = []
else:
tokens = line.split('\t')
d = GenomicDomain(tokens)
gene.append(d)
data.append(gene)
return data
def jumpToMatch(iFile, regex):
"""Jump to regex match in file.
@param iFile: File object
@param regex: Compiled regex object
@return: True if successful, False otherwise
"""
for line in iFile:
if regex.match(line):
return True
return False
def extractUptoMatch(iFile, regex):
"""Extract up to regex match from file.
@param iFile: File object
@param regex: Compiled regex object
@return: string
"""
block = []
for line in iFile:
if regex.match(line):
break
else:
block.append(line.rstrip())
return block
def parseSixFrameHeader(header):
"""Parse a 6 frame header (from translate or python).
@param header: Six frame header "<name>:<frame>" or "<name>.<start>-<end>:<frame>"
(assumes input frame is hmmer frame (0-5)).
@return: a simple class with attributes name, start, end, strand and frame.
"""
header = header.strip()
regex = re.compile(
'(?P<name>\w+)([\.|:](?P<start>\d+)[-|,](?P<end>\d+))?:(?P<frame>[0-5])')
rs = regex.search(header)
d = rs.groupdict()
d['frame'] = hmmer2frame[int(d['frame'])]
if d['frame']>0:
d['strand'] = '+'
else:
d['strand'] = '-'
try:
d['start'] = int(d['start'])
d['end'] = int(d['end'])
except:
pass
return ClassFromDict(d)
def parseOrfHeader(header):
"""Parse an ORF header (from extractORFs.py).
@param header: ORF header "<name>.<orfId>.<start>-<end> Length=<length>"
(Length optional).
@return: a simple class with attributes name, start, end, strand and length.
"""
regex = re.compile(
'(?P<name>\w+)\.(?P<orfId>\d+)\.(?P<start>\d+)-(?P<end>\d+)(\SLength=(?P<length>\d+))?')
rs = regex.match(header.strip())
d = rs.groupdict()
try:
d['start'] = int(d['start'])
d['end'] = int(d['end'])
d['length'] = int(d['length'])
except:
pass
if d['start']>d['end']:
d['strand'] = '-'
else:
d['strand'] = '+'
return ClassFromDict(d)
def convertSixFrameToGenomic(start, end, frame, L):
"""Convert 6 frame coords to genomic.
@param start: Amino acid start coord
@param end: Amino acid end coord
@param frame: Frame
@param L: Nucleotide seq length
@return: (gStart, gEnd, strand)
"""
if frame>=0:
gStart = 3*(start-1)+(frame-1)+1
gEnd = 3*(end-1)+(frame-1)+3
else:
gStart = L-(3*(start-1)+abs(frame)-1)
gEnd = L-(3*(end-1)+abs(frame)+1)
return gStart,gEnd
def convertBlockSixFrameToGenomic(block, start, end):
"""Convenience function that takes block 6 frame coords
(block,start,end), extracts the block start/end and frame
and converts them to genomic coords
ie.
chrom.blockStart-blockEnd:frame aaStart aaEnd or
chrom:blockStart-blockEnd:frame aaStart aaEnd
--> chrom,blockStart,blockEnd,gStart,gEnd,strand
@param block: Block accession ("<name>.<blockStart>-<blockEnd>:<frame>")
@param start: Domain start
@param end: Domain end
@return: (chrom, blockStart, blockEnd, gStart, gEnd, strand)
string[:.]number-number:number
"""
#prog = re.compile('\.|-|\:')
#tokens = prog.split(block)
#prog = re.compile("(?P<chrom>[\w]+)[.:](?P<bstart>[0-9]+)-(?P<bend>[0-9]+):(?P<frame>[0-9]+)")
#rs = prog.search(block)
#if rs:
# g = rs.groupdict()
# chrom,blockStart,blockEnd,hmmerFrame = g["chrom"],g["bstart"],g["bend"],g["frame"]
# blockStart = int(blockStart)
# blockEnd = int(blockEnd)
# hmmerFrame = int(hmmerFrame)
# L = blockEnd-blockStart+1
tokens = block.split(":")
if len(tokens)==2:
hmmerFrame = tokens[1]
tokens = tokens[0].split(".")
chrom = tokens[0]
blockStart,blockEnd = tokens[1].split("-")
elif len(tokens)==3:
chrom = tokens[0]
blockStart,blockEnd = tokens[1].split("-")
hmmerFrame = tokens[2]
else:
print(tokens, file=sys.stderr)
raise Exception("Don't know what to do")
blockStart = int(blockStart)
blockEnd = int(blockEnd)
L = blockEnd-blockStart+1
hmmerFrame = int(hmmerFrame)
frame = hmmer2frame[hmmerFrame]
if frame>0:
strand = '+'
else:
strand = '-'
gStart,gEnd = convertSixFrameToGenomic(start, end, frame, L)
return chrom,blockStart,blockEnd,gStart,gEnd,strand
def convertGenomicToBlockCoords(domain, chrLen, blockSize=5000000, delimiter='.'):
domain.accession, domain.sStart, domain.sEnd = \
blast.genomeToBlock(
domain.accession, domain.sStart, domain.sEnd,
L=chrLen, blockSize=blockSize, delimiter=delimiter)
return domain
def convertOrfToGenomic(start, end, strand, orfStart):
"""Convert domain coordinates in ORF to genomic.
@param start: Domain start coord
@param end: Domain end coord
@param strand: Strand
@param orfStart: ORF start coord
@return: (gStart, gEnd)
"""
if strand=='+':
gStart = orfStart + 3*(start-1)
gEnd = orfStart + 3*(end-1) + 2
else:
gStart = orfStart - 3*(start-1)
gEnd = orfStart - 3*(end-1) - 2
return gStart, gEnd
def loadDomains(iFileHandle):
"""Load hmmer domain results.
@param iFileHandle: Input file or filename
@param seqType: Type of sequence searched
[None (default), 'SixFrame', 'BlockSixFrame' or 'ORFs']
@param eValueCutoff: E-value threshold (default None)
@param scoreCutoff: Score threshold (default None)
@return: list of domains
"""
domains = []
for d in HmmerFile(iFileHandle):
domains.append(d)
return domains
|
PapenfussLab/Mungo
|
mungo/hmmer.py
|
Python
|
artistic-2.0
| 15,959 |
package ttftcuts.atg.api;
import java.util.List;
import ttftcuts.atg.api.events.*;
import ttftcuts.atg.api.events.listenable.ATGBiomeGroupAssignmentEvent.ATGGroupActivationEvent;
import net.minecraft.world.World;
import net.minecraft.world.biome.BiomeGenBase;
import net.minecraftforge.common.MinecraftForge;
import com.google.common.base.Optional;
/**
*
* @author TTFTCUTS
*
* Biome related API things! Biome groups, adding biomes to those groups and more.
*
*/
public abstract class ATGBiomes {
public static enum BiomeType { LAND, COAST, SEA }
/**
* Gets an ATG biome by name.
*
* @param biomeName
* The name of the biome you want to get.
*
* @return the corresponding biome.
*/
public static BiomeGenBase getBiome(String biomeName) {
final ATGBiomeRequestEvent event = new ATGBiomeRequestEvent(biomeName);
MinecraftForge.EVENT_BUS.post(event);
if ( !event.biome.isPresent() ) {
return null;
}
return event.biome.get();
}
/**
* Gets a list of names corresponding to the Biome Groups which contain a specified biome.
*
* @param biome
* The biome you want to find groups for.
*
* @return a list of names of containing Biome Groups.
*/
public static List<String> getGroupFromBiome(BiomeGenBase biome) {
final ATGBiomeGroupRequestEvent event = new ATGBiomeGroupRequestEvent(biome);
MinecraftForge.EVENT_BUS.post(event);
return event.groups;
}
/**
* Gets the raw height, temperature and moisture values from the generator for a specific pair of x/z coordinates.
*
* WARNING: This is a VERY expensive calculation and the result is NOT cached, so please use as little as possible!
*
* @param world
* The world that you want to get the information for.
*
* @param x
* X coordinate of the point to query.
*
* @param z
* Z coordinate of the point to query.
*
* @return an array of three doubles corresponding to the height, temperature and moisture at the specified point in the ranges 0.0-1.0.
*/
public static double[] getGeneratorInfo(World world, double x, double z) {
final ATGGeneratorInfoEvent event = new ATGGeneratorInfoEvent(world,x,z);
MinecraftForge.EVENT_BUS.post(event);
return event.info;
}
/**
* Adds a new biome GROUP to ATG. Not something that would usually need to be used.
*
* @param type
* The biome type that this group belongs to. LAND, COAST or SEA.
*
* @param name
* The name of this group.
*
* @param temp
* Temperature value for this group. Same range as biome temperatures.
*
* @param moisture
* Moisture value for this group. Same range as biome rainfall.
*
* @param height
* Average height value for this group. Same range as biome heights.
*
* @param minHeight
* Minimum height to generate this group. Above this value, it will be skipped.
*
* @param maxHeight
* Maximum height to generate this group. Below this value, it will be skipped.
*
* @param salt
* Biome blob generation salt. Used to offset biome boundaries from other groups to avoid strange artifacts.
*
* @param generate
* Set to false to prevent this group generating in the default manner. Primarily for use with the biome group assignment events.
*/
public static void addBiomeGroup(BiomeType type, String name, double temp, double moisture, double height, double minHeight, double maxHeight, long salt, boolean generate) {
ATGBiomeGroupAddEvent event = new ATGBiomeGroupAddEvent(type, name, temp, moisture, height, minHeight, maxHeight, salt, generate);
MinecraftForge.EVENT_BUS.post(event);
if ( event.response == ATGBiomeGroupAddEvent.ResponseType.FAILED ) {
// FAILED!
}
}
public static void addBiomeGroup(BiomeType type, String name, double temp, double moisture, double height, double minHeight, double maxHeight, long salt) {
addBiomeGroup(type, name, temp, moisture, height, minHeight, maxHeight, salt, true);
}
public static void addBiomeGroup(BiomeType type, String name, double temp, double moisture, double height, long salt) {
addBiomeGroup(type, name, temp, moisture, height, 0.0, 1.0, salt);
}
public static void addBiomeGroup(BiomeType type, String name, double temp, double moisture, double height) {
addBiomeGroup(type, name, temp, moisture, height, 0);
}
/**
* Modifies a biome group to make it more or less likely to be chosen by the generator.
* Best used to ensure a height-constrained biome group generates in favour of an otherwise identically ranged group.
*
* @param type
* Group type for the second parameter. LAND, COAST or SEA.
*
* @param name
* Name of the group to modify.
*
* @param modifier
* Modifier value. Positive makes the group more likely to be picked. Very small values can have a large effect.
*/
public static void modGroupSuitability(BiomeType type, String name, double modifier) {
ATGBiomeGroupEvent event = new ATGBiomeGroupEvent( ATGBiomeGroupEvent.EventType.SUITABILITY, type, name, modifier );
MinecraftForge.EVENT_BUS.post(event);
if ( event.response == ATGBiomeGroupEvent.ResponseType.FAILED ) {
// FAILED!
}
}
/**
* Register a biome with ATG.
*
* @param type
* Type of the biome group this biome will inhabit. LAND, COAST or SEA.
*
* @param group
* Name of the biome group this biome will inhabit.
*
* @param biome
* The biome to be registered.
*
* @param weight
* Generation weight for this biome. All vanilla biomes are weighted 1.0 except mushroom island.
*/
public static void addBiome(BiomeType type, String group, BiomeGenBase biome, double weight) {
ATGBiomeEvent event = new ATGBiomeEvent( type, group, biome, null, weight);
MinecraftForge.EVENT_BUS.post(event);
}
/**
* Replace a biome in a group with a different biome.
*
* @param type
* Type of the target biome group. LAND, COAST or SEA.
*
* @param group
* Name of the target biome group.
*
* @param toReplace
* Biome to replace in the specified group.
*
* @param replacement
* Biome which will replace toReplace in the group.
*
* @param weight
* Generation weight for the replacement biome.
*/
public static void replaceBiome(BiomeType type, String group, BiomeGenBase toReplace, BiomeGenBase replacement, double weight) {
ATGBiomeEvent event = new ATGBiomeEvent( type, group, replacement, toReplace, weight );
MinecraftForge.EVENT_BUS.post(event);
}
/**
* Add a sub-biome to a biome. Sub-biomes appear as smaller patches within their parent biome.
*
* @param biome
* Parent biome.
*
* @param subBiome
* Biome that will appear as a sub-biome.
*
* @param weight
* Generation weight for the sub-biome. The parent biome is always weighted at 1.0, so a 1.0 weight here with a single sub-biome would be a 50/50 split.
*/
public static void addSubBiome(BiomeGenBase biome, BiomeGenBase subBiome, double weight) {
ATGBiomeModEvent event = new ATGBiomeModEvent(ATGBiomeModEvent.EventType.SUBBIOME, biome, null, subBiome, weight);
MinecraftForge.EVENT_BUS.post(event);
}
/**
* Add an IGenMod to a biome to modify how it generates.
*
* @param biome
* Biome to attach the mod to.
*
* @param mod
* IGenMod object that will modify the biome.
*/
public static void addGenMod(BiomeGenBase biome, IGenMod mod) {
ATGBiomeModEvent event = new ATGBiomeModEvent(ATGBiomeModEvent.EventType.GENMOD, biome, mod, null, 0);
MinecraftForge.EVENT_BUS.post(event);
}
/**
* Get the IGenMod assigned to a biome, or Optional.absent if there isn't one.
*
* @param biome
* The biome to get the IGenMod for.
*
* @return an Optional corresponding to the IGenMod for the biome, or Optional.absent.
*/
public static Optional<IGenMod> getGenMod(BiomeGenBase biome) {
ATGBiomeModRequestEvent event = new ATGBiomeModRequestEvent(biome);
MinecraftForge.EVENT_BUS.post(event);
return event.mod;
}
/**
* Sets the rock parameters for a biome, to modify how ATG boulders generate there.
*
* @param biome
* The biome to set rock properties for.
*
* @param rockChance
* 1 in rockChance chunks will contain a rock.
*
* @param bigRockChance
* 1 in bigRockChance rocks will be large.
*
* @param rocksPerChunk
* rockChance will be checked rocksPerChunk times per chunk.
*/
public static void setBiomeRocks(BiomeGenBase biome, int rockChance, int bigRockChance, int rocksPerChunk) {
ATGBiomeRocksEvent event = new ATGBiomeRocksEvent(biome, rockChance, bigRockChance, rocksPerChunk);
MinecraftForge.EVENT_BUS.post(event);
}
/**
* Use this to enable the posting of "ATGBiomeGroupAssignmentEvent"s at generation, to allow custom biome group overrides.
* If this is not called at least once, none of those events will be sent.
*
* Listening for ATGBiomeGroupAssignmentEvent allows direct replacement of the biome group at every x/z coordinate pair.
* When enabled, it slows generation by about 10% due to event volume, so it's off by default.
*
* Only call this if you intend to listen for those events.
*/
public static void enableBiomeGroupAssignmentEvent() {
ATGGroupActivationEvent event = new ATGGroupActivationEvent();
MinecraftForge.EVENT_BUS.post(event);
}
}
|
reteo/CustomOreGen
|
src/api/java/ttftcuts/atg/api/ATGBiomes.java
|
Java
|
artistic-2.0
| 9,346 |
#! /usr/bin/env python
"""
stats -- Prints some channel information.
disconnect -- Disconnect the bot. The bot will try to reconnect
after 60 seconds.
die -- Let the bot cease to exist.
"""
import liblo
import irc.bot
import irc.strings
from irc.client import ip_numstr_to_quad, ip_quad_to_numstr
class TestBot(irc.bot.SingleServerIRCBot):
def __init__(self, channel, nickname, server, port=6667, OSCport=57120):
irc.bot.SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
self.server = server
self.channel = channel
self.nickname = nickname
try:
self.target = liblo.Address(OSCport)
except liblo.AddressError, err:
print str(err)
sys.exit("OSC address error")
def on_nicknameinuse(self, c, e):
c.nick(c.get_nickname() + "_")
def on_welcome(self, c, e):
c.join(self.channel)
print "connected to:\t" + self.server
def on_privmsg(self, c, e):
self.do_command(e, e.arguments[0])
def on_pubmsg(self, c, e):
a = e.arguments[0].split(":", 1)
if len(a) > 1 and irc.strings.lower(a[0]) == irc.strings.lower(self.connection.get_nickname()):
self.do_command(e, a[1].strip())
return
def do_command(self, e, cmd):
nick = e.source.nick
c = self.connection
target = self.target
c.notice(nick, "--- Channel statistics ---")
msg = liblo.Message(self.nickname) # nickname is osc tag...
#msg.add(nick)
#~ if nick == "iow":
#~ for i in cmd:
#~ #msg.add(ord(i)) #ord: char's ascii number
#~ msg.add(i)
#~ liblo.send(target, msg)
#~ for i in cmd:
#~ msg.add(ord(i))
#~ liblo.send(target, msg)
#~ print msg
for i in cmd:
msg.add(ord(i))
liblo.send(target, msg)
if cmd == "disconnect":
self.disconnect()
elif cmd == "die":
self.die()
elif cmd == "stats":
print 'stats?'
for chname, chobj in self.channels.items():
c.notice(nick, "--- Channel statistics ---")
c.notice(nick, "Channel: " + chname)
users = chobj.users()
users.sort()
c.notice(nick, "Users: " + ", ".join(users))
opers = chobj.opers()
opers.sort()
c.notice(nick, "Opers: " + ", ".join(opers))
voiced = chobj.voiced()
voiced.sort()
c.notice(nick, "Voiced: " + ", ".join(voiced))
else:
c.notice(nick, "Not understood: " + cmd)
def main():
import sys
nickname = "p1n1"
#channel = "#mode+v"
server = "127.0.0.1"
IRCport = 6667
OSCport = 57120
print len(sys.argv)
if len(sys.argv) != 5:
print("Usage: Dtestbot <server[:port]> <channel> <nickname> <oscport>")
print("$ ./ircbot.py 127.0.0.1 \"mode+v\" jk 57124")
sys.exit(1)
s = sys.argv[1].split(":", 1)
server = s[0]
if len(s) == 2:
try:
port = int(s[1])
except ValueError:
print("Error: Erroneous port.")
sys.exit(1)
else:
port = 6667
channel = sys.argv[2]
nickname = sys.argv[3]
OSCport = sys.argv[4]
#print nickname
#bot = TestBot(channel, nickname, server, port)
bot = TestBot("#mode+v", nickname, "127.0.0.1", 6667, OSCport)
#bot = TestBot(channel, nickname, server, IRCport, OSCport)
bot.start()
print 'started...'
if __name__ == "__main__":
main()
|
sonoprob/0x56
|
bot/py/ircoscbot.py
|
Python
|
artistic-2.0
| 3,668 |
// Machine generated IDispatch wrapper class(es) created by Microsoft Visual C++
// NOTE: Do not modify the contents of this file. If this class is regenerated by
// Microsoft Visual C++, your modifications will be overwritten.
#include "stdafx.h"
#include "printer.h"
/////////////////////////////////////////////////////////////////////////////
// CPrinter properties
/////////////////////////////////////////////////////////////////////////////
// CPrinter operations
long CPrinter::GetDetail()
{
long result;
InvokeHelper(0x18, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
void CPrinter::SetDetail(long nNewValue)
{
static BYTE parms[] =
VTS_I4;
InvokeHelper(0x18, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
nNewValue);
}
long CPrinter::GetMarginBottom()
{
long result;
InvokeHelper(0x2, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
void CPrinter::SetMarginBottom(long nNewValue)
{
static BYTE parms[] =
VTS_I4;
InvokeHelper(0x2, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
nNewValue);
}
long CPrinter::GetMarginLeft()
{
long result;
InvokeHelper(0x3, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
void CPrinter::SetMarginLeft(long nNewValue)
{
static BYTE parms[] =
VTS_I4;
InvokeHelper(0x3, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
nNewValue);
}
long CPrinter::GetMarginTop()
{
long result;
InvokeHelper(0x4, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
void CPrinter::SetMarginTop(long nNewValue)
{
static BYTE parms[] =
VTS_I4;
InvokeHelper(0x4, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
nNewValue);
}
long CPrinter::GetMarginRight()
{
long result;
InvokeHelper(0x5, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
void CPrinter::SetMarginRight(long nNewValue)
{
static BYTE parms[] =
VTS_I4;
InvokeHelper(0x5, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
nNewValue);
}
long CPrinter::GetOrientation()
{
long result;
InvokeHelper(0x1, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
void CPrinter::SetOrientation(long nNewValue)
{
static BYTE parms[] =
VTS_I4;
InvokeHelper(0x1, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
nNewValue);
}
void CPrinter::Print()
{
InvokeHelper(0x40, DISPATCH_METHOD, VT_EMPTY, NULL, NULL);
}
void CPrinter::PrintLandscape()
{
InvokeHelper(0x41, DISPATCH_METHOD, VT_EMPTY, NULL, NULL);
}
void CPrinter::PrintPortrait()
{
InvokeHelper(0x43, DISPATCH_METHOD, VT_EMPTY, NULL, NULL);
}
void CPrinter::ShowPreview()
{
InvokeHelper(0x1c, DISPATCH_METHOD, VT_EMPTY, NULL, NULL);
}
void CPrinter::PrintPartial(long Left, long Top, long Right, long Bottom)
{
static BYTE parms[] =
VTS_I4 VTS_I4 VTS_I4 VTS_I4;
InvokeHelper(0x6, DISPATCH_METHOD, VT_EMPTY, NULL, parms,
Left, Top, Right, Bottom);
}
void CPrinter::BeginDoc()
{
InvokeHelper(0x7, DISPATCH_METHOD, VT_EMPTY, NULL, NULL);
}
void CPrinter::EndDoc()
{
InvokeHelper(0x8, DISPATCH_METHOD, VT_EMPTY, NULL, NULL);
}
long CPrinter::GetPrinterIndex()
{
long result;
InvokeHelper(0x9, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
void CPrinter::SetPrinterIndex(long nNewValue)
{
static BYTE parms[] =
VTS_I4;
InvokeHelper(0x9, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
nNewValue);
}
long CPrinter::GetPrinterCount()
{
long result;
InvokeHelper(0xa, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
CString CPrinter::GetPrinterDescription(long Index)
{
CString result;
static BYTE parms[] =
VTS_I4;
InvokeHelper(0xb, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, parms,
Index);
return result;
}
void CPrinter::PrintChart()
{
InvokeHelper(0xc, DISPATCH_METHOD, VT_EMPTY, NULL, NULL);
}
long CPrinter::GetPageHeight()
{
long result;
InvokeHelper(0xd, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
long CPrinter::GetPageWidth()
{
long result;
InvokeHelper(0xe, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL);
return result;
}
CString CPrinter::GetJobTitle()
{
CString result;
InvokeHelper(0xf, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&result, NULL);
return result;
}
void CPrinter::SetJobTitle(LPCTSTR lpszNewValue)
{
static BYTE parms[] =
VTS_BSTR;
InvokeHelper(0xf, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
lpszNewValue);
}
BOOL CPrinter::GetPrintProportional()
{
BOOL result;
InvokeHelper(0x11, DISPATCH_PROPERTYGET, VT_BOOL, (void*)&result, NULL);
return result;
}
void CPrinter::SetPrintProportional(BOOL bNewValue)
{
static BYTE parms[] =
VTS_BOOL;
InvokeHelper(0x11, DISPATCH_PROPERTYPUT, VT_EMPTY, NULL, parms,
bNewValue);
}
void CPrinter::PrintPartialHandle(const VARIANT& DC, long Left, long Top, long Right, long Bottom)
{
static BYTE parms[] =
VTS_VARIANT VTS_I4 VTS_I4 VTS_I4 VTS_I4;
InvokeHelper(0x12, DISPATCH_METHOD, VT_EMPTY, NULL, parms,
&DC, Left, Top, Right, Bottom);
}
void CPrinter::PrintPages(long FromPage, long ToPage)
{
static BYTE parms[] =
VTS_I4 VTS_I4;
InvokeHelper(0x10, DISPATCH_METHOD, VT_EMPTY, NULL, parms,
FromPage, ToPage);
}
|
ChIna-king-Arthur/MFC
|
cow2/TeeChartAPI/printer.cpp
|
C++
|
artistic-2.0
| 5,140 |
package com.work.pm25;
import android.text.TextUtils;
import bean.City;
import bean.County;
import bean.Province;
/**
* Created by KalinaRain on 2015/5/20.
*/
public class Utility {
/**
* 解析和处理服务器返回的省级数据
*/
public synchronized static boolean handleProvincesResponse(PM25DB pm25DB, String response) {
if (!TextUtils.isEmpty(response)) {
String[] allProvinces = response.split(",");
if (allProvinces != null && allProvinces.length > 0) {
for (String p : allProvinces) {
String[] array = p.split("\\|");
Province province = new Province();
province.setProvinceCode(array[0]);
province.setProvinceName(array[1]);
// 将解析出来的数据存储到Province表
pm25DB.saveProvince(province);
}
return true;
}
}
return false;
}
/**
* 解析和处理服务器返回的市级数据
*/
public static boolean handleCitiesResponse(PM25DB pm25DB,
String response, int provinceId) {
if (!TextUtils.isEmpty(response)) {
String[] allCities = response.split(",");
if (allCities != null && allCities.length > 0) {
for (String c : allCities) {
String[] array = c.split("\\|");
City city = new City();
city.setCityCode(array[0]);
city.setCityName(array[1]);
city.setProvinceId(provinceId);
// 将解析出来的数据存储到City表
pm25DB.saveCity(city);
}
return true;
}
}
return false;
}
/**
* 解析和处理服务器返回的县级数据
*/
public static boolean handleCountiesResponse(PM25DB pm25DB,
String response, int cityId) {
if (!TextUtils.isEmpty(response)) {
String[] allCounties = response.split(",");
if (allCounties != null && allCounties.length > 0) {
for (String c : allCounties) {
String[] array = c.split("\\|");
County county = new County();
county.setCountyCode(array[0]);
county.setCountyName(array[1]);
county.setCityId(cityId);
// 将解析出来的数据存储到County表
pm25DB.saveCounty(county);
}
return true;
}
}
return false;
}
}
|
KalinaRain/MyWorkSpace
|
pmdetection/src/main/java/com/work/pm25/Utility.java
|
Java
|
artistic-2.0
| 2,771 |
package com.germi.indrob.utility;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
public class UtilityExtension{
protected String name;
protected String[] defs;
protected FileFilter filt;
public UtilityExtension(String a, String... b) {
this.name=a;
this.defs=b;
this.filt=new FileNameExtensionFilter(a,b);
}
public String getName() {
return this.name;
}
public String getPreferedExtension() {
return this.defs[0];
}
public FileFilter getFilter() {
return this.filt;
}
public String[] getDefinitions() {
return this.defs;
}
}
|
el-germi/industrial-robot
|
src/main/java/com/germi/indrob/utility/UtilityExtension.java
|
Java
|
artistic-2.0
| 619 |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Event.location'
db.add_column(u'calendar_event', 'location',
self.gf('django.db.models.fields.TextField')(null=True, blank=True),
keep_default=False)
# Adding field 'Event.link_url'
db.add_column(u'calendar_event', 'link_url',
self.gf('django.db.models.fields.URLField')(max_length=200, null=True, blank=True),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Event.location'
db.delete_column(u'calendar_event', 'location')
# Deleting field 'Event.link_url'
db.delete_column(u'calendar_event', 'link_url')
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'calendar.dummytable': {
'Meta': {'object_name': 'DummyTable'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
u'calendar.event': {
'Meta': {'object_name': 'Event'},
'_meta_title': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
'category': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'events'", 'to': u"orm['sfpirgapp.Category']"}),
'content': ('mezzanine.core.fields.RichTextField', [], {}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'end': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'featured_image': ('mezzanine.core.fields.FileField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'gen_description': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'in_menus': ('mezzanine.pages.fields.MenusField', [], {'default': '(1, 2, 3, 4, 5)', 'max_length': '100', 'null': 'True', 'blank': 'True'}),
'in_sitemap': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'keywords': ('mezzanine.generic.fields.KeywordsField', [], {'object_id_field': "'object_pk'", 'to': u"orm['generic.AssignedKeyword']", 'frozen_by_south': 'True'}),
'keywords_string': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}),
'link_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'location': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'start': ('django.db.models.fields.DateTimeField', [], {}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'theme_color': ('django.db.models.fields.CharField', [], {'default': "'grey'", 'max_length': '255'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['calendar.EventType']", 'null': 'True', 'blank': 'True'}),
'zip_import': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'})
},
u'calendar.eventimage': {
'Meta': {'ordering': "('_order',)", 'object_name': 'EventImage'},
'_order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'description': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'blank': 'True'}),
'file': ('mezzanine.core.fields.FileField', [], {'max_length': '200'}),
'gallery': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'images'", 'to': u"orm['calendar.Event']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
u'calendar.eventtype': {
'Meta': {'ordering': "['name']", 'object_name': 'EventType'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['sites.Site']"})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'generic.assignedkeyword': {
'Meta': {'ordering': "('_order',)", 'object_name': 'AssignedKeyword'},
'_order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'keyword': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'assignments'", 'to': u"orm['generic.Keyword']"}),
'object_pk': ('django.db.models.fields.IntegerField', [], {})
},
u'generic.keyword': {
'Meta': {'object_name': 'Keyword'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'})
},
u'sfpirgapp.category': {
'Meta': {'ordering': "('_order',)", 'object_name': 'Category'},
'_meta_title': ('django.db.models.fields.CharField', [], {'max_length': '500', 'null': 'True', 'blank': 'True'}),
'_order': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),
'content': ('mezzanine.core.fields.RichTextField', [], {}),
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'expiry_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'featured_image': ('sfpirgapp.fields.MyImageField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'gen_description': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'in_sitemap': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'keywords': ('mezzanine.generic.fields.KeywordsField', [], {'object_id_field': "'object_pk'", 'to': u"orm['generic.AssignedKeyword']", 'frozen_by_south': 'True'}),
'keywords_string': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}),
'login_required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'publish_date': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'short_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['sites.Site']"}),
'slug': ('django.db.models.fields.CharField', [], {'max_length': '2000', 'null': 'True', 'blank': 'True'}),
'status': ('django.db.models.fields.IntegerField', [], {'default': '2'}),
'theme_color': ('django.db.models.fields.CharField', [], {'default': "'grey'", 'max_length': '255'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
'titles': ('django.db.models.fields.CharField', [], {'max_length': '1000', 'null': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'categorys'", 'to': u"orm['auth.User']"})
},
u'sites.site': {
'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"},
'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
}
}
complete_apps = ['calendar']
|
orlenko/sfpirg
|
mezzanine/calendar/migrations/0006_auto__add_field_event_location__add_field_event_link_url.py
|
Python
|
bsd-2-clause
| 12,037 |
from django.conf import settings
from django.db.models.loading import get_model
from models import MasterSetting, SettingTypes
def get(name, default=None):
try:
setting = MasterSetting.objects.get(name=name)
if setting.type == SettingTypes.INT:
return int(setting.value)
elif setting.type == SettingTypes.FLOAT:
return float(setting.value)
elif setting.type == SettingTypes.FOREIGN:
model = get_model(*setting.foreign_model.split("."))
try:
return model.objects.get(id=int(setting.value))
except model.DoesNotExist:
return default
elif setting.type == SettingTypes.CHOICES:
return setting.value
else:
return setting.value
except MasterSetting.DoesNotExist:
return default
def set(name, value):
setting = MasterSetting.objects.get(name=name)
if setting.type == SettingTypes.INT:
setting.value = str(int(setting.value))
elif setting.type == SettingTypes.FLOAT:
setting.value = str(float(setting.value))
elif setting.type == SettingTypes.FOREIGN:
model = get_model(*setting.foreign_model.split("."))
try:
object_ = model.objects.get(id=int(value.id))
setting.value = str(object_.id)
except model.DoesNotExist:
return None
elif setting.type == SettingTypes.CHOICES:
options_ = settings.MASTER_SETTINGS[setting.name]['options']
if value in options_:
setting.value = value
else:
raise ValueError("Available options are: %s " % str(options_))
else:
setting.value = value
setting.save()
def exists(name):
try:
MasterSetting.objects.get(name=name)
return True
except MasterSetting.DoesNotExist:
return False
|
MasterAlish/django-ma-settings
|
ma_settings/master_settings.py
|
Python
|
bsd-2-clause
| 1,876 |
# coding: utf-8
"""
MINDBODY Public API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_client
from swagger_client.models.get_session_types_request import GetSessionTypesRequest # noqa: E501
from swagger_client.rest import ApiException
class TestGetSessionTypesRequest(unittest.TestCase):
"""GetSessionTypesRequest unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testGetSessionTypesRequest(self):
"""Test GetSessionTypesRequest"""
# FIXME: construct object with mandatory attributes with example values
# model = swagger_client.models.get_session_types_request.GetSessionTypesRequest() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
|
mindbody/API-Examples
|
SDKs/Python/test/test_get_session_types_request.py
|
Python
|
bsd-2-clause
| 1,006 |
package battleship
type ShipType uint8
const (
Missed ShipType = iota
Hit
AircraftCarrier
Battleship
Submarine
Destroyer
Cruiser
PatrolBoat
)
func (st ShipType) Mark() string {
s := "\u2573\u29BFA*CARRIERDESTR*SUB*SHIP*BCRUIS"
switch st {
case Missed:
return s[0:3] //"\u2573"
case Hit:
return s[3:6] //"\u29BF"
case AircraftCarrier:
return s[6:15] //"A*CARRIER"
case Destroyer:
return s[15:20] //"DESTR"
case Submarine:
return s[20:25] //"*SUB*"
case Battleship:
return s[23:30] //"B*SHIP*"
case PatrolBoat:
return s[28:31] //"P*B"
case Cruiser:
return s[31:] //"CRUIS"
default:
return ""
}
}
func (st ShipType) String() string {
switch st {
case Missed:
return "missed"
case Hit:
return "hit"
case AircraftCarrier:
return "aircraft carrier"
case Destroyer:
return "destroyer"
case Submarine:
return "submarine"
case Battleship:
return "battleship"
case PatrolBoat:
return "patrol boat"
case Cruiser:
return "cruiser"
default:
return ""
}
}
func (st ShipType) Size() int {
switch st {
case Missed:
return 1
case Hit:
return 1
case AircraftCarrier:
return 5
case Destroyer:
return 3
case Submarine:
return 3
case Battleship:
return 4
case PatrolBoat:
return 2
case Cruiser:
return 3
default:
return 0
}
}
func (st ShipType) Score() int {
switch st {
case AircraftCarrier:
return 20
case Destroyer:
return 6
case Submarine:
return 6
case Battleship:
return 12
case PatrolBoat:
return 2
case Cruiser:
return 6
default:
return 0
}
}
|
gdey/go-challange-battleship
|
battleship/ship_type.go
|
GO
|
bsd-2-clause
| 1,552 |
/*********************************************************************
* Maxeler Technologies: BrainNetwork *
* *
* Version: 1.2 *
* Date: 05 July 2013 *
* *
* GUI code source file *
* *
*********************************************************************/
package com.maxeler.brainnetwork.gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JToggleButton;
//Toggle button used to start/stop the demo
public class ComputeButton extends JToggleButton implements ActionListener, Runnable{
//UID generated for component serialization
private static final long serialVersionUID = -145094948834407005L;
//Reference to image correlation kernel and speed-up
private LinearCorrelation [] kernel = null;
private SpeedUpTextField speedup = null;
//Constructor
public ComputeButton (LinearCorrelation [] kernel, SpeedUpTextField speedup){
//Instantiate a toggle button initialized to false
super("Compute",false);
//Store external references
this.kernel = kernel;
this.speedup = speedup;
//Button size
setSize(150,40);
//In order to react to action on the button
addActionListener(this);
}
//Describe reaction to event
@Override
public void actionPerformed(ActionEvent actionEvent) {
//Trigger a new thread to manage the event
Thread t = new Thread(this);
t.start();
}
//Thread to manage the event
@Override
public void run() {
//Deactivate the button until the threads end
setEnabled(false);
//Switch the running flag according to the status
BrainNetwork.running = isSelected();
//When stop execution, restart all the correlation kernel
if (!BrainNetwork.running)
for (int i=0; i<kernel.length; ++i){
kernel[i].restart();
}
else
speedup.resetToZero();
//Finally, reactivate the button
setEnabled(true);
}
}
|
maxeler/Brain-Network
|
APP/CPUCode/gui/src/com/maxeler/brainnetwork/gui/ComputeButton.java
|
Java
|
bsd-2-clause
| 2,215 |
<?php
/**
* This file is part of the PHP Generics package.
*
* @package Generics
*/
namespace Generics\Streams;
use Generics\Streams\Interceptor\StreamInterceptor;
use Countable;
/**
* This class provides a stream for standard output
*
* @author Maik Greubel <greubel@nkey.de>
*/
class StandardOutputStream implements OutputStream
{
/**
* Interceptor
*
* @var StreamInterceptor
*/
private $interceptor;
/**
* The standard out channel
*
* @var resource
*/
private $stdout;
/**
* Create a new instance of StandardOutputStream
*/
public function __construct()
{
$this->open();
}
/**
* Opens a new standard output channel
*/
private function open()
{
$this->stdout = fopen("php://stdout", "w");
}
/**
*
* {@inheritdoc}
* @see \Generics\Streams\Stream::isOpen()
*/
public function isOpen(): bool
{
return is_resource($this->stdout);
}
/**
*
* {@inheritdoc}
* @see \Generics\Streams\OutputStream::flush()
*/
public function flush()
{
if ($this->isOpen()) {
fflush($this->stdout);
}
if ($this->interceptor instanceof StreamInterceptor) {
$this->interceptor->reset();
}
}
/**
*
* {@inheritdoc}
* @see \Generics\Streams\Stream::ready()
*/
public function ready(): bool
{
return $this->isOpen();
}
/**
*
* {@inheritdoc}
* @see Countable::count()
*/
public function count()
{
return 0;
}
/**
*
* {@inheritdoc}
* @see \Generics\Resettable::reset()
*/
public function reset()
{
$this->close();
$this->open();
if ($this->interceptor instanceof StreamInterceptor) {
$this->interceptor->reset();
$this->setInterceptor($this->interceptor);
}
}
/**
*
* {@inheritdoc}
* @see \Generics\Streams\OutputStream::write()
*/
public function write($buffer)
{
if ($this->isWriteable()) {
fwrite($this->stdout, $buffer);
}
}
/**
*
* {@inheritdoc}
* @see \Generics\Streams\Stream::close()
*/
public function close()
{
if ($this->isOpen()) {
fclose($this->stdout);
$this->stdout = null;
}
}
/**
*
* {@inheritdoc}
* @see \Generics\Streams\OutputStream::isWriteable()
*/
public function isWriteable(): bool
{
return $this->isOpen();
}
/**
* Apply a stream interceptor
*
* @param StreamInterceptor $interceptor
*/
public function setInterceptor(StreamInterceptor $interceptor)
{
$this->interceptor = $interceptor;
stream_filter_append($this->stdout, $interceptor->getFilterName());
}
}
|
maikgreubel/phpgenerics
|
src/Generics/Streams/StandardOutputStream.php
|
PHP
|
bsd-2-clause
| 2,960 |
# Copyright (c) 2003-present, Jodd Team (http://jodd.org)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
f = open('ConvertBean.java', 'r')
java = f.read()
f.close()
genStart = java.find('@@generated')
java = java[0:genStart + 11]
### -----------------------------------------------------------------
types = [
[0, 'Boolean', 'boolean', 'false'],
[2, 'Integer', 'int', '0'],
[4, 'Long', 'long', '0'],
[6, 'Float', 'float', '0'],
[8, 'Double', 'double', '0'],
[10, 'Short', 'short', '(short) 0'],
[12, 'Character', 'char', '(char) 0'],
[14, 'Byte', 'byte', '(byte) 0'],
]
template = '''
/**
* Converts value to <code>$T</code>.
*/
public $T to$T(Object value) {
return ($T) typeConverters[#].convert(value);
}
/**
* Converts value to <code>$T</code>. Returns default value
* when conversion result is <code>null</code>
*/
public $T to$T(Object value, $T defaultValue) {
$T result = ($T) typeConverters[#].convert(value);
if (result == null) {
return defaultValue;
}
return result;
}
/**
* Converts value to <code>$t</code>. Returns default value
* when conversion result is <code>null</code>.
*/
public $t to$PValue(Object value, $t defaultValue) {
$T result = ($T) typeConverters[#++].convert(value);
if (result == null) {
return defaultValue;
}
return result.$tValue();
}
/**
* Converts value to <code>$t</code> with common default value.
*/
public $t to$PValue(Object value) {
return to$PValue(value, $D);
}
'''
for type in types:
# small type
data = template
data = data.replace('#++', str(type[0] + 1))
data = data.replace('#', str(type[0]))
data = data.replace('$T', type[1])
data = data.replace('$t', type[2])
data = data.replace('$P', type[2].title())
data = data.replace('$D', type[3])
java += data
### -----------------------------------------------------------------
types = [
[16, 'boolean[]', 'BooleanArray', 0],
[17, 'int[]', 'IntegerArray', 0],
[18, 'long[]', 'LongArray', 0],
[19, 'float[]', 'FloatArray', 0],
[20, 'double[]', 'DoubleArray', 0],
[21, 'short[]', 'ShortArray', 0],
[22, 'char[]', 'CharacterArray', 0],
[23, 'String', 'String', 1],
[24, 'String[]', 'StringArray', 0],
[25, 'Class', 'Class', 0],
[26, 'Class[]', 'ClassArray', 0],
[27, 'JDateTime', 'JDateTime', 1],
[28, 'Date', 'Date', 1],
[29, 'Calendar', 'Calendar', 1],
[30, 'BigInteger', 'BigInteger', 1],
[31, 'BigDecimal', 'BigDecimal', 1],
]
template = '''
/**
* Converts value to <code>$T</code>.
*/
public $T to$N(Object value) {
return ($T) typeConverters[#].convert(value);
}
'''
template2 = '''
/**
* Converts value to <code>$T</code>. Returns default value
* when conversion result is <code>null</code>
*/
public $T to$N(Object value, $T defaultValue) {
$T result = ($T) typeConverters[#].convert(value);
if (result == null) {
return defaultValue;
}
return result;
}
'''
for type in types:
# small type
data = template
data = data.replace('#', str(type[0]))
data = data.replace('$T', type[1])
data = data.replace('$N', type[2])
java += data
if type[3] == 1:
data = template2
data = data.replace('#', str(type[0]))
data = data.replace('$T', type[1])
data = data.replace('$N', type[2])
java += data
### -----------------------------------------------------------------
java += '}'
f = open('ConvertBean.java', 'w')
f.write(java)
f.close()
|
vilmospapp/jodd
|
jodd-core/src/main/python/ConvertBean.py
|
Python
|
bsd-2-clause
| 4,825 |
package com.kbsriram.keypan.core;
import java.io.IOException;
import java.io.Reader;
import java.util.regex.Pattern;
public final class CUtils
{
public final static String byte2hex(byte[] b)
{
StringBuilder sb = new StringBuilder();
for (int i=0; i<b.length; i++) {
int v = b[i] & 0xff;
sb.append(s_byte2hex[v >> 4]);
sb.append(s_byte2hex[v & 0xf]);
}
return sb.toString();
}
public final static String asString(Reader r)
throws IOException
{
char[] buf = new char[2048];
int nread;
StringBuilder sb = new StringBuilder();
while ((nread = r.read(buf)) > 0) {
sb.append(buf, 0, nread);
}
return sb.toString();
}
public final static String groupedFingerprint(String fp)
{
if (fp.length() != 40) {
throw new IllegalArgumentException("bad fp");
}
StringBuilder sb = new StringBuilder();
for (int i=0; i<40; i+=4) {
if (i > 0) { sb.append(" "); }
sb.append(fp.substring(i, i+4));
}
return sb.toString().toLowerCase();
}
public final static Pattern asPattern(String fp)
{
if (fp.length() != 40) {
throw new IllegalArgumentException("bad fp");
}
StringBuilder sb = new StringBuilder();
for (int i=0; i<40; i+=4) {
if (i > 0) { sb.append("[\\p{Z}\\s]*"); }
sb.append(fp.substring(i, i+4));
}
return Pattern.compile(sb.toString(), Pattern.CASE_INSENSITIVE);
}
public final static <T> void lognote(Class<T> cls, String msg)
{
if (s_debug) {
System.out.println("NOTE: "+cls.getSimpleName()+": "+msg);
return;
}
int mlen = msg.length();
if (mlen > MAX_NOTE_LEN) {
msg = msg.substring(0, MAX_NOTE_LEN-3)+"...";
mlen = MAX_NOTE_LEN;
}
System.out.print(msg);
int delta = (MAX_NOTE_LEN - msg.length());
while (delta > 0) {
System.out.print(" ");
delta--;
}
if (s_cli) { System.out.print("\r"); }
else { System.out.println(); }
System.out.flush();
}
public final static void clear()
{
if (s_debug) { return; }
for (int i=0; i<MAX_NOTE_LEN; i++) {
System.out.print(" ");
}
System.out.print("\r");
System.out.flush();
}
public final static String nullIfEmpty(String s)
{
if ((s == null) || (s.length() == 0)) {
return null;
}
else {
return s;
}
}
public final static void setDebug(boolean v)
{ s_debug = v; }
public final static void setCLI(boolean v)
{ s_cli = v; }
public final static boolean isDebug()
{ return s_debug; }
public final static <T> void logw(Class<T> cls, String msg)
{ logw(cls, msg, null); }
public final static <T> void logw(Class<T> cls, String msg, Throwable th)
{
System.err.println("WARN: "+cls.getSimpleName()+": "+msg);
if (th != null) { th.printStackTrace(); }
}
public final static <T> void logd(Class<T> cls, String msg)
{ logd(cls, msg, null); }
public final static <T> void logd(Class<T> cls, String msg, Throwable th)
{
if (s_debug) {
System.err.println("DEBUG: "+cls.getSimpleName()+": "+msg);
if (th != null) { th.printStackTrace(); }
}
}
private static boolean s_debug = false;
private static boolean s_cli = true;
private final static int MAX_NOTE_LEN = 35;
private final static char[] s_byte2hex = new char[] {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
}
|
kbsriram/keypan
|
src/core/com/kbsriram/keypan/core/CUtils.java
|
Java
|
bsd-2-clause
| 3,841 |
package cs499blue.models;
import cs499blue.algorithms.Distance;
/**
* author: vwilson
* date: 4/1/14
*/
public class Edge {
private Vertex a, b;
public Edge(Vertex a, Vertex b) {
this.a = a;
this.b = b;
}
public Vertex getA() {
return a;
}
public Vertex getB() {
return b;
}
public Double getWeight() {
return Distance.distanceFrom(a, b);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Edge edge = (Edge) o;
if (!a.equals(edge.a)) return false;
if (!b.equals(edge.b)) return false;
return true;
}
@Override
public int hashCode() {
int result = a.hashCode();
result = 31 * result + b.hashCode();
return result;
}
}
|
vwilson/CS499-Shortest-Path
|
CS499/src/main/java/cs499blue/models/Edge.java
|
Java
|
bsd-2-clause
| 887 |
class PerconaServerAT56 < Formula
desc "Drop-in MySQL replacement"
homepage "https://www.percona.com"
url "https://www.percona.com/downloads/Percona-Server-5.6/Percona-Server-5.6.37-82.2/source/tarball/percona-server-5.6.37-82.2.tar.gz"
version "5.6.37-82.2"
sha256 "3cf04b64c8bf5b9cc1ea1a68c54ba77a4709d9c9051314e70a4cbd4c904da702"
bottle do
sha256 "2eca6a7f69f893abeadf61df5eccc97510099686275140f1934e5ee8122c202f" => :high_sierra
sha256 "a5dc522f52d0c853b2ff04291884156111729f67379b24fa7d7022bcd3347632" => :sierra
sha256 "a9ba8cad6f5237e783ad3495206f3ba63365fff78048e34008f23cdd500a2c90" => :el_capitan
sha256 "ef56b2abe4ad121257e62cc4178c459dc034407b18ffc06bea6cf39c60d7286b" => :yosemite
end
keg_only :versioned_formula
option "with-test", "Build with unit tests"
option "with-embedded", "Build the embedded server"
option "with-memcached", "Build with InnoDB Memcached plugin"
option "with-local-infile", "Build with local infile loading support"
depends_on "cmake" => :build
depends_on "pidof" unless MacOS.version >= :mountain_lion
depends_on "openssl"
# Where the database files should be located. Existing installs have them
# under var/percona, but going forward they will be under var/mysql to be
# shared with the mysql and mariadb formulae.
def datadir
@datadir ||= (var/"percona").directory? ? var/"percona" : var/"mysql"
end
pour_bottle? do
reason "The bottle needs a var/mysql datadir (yours is var/percona)."
satisfy { datadir == var/"mysql" }
end
def install
# Don't hard-code the libtool path. See:
# https://github.com/Homebrew/homebrew/issues/20185
inreplace "cmake/libutils.cmake",
"COMMAND /usr/bin/libtool -static -o ${TARGET_LOCATION}",
"COMMAND libtool -static -o ${TARGET_LOCATION}"
args = std_cmake_args + %W[
-DMYSQL_DATADIR=#{datadir}
-DINSTALL_PLUGINDIR=lib/plugin
-DSYSCONFDIR=#{etc}
-DINSTALL_MANDIR=#{man}
-DINSTALL_DOCDIR=#{doc}
-DINSTALL_INFODIR=#{info}
-DINSTALL_INCLUDEDIR=include/mysql
-DINSTALL_MYSQLSHAREDIR=#{share.basename}/mysql
-DWITH_SSL=yes
-DDEFAULT_CHARSET=utf8
-DDEFAULT_COLLATION=utf8_general_ci
-DCOMPILATION_COMMENT=Homebrew
-DWITH_EDITLINE=system
-DCMAKE_FIND_FRAMEWORK=LAST
-DCMAKE_VERBOSE_MAKEFILE=ON
]
# PAM plugin is Linux-only at the moment
args.concat %w[
-DWITHOUT_AUTH_PAM=1
-DWITHOUT_AUTH_PAM_COMPAT=1
-DWITHOUT_DIALOG=1
]
# TokuDB is broken on MacOsX
# https://bugs.launchpad.net/percona-server/+bug/1531446
args.concat %w[-DWITHOUT_TOKUDB=1]
# To enable unit testing at build, we need to download the unit testing suite
if build.with? "test"
args << "-DENABLE_DOWNLOADS=ON"
else
args << "-DWITH_UNIT_TESTS=OFF"
end
# Build the embedded server
args << "-DWITH_EMBEDDED_SERVER=ON" if build.with? "embedded"
# Build with InnoDB Memcached plugin
args << "-DWITH_INNODB_MEMCACHED=ON" if build.with? "memcached"
# Build with local infile loading support
args << "-DENABLED_LOCAL_INFILE=1" if build.with? "local-infile"
system "cmake", ".", *std_cmake_args, *args
system "make"
system "make", "install"
# Don't create databases inside of the prefix!
# See: https://github.com/Homebrew/homebrew/issues/4975
rm_rf prefix+"data"
# Link the setup script into bin
bin.install_symlink prefix/"scripts/mysql_install_db"
# Fix up the control script and link into bin
inreplace "#{prefix}/support-files/mysql.server",
/^(PATH=".*)(")/, "\\1:#{HOMEBREW_PREFIX}/bin\\2"
bin.install_symlink prefix/"support-files/mysql.server"
# mysqlaccess deprecated on 5.6.17, and removed in 5.7.4.
# See: https://bugs.mysql.com/bug.php?id=69012
# Move mysqlaccess to libexec
libexec.mkpath
mv "#{bin}/mysqlaccess", libexec
mv "#{bin}/mysqlaccess.conf", libexec
# Install my.cnf that binds to 127.0.0.1 by default
(buildpath/"my.cnf").write <<-EOS.undent
# Default Homebrew MySQL server config
[mysqld]
# Only allow connections from localhost
bind-address = 127.0.0.1
EOS
etc.install "my.cnf"
end
def post_install
# Make sure that data directory exists
datadir.mkpath
unless File.exist? "#{datadir}/mysql/user.frm"
ENV["TMPDIR"] = nil
system "#{bin}/mysql_install_db", "--verbose", "--user=#{ENV["USER"]}",
"--basedir=#{prefix}", "--datadir=#{datadir}", "--tmpdir=/tmp"
end
end
def caveats; <<-EOS.undent
A "/etc/my.cnf" from another install may interfere with a Homebrew-built
server starting up correctly.
MySQL is configured to only allow connections from localhost by default
To connect:
mysql -uroot
EOS
end
plist_options :manual => "mysql.server start"
def plist; <<-EOS.undent
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<true/>
<key>Label</key>
<string>#{plist_name}</string>
<key>Program</key>
<string>#{opt_bin}/mysqld_safe</string>
<key>RunAtLoad</key>
<true/>
<key>WorkingDirectory</key>
<string>#{var}</string>
</dict>
</plist>
EOS
end
test do
system "/bin/sh", "-n", "#{bin}/mysqld_safe"
(prefix/"mysql-test").cd do
system "./mysql-test-run.pl", "status", "--vardir=#{testpath}"
end
end
end
|
bfontaine/homebrew-core
|
Formula/percona-server@5.6.rb
|
Ruby
|
bsd-2-clause
| 5,617 |
// This file was procedurally generated from the following sources:
// - src/dstr-assignment/obj-id-identifier-resolution-last.case
// - src/dstr-assignment/default/for-of.template
/*---
description: Evaluation of DestructuringAssignmentTarget (last of many) (For..of statement)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation
es6id: 13.7.5.11
features: [destructuring-binding]
flags: [generated]
info: |
IterationStatement :
for ( LeftHandSideExpression of AssignmentExpression ) Statement
1. Let keyResult be the result of performing ? ForIn/OfHeadEvaluation(« »,
AssignmentExpression, iterate).
2. Return ? ForIn/OfBodyEvaluation(LeftHandSideExpression, Statement,
keyResult, assignment, labelSet).
13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation
[...]
4. If destructuring is true and if lhsKind is assignment, then
a. Assert: lhs is a LeftHandSideExpression.
b. Let assignmentPattern be the parse of the source text corresponding to
lhs using AssignmentPattern as the goal symbol.
[...]
---*/
var x = null;
var w;
var counter = 0;
for ({ w, x } of [{ x: 4 }]) {
assert.sameValue(x, 4);
counter += 1;
}
assert.sameValue(counter, 1);
|
sebastienros/jint
|
Jint.Tests.Test262/test/language/statements/for-of/dstr-obj-id-identifier-resolution-last.js
|
JavaScript
|
bsd-2-clause
| 1,252 |
/*
* Copyright (c) 2014 Abdul Hannan Ahsan <abdulhannan.ahsan@gmail.com>
*
* 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.
*/
package aha.datastructure;
public class DoubleLinkedList<T>
{
private T value;
private DoubleLinkedList<T> previous;
private DoubleLinkedList<T> next;
public DoubleLinkedList( T value )
{
this.value = value;
this.previous = null;
this.next = null;
}
public DoubleLinkedList( T value, DoubleLinkedList<T> previous, DoubleLinkedList<T> next )
{
this.value = value;
this.previous = previous;
this.next = next;
}
@Override
public String toString()
{
StringBuilder builder = new StringBuilder();
builder.append( "[" ).append( value );
DoubleLinkedList<T> current = next;
while( current != null )
{
builder.append( "," + current.getValue() );
current = current.getNext();
}
builder.append( "]" );
return builder.toString();
}
public T getValue()
{
return value;
}
public DoubleLinkedList<T> getPrevious()
{
return previous;
}
public DoubleLinkedList<T> getNext()
{
return next;
}
public void setValue( final T value )
{
this.value = value;
}
public void setPrevious( final DoubleLinkedList<T> previous )
{
this.previous = previous;
}
public void setNext( final DoubleLinkedList<T> next )
{
this.next = next;
}
public static<T>
DoubleLinkedList<T> createList( final T[] values )
{
if( values.length == 0 )
{
return null;
}
DoubleLinkedList<T> root = new DoubleLinkedList<T>( values[0] );
DoubleLinkedList<T> current = root;
for( int idx = 1; idx < values.length; ++idx )
{
DoubleLinkedList<T> next = new DoubleLinkedList<T>( values[idx] );
current.setNext( next );
next.setPrevious( current );
current = current.getNext();
}
return root;
}
public static void main( String[] args )
{
Integer[] values = { 34, -29, 45, 342, 99, 7 };
DoubleLinkedList<Integer> dlist = DoubleLinkedList.createList( values );
System.out.println( dlist );
}
}
|
aha0x0x/snippets
|
java/aha/datastructure/DoubleLinkedList.java
|
Java
|
bsd-2-clause
| 3,509 |
# Example: How to prepare a new refund with the Mollie API.
#
import os
from mollie.api.client import Client
from mollie.api.error import Error
def main():
try:
#
# Initialize the Mollie API library with your API key.
#
# See: https://www.mollie.com/dashboard/settings/profiles
#
api_key = os.environ.get("MOLLIE_API_KEY", "test_test")
mollie_client = Client()
mollie_client.set_api_key(api_key)
body = ""
payment_id = ""
body += "<p>Attempting to retrieve the first page of payments and grabbing the first.</p>"
payments = mollie_client.payments.list()
if not len(payments):
body += "<p>You have no payments. You can create one from the examples.</p>"
return body
payment = next(payments)
if (
payment.can_be_refunded()
and payment.amount_remaining["currency"] == "EUR"
and float(payment.amount_remaining["value"]) >= 2.0
):
data = {"amount": {"value": "2.00", "currency": "EUR"}}
refund = mollie_client.payment_refunds.with_parent_id(payment_id).create(data)
body += f'<p>{refund.amount["currency"]} {refund.amount["value"]} of payment {payment_id} refunded</p>'
else:
body += f"<p>Payment {payment_id} can not be refunded</p>"
return body
except Error as err:
return f"API call failed: {err}"
if __name__ == "__main__":
print(main())
|
mollie/mollie-api-python
|
examples/11-refund-payment.py
|
Python
|
bsd-2-clause
| 1,522 |
class GitGui < Formula
desc "Tcl/Tk UI for the git revision control system"
homepage "https://git-scm.com"
# NOTE: Please keep these values in sync with git.rb when updating.
url "https://mirrors.edge.kernel.org/pub/software/scm/git/git-2.31.1.tar.xz"
sha256 "9f61417a44d5b954a5012b6f34e526a3336dcf5dd720e2bb7ada92ad8b3d6680"
license "GPL-2.0-only"
head "https://github.com/git/git.git", shallow: false
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "f6941b6984b73e4f89c9635a6113a0401461821febd431116dd06cf4971ec469"
sha256 cellar: :any_skip_relocation, big_sur: "430d3e73a3d07bb170c1bd3eb3db3a5cbb283e1fd72671e9607f00cce23982eb"
sha256 cellar: :any_skip_relocation, catalina: "603bf37ef37e46f4ec88855d44bd61a227299638dda5690c367b55c733ba3cf7"
sha256 cellar: :any_skip_relocation, mojave: "59df29678a0fa2c9546ee91ec1c8d4061ad3ae7436ecb4beef92fecd6c62de41"
end
depends_on "tcl-tk"
# Patch to fix Homebrew/homebrew-core#68798.
# Remove when the following PR has been merged
# and included in a release:
# https://github.com/git/git/pull/944
patch do
url "https://github.com/git/git/commit/1db62e44b7ec93b6654271ef34065b31496cd02e.patch?full_index=1"
sha256 "0c7816ee9c8ddd7aa38aa29541c9138997650713bce67bdef501b1de0b50f539"
end
def install
# build verbosely
ENV["V"] = "1"
# By setting TKFRAMEWORK to a non-existent directory we ensure that
# the git makefiles don't install a .app for git-gui
# We also tell git to use the homebrew-installed wish binary from tcl-tk.
# See https://github.com/Homebrew/homebrew-core/issues/36390
tcl_bin = Formula["tcl-tk"].opt_bin
args = %W[
TKFRAMEWORK=/dev/null
prefix=#{prefix}
gitexecdir=#{bin}
sysconfdir=#{etc}
CC=#{ENV.cc}
CFLAGS=#{ENV.cflags}
LDFLAGS=#{ENV.ldflags}
TCL_PATH=#{tcl_bin}/tclsh
TCLTK_PATH=#{tcl_bin}/wish
]
system "make", "-C", "git-gui", "install", *args
system "make", "-C", "gitk-git", "install", *args
end
test do
system bin/"git-gui", "--version"
end
end
|
cblecker/homebrew-core
|
Formula/git-gui.rb
|
Ruby
|
bsd-2-clause
| 2,119 |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Free.Controls.TreeView.Tree
{
/// <summary>
/// Provides a simple ready to use implementation of <see cref="ITreeModel"/>. Warning: this class is not optimized
/// to work with big amount of data. In this case create you own implementation of <c>ITreeModel</c>, and pay attention
/// on GetChildren and IsLeaf methods.
/// </summary>
public class TreeModel : ITreeModel
{
private Node _root;
public Node Root
{
get { return _root; }
}
public Collection<Node> Nodes
{
get { return _root.Nodes; }
}
public TreeModel()
{
_root=new Node();
_root.Model=this;
}
public TreePath GetPath(Node node)
{
if(node==_root)
return TreePath.Empty;
else
{
Stack<object> stack=new Stack<object>();
while(node!=_root)
{
stack.Push(node);
node=node.Parent;
}
return new TreePath(stack.ToArray());
}
}
public Node FindNode(TreePath path)
{
if(path.IsEmpty())
return _root;
else
return FindNode(_root, path, 0);
}
private Node FindNode(Node root, TreePath path, int level)
{
foreach(Node node in root.Nodes)
if(node==path.FullPath[level])
{
if(level==path.FullPath.Length-1)
return node;
else
return FindNode(node, path, level+1);
}
return null;
}
#region ITreeModel Members
public System.Collections.IEnumerable GetChildren(TreePath treePath)
{
Node node=FindNode(treePath);
if(node!=null)
foreach(Node n in node.Nodes)
yield return n;
else
yield break;
}
public bool IsLeaf(TreePath treePath)
{
Node node=FindNode(treePath);
if(node!=null)
return node.IsLeaf;
else
throw new ArgumentException("treePath");
}
public event EventHandler<TreeModelEventArgs> NodesChanged;
internal void OnNodesChanged(TreeModelEventArgs args)
{
if(NodesChanged!=null)
NodesChanged(this, args);
}
public event EventHandler<TreePathEventArgs> StructureChanged;
public void OnStructureChanged(TreePathEventArgs args)
{
if(StructureChanged!=null)
StructureChanged(this, args);
}
public event EventHandler<TreeModelEventArgs> NodesInserted;
internal void OnNodeInserted(Node parent, int index, Node node)
{
if(NodesInserted!=null)
{
TreeModelEventArgs args=new TreeModelEventArgs(GetPath(parent), new int[] { index }, new object[] { node });
NodesInserted(this, args);
}
}
public event EventHandler<TreeModelEventArgs> NodesRemoved;
internal void OnNodeRemoved(Node parent, int index, Node node)
{
if(NodesRemoved!=null)
{
TreeModelEventArgs args=new TreeModelEventArgs(GetPath(parent), new int[] { index }, new object[] { node });
NodesRemoved(this, args);
}
}
#endregion
}
}
|
shintadono/Free.Controls.TreeView
|
Tree/TreeModel.cs
|
C#
|
bsd-2-clause
| 2,834 |
/*
* Copyright (c) 2012, JInterval Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.java.jinterval.field;
import java.math.RoundingMode;
import net.java.jinterval.rational.BinaryValueSet;
import net.java.jinterval.rational.ExtendedRational;
import net.java.jinterval.rational.ExtendedRationalContexts;
import net.java.jinterval.rational.ExtendedRationalContext;
import org.apache.commons.math3.Field;
/**
*
*/
public class RationalField implements Field<RationalFieldElement> {
private ExtendedRationalContext context;
private final RationalFieldElement zero;
private final RationalFieldElement one;
public RationalField(RoundingMode rm) {
this(BinaryValueSet.BINARY64, rm);
}
public RationalField(BinaryValueSet valueSet, RoundingMode rm) {
this(ExtendedRationalContexts.valueOf(valueSet, rm));
}
public RationalField(ExtendedRationalContext context) {
this.context = context;
zero = get(ExtendedRational.zero());
one = get(ExtendedRational.one());
}
public RationalFieldElement getZero() {
return zero;
}
public RationalFieldElement getOne() {
return one;
}
public RationalFieldElement get(Number value) {
return new RationalFieldElement(this, context.rnd(value));
}
public RationalFieldElement get(ExtendedRational value) {
return new RationalFieldElement(this, context.rnd(value));
}
public Class<RationalFieldElement> getRuntimeClass() {
return RationalFieldElement.class;
}
ExtendedRationalContext getContext() {
return context;
}
}
|
jinterval/jinterval
|
jinterval-field/src/main/java/net/java/jinterval/field/RationalField.java
|
Java
|
bsd-2-clause
| 2,936 |
// Copyright (C) 2017 Robin Templeton. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
description: Octal BigInt literal containing an invalid digit
esid: prod-NumericLiteral
info: |
NumericLiteral ::
NumericLiteralBase NumericLiteralSuffix
NumericLiteralBase ::
DecimalLiteral
BinaryIntegerLiteral
OctalIntegerLiteral
HexIntegerLiteral
NumericLiteralSuffix :: n
negative:
phase: parse
type: SyntaxError
features: [BigInt]
---*/
throw "Test262: This statement should not be evaluated.";
0o9n;
|
sebastienros/jint
|
Jint.Tests.Test262/test/language/literals/bigint/octal-invalid-digit.js
|
JavaScript
|
bsd-2-clause
| 578 |
cask 'onedrive' do
version '17.3.6945.0724'
sha256 '5285b60a8f81f820ff7e7ad1e9177520e0b1394901f301e7da3a3258962537be'
# oneclient.sfx.ms/Mac/Direct was verified as official when first introduced to the cask
url "https://oneclient.sfx.ms/Mac/Direct/#{version}/OneDrive.pkg"
name 'OneDrive'
homepage 'https://onedrive.live.com/'
pkg 'OneDrive.pkg'
uninstall delete: '/Applications/OneDrive.app',
launchctl: 'com.microsoft.OneDriveUpdaterDaemon',
pkgutil: 'com.microsoft.OneDrive',
quit: [
'com.microsoft.OneDrive',
'com.microsoft.OneDriveUpdater',
'com.microsoft.OneDrive.FinderSync',
]
zap delete: [
'~/Library/Application Support/OneDrive',
'~/Library/Application Support/com.microsoft.OneDrive',
'~/Library/Application Support/com.microsoft.OneDriveUpdater',
'~/Library/Application Support/OneDriveUpdater',
'~/Library/Application Scripts/com.microsoft.OneDrive.FinderSync',
'~/Library/Application Scripts/com.microsoft.OneDriveLauncher',
'~/Library/Caches/com.microsoft.OneDrive',
'~/Library/Caches/com.microsoft.OneDriveUpdater',
'~/Library/Caches/com.plausiblelabs.crashreporter.data/com.microsoft.OneDrive',
'~/Library/Caches/com.plausiblelabs.crashreporter.data/com.microsoft.OneDriveUpdater',
'~/Library/Containers/com.microsoft.OneDriveLauncher',
'~/Library/Containers/com.microsoft.OneDrive.FinderSync',
'~/Library/Cookies/com.microsoft.OneDrive.binarycookies',
'~/Library/Cookies/com.microsoft.OneDriveUpdater.binarycookies',
'~/Library/Group Containers/*.OneDriveStandaloneSuite',
'~/Library/Logs/OneDrive',
'~/Library/Preferences/com.microsoft.OneDrive.plist',
'~/Library/Preferences/com.microsoft.OneDriveUpdater.plist',
'~/Library/Preferences/*.OneDriveStandaloneSuite.plist',
]
end
|
syscrusher/homebrew-cask
|
Casks/onedrive.rb
|
Ruby
|
bsd-2-clause
| 2,181 |
#!/usr/bin/env python
from __future__ import print_function
import json
import logging
from .taxon_concept_node import TaxonConceptSemNode
from .verbatim_name import VerbatimSemNode
from .names_for_ranks import (GenusGroupSemNode,
HigherGroupSemNode,
SpecimenCodeSemNode,
SpeciesGroupSemNode,
TypeSpecimen
)
from .name import CombinationSemNode
from .graph_node import AuthoritySemNode
_LOG = logging.getLogger(__name__)
class SemGraph(object):
att_list = ['_authorities',
'_combinations',
'_genus_group_names',
'_higher_group_names',
'_references',
'_species_group_epithets',
'_specimen_codes',
'_specimens',
'_taxon_concepts',
'_type_specimens',
'_verbatim_name',
]
att_set = frozenset(att_list)
def register_obj(self, id_minting_context, obj):
return _register_new_node(self, id_minting_context, obj)
def __init__(self, taxolotl_config, res):
self.config = taxolotl_config
self.res = res
self._by_id = {}
self._authorities = None
self._specimens = None
self._specimen_codes = None
self._species_group_epithets = None
self._genus_group_names = None
self._combinations = None
self._higher_group_names = None
self._verbatim_name = None
self._taxon_concepts = None
self._references = None
self._type_specimens = None
def impute_type_specimens(self):
for tc in self.taxon_concept_list:
if not tc.is_specimen_based:
continue
if tc.hybrid or tc.undescribed or not tc.rank:
continue
if tc.rank == 'species':
epithet = tc.most_terminal_name
try:
if not epithet.type_materials:
self._add_type_specimen(None, epithet, tc.is_synonym_of)
except:
_LOG.exception("problem adding type materials")
for tc in self.taxon_concept_list:
if tc.hybrid or tc.undescribed or not tc.rank:
continue
if tc.is_specimen_based and tc.rank != 'species':
infra_epithet = tc.most_terminal_name
if infra_epithet is tc.has_name.sp_epithet:
continue
if not infra_epithet.type_materials:
self._add_type_specimen(None, infra_epithet, tc.is_synonym_of)
def denormalize_homonyms(self):
# for species ranK:
# multiple authority entries
# same valid epithet in multiple valid genera
dup_auth_to_mint = {}
for tc in self.taxon_concept_list:
if tc.rank and tc.rank == 'species':
epithet = tc.most_terminal_name
if epithet is None:
if not (tc.hybrid or tc.undescribed):
_LOG.warning('NO Epithet for = {}'.format(tc.__dict__))
continue
if isinstance(epithet._authority, list):
dup_auth_to_mint.setdefault(epithet, []).append(tc)
for name, tc_list in dup_auth_to_mint.items():
verb_name = tc_list[0].has_name
other_name_tc_pairs = []
same_name_tc = []
for tc in tc_list[1:]:
if tc.has_name is verb_name:
same_name_tc.append(tc)
else:
other_name_tc_pairs.append(tc)
for other in other_name_tc_pairs:
self._split_tc_with_shared_sp_epithet(tc_list[0], other)
for other in same_name_tc:
self._split_tc_with_shared_name(tc_list[0], other)
if self.res.id.startswith('cof'):
import sys
# sys.exit(1)
def _split_tc_with_shared_sp_epithet(self, fixed, other):
assert fixed is not other
fix_name, oth_name = fixed.has_name, other.has_name
_LOG.debug('splitting "{}" from ["{}"]'.format(fix_name.name, oth_name.name))
fix_genus, oth_genus = fix_name.genus_name, oth_name.genus_name
fix_sp_epi, oth_sp_epi = fix_name.sp_epithet, oth_name.sp_epithet
assert fix_sp_epi is oth_sp_epi
if fix_sp_epi in oth_genus.contained:
oth_genus.contained.remove(fix_sp_epi)
new_epi = self._add_sp_epithet(other, fix_sp_epi._name, oth_genus, avoid_dup=False)
oth_genus.contained.append(new_epi)
oth_name.sp_epithet = new_epi
vtc = other
if vtc._is_synonym_of:
vtc = vtc._is_synonym_of
for a in fix_sp_epi._authority:
if other in a.taxon_concept_set or vtc in a.taxon_concept_set:
new_epi.claim_authority(a)
break
assert new_epi._authority
fix_sp_epi._authority.remove(new_epi._authority)
if len(fix_sp_epi._authority) == 1:
fix_sp_epi._authority = fix_sp_epi._authority[0]
def _split_tc_with_shared_name(self, fixed, other):
fix_vname = fixed.has_name
assert fix_vname is other.has_name
new_vname = self._add_verbatim_name(other, fix_vname.name, avoid_dup=False)
assert not fix_vname.specimen_codes
for attr in VerbatimSemNode.extra_pred:
v = getattr(fix_vname, attr, None)
if v:
setattr(new_vname, attr, v)
other.has_name = new_vname
self._split_tc_with_shared_sp_epithet(fixed, other)
def postorder_taxon_concepts(self):
yielded = set()
tcl = self.taxon_concept_list
todo = []
for tc in tcl:
if not tc.child_set:
yielded.add(tc)
yield tc
else:
todo.append(tc)
prev_todo_len = 1 + len(todo)
while todo:
assert prev_todo_len > len(todo)
prev_todo_len = len(todo)
ntd = []
for tc in todo:
if tc.child_set.issubset(yielded):
yielded.add(tc)
yield tc
else:
ntd.append(tc)
todo = ntd
@property
def taxon_concept_list(self):
return self._taxon_concepts if self._taxon_concepts else []
def _all_specimen_based_tax_con_dict(self):
r = {}
for tcobj in self.taxon_concept_list:
if tcobj.is_specimen_based:
r[tcobj.canonical_id] = tcobj
return r
def _all_higher_tax_con_dict(self):
r = {}
for tcobj in self.taxon_concept_list:
if not tcobj.is_specimen_based:
r[tcobj.canonical_id] = tcobj
return r
def find_valid_genus(self, genus_name):
r = []
for tc in self._all_higher_tax_con_dict().values():
if tc.rank and tc.rank == 'genus':
if tc.is_valid_for_name(genus_name):
r.append(tc)
return r
def specimen_based_synonym_taxa(self):
d = self._all_specimen_based_tax_con_dict()
r = {}
for tcid, tcobj in d.items():
syn_list = tcobj.synonyms if tcobj.synonyms else []
for syn_id in syn_list:
r[syn_id] = d[syn_id]
return r
@property
def valid_specimen_based_taxa(self):
d = self._all_specimen_based_tax_con_dict()
r = {}
for tcid, tcobj in d.items():
if not tcobj.is_synonym_of:
r[tcid] = tcobj
return r
@property
def valid_taxa_dict(self):
raw = self._taxon_concepts if self._taxon_concepts else []
r = {}
for tcobj in raw:
if not tcobj.is_synonym_of:
r[tcobj.canonical_id] = tcobj
return r
@property
def canonical_name_str_to_taxon_concept_map(self):
return {i.canonical_name.name: i for i in self._taxon_concepts}
@property
def valid_name_to_taxon_concept_map(self):
return {i.valid_name.name: i for i in self.valid_taxa_dict.values()}
def get_by_id(self, can_id, default=None):
return self._by_id.get(can_id, default)
def _add_name(self, container, node_type, parent_sem_node, name, extra_container=None, avoid_dup=True):
search_cont = container if extra_container is None else extra_container.contained
x = None if (not avoid_dup) else _find_by_name(search_cont, name)
if x is None:
d = {'parent_id': parent_sem_node.canonical_id}
if extra_container is not None:
d['class_tag'] = 'epi' # need to figure out if this is the best choice for any extra container obj
x = node_type(self, d, name)
search_cont.append(x)
if search_cont is not container:
container.append(x)
return x
def add_authority(self, tax_con_sem_node, name_sem, authors, year):
auth_list = self.authorities
x = None
for a in auth_list:
if a.authors == authors and a.year == year:
x = a
break
if x is None:
d = {'parent_id': name_sem.canonical_id}
x = AuthoritySemNode(self, d, authors, year, tax_con_sem_node)
else:
x.taxon_concept_set.add(tax_con_sem_node)
auth_list.append(x)
name_sem.claim_authority(x)
return x
def _add_normalized(self, par_sem_node, name_str):
return self._add_name(self.combinations, CombinationSemNode, par_sem_node, name_str)
def _add_combination(self, par_sem_node, name_str):
return self._add_name(self.combinations, CombinationSemNode, par_sem_node, name_str)
def _add_verbatim_name(self, tax_con_sem_node, name_str, avoid_dup=True):
return self._add_name(self.verbatim_name, VerbatimSemNode, tax_con_sem_node, name_str, avoid_dup=avoid_dup)
def _add_genus(self, par_sem_node, name_str):
return self._add_name(self.genus_group_names, GenusGroupSemNode, par_sem_node, name_str)
_add_subgenus = _add_genus
def _add_higher_group_name(self, par_sem_node, name_str):
return self._add_name(self.higher_group_names, HigherGroupSemNode, par_sem_node, name_str)
def _add_sp_epithet(self, par_sem_node, name_str, prev_word_sn, avoid_dup=True):
return self._add_name(self.species_group_epithets, SpeciesGroupSemNode,
par_sem_node, name_str, prev_word_sn, avoid_dup=avoid_dup)
_add_infra_epithet = _add_sp_epithet
def _add_specimen_code(self, par_sem_node, name_str):
return self._add_name(self.specimen_codes, SpecimenCodeSemNode, par_sem_node, name_str)
def add_taxon_concept(self, foreign_id):
x = TaxonConceptSemNode(self, foreign_id)
self.taxon_concepts.append(x)
return x
def remove_taxon_concept(self, tc):
if tc in self._taxon_concepts:
self._taxon_concepts.remove(tc)
if tc.canonical_id in self._by_id:
del self._by_id[tc.canonical_id]
def _add_type_specimen(self, spec_code, epithet_syn_name, valid_taxon):
d = {'parent_id': epithet_syn_name.canonical_id}
x = TypeSpecimen(self, d, spec_code, epithet_syn_name, valid_taxon)
self.type_specimens.append(x)
epithet_syn_name.claim_type_material(x)
return x
def __getattr__(self, item):
hidden = '_{}'.format(item)
if hidden not in SemGraph.att_set:
return self.__getattribute__(item)
v = getattr(self, hidden)
if v is None:
v = []
setattr(self, hidden, v)
return v
def as_dict(self):
d = {}
for hidden in SemGraph.att_list:
v = getattr(self, hidden)
if v is not None:
d[hidden[1:]] = {i.canonical_id: i.as_dict() for i in v}
return d
def _find_by_name(container, name):
if container:
for el in container:
if el._name == name:
return el
return None
_NODE_CLASS_NAME_TO_CT = {AuthoritySemNode: 'auth',
SpecimenCodeSemNode: 'spec_code',
HigherGroupSemNode: 'clade',
SpeciesGroupSemNode: 'sp',
GenusGroupSemNode: 'gen',
VerbatimSemNode: 'verbatim',
CombinationSemNode: 'combin',
}
def _register_new_node(graph, id_minting_context, obj):
"""Returns a canonical_id for a new obj.
The goal is to generate unique IDs that are somewhat human readable to make it
easier to browse the graph.
`id_minting_context`: has
* "parent_id" or "context_id"
* "class_tag" or func will use the class of `obj` to tag classes
"""
assert isinstance(id_minting_context, dict)
pref_str, context_id = id_minting_context.get('parent_id'), ''
if pref_str is None:
pref_str = graph.res.base_resource.id
context_id = id_minting_context['context_id']
ct = id_minting_context.get('class_tag')
if ct is None:
ct = _NODE_CLASS_NAME_TO_CT[obj.__class__]
can_id = _canonicalize(pref_str, ct, context_id)
rci, n = can_id, 1
while True:
wtid = graph._by_id.get(can_id)
if wtid is None:
graph._by_id[can_id] = obj
return can_id
if wtid == obj:
return can_id
n += 1
can_id = '{}:v{}'.format(rci, n)
def _canonicalize(res_id, pred_id, entity_id):
ne = [str(i) for i in (res_id, pred_id, entity_id) if i]
return ':'.join(ne)
|
mtholder/taxalotl
|
taxalotl/sem_graph/graph.py
|
Python
|
bsd-2-clause
| 13,901 |
import codecs
import six
from builtins import super
from builtins import range
import struct
import time
class InvalidPacketError(Exception):
pass
class BootloaderError(Exception):
pass
class BootloaderTimeoutError(BootloaderError):
pass
# TODO: Implement Security key functionality
class BootloaderKeyError(BootloaderError):
STATUS = 0x01
def __init__(self):
super().__init__("The provided security key was incorrect")
class VerificationError(BootloaderError):
STATUS = 0x02
def __init__(self):
super().__init__("The flash verification failed.")
class IncorrectLength(BootloaderError):
STATUS = 0x03
def __init__(self):
super().__init__("The amount of data available is outside the expected range")
class InvalidData(BootloaderError):
STATUS = 0x04
def __init__(self):
super().__init__("The data is not of the proper form")
class InvalidCommand(BootloaderError):
STATUS = 0x05
def __init__(self):
super().__init__("Command unsupported on target device")
class UnexpectedDevice(BootloaderError):
STATUS = 0x06
class UnsupportedBootloaderVersion(BootloaderError):
STATUS = 0x07
class InvalidChecksum(BootloaderError):
STATUS = 0x08
class InvalidArray(BootloaderError):
STATUS = 0x09
class InvalidFlashRow(BootloaderError):
STATUS = 0x0A
class ProtectedFlash(BootloaderError):
STATUS = 0x0B
class InvalidApp(BootloaderError):
STATUS = 0x0C
class TargetApplicationIsActive(BootloaderError):
STATUS = 0x0D
def __init__(self):
super().__init__("The application is currently marked as active or golden image")
class CallbackResponseInvalid(BootloaderError):
STATUS = 0x0E
class UnknownError(BootloaderError):
STATUS = 0x0F
class BootloaderResponse(object):
FORMAT = ""
ARGS = ()
ERRORS = {klass.STATUS: klass for klass in [
BootloaderKeyError,
VerificationError,
IncorrectLength,
InvalidData,
InvalidCommand,
InvalidChecksum,
UnexpectedDevice,
UnsupportedBootloaderVersion,
InvalidArray,
InvalidFlashRow,
ProtectedFlash,
InvalidApp,
TargetApplicationIsActive,
CallbackResponseInvalid,
UnknownError
]}
def __init__(self, data):
try:
unpacked = struct.unpack(self.FORMAT, data)
except struct.error as e:
raise InvalidPacketError("Cannot unpack packet data '{}': {}".format(data, e))
for arg, value in zip(self.ARGS, unpacked):
if arg:
setattr(self, arg, value)
@classmethod
def decode(cls, data, checksum_func):
start, status, length = struct.unpack("<BBH", data[:4])
if start != 0x01:
raise InvalidPacketError("Expected Start Of Packet signature 0x01, found 0x{0:01X}".format(start))
expected_dlen = len(data) - 7
if length != expected_dlen:
raise InvalidPacketError("Expected packet data length {} actual {}".format(length, expected_dlen))
checksum, end = struct.unpack("<HB", data[-3:])
data = data[:length + 4]
if end != 0x17:
raise InvalidPacketError("Invalid end of packet code 0x{0:02X}, expected 0x17".format(end))
calculated_checksum = checksum_func(data)
if checksum != calculated_checksum:
raise InvalidPacketError(
"Invalid packet checksum 0x{0:02X}, expected 0x{1:02X}".format(checksum, calculated_checksum))
# TODO Handle status 0x0D: The application is currently marked as active
if (status != 0x00):
response_class = cls.ERRORS.get(status)
if response_class:
raise response_class()
else:
raise InvalidPacketError("Unknown status code 0x{0:02X}".format(status))
data = data[4:]
return cls(data)
class BootloaderCommand(object):
COMMAND = None
FORMAT = ""
ARGS = ()
RESPONSE = None
def __init__(self, **kwargs):
for arg in kwargs:
if arg not in self.ARGS:
raise TypeError("Argument {} not in command arguments".format(arg))
self.args = [kwargs[arg] for arg in self.ARGS]
@property
def data(self):
return struct.pack(self.FORMAT, *self.args)
class BooleanResponse(BootloaderResponse):
FORMAT = "B"
ARGS = ("status",)
class EmptyResponse(BootloaderResponse):
pass
class VerifyChecksumCommand(BootloaderCommand):
COMMAND = 0x31
RESPONSE = BooleanResponse
class GetFlashSizeResponse(BootloaderResponse):
FORMAT = "<HH"
ARGS = ("first_row", "last_row")
class GetFlashSizeCommand(BootloaderCommand):
COMMAND = 0x32
FORMAT = "B"
ARGS = ("array_id",)
RESPONSE = GetFlashSizeResponse
class GetAppStatusResponse(BootloaderResponse):
FORMAT = "<BB"
ARGS = ("app_valid", "app_active")
class GetAppStatusCommand(BootloaderCommand):
COMMAND = 0x33
FORMAT = "B"
ARGS = ("application_id",)
RESPONSE = GetAppStatusResponse
class EraseRowCommand(BootloaderCommand):
COMMAND = 0x34
FORMAT = "<BH"
ARGS = ("array_id", "row_id")
RESPONSE = EmptyResponse
class SyncBootloaderCommand(BootloaderCommand):
COMMAND = 0x35
RESPONSE = EmptyResponse
class SetAppActive(BootloaderCommand):
COMMAND = 0x36
FORMAT = "B"
ARGS = ("application_id",)
RESPONSE = EmptyResponse
class SendDataCommand(BootloaderCommand):
COMMAND = 0x37
RESPONSE = EmptyResponse
def __init__(self, data):
self._data = data
super(SendDataCommand, self).__init__()
@property
def data(self):
return self._data
class EnterBootloaderResponse(BootloaderResponse):
FORMAT = "<IBHB"
ARGS = ("silicon_id", "silicon_rev", "bl_version", "bl_version_2")
class EnterBootloaderCommand(BootloaderCommand):
COMMAND = 0x38
RESPONSE = EnterBootloaderResponse
def __init__(self, key):
self._key = key
super(EnterBootloaderCommand, self).__init__()
@property
def data(self):
if self._key is None:
return super(EnterBootloaderCommand, self).data
return super(EnterBootloaderCommand, self).data + struct.pack("<BBBBBB",
*self._key)
class ProgramRowCommand(BootloaderCommand):
COMMAND = 0x39
FORMAT = "<BH"
ARGS = ("array_id", "row_id")
RESPONSE = EmptyResponse
def __init__(self, data, **kwargs):
self._data = data
super(ProgramRowCommand, self).__init__(**kwargs)
@property
def data(self):
return super(ProgramRowCommand, self).data + self._data
class ChecksumResponse(BootloaderResponse):
FORMAT = "<B"
ARGS = ("checksum",)
class VerifyRowCommand(BootloaderCommand):
COMMAND = 0x3A
FORMAT = "<BH"
ARGS = ("array_id", "row_id")
RESPONSE = ChecksumResponse
class ExitBootloaderCommand(BootloaderCommand):
COMMAND = 0x3B
RESPONSE = EmptyResponse
class GetMetadataResponse(BootloaderResponse):
# TODO: metadata format differs in PSOC3 and 4/5
FORMAT = "<BIII7xBBHHH28x"
ARGS = (
"checksum",
"bootloadable_addr",
"bootloader_last_row",
"bootloadable_len",
"active",
"verified",
"app_version",
"app_id",
"custom_id",
)
def __str__(self):
sb = []
for key in self.__dict__:
sb.append("{key}='{value}'".format(key=key, value=self.__dict__[key]))
return ', '.join(sb)
def __repr__(self):
return self.__str__()
class GetPSOC5MetadataResponse(BootloaderResponse):
# TODO: metadata format differs in PSOC3 and 4/5
FORMAT = "<BIHxxIxxxBBHHHI28x"
ARGS = (
"checksum",
"bootloadable_addr",
"bootloader_last_row",
"bootloadable_len",
"active",
"verified",
"bootloader_version",
"app_id",
"app_version",
"app_custom_id",
)
def __str__(self):
sb = []
for key in self.__dict__:
sb.append("{key}='{value}'".format(key=key, value=self.__dict__[key]))
return ', '.join(sb)
def __repr__(self):
return self.__str__()
class GetMetadataCommand(BootloaderCommand):
COMMAND = 0x3C
FORMAT = "<B"
ARGS = ("application_id",)
RESPONSE = GetMetadataResponse
class GetPSOC5MetadataCommand(BootloaderCommand):
COMMAND = 0x3C
FORMAT = "<B"
ARGS = ("application_id",)
RESPONSE = GetPSOC5MetadataResponse
class BootloaderSession(object):
def __init__(self, transport, checksum_func):
self.transport = transport
self.checksum_func = checksum_func
def send(self, command, read=True):
data = command.data
packet = b"\x01" + struct.pack("<BH", command.COMMAND, len(data)) + data
packet = packet + struct.pack('<H', self.checksum_func(packet)) + b"\x17"
self.transport.send(packet)
if read:
response = self.transport.recv()
return command.RESPONSE.decode(response, self.checksum_func)
else:
return None
def enter_bootloader(self, key):
response = self.send(EnterBootloaderCommand(key))
return response.silicon_id, response.silicon_rev, response.bl_version | (response.bl_version_2 << 16)
def application_status(self, application_id):
response = self.send(GetAppStatusCommand(application_id=application_id))
return response.app_valid, response.app_active
def exit_bootloader(self):
self.send(ExitBootloaderCommand(), read=False)
def get_flash_size(self, array_id):
response = self.send(GetFlashSizeCommand(array_id=array_id))
return response.first_row, response.last_row
def verify_checksum(self):
return bool(self.send(VerifyChecksumCommand()).status)
def get_metadata(self, application_id=0):
return self.send(GetMetadataCommand(application_id=application_id))
def get_psoc5_metadata(self, application_id=0):
return self.send(GetPSOC5MetadataCommand(application_id=application_id))
def program_row(self, array_id, row_id, rowdata, chunk_size):
chunked = [rowdata[i:i + chunk_size] for i in range(0, len(rowdata), chunk_size)]
for chunk in chunked[0:-1]:
self.send(SendDataCommand(chunk))
self.send(ProgramRowCommand(chunked[-1], array_id=array_id, row_id=row_id))
def get_row_checksum(self, array_id, row_id):
return self.send(VerifyRowCommand(array_id=array_id, row_id=row_id)).checksum
def set_application_active(self, application_id):
self.send(SetAppActive(application_id=application_id))
class SerialTransport(object):
def __init__(self, f, verbose):
self.f = f
self._verbose = verbose
def send(self, data):
if self._verbose:
for part in bytearray(data):
print("s: 0x{:02x}".format(part))
self.f.write(data)
def recv(self):
data = self.f.read(4)
if len(data) < 4:
raise BootloaderTimeoutError("Timed out waiting for Bootloader response.")
size = struct.unpack("<H", data[-2:])[0]
data += self.f.read(size + 3)
if self._verbose:
for part in bytearray(data):
print("r: 0x{:02x}".format(part))
if len(data) < size + 7:
raise BootloaderTimeoutError("Timed out waiting for Bootloader response.")
return data
class CANbusTransport(object):
MESSAGE_CLASS = None
def __init__(self, transport, frame_id, timeout, echo_frames, wait_send_ms):
self.transport = transport
self.frame_id = frame_id
self.timeout = timeout
self.echo_frames = echo_frames
self.wait_send_s = wait_send_ms / 1000.0
self._last_sent_frame = None
def send(self, data):
start = 0
maxlen = len(data)
while (start < maxlen):
remaining = maxlen - start
if (remaining > 8):
msg = self.MESSAGE_CLASS(
extended_id=False,
arbitration_id=self.frame_id,
data=data[start:start + 8]
)
else:
msg = self.MESSAGE_CLASS(
extended_id=False,
arbitration_id=self.frame_id,
data=data[start:]
)
# Flush input mailbox(es)
while (self.transport.recv(timeout=0)):
pass
self.transport.send(msg)
self._last_sent_frame = msg
if (self.echo_frames):
# Read back the echo message
while (True):
frame = self.transport.recv(self.timeout)
if (not frame):
raise BootloaderTimeoutError("Did not receive echo frame within {} timeout".format(self.timeout))
# Don't check the frame arbitration ID, it may be used for varying purposes
if (frame.data[:frame.dlc] != msg.data[:msg.dlc]):
continue
# Ok, got a good frame
break
elif (self.wait_send_s > 0.0):
time.sleep(self.wait_send_s)
start += 8
def recv(self):
# Response packets read from the Bootloader have the following structure:
# Start of Packet (0x01): 1 byte
# Status Code: 1 byte
# Data Length: 2 bytes
# Data: N bytes of data
# Checksum: 2 bytes
# End of Packet (0x17): 1 byte
data = bytearray()
# Read first frame, contains data length
while True:
frame = self.transport.recv(self.timeout)
if (not frame):
raise BootloaderTimeoutError("Timed out waiting for Bootloader 1st response frame")
if frame.arbitration_id != self.frame_id:
continue
# Don't check the frame arbitration ID, it may be used for varying purposes
if len(frame.data) < 4:
raise BootloaderTimeoutError("Unexpected response data: length {}, minimum is 4".format(len(frame.data)))
if (frame.data[0] != 0x01):
raise BootloaderTimeoutError("Unexpected start of frame data: 0x{0:02X}, expected 0x01".format(frame.data[0]))
break
data += frame.data[:frame.dlc]
# 4 initial bytes, reported size, 3 tail
total_size = 4 + (struct.unpack("<H", data[2:4])[0]) + 3
while (len(data) < total_size):
frame = self.transport.recv(self.timeout)
if (not frame):
raise BootloaderTimeoutError("Timed out waiting for Bootloader response frame")
if (self.echo_frames) and (frame.arbitration_id != self.frame_id):
# Got a frame from another device, ignore
continue
data += frame.data[:frame.dlc]
return data
def crc16_checksum(data):
crc = 0xffff
for b in data:
if not isinstance(b, int):
b = ord(b)
for i in range(8):
if (crc & 1) ^ (b & 1):
crc = (crc >> 1) ^ 0x8408
else:
crc >>= 1
b >>= 1
crc = (crc << 8) | (crc >> 8)
return ~crc & 0xffff
def sum_2complement_checksum(data):
if (type(data) is str):
return (1 + ~sum([ord(c) for c in data])) & 0xFFFF
elif (type(data) in (bytearray, bytes)):
return (1 + ~sum(data)) & 0xFFFF
|
arachnidlabs/cyflash
|
cyflash/protocol.py
|
Python
|
bsd-2-clause
| 15,768 |
#include "stdafx.h"
#include "Group.h"
#include "GapSpring.h"
#include "ComponentSpring.h"
namespace scv {
Group *Group::addGroup(Group *group) {
return addSpring(group);
}
Group *Group::addComponent(Component *component) {
return addComponent(component, Spring::DEFAULT_SIZE, Spring::DEFAULT_SIZE, Spring::DEFAULT_SIZE);
}
Group *Group::addComponent(Component *component, int size) {
return addComponent(component, size, size, size);
}
Group *Group::addComponent(Component *component, int min, int pref, int max) {
return addSpring(new ComponentSpring(component, min, pref, max));
}
void Group::removeComponent(scv::Component * object) {
SpringsList::iterator iter = _springs.begin();
while (iter != _springs.end()) {
ComponentSpring* spring;
Group* group;
if ((spring = dynamic_cast<ComponentSpring *>(*iter)) && spring->getComponent() == object) {
iter = _springs.erase(iter);
} else if (group = dynamic_cast<Group *>(*iter)) {
group->removeComponent(object);
++iter;
} else {
++iter;
}
}
}
Group *Group::addGap(int size) {
return addGap(size, size, size);
}
Group * Group::addGap(int min, int pref, int max) {
return addSpring(new GapSpring(min, pref, max));
}
Group * Group::addSpring(Spring *spring) {
_springs.push_back(spring);
return this;
}
int Group::calculateMinimumSize(Axis axis) {
return calculateSize(axis, MIN_SIZE);
}
int Group::calculatePreferredSize(Axis axis) {
return calculateSize(axis, PREF_SIZE);
}
int Group::calculateMaximumSize(Axis axis) {
return calculateSize(axis, MAX_SIZE);
}
int Group::calculateSize(Spring::Axis axis, SizeType type) {
int count = _springs.size();
if (count == 0) {
return 0;
}
if (count == 1) {
return getSpringSize(getSpring(0), axis, type);
}
int size = constrain(combined(getSpringSize(getSpring(0), axis, type),
getSpringSize(getSpring(1), axis, type)));
for (int i = 2; i < count; ++i) {
size = constrain(combined(size, getSpringSize(getSpring(i), axis, type)));
}
return size;
}
int Group::getSpringSize(Spring *spring, Spring::Axis axis, SizeType type) {
switch (type) {
case MIN_SIZE:
return spring->getMinimumSize(axis);
break;
case PREF_SIZE:
return spring->getPreferredSize(axis);
break;
case MAX_SIZE:
return spring->getMaximumSize(axis);
break;
default:
return 0;
break;
}
}
void Group::setSize(Spring::Axis axis, int origin, int size) {
Spring::setSize(axis, origin, size);
if (size == Spring::UNSET) {
for (int counter = _springs.size() - 1; counter >= 0; --counter) {
getSpring(counter)->setSize(axis, origin, size);
}
} else {
setValidSize(axis, origin, size);
}
}
/*
Group *Group::enableAutoCreateContainerGaps(void) {
_autoCreateContainerPadding = true;
}
bool Group::getAutoCreateContainerGaps(void) const {
return _autoCreateContainerPadding;
}*/
} //namespace scv
|
yuriks/SCV
|
SCV/src/Group.cpp
|
C++
|
bsd-2-clause
| 3,173 |
// This file was procedurally generated from the following sources:
// - src/dstr-binding/obj-init-null.case
// - src/dstr-binding/error/gen-meth.template
/*---
description: Value specifed for object binding pattern must be object coercible (null) (generator method)
esid: sec-generator-function-definitions-runtime-semantics-propertydefinitionevaluation
es6id: 14.4.13
features: [generators, destructuring-binding]
flags: [generated]
info: |
GeneratorMethod :
* PropertyName ( StrictFormalParameters ) { GeneratorBody }
1. Let propKey be the result of evaluating PropertyName.
2. ReturnIfAbrupt(propKey).
3. If the function code for this GeneratorMethod is strict mode code,
let strict be true. Otherwise let strict be false.
4. Let scope be the running execution context's LexicalEnvironment.
5. Let closure be GeneratorFunctionCreate(Method,
StrictFormalParameters, GeneratorBody, scope, strict).
[...]
9.2.1 [[Call]] ( thisArgument, argumentsList)
[...]
7. Let result be OrdinaryCallEvaluateBody(F, argumentsList).
[...]
9.2.1.3 OrdinaryCallEvaluateBody ( F, argumentsList )
1. Let status be FunctionDeclarationInstantiation(F, argumentsList).
[...]
9.2.12 FunctionDeclarationInstantiation(func, argumentsList)
[...]
23. Let iteratorRecord be Record {[[iterator]]:
CreateListIterator(argumentsList), [[done]]: false}.
24. If hasDuplicates is true, then
[...]
25. Else,
b. Let formalStatus be IteratorBindingInitialization for formals with
iteratorRecord and env as arguments.
[...]
Runtime Semantics: BindingInitialization
ObjectBindingPattern : { }
1. Return NormalCompletion(empty).
---*/
var obj = {
*method({}) {}
};
assert.throws(TypeError, function() {
obj.method(null);
});
|
sebastienros/jint
|
Jint.Tests.Test262/test/language/expressions/object/dstr-gen-meth-obj-init-null.js
|
JavaScript
|
bsd-2-clause
| 1,850 |
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing.Printing;
using System.ComponentModel;
using WebKit.Interop;
using System.Drawing;
using System.Windows.Forms;
namespace WebKit
{
internal class PrintManager
{
private PrintDocument _document;
private IWebFramePrivate _webFramePrivate;
private WebKitBrowser _owner;
private Graphics _printGfx;
private uint _nPages;
private uint _page;
private int _hDC;
private bool _printing = false;
public PrintManager(PrintDocument Document, WebKitBrowser Owner)
{
this._document = Document;
this._owner = Owner;
this._webFramePrivate =
(IWebFramePrivate)((IWebView)_owner.GetWebView()).mainFrame();
}
public void Print()
{
// potential concurrency issues with shared state variable
if (_printing)
return;
_printing = true;
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync();
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
_document.PrintPage += new PrintPageEventHandler(_document_PrintPage);
_document.Print();
_printing = false;
}
private delegate uint GetPrintedPageCountDelegate();
private void _document_PrintPage(object sender, PrintPageEventArgs e)
{
// running on a seperate thread, so we invoke _webFramePrivate
// methods on the owners ui thread
if (_printGfx == null)
{
// initialise printing
_printGfx = e.Graphics;
_hDC = _printGfx.GetHdc().ToInt32();
_owner.Invoke(new MethodInvoker(delegate() {
_webFramePrivate.setInPrintingMode(1, _hDC);
}));
_nPages = (uint)_owner.Invoke(
new GetPrintedPageCountDelegate(delegate() {
return _webFramePrivate.getPrintedPageCount(_hDC);
}));
_page = 1;
}
_owner.Invoke(new MethodInvoker(delegate() {
_webFramePrivate.spoolPages(_hDC, _page, _page, 0);
}));
++_page;
if (_page <= _nPages)
{
e.HasMorePages = true;
}
else
{
_owner.Invoke(new MethodInvoker(delegate() {
_webFramePrivate.setInPrintingMode(0, _hDC);
}));
e.HasMorePages = false;
}
}
}
}
|
windygu/webkitdotnet
|
WebKitBrowser/PrintManager.cs
|
C#
|
bsd-2-clause
| 2,909 |
//====================================================================================
//DynamicRepresentation.cpp
//
//This code is part of Anubis Engine.
//
//Anubis Engine is a free game engine created as a fan project to be
//awesome platform for developing games!
//
//All sources can be found here:
// https://github.com/Dgek/Anubis-Engine
//
//Demos based on Anubis Engine can be found here:
// https://github.com/Dgek/Demos
//
//Copyright (c) 2013, Muralev Evgeny
//All rights reserved.
//
//Redistribution and use in source and binary forms, with
//or without modification, are permitted provided that the
//following conditions are met:
//
//Redistributions of source code must retain the above copyright notice,
//this list of conditions and the following disclaimer.
//
//Redistributions in binary form must reproduce the above copyright notice,
//this list of conditions and the following disclaimer in the documentation
//and/or other materials provided with the distribution.
//
//Neither the name of the Minotower Games 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 MURALEV EVGENY "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 MURALEV EVGENY BE LIABLE
//FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
//(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
//ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
//(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//====================================================================================
#include "Scene_pch.h"
#include "DynamicRepresentation.h"
#include "../../../Math/Source/Interpolation.h"
using namespace Anubis;
AVOID DynamicRepresentation::SetCurrentTransform(Mat4x4 & mat, AREAL64 r64CurrentTime)
{
m_prevWorldMatrix = m_currentWorldMatrix;
m_currentWorldMatrix = mat;
m_r64LastUpdate = r64CurrentTime;
}
AVOID DynamicRepresentation::SetBothTransforms(Mat4x4 & mat, AREAL64 r64CurrentTime)
{
m_prevWorldMatrix = mat;
m_currentWorldMatrix = mat;
m_r64LastUpdate = r64CurrentTime;
}
//pre-rendering modifications
AVOID DynamicRepresentation::VPushParameters(Scene *pScene, AREAL64 r64CurrentTime)
{
Mat4x4 transform;
//new update cycle - current transform has changed
if (m_prevWorldMatrix != m_currentWorldMatrix)
{
transform = LERP(m_prevWorldMatrix, m_currentWorldMatrix, min((r64CurrentTime - m_r64LastUpdate) / pScene->GetFixedTimeStep(), 1));
}
else
{
//we are not updating anything, so use current transform
transform = m_currentWorldMatrix;
}
pScene->PushTransform(transform);
}
|
Solidstatewater/Anubis-Engine
|
Scene/Source/Representations/DynamicRepresentation.cpp
|
C++
|
bsd-2-clause
| 3,047 |
"""
Django settings for d3matt project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
ENV_ROOT = os.path.dirname(os.path.dirname(BASE_DIR))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'xz@e41f!kjulkntr!e8f2sahhguv)eqy_04qd5st-g8vvlkx**'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
'blog',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'd3matt.urls'
WSGI_APPLICATION = 'd3matt.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(ENV_ROOT, 'd3matt.db'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Chicago'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(ENV_ROOT, 'static'),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
os.path.join(ENV_ROOT, 'templates'),
)
CRISPY_TEMPLATE_PACK = 'bootstrap3'
LOGIN_REDIRECT_URL = '/d3matt/'
|
d3matt/d3matt.com
|
src/d3matt/d3matt/settings.py
|
Python
|
bsd-2-clause
| 2,826 |
# frozen_string_literal: true
# See LICENSE.txt at root of repository
# GENERATED FILE - DO NOT EDIT!!
require 'ansible/ruby/modules/base'
module Ansible
module Ruby
module Modules
# Create, destroy, or update access groups on Element Software Cluster.
class Na_elementsw_access_group < Base
# @return [:present, :absent] Whether the specified access group should exist or not.
attribute :state
validates :state, presence: true, expression_inclusion: {:in=>[:present, :absent], :message=>"%{value} needs to be :present, :absent"}
# @return [String, Integer, nil] ID or Name of the access group to modify or delete.,Required for delete and modify operations.
attribute :src_access_group_id
validates :src_access_group_id, type: MultipleTypes.new(String, Integer)
# @return [String, nil] New name for the access group for create and modify operation.,Required for create operation.
attribute :new_name
validates :new_name, type: String
# @return [Object, nil] List of initiators to include in the access group. If unspecified, the access group will start out without configured initiators.
attribute :initiators
# @return [Array<Integer>, Integer, nil] List of volumes to initially include in the volume access group. If unspecified, the access group will start without any volumes.
attribute :volumes
validates :volumes, type: TypeGeneric.new(Integer)
# @return [Object, nil] The ID of the Element SW Software Cluster Virtual Network ID to associate the access group with.
attribute :virtual_network_id
# @return [Object, nil] The ID of the VLAN Virtual Network Tag to associate the access group with.
attribute :virtual_network_tags
# @return [Hash, nil] List of Name/Value pairs in JSON object format.
attribute :attributes
validates :attributes, type: Hash
end
end
end
end
|
wied03/ansible-ruby
|
lib/ansible/ruby/modules/generated/storage/netapp/na_elementsw_access_group.rb
|
Ruby
|
bsd-2-clause
| 1,981 |
package com.github.aview.api.mobile;
/*
* #%L
* iview-api
* %%
* Copyright (C) 2013 The aview authors
* %%
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
import java.util.Arrays;
import java.util.Date;
import com.github.aview.api.Series;
import com.google.gson.annotations.SerializedName;
/**
*
* @author aview
*
*/
public class MobileSeries implements Series {
private static final long serialVersionUID = -4714586420569623473L;
@SerializedName("episodes")
private MobileEpisode[] episodes;
@SerializedName("keywords")
private String keywords;
@SerializedName("seriesDescription")
private String seriesDescription;
@SerializedName("seriesExpireDate")
private Date seriesExpireDate;
@SerializedName("seriesId")
private int seriesId;
@SerializedName("seriesNumber")
private Integer seriesNumber;
@SerializedName("seriesPubDate")
private Date seriesPubDate;
@SerializedName("seriesTitle")
private String seriesTitle;
@SerializedName("thumbnail")
private String thumbnail;
/*
* @see com.github.aview.Series#getPrograms()
*/
@Override
public MobileEpisode[] getEpisodes() {
return episodes;
}
/*
* @see com.github.aview.Series#getKeywords()
*/
@Override
public String getKeywords() {
return keywords;
}
/*
* @see com.github.aview.Series#getDescription()
*/
@Override
public String getDescription() {
return seriesDescription;
}
public Date getSeriesExpireDate() {
return seriesExpireDate;
}
/*
* @see com.github.aview.Series#getId()
*/
@Override
public Integer getId() {
return seriesId;
}
public Integer getSeriesNumber() {
return seriesNumber;
}
public Date getSeriesPubDate() {
return seriesPubDate;
}
/*
* @see com.github.aview.Series#getName()
*/
@Override
public String getName() {
return seriesTitle;
}
/*
* @see com.github.aview.Series#getThumbnailUrl()
*/
@Override
public String getThumbnailUrl() {
return thumbnail;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + seriesId;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MobileSeries other = (MobileSeries) obj;
if (seriesId != other.seriesId)
return false;
return true;
}
/*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("MobileSeries [episodes=").append(Arrays.toString(episodes)).append(", keywords=")
.append(keywords).append(", seriesDescription=").append(seriesDescription)
.append(", seriesExpireDate=").append(seriesExpireDate).append(", seriesId=").append(seriesId)
.append(", seriesNumber=").append(seriesNumber).append(", seriesPubDate=").append(seriesPubDate)
.append(", seriesTitle=").append(seriesTitle).append(", thumbnail=").append(thumbnail).append("]");
return builder.toString();
}
}
|
aviewdevs/aview
|
iview-api/src/main/java/com/github/aview/api/mobile/MobileSeries.java
|
Java
|
bsd-2-clause
| 4,784 |
/************************************************************************
*
* Flood Project © (2008-201x)
* Licensed under the simplified BSD license. All rights reserved.
*
************************************************************************/
#include "Engine/API.h"
#include "Engine/Input/InputManager.h"
#include "Engine/Input/Device.h"
#include "Engine/Input/Keyboard.h"
#include "Engine/Input/Mouse.h"
#include "Engine/Input/Joystick.h"
#include "Engine/Window/Window.h"
NAMESPACE_ENGINE_BEGIN
//-----------------------------------//
static Allocator* gs_InputAllocator = nullptr;
static InputManager* gs_InputManager = nullptr;
InputManager* GetInputManager() { return gs_InputManager; }
void InputInitialize()
{
gs_InputAllocator = AllocatorCreateHeap( AllocatorGetHeap() );
AllocatorSetGroup(gs_InputAllocator, "Input");
}
void InputDeinitialize()
{
AllocatorDestroy(gs_InputAllocator);
}
//-----------------------------------//
InputManager::InputManager()
{
gs_InputManager = this;
}
//-----------------------------------//
InputManager::~InputManager()
{
}
//-----------------------------------//
NAMESPACE_ENGINE_END
|
FloodProject/flood
|
src/Engine/Input/InputManager.cpp
|
C++
|
bsd-2-clause
| 1,203 |
class CreateApiKeys < ActiveRecord::Migration
def change
create_table :api_keys do |t|
t.string :access_token
t.references :user
t.timestamps
end
add_index :api_keys, :user_id
add_index :api_keys, :access_token
end
end
|
brewbit/brewbit-dashboard
|
db/migrate/20140104214015_create_api_keys.rb
|
Ruby
|
bsd-2-clause
| 258 |
namespace DeOps.Services.Profile
{
partial class ProfileView
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.Browser = new DeOps.Interface.Views.WebBrowserEx();
this.RightClickMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.EditMenu = new System.Windows.Forms.ToolStripMenuItem();
this.RightClickMenu.SuspendLayout();
this.SuspendLayout();
//
// Browser
//
this.Browser.AllowWebBrowserDrop = false;
this.Browser.ContextMenuStrip = this.RightClickMenu;
this.Browser.Dock = System.Windows.Forms.DockStyle.Fill;
this.Browser.IsWebBrowserContextMenuEnabled = false;
this.Browser.Location = new System.Drawing.Point(0, 0);
this.Browser.MinimumSize = new System.Drawing.Size(20, 20);
this.Browser.Name = "Browser";
this.Browser.ScriptErrorsSuppressed = true;
this.Browser.Size = new System.Drawing.Size(216, 200);
this.Browser.TabIndex = 0;
this.Browser.WebBrowserShortcutsEnabled = false;
this.Browser.Navigating += new System.Windows.Forms.WebBrowserNavigatingEventHandler(this.Browser_Navigating);
//
// RightClickMenu
//
this.RightClickMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.EditMenu});
this.RightClickMenu.Name = "RightClickMenu";
this.RightClickMenu.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.RightClickMenu.Size = new System.Drawing.Size(116, 26);
this.RightClickMenu.Opening += new System.ComponentModel.CancelEventHandler(this.RightClickMenu_Opening);
//
// EditMenu
//
this.EditMenu.Name = "EditMenu";
this.EditMenu.Size = new System.Drawing.Size(115, 22);
this.EditMenu.Text = "Edit...";
this.EditMenu.Click += new System.EventHandler(this.EditMenu_Click);
//
// ProfileView
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.Browser);
this.Name = "ProfileView";
this.Size = new System.Drawing.Size(216, 200);
this.RightClickMenu.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private DeOps.Interface.Views.WebBrowserEx Browser;
private System.Windows.Forms.ContextMenuStrip RightClickMenu;
private System.Windows.Forms.ToolStripMenuItem EditMenu;
}
}
|
swax/DeOps
|
UI/Services/Profile/ProfileView.Designer.cs
|
C#
|
bsd-2-clause
| 3,654 |
// Copyright 2015-2019 Elviss Strazdins. All rights reserved.
#ifndef OUZEL_GRAPHICS_D3D11RENDERTARGET_HPP
#define OUZEL_GRAPHICS_D3D11RENDERTARGET_HPP
#include "core/Setup.h"
#if OUZEL_COMPILE_DIRECT3D11
#include <d3d11.h>
#include <set>
#include <vector>
#include "graphics/direct3d11/D3D11RenderResource.hpp"
#include "math/Color.hpp"
namespace ouzel
{
namespace graphics
{
class D3D11RenderDevice;
class D3D11Texture;
class D3D11RenderTarget final: public D3D11RenderResource
{
public:
D3D11RenderTarget(D3D11RenderDevice& renderDeviceD3D11,
const std::set<D3D11Texture*>& initColorTextures,
D3D11Texture* initDepthTexture);
~D3D11RenderTarget();
void resolve();
inline const std::vector<ID3D11RenderTargetView*>& getRenderTargetViews() const { return renderTargetViews; }
inline ID3D11DepthStencilView* getDepthStencilView() const { return depthStencilView; }
private:
std::set<D3D11Texture*> colorTextures;
D3D11Texture* depthTexture = nullptr;
std::vector<ID3D11RenderTargetView*> renderTargetViews;
ID3D11DepthStencilView* depthStencilView = nullptr;
};
} // namespace graphics
} // namespace ouzel
#endif
#endif // OUZEL_GRAPHICS_D3D11RENDERTARGET_HPP
|
elvman/ouzel
|
ouzel/graphics/direct3d11/D3D11RenderTarget.hpp
|
C++
|
bsd-2-clause
| 1,409 |
module VCLog
require 'vclog/core_ext'
require 'vclog/changelog'
require 'vclog/tag'
require 'vclog/release'
require 'erb'
# A Release History is very similar to a ChangeLog.
# It differs in that it is divided into releases with
# version, release date and release note.
#
# The release version, date and release note can be
# descerened from the underlying SCM by identifying
# the hard tag commits.
#
# TODO: Extract output formating from delta parser. Later---Huh?
#
class History
# Location of this file in the file system.
DIR = File.dirname(__FILE__)
#
attr :repo
## Alternate title.
#attr_accessor :title
## Current working version.
#attr_accessor :version
## Exclude commit details.
#attr_accessor :summary
#
def initialize(repo)
@repo = repo
#opts = OpenStruct.new(opts) if Hash === opts
#@title = opts.title || "RELEASE HISTORY"
#@extra = opts.extra
#@version = opts.version
#@level = opts.level || 0
end
# Tag list from version control system.
def tags
@tags ||= repo.tags
end
# Changelog object
#def changelog
# @changlog ||= repo.changelog #ChangeLog.new(changes)
#end
# Change list from version control system filter for level setting.
def changes
@changes ||= (
if @repo.point
repo.change_points
else
repo.changes
end
)
end
#
def releases
@releases ||= (
rel = []
tags = self.tags
#ver = repo.bump(version)
user = repo.user
time = ::Time.now + (3600 * 24) # one day ahead
tags << Tag.new(:name=>'HEAD', :id=>'HEAD', :date=>time, :who=>user, :msg=>"Current Development")
# TODO: Do we need to add a Time.now tag?
# add current verion to release list (if given)
#previous_version = tags[0].name
#if current_version < previous_version # TODO: need to use natural comparision
# raise ArgumentError, "Release version is less than previous version (#{previous_version})."
#end
#rels << [current_version, current_release || Time.now]
#rels = rels.uniq # only uniq releases
# sort by release date
tags = tags.sort{ |a,b| a.date <=> b.date }
# organize into deltas
delta = []
last = nil
tags.each do |tag|
delta << [tag, [last, tag.commit_date]]
last = tag.commit_date
end
# gather changes for each delta
delta.each do |tag, (started, ended)|
if started
set = changes.select{ |c| c.date >= started && c.date < ended }
#gt_vers, gt_date = gt.name, gt.date
#lt_vers, lt_date = lt.name, lt.date
#gt_date = Time.parse(gt_date) unless Time===gt_date
#lt_date = Time.parse(lt_date) unless Time===lt_date
#log = changelog.after(gt).before(lt)
else
#lt_vers, lt_date = lt.name, lt.date
#lt_date = Time.parse(lt_date) unless Time===lt_date
#log = changelog.before(lt_date)
set = changes.select{ |c| c.date < ended }
end
rel << Release.new(tag, set)
end
rel
)
end
# Group +changes+ by tag type.
def groups(changes)
@groups ||= changes.group_by{ |e| e.label } #type
end
#
def to_h
releases.map{ |rel| rel.to_h }
end
end
end
|
rubyworks/vclog
|
work/deprecated/history.rb
|
Ruby
|
bsd-2-clause
| 3,524 |
(function() {
var LOAD_TIMEOUT = 60000;
var PLAY_BUTTON = [0, 173, 0];
var PAUSE_BUTTON = [0, 172, 1];
// Code taken from BurninRubber-v0.js.
function childAtPath(path) {
var child = ((window.game || {}).stage) || {};
path.forEach((x) => child = ((child || {}).children || [])[x]);
return child || null;
}
function clickButton(button) {
if (!button || !button.events || !button.events.onInputDown) {
throw 'cannot click null button';
}
button.events.onInputDown.dispatch();
}
var gameOver = false;
window.muniverse = {
init: function() {
return pollAndWait(LOAD_TIMEOUT, function() {
return window.game &&
window.game.isBooted &&
window.game.isRunning &&
window.game.state &&
window.game.state.getCurrentState().key === 'GameState' &&
childAtPath(PLAY_BUTTON) &&
window.game.tweens.getAll().length === 0;
}).then(function() {
window.faketime.pause();
GameState.prototype.onGameOver = () => gameOver = true;
clickButton(childAtPath(PLAY_BUTTON));
childAtPath(PAUSE_BUTTON).events.onInputDown.removeAll();
window.faketime.advance(100);
});
},
step: function(millis) {
window.faketime.advance(millis);
return Promise.resolve(gameOver);
},
score: function() {
// The score is -5 before the game starts.
return Promise.resolve(Math.max(score, 0));
}
};
})();
|
unixpickle/muniverse
|
games/injections/BirdyRush-v0.js
|
JavaScript
|
bsd-2-clause
| 1,488 |
//package com.pineone.icbms.so.servicemodel;
//
//import com.pineone.icbms.so.domain.entity.Domain;
//import com.pineone.icbms.so.service.ref.DeviceObject;
//import com.pineone.icbms.so.service.ref.Status;
//import com.pineone.icbms.so.service.ref.VirtualObject;
//import com.pineone.icbms.so.servicemodel.logic.ServiceModelLogic;
//import com.pineone.icbms.so.servicemodel.logic.ServiceModelLogicImpl;
//import com.pineone.icbms.so.servicemodel.pr.ServiceModelPresentation;
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.test.context.ContextConfiguration;
//import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
//import org.springframework.test.context.web.WebAppConfiguration;
//
///**
// * Created by melvin on 2016. 8. 16..
// NOTE: 실제 서비스 구동 과정 테스트
// */
//
//@RunWith(SpringJUnit4ClassRunner.class)
//@WebAppConfiguration
//@ContextConfiguration(classes = ServiceModelApplication.class)
//public class ServiceModelExecuteTest {
//
// @Autowired
// ServiceModelPresentation serviceModelPresentation;
//
// @Test
// public void executeTest() throws Exception {
//
//// ServiceModelLogic serviceModelLogic = ServiceModelLogicImpl.newServiceModelLogic();
//
// Domain domain = new Domain("DO-1", "강의실" , "http://xxx.xxx.xx");
// DeviceObject deviceObject = VirtualObject.SonamooHeater;
// Status status = Status.Active;
//
//// ServiceMessage serviceMessage = new ServiceMessage(domain, deviceObject, status);
//// serviceModelLogic.executeServiceModel(serviceMessage);
// }
//}
|
oblivion14/SO
|
so-servicemodel/src/test/java/com/pineone/icbms/so/servicemodel/ServiceModelExecuteTest.java
|
Java
|
bsd-2-clause
| 1,696 |
package com.atlassian.jira.plugins.dvcs.listener;
import com.atlassian.crowd.embedded.api.CrowdService;
import com.atlassian.crowd.embedded.api.UserWithAttributes;
import com.atlassian.crowd.event.user.UserAttributeStoredEvent;
import com.atlassian.crowd.exception.OperationNotPermittedException;
import com.atlassian.crowd.exception.runtime.OperationFailedException;
import com.atlassian.crowd.exception.runtime.UserNotFoundException;
import com.atlassian.event.api.EventListener;
import com.atlassian.event.api.EventPublisher;
import com.atlassian.jira.event.web.action.admin.UserAddedEvent;
import com.atlassian.jira.plugins.dvcs.analytics.DvcsAddUserAnalyticsEvent;
import com.atlassian.jira.plugins.dvcs.service.OrganizationService;
import com.atlassian.jira.plugins.dvcs.service.remote.DvcsCommunicatorProvider;
import com.atlassian.jira.security.groups.GroupManager;
import com.atlassian.jira.user.ApplicationUser;
import com.atlassian.jira.user.ApplicationUsers;
import com.atlassian.jira.user.util.UserManager;
import com.google.common.base.Joiner;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
/**
* Listens to user events (just for <code>CREATED</code> type).
*
* Handler methods run asynchronously and are safe to fail. That means that it
* does not corrupt process of adding the user because of some unexpected error
* at this place.
*
* @see #onUserAddViaInterface(UserAddedEvent)
* @see #onUserAttributeStore(UserAttributeStoredEvent)
*/
public class DvcsAddUserListener
{
/** The Constant log. */
private static final Logger log = LoggerFactory.getLogger(DvcsAddUserListener.class);
private static final String UI_USER_INVITATIONS_PARAM_NAME = "com.atlassian.jira.dvcs.invite.groups";
/** BBC-957: Attribute key to recognise Service Desk Customers during user creation */
private static final String SERVICE_DESK_CUSTOMERS_ATTRIBUTE_KEY = "synch.servicedesk.requestor";
/** The event publisher. */
private final EventPublisher eventPublisher;
/** The organization service. */
private final OrganizationService organizationService;
/** The communicator provider. */
private final DvcsCommunicatorProvider communicatorProvider;
private final UserManager userManager;
private final GroupManager groupManager;
private final CrowdService crowd;
/**
* The Constructor.
*
* @param eventPublisher
* the event publisher
* @param organizationService
* the organization service
* @param communicatorProvider
* the communicator provider
*/
public DvcsAddUserListener(EventPublisher eventPublisher,
OrganizationService organizationService,
DvcsCommunicatorProvider communicatorProvider,
UserManager userManager,
GroupManager groupManager,
CrowdService crowd)
{
this.eventPublisher = eventPublisher;
this.organizationService = organizationService;
this.communicatorProvider = communicatorProvider;
this.userManager = userManager;
this.groupManager = groupManager;
this.crowd = crowd;
}
//---------------------------------------------------------------------------------------
// Handler methods
//---------------------------------------------------------------------------------------
@EventListener
public void onUserAddViaInterface(final UserAddedEvent event)
{
if (event == null)
{
return;
}
try
{
log.debug("Running onUserAddViaInterface ...");
String username = event.getRequestParameters().get("username")[0];
String[] organizationIdsAndGroupSlugs = event.getRequestParameters().get(
UserAddedViaInterfaceEventProcessor.ORGANIZATION_SELECTOR_REQUEST_PARAM);
ApplicationUser user = userManager.getUserByName(username);
String userInvitations;
if (organizationIdsAndGroupSlugs != null)
{
userInvitations = Joiner.on(
UserAddedViaInterfaceEventProcessor.ORGANIZATION_SELECTOR_REQUEST_PARAM_JOINER).join(
organizationIdsAndGroupSlugs);
eventPublisher.publish(new DvcsAddUserAnalyticsEvent());
} else
{
// setting blank String to be sure that the crowd will not return null
// https://sdog.jira.com/browse/BBC-432
userInvitations = " ";
}
crowd.setUserAttribute(
ApplicationUsers.toDirectoryUser(user),
UI_USER_INVITATIONS_PARAM_NAME,
Collections.singleton(userInvitations)
);
} catch (UserNotFoundException e)
{
log.warn("UserNotFoundException : " + e.getMessage());
} catch (OperationFailedException e)
{
log.warn("OperationFailedException : " + e.getMessage());
} catch (OperationNotPermittedException e)
{
log.warn("OperationNotPermittedException : " + e.getMessage());
} catch (Exception e) {
log.warn("Unexpected exception " + e.getClass() + " : " + e.getMessage());
}
}
/**
* This way we are handling the google user from studio which has not been activated yet.
* They will get Bitbucket invitation after the first successful login.
*
* @param event the event
*/
@SuppressWarnings("rawtypes")
@EventListener
public void onUserAttributeStore(final UserAttributeStoredEvent event)
{
if (event.getUser() == null)
{
return;
}
safeExecute(new Runnable()
{
@Override
public void run()
{
Set attributeNames = event.getAttributeNames();
String loginCountAttName = "login.count";
if (attributeNames != null &&
attributeNames.contains(loginCountAttName) && attributeNames.size() == 1)
{
Set<String> count = event.getAttributeValues(loginCountAttName);
log.debug("Got {} as the 'login.count' values.", count);
Iterator<String> countValueIterator = count.iterator();
if (!countValueIterator.hasNext())
{
return;
}
int loginCount = NumberUtils.toInt(countValueIterator.next());
// do the invitation for the first time login
if (loginCount == 1)
{
firstTimeLogin(event);
}
}
}
}, "Failed to properly handle event " + event + " for user " + event.getUser().getName());
}
private void firstTimeLogin(final UserAttributeStoredEvent event)
{
String user = event.getUser().getName();
UserWithAttributes attributes = crowd.getUserWithAttributes(user);
String uiChoice = attributes.getValue(UI_USER_INVITATIONS_PARAM_NAME);
log.debug("UI choice for user " + event.getUser().getName() + " : " + uiChoice);
// BBC-957: ignore Service Desk Customers when processing the event.
boolean isServiceDeskRequestor = Boolean.toString(true).equals(attributes.getValue(SERVICE_DESK_CUSTOMERS_ATTRIBUTE_KEY));
if(!isServiceDeskRequestor)
{
if (uiChoice == null)
{
// created by NON UI mechanism, e.g. google user
new UserAddedExternallyEventProcessor(user, organizationService, communicatorProvider, userManager,
groupManager).run();
} else /* something has been chosen from UI */if (StringUtils.isNotBlank(uiChoice))
{
new UserAddedViaInterfaceEventProcessor(uiChoice, ApplicationUsers.from(event.getUser()), organizationService,
communicatorProvider, userManager, groupManager).run();
}
}
}
//---------------------------------------------------------------------------------------
// Handler methods end
//---------------------------------------------------------------------------------------
/**
* Wraps executorService.submit(task) method invocation with
* <code>try-catch</code> block to ensure that no exception is propagated
* up.
*
* @param task
* the task
* @param onFailMessage
* the on fail message
*/
private void safeExecute(Runnable task, String onFailMessage)
{
try
{
if (task != null)
{
task.run();
}
} catch (Throwable t)
{
log.warn(onFailMessage, t);
}
}
private void unregisterSelf()
{
try
{
eventPublisher.unregister(this);
log.info("Listener unregistered ...");
} catch (Exception e)
{
log.warn("Failed to unregister " + this + ", cause message is " + e.getMessage(), e);
}
}
public void unregister() throws Exception
{
log.info("Attempting to unregister listener ... ");
unregisterSelf();
}
public void register() throws Exception
{
log.info("Attempting to register listener ... ");
eventPublisher.register(this);
}
}
|
edgehosting/jira-dvcs-connector
|
jira-dvcs-connector-plugin/src/main/java/com/atlassian/jira/plugins/dvcs/listener/DvcsAddUserListener.java
|
Java
|
bsd-2-clause
| 10,226 |
/*
* Copyright (c) 2018, PandahRS <https://github.com/PandahRS>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.discord;
enum DiscordAreaType
{
BOSSES,
CITIES,
DUNGEONS,
MINIGAMES;
}
|
KronosDesign/runelite
|
runelite-client/src/main/java/net/runelite/client/plugins/discord/DiscordAreaType.java
|
Java
|
bsd-2-clause
| 1,506 |
// This file was procedurally generated from the following sources:
// - src/function-forms/dflt-params-arg-val-undefined.case
// - src/function-forms/default/async-func-expr-named.template
/*---
description: Use of initializer when argument value is `undefined` (async function named expression)
esid: sec-async-function-definitions
features: [default-parameters]
flags: [generated, async]
info: |
14.6 Async Function Definitions
AsyncFunctionExpression :
async function BindingIdentifier ( FormalParameters ) { AsyncFunctionBody }
14.1.19 Runtime Semantics: IteratorBindingInitialization
FormalsList : FormalsList , FormalParameter
[...]
23. Let iteratorRecord be Record {[[Iterator]]:
CreateListIterator(argumentsList), [[Done]]: false}.
24. If hasDuplicates is true, then
[...]
25. Else,
a. Perform ? IteratorBindingInitialization for formals with
iteratorRecord and env as arguments.
[...]
---*/
var callCount = 0;
// Stores a reference `ref` for case evaluation
var ref;
ref = async function ref(fromLiteral = 23, fromExpr = 45, fromHole = 99) {
assert.sameValue(fromLiteral, 23);
assert.sameValue(fromExpr, 45);
assert.sameValue(fromHole, 99);
callCount = callCount + 1;
};
ref(undefined, void 0).then(() => {
assert.sameValue(callCount, 1, 'function invoked exactly once');
}).then($DONE, $DONE);
|
sebastienros/jint
|
Jint.Tests.Test262/test/language/expressions/async-function/named-dflt-params-arg-val-undefined.js
|
JavaScript
|
bsd-2-clause
| 1,404 |
class HapiFhirCli < Formula
desc "Command-line interface for the HAPI FHIR library"
homepage "https://hapifhir.io/"
url "https://github.com/hapifhir/hapi-fhir/releases/download/v5.4.0/hapi-fhir-5.4.0-cli.zip"
sha256 "142022d1d5b1d849e9a894bac0a8269bfccf3be4b1364b3eaeb685c588966995"
license "Apache-2.0"
livecheck do
url :stable
strategy :github_latest
end
depends_on "openjdk"
resource "test_resource" do
url "https://github.com/hapifhir/hapi-fhir/raw/v5.4.0/hapi-fhir-structures-dstu3/src/test/resources/specimen-example.json"
sha256 "4eacf47eccec800ffd2ca23b704c70d71bc840aeb755912ffb8596562a0a0f5e"
end
def install
inreplace "hapi-fhir-cli", /SCRIPTDIR=(.*)/, "SCRIPTDIR=#{libexec}"
libexec.install "hapi-fhir-cli.jar"
bin.install "hapi-fhir-cli"
bin.env_script_all_files libexec/"bin", JAVA_HOME: Formula["openjdk"].opt_prefix
end
test do
testpath.install resource("test_resource")
system bin/"hapi-fhir-cli", "validate", "--file", "specimen-example.json",
"--fhir-version", "dstu3"
end
end
|
Linuxbrew/homebrew-core
|
Formula/hapi-fhir-cli.rb
|
Ruby
|
bsd-2-clause
| 1,080 |
// C++ General Utility Library (mailto:cgul@zethes.com)
// Copyright (C) 2012-2014, Joshua Brookover and Amber Thrall
// All rights reserved.
/** @file SocketTCP.hpp
*/
#pragma once
// Configuration
#include <CGUL/Config.hpp>
// CGUL Includes
#include "../Network/IPAddress.hpp"
#include "../Utility/String.hpp"
// Defines
#include "../External/Defines.hpp"
namespace CGUL
{
namespace Network
{
/** @class SocketTCP SocketTCP.hpp <CGUL/Network/SocketTCP.hpp>
* @brief A class to connect to or listen on a TCP network.
*/
class SocketTCP
{
# if defined(MSVC)
unsigned int __w64 sock;
# elif defined(CGUL_WINDOWS)
unsigned int sock;
# else
int sock;
# endif
# ifdef OpenSSL_FOUND
bool connectionSecure;
_CGUL_SSL sslHandle;
_CGUL_SSL_CTX sslContext;
# endif
bool MakeNonBlocking();
bool MakeNoDelay();
public:
SocketTCP();
~SocketTCP();
void Connect(const IPAddress& ip, unsigned short port);
void Listen(unsigned short port, bool ipv4 = true, int backlog = 10);
bool Accept(SocketTCP* socket);
void Close();
# ifdef OpenSSL_FOUND
void ConnectSSL(const IPAddress& ip, unsigned short port);
void ListenSSL(unsigned short port, bool ipv4 = true, int backlog = 10);
# endif
bool IsConnected();
IPAddress GetIP();
int Send(const void* data, unsigned int size);
int Receive(void* data, unsigned int size);
int Peek(void* data, unsigned int size);
template <typename T>
int Send(const T& data);
# ifdef CPP_HAS_DOUBLE_REFERENCE
template <typename T>
int Send(const T&& data);
# endif
template <typename T>
int Receive(T* data);
template <typename T>
int Peek(T* data);
};
}
}
// Undefines
#include "../External/Undefines.hpp"
// Implementation
#include "SocketTCP_Implement.hpp"
|
Zethes/CGUL
|
src/CGUL/Network/SocketTCP.hpp
|
C++
|
bsd-2-clause
| 2,209 |
import json
import re
from kqml import KQMLString
from .kqml_list import KQMLList
from .kqml_token import KQMLToken
from .kqml_exceptions import KQMLException
class CLJsonConverter(object):
def __init__(self, token_bools=False):
self.token_bools = token_bools
def cl_from_json(self, json_obj):
"""Read a json into a KQMLList, recursively using the CLJson paradigm.
Note: both false an None are mapped to NIL. This means parsing back will
not have exactly the same result as the original json dict/list, in some
cases.
"""
if isinstance(json_obj, str):
json_obj = json.loads(json_obj)
elif isinstance(json_obj, bytes):
json_obj = json.loads(json_obj.decode('utf-8'))
elif not isinstance(json_obj, list) and not isinstance(json_obj, dict):
raise ValueError("Input must be list, dict, or string/bytes "
"json, got %s." % type(json_obj))
return self._cl_from_json(json_obj)
def _cl_from_json(self, json_obj):
if isinstance(json_obj, list):
ret = KQMLList()
for elem in json_obj:
ret.append(self._cl_from_json(elem))
elif isinstance(json_obj, dict):
ret = KQMLList()
for key, val in json_obj.items():
ret.set(_key_from_string(key), self._cl_from_json(val))
elif isinstance(json_obj, str):
ret = KQMLString(json_obj)
elif isinstance(json_obj, bool):
if json_obj:
if self.token_bools:
ret = KQMLToken('TRUE')
else:
ret = KQMLToken('T')
else:
if self.token_bools:
ret = KQMLToken('FALSE')
else:
ret = KQMLToken('NIL')
elif isinstance(json_obj, int) or isinstance(json_obj, float):
ret = str(json_obj)
elif json_obj is None:
return KQMLToken('NIL')
else:
raise KQMLException("Unexpected value %s of type %s."
% (json_obj, type(json_obj)))
return ret
def cl_to_json(self, kqml_list):
"""Recursively convert a KQMLList into a json-style dict/list.
Note: Because NIL is used as both None and False in lisp, all NIL is
returned as None, even if the value was intended, or originally, False.
"""
if not isinstance(kqml_list, KQMLList):
raise ValueError("Only a KQMLList might be converted into json, "
"got %s." % type(kqml_list))
return self._cl_to_json(kqml_list)
def _cl_to_json(self, kqml_thing):
if isinstance(kqml_thing, KQMLList):
# Find all possible keys (things that start with ":")
possible_keys = re.findall(':([^\s]+)', kqml_thing.to_string())
# Determine the true keys by checking we can actually get something
# from them.
true_key_values = {}
for k in possible_keys:
val = kqml_thing.get(k)
if val is not None:
true_key_values[k] = val
# Extract the return value.
if len(true_key_values) == len(kqml_thing)/2:
# It's a dict!
ret = {}
for key, val in true_key_values.items():
ret[_string_from_key(key)] = self._cl_to_json(val)
elif not len(true_key_values):
# It's a list!
ret = []
for item in kqml_thing:
ret.append(self._cl_to_json(item))
else:
# It's not valid for json.
raise KQMLException("Cannot convert %s into json, neither "
"list nor dict." % kqml_thing.to_string())
elif isinstance(kqml_thing, KQMLToken):
s = kqml_thing.to_string()
if s == 'NIL':
# This could be either false or None. Because None will almost
# always have the same meaning as False in pep-8 compliant
# python, but not vice-versa, we choose None. To avoid this,
# you can set `token_bools` to True on your converter class,
# and True will be mapped to the token TRUE and False to FALSE.
ret = None
elif (not self.token_bools and s == 'T') \
or (self.token_bools and s == 'TRUE'):
ret = True
elif self.token_bools and s == 'FALSE':
ret = False
elif s.isdigit():
ret = int(s)
elif s.count('.') == 1 and all(seg.isdigit()
for seg in s.split('.')):
ret = float(s)
else:
ret = s
elif isinstance(kqml_thing, KQMLString):
ret = kqml_thing.string_value()
else:
raise KQMLException("Unexpected value %s of type %s."
% (kqml_thing, type(kqml_thing)))
return ret
JSON_TO_CL_PATTS = [
# Add a * before upper case at the beginning of lines or after an
# underscore.
([re.compile('^([A-Z][a-z])'), re.compile('_([A-Z][a-z])')],
lambda m: m.group(0).replace(m.group(1), '') + '*'
+ m.group(1).lower()),
# Replace Upper case not at the beginning or after an underscore.
([re.compile('([A-Z][a-z])')], lambda m: '-' + m.group(1).lower()),
# Replace groups of upper case words with surrounding pluses.
([re.compile('([A-Z0-9]+[A-Z0-9_]*[A-Z0-9]*)')],
lambda m: '+%s+' % m.group(1).lower().replace('_', '-')),
# Convert some other special underscores to --
([re.compile('([a-z])_([a-z0-9\+*])')], '\\1--\\2'),
]
def _key_from_string(key):
for patts, repl in JSON_TO_CL_PATTS:
for patt in patts:
try:
new_key = patt.sub(repl, key)
except Exception:
print("Exeption in key_from_string:", patt.pattern, repl, key)
raise
key = new_key
return key.upper()
CL_TO_JSON_PATTS = [
# Replacy -- with _
(re.compile('(--)'), '_'),
# Replace *a with A
(re.compile('\*([a-z])'), lambda m: m.group(1).upper()),
# Replace +abc-d+ with ABC_D
(re.compile('\+([a-z0-9-]+)\+'),
lambda m: m.group(1).upper().replace('-', '_')),
# Replace foo-bar with fooBar
(re.compile('-([a-z])'), lambda m: m.group(1).upper())
]
def _string_from_key(s):
s = s.lower()
for patt, repl in CL_TO_JSON_PATTS:
new_s = patt.sub(repl, s)
s = new_s
return s
|
bgyori/pykqml
|
kqml/cl_json.py
|
Python
|
bsd-2-clause
| 6,768 |
package transform
import "github.com/twpayne/go-geom"
// UniqueCoords creates a new coordinate array (with the same layout as the inputs) that
// contains each unique coordinate in the coordData. The ordering of the coords are the
// same as the input.
func UniqueCoords(layout geom.Layout, compare Compare, coordData []float64) []float64 {
set := NewTreeSet(layout, compare)
stride := layout.Stride()
uniqueCoords := make([]float64, 0, len(coordData))
numCoordsAdded := 0
for i := 0; i < len(coordData); i += stride {
coord := coordData[i : i+stride]
added := set.Insert(geom.Coord(coord))
if added {
uniqueCoords = append(uniqueCoords, coord...)
numCoordsAdded++
}
}
return uniqueCoords[:numCoordsAdded*stride]
}
|
twpayne/go-geom
|
transform/transform.go
|
GO
|
bsd-2-clause
| 740 |
import csv
import os
from json import loads
from os.path import exists
from old.project import CassandraInsert
from old.project import CassandraUtils
cassandra = CassandraUtils()
QTD_STS_KEY = 'quotedStatus'
RTD_STS_KEY = 'retweetedStatus'
MT_STS_KEY = 'userMentionEntities'
def check_mention_entities(tweet):
return RTD_STS_KEY not in tweet and MT_STS_KEY in tweet and len(tweet[MT_STS_KEY]) > 0
def remove_retweets(tts_rows):
tts = map(lambda tt_row: loads(tt_row.tweet), tts_rows)
return filter(lambda tt: QTD_STS_KEY not in tt and RTD_STS_KEY not in tt, tts)
def find_retweets(tts_rows):
tts = map(lambda tt_row: loads(tt_row.tweet), tts_rows)
rts = []
rts.extend(map(lambda tt: tt[RTD_STS_KEY], filter(lambda tt: RTD_STS_KEY in tt, tts)))
rts.extend(map(lambda tt: tt[QTD_STS_KEY], filter(lambda tt: QTD_STS_KEY in tt, tts)))
return rts
def find_mentions(tts_rows):
tts = map(lambda tt_row: loads(tt_row.tweet), tts_rows)
return filter(lambda tt: check_mention_entities(tt), tts)
def mount_path(dirfile, user_id):
return '/home/joao/Dev/Data/Twitter/' + dirfile + str(user_id) + '.csv'
def check_file(path):
return exists(path)
def save_friends(user_id, friends_rows):
path = mount_path('friends/', user_id)
with open(path, 'w') as writer:
friends_ids = map(lambda friend: friend.friend_id, friends_rows)
for friend_id in friends_ids:
writer.write(str(friend_id) + '\n')
writer.flush()
writer.close()
def delete_file(path):
if os.stat(path).st_size == 0:
os.remove(path)
def friends2file():
print "Saving Friends..."
seeds = cassandra.find_seeds()
c = 0
for seeds_row in seeds:
user_id = seeds_row.user_id
friends_rows = cassandra.find_friends(user_id=user_id)
ci = CassandraInsert()
for friend_row in friends_rows:
ci.insert_friendship({'user_id': user_id, 'friend_id': friend_row.friend_id})
c = c + 1
print 'Users: ', c
print "Friends Saved..."
def save_likes(user_id, likes_rows):
lks_tts = map(lambda row: loads(row.tweet), likes_rows)
with open(mount_path('likes/', user_id), 'w') as csvfile:
fieldnames = ['alter_id', 'tweet_id']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for tt in lks_tts:
writer.writerow({
'alter_id': tt['user']['id'],
'tweet_id': tt['id']
})
def likes2file():
print "Saving likes..."
seeds = cassandra.find_seeds()
c = 0
for seeds_row in seeds:
user_id = seeds_row.user_id
ci = CassandraInsert()
likes = map(lambda lk: loads(lk.tweet), cassandra.find_likes(user_id=user_id))
for like in likes:
lk = {
'user_id': user_id,
'tweet_id': like['id'],
'alter_id': like['user']['id']}
ci.insert_lk_interaction(lk)
tt = {
'tweet_id': like['id'],
'date': like['createdAt'],
'lang': like['lang'],
'text': like['text'],
'user_id': like['user']['id']}
ci.insert_tweet(tt)
usr = {
'id': like['user']['id'],
'flw_count': like['user']['followersCount'],
'frd_count': like['user']['friendsCount'],
'is_protected': like['user']['isProtected'],
'is_verified': like['user']['isVerified'],
'lk_count': like['user']['favouritesCount'],
'lang': like['user']['lang'],
'tt_count': like['user']['statusesCount']}
ci.insert_user(usr)
c = c + 1
print 'Users: ', c
print "Likes saved"
def save_retweets(ci, user_id, tweets_rows):
retweets = find_retweets(tweets_rows)
for tt in retweets:
rt = {
'user_id': user_id,
'tweet_id': tt['id'],
'alter_id': tt['user']['id']}
ci.insert_rt_interaction(rt)
_tt = {
'tweet_id': tt['id'],
'date': tt['createdAt'],
'lang': tt['lang'],
'text': tt['text'],
'user_id': tt['user']['id']}
ci.insert_tweet(_tt)
usr = {
'id': tt['user']['id'],
'flw_count': tt['user']['followersCount'],
'frd_count': tt['user']['friendsCount'],
'is_protected': tt['user']['isProtected'],
'is_verified': tt['user']['isVerified'],
'lk_count': tt['user']['favouritesCount'],
'lang': tt['user']['lang'],
'tt_count': tt['user']['statusesCount']}
ci.insert_user(usr)
def save_mentions(ci, user_id, tweets_rows):
tweets = find_mentions(tweets_rows)
for tt in tweets:
for me in tt[MT_STS_KEY]:
me = {
'user_id': user_id,
'tweet_id': tt['id'],
'alter_id': me['id']}
ci.insert_mt_interaction(me)
_tt = {
'tweet_id': tt['id'],
'date': tt['createdAt'],
'lang': tt['lang'],
'text': tt['text'],
'user_id': tt['user']['id']}
ci.insert_tweet(_tt)
usr = {
'id': tt['user']['id'],
'flw_count': tt['user']['followersCount'],
'frd_count': tt['user']['friendsCount'],
'is_protected': tt['user']['isProtected'],
'is_verified': tt['user']['isVerified'],
'lk_count': tt['user']['favouritesCount'],
'lang': tt['user']['lang'],
'tt_count': tt['user']['statusesCount']}
ci.insert_user(usr)
def save_tweets(ci, user_id, tweets_rows):
save_retweets(ci, user_id, tweets_rows)
save_mentions(ci, user_id, tweets_rows)
tweets = remove_retweets(tweets_rows)
for tt in tweets:
_tt = {
'tweet_id': tt['id'],
'date': tt['createdAt'],
'lang': tt['lang'],
'text': tt['text'],
'user_id': tt['user']['id']}
ci.insert_tweet(_tt)
usr = {
'id': tt['user']['id'],
'flw_count': tt['user']['followersCount'],
'frd_count': tt['user']['friendsCount'],
'is_protected': tt['user']['isProtected'],
'is_verified': tt['user']['isVerified'],
'lk_count': tt['user']['favouritesCount'],
'lang': tt['user']['lang'],
'tt_count': tt['user']['statusesCount']}
ci.insert_user(usr)
def tweets2file():
print "Saving Tweets..."
seeds = cassandra.find_seeds()
ci = CassandraInsert()
c = 0
for seeds_row in seeds:
user_id = seeds_row.user_id
tweets_rows = cassandra.find_tweets(user_id=user_id)
save_tweets(ci=ci, user_id=user_id, tweets_rows=tweets_rows)
c = c + 1
print 'Users: ', c
print "Tweets saved"
|
jblupus/PyLoyaltyProject
|
old/project/integration/to_files2.py
|
Python
|
bsd-2-clause
| 7,009 |
package org.gazebosim.transport;
public interface SubscriberCallback<T> {
void callback(T msg);
}
|
FRC1296/CheezyDriver2016
|
third_party/allwpilib_2016/simulation/JavaGazebo/src/main/java/org/gazebosim/transport/SubscriberCallback.java
|
Java
|
bsd-2-clause
| 100 |
#include "operators/activation/elu_op.h"
#include "utils/math_functions.h"
#include "utils/op_kernel.h"
namespace dragon {
template <class Context> template <typename T>
void EluOp<Context>::RunWithType() {
auto* Xdata = input(0).template data<T, Context>();
auto* Ydata = output(0)->template mutable_data<T, Context>();
kernel::Elu<T, Context>(output(0)->count(), Xdata, alpha, Ydata);
}
template <class Context>
void EluOp<Context>::RunOnDevice() {
output(0)->ReshapeLike(input(0));
if (input(0).template IsType<float>()) RunWithType<float>();
else LOG(FATAL) << "Unsupported input types.";
}
DEPLOY_CPU(Elu);
#ifdef WITH_CUDA
DEPLOY_CUDA(Elu);
#endif
OPERATOR_SCHEMA(Elu).NumInputs(1).NumOutputs(1).Inplace({ { 0, 0 } });
template <class Context> template <typename T>
void EluGradientOp<Context>::RunWithType() {
auto* Ydata = input(0).template data<T, Context>();
auto* dYdata = input(1).template data<T, Context>();
auto* dXdata = output(0)->template mutable_data<T, Context>();
kernel::EluGrad<T, Context>(output(0)->count(), dYdata, Ydata, alpha, dXdata);
}
template <class Context>
void EluGradientOp<Context>::RunOnDevice() {
output(0)->ReshapeLike(input(0));
if (input(0).template IsType<float>()) RunWithType<float>();
else LOG(FATAL) << "Unsupported input types.";
}
DEPLOY_CPU(EluGradient);
#ifdef WITH_CUDA
DEPLOY_CUDA(EluGradient);
#endif
OPERATOR_SCHEMA(EluGradient).NumInputs(2).NumOutputs(1).Inplace({ { 1, 0 }});
class GetEluGradient final : public GradientMakerBase {
public:
GRADIENT_MAKER_CTOR(GetEluGradient);
vector<OperatorDef> MakeDefs() override {
return SingleDef(def.type() + "Gradient", "",
vector<string> {O(0), GO(0)},
vector<string> {GI(0)});
}
};
REGISTER_GRADIENT(Elu, GetEluGradient);
} // namespace dragon
|
neopenx/Dragon
|
Dragon/src/operators/activation/elu_op.cc
|
C++
|
bsd-2-clause
| 1,854 |
var voxelPainter = require('./../')
// Options
var options = {
container: '#container'
}
var painter = voxelPainter(options)
var loopThrough = function(elements, cb) {
[].forEach.call(elements, function(item) {
cb(item)
})
}
// Color selector
var colorSelector = document.querySelectorAll('.color-selector li')
loopThrough(colorSelector, function(color) {
color.addEventListener('click', function() {
painter.setColor(this.getAttribute('data-color'))
loopThrough(colorSelector, function(item) {
item.className = ''
})
this.className = 'selected'
}, false)
})
|
romainberger/voxel-painter-core
|
example/main.js
|
JavaScript
|
bsd-2-clause
| 604 |
//-----------------------------------------------------------------------
// <copyright file="Th105Converter.cs" company="None">
// Copyright (c) IIHOSHI Yoshinori.
// Licensed under the BSD-2-Clause license. See LICENSE.txt file in the project root for full license information.
// </copyright>
//-----------------------------------------------------------------------
#pragma warning disable SA1600 // ElementsMustBeDocumented
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using ThScoreFileConverter.Helpers;
using ThScoreFileConverter.Models.Th105;
using ThScoreFileConverter.Properties;
namespace ThScoreFileConverter.Models
{
#if !DEBUG
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1812", Justification = "Instantiated by ThConverterFactory.")]
#endif
internal class Th105Converter : ThConverter
{
private AllScoreData? allScoreData;
public override string SupportedVersions { get; } = "1.06a";
protected override bool ReadScoreFile(Stream input)
{
using var decrypted = new MemoryStream();
#if DEBUG
using var decoded = new FileStream("th105decoded.dat", FileMode.Create, FileAccess.ReadWrite);
#else
using var decoded = new MemoryStream();
#endif
if (!Decrypt(input, decrypted))
return false;
decrypted.Seek(0, SeekOrigin.Begin);
if (!Extract(decrypted, decoded))
return false;
decoded.Seek(0, SeekOrigin.Begin);
this.allScoreData = Read(decoded);
return this.allScoreData is not null;
}
protected override IEnumerable<IStringReplaceable> CreateReplacers(
INumberFormatter formatter, bool hideUntriedCards, string outputFilePath)
{
if (this.allScoreData is null)
{
throw new InvalidDataException(
Utils.Format(Resources.InvalidOperationExceptionMustBeInvokedAfter, nameof(this.ReadScoreFile)));
}
return new List<IStringReplaceable>
{
new CareerReplacer(this.allScoreData.ClearData, formatter),
new CardReplacer(this.allScoreData.ClearData, hideUntriedCards),
new CollectRateReplacer(this.allScoreData.ClearData, formatter),
new CardForDeckReplacer(this.allScoreData.SystemCards, this.allScoreData.ClearData, formatter, hideUntriedCards),
};
}
private static bool Decrypt(Stream input, Stream output)
{
var size = (int)input.Length;
var inData = new byte[size];
var outData = new byte[size];
_ = input.Seek(0, SeekOrigin.Begin);
_ = input.Read(inData, 0, size);
for (var index = 0; index < size; index++)
outData[index] = (byte)((index * 7) ^ inData[size - index - 1]);
_ = output.Seek(0, SeekOrigin.Begin);
output.Write(outData, 0, size);
// See section 2.2 of RFC 1950
return (outData[0] == 0x78) && (outData[1] == 0x9C);
}
private static bool Extract(Stream input, Stream output)
{
var extracted = new byte[0x80000];
var extractedSize = 0;
// Skip the header bytes of a zlib stream
_ = input.Seek(2, SeekOrigin.Begin);
using (var deflate = new DeflateStream(input, CompressionMode.Decompress, true))
extractedSize = deflate.Read(extracted, 0, extracted.Length);
_ = output.Seek(0, SeekOrigin.Begin);
output.Write(extracted, 0, extractedSize);
return true;
}
private static AllScoreData? Read(Stream input)
{
using var reader = new BinaryReader(input, EncodingHelper.UTF8NoBOM, true);
var allScoreData = new AllScoreData();
try
{
allScoreData.ReadFrom(reader);
}
catch (EndOfStreamException)
{
}
if (allScoreData.ClearData.Count == EnumHelper<Chara>.NumValues)
return allScoreData;
else
return null;
}
}
}
|
y-iihoshi/ThScoreFileConverter
|
ThScoreFileConverter/Models/Th105Converter.cs
|
C#
|
bsd-2-clause
| 4,300 |
package org.randomcoder.taglibs.url;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Tag class which adds a parameter to a URL.
*
* <pre>
* Copyright (c) 2006, Craig Condit. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
* </pre>
*/
public class AddParamTag extends TagSupport {
private static final long serialVersionUID = -1726710757304026189L;
private String name;
private String value;
/**
* Sets the parameter name.
*
* @param name parameter name
*/
public void setName(String name) {
this.name = name;
}
/**
* Sets the parameter value.
*
* @param value parameter value
*/
public void setValue(String value) {
this.value = value;
}
/**
* Release state.
*/
@Override public void release() {
super.release();
cleanup();
}
/**
* Adds the given parameter to the URL.
*
* @return EVAL_PAGE
*/
@Override public int doEndTag() throws JspException {
try {
ModifyTag mtag = (ModifyTag) findAncestorWithClass(this, ModifyTag.class);
if (mtag == null)
throw new JspException("No modify tag parent found");
Map<String, List<String>> params = mtag.getParams();
List<String> values = params.get(name);
if (values == null) {
values = new ArrayList<String>();
params.put(name, values);
}
values.add(value);
return EVAL_PAGE;
} finally {
cleanup();
}
}
private void cleanup() {
name = null;
value = null;
}
}
|
insideo/randomcoder-taglibs
|
src/main/java/org/randomcoder/taglibs/url/AddParamTag.java
|
Java
|
bsd-2-clause
| 3,000 |
package ninchatapi
// AppendStrings duplicates the source slice while unwrapping the elements.
func AppendStrings(target []string, source []interface{}) []string {
if source != nil {
if target == nil || cap(target) < len(target)+len(source) {
t := make([]string, len(target), len(target)+len(source))
copy(t, target)
target = t
}
for _, x := range source {
y, _ := x.(string)
target = append(target, y)
}
}
return target
}
func intPointer(x float64) *int {
y := int(x)
return &y
}
|
ninchat/ninchat-go
|
ninchatapi/params.go
|
GO
|
bsd-2-clause
| 513 |
#
# Polymorphic Mixins
#
from silverflask import db
from sqlalchemy.ext.declarative import declared_attr
from silverflask.helper import classproperty
class PolymorphicMixin(object):
type = db.Column(db.String(50))
@declared_attr
def __mapper_args__(cls):
if hasattr(cls, '__versioned_draft_class__'):
# Use same identities as draft class
ident = cls.__versioned_draft_class__.__mapper_args__["polymorphic_identity"]
else:
ident = cls.__tablename__
d = {
'polymorphic_identity': ident,
}
# this is a base object, therefore we are not
# redefining the column on which it is polymorphic
if hasattr(cls.__table__.columns, 'id') and not cls.__table__.columns.id.foreign_keys:
d['polymorphic_on'] = 'type'
return d
|
wolfv/SilverFlask
|
silverflask/mixins/PolymorphicMixin.py
|
Python
|
bsd-2-clause
| 850 |
//===--- LiteralSupport.cpp - Code to parse and process literals ----------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the NumericLiteralParser, CharLiteralParser, and
// StringLiteralParser interfaces.
//
//===----------------------------------------------------------------------===//
#include "clang/Lex/LiteralSupport.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/LexDiagnostic.h"
#include "clang/Lex/Lexer.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/Token.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/ErrorHandling.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <string>
using namespace clang;
static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
switch (kind) {
default: llvm_unreachable("Unknown token type!");
case tok::char_constant:
case tok::string_literal:
case tok::utf8_char_constant:
case tok::utf8_string_literal:
return Target.getCharWidth();
case tok::wide_char_constant:
case tok::wide_string_literal:
return Target.getWCharWidth();
case tok::utf16_char_constant:
case tok::utf16_string_literal:
return Target.getChar16Width();
case tok::utf32_char_constant:
case tok::utf32_string_literal:
return Target.getChar32Width();
}
}
static CharSourceRange MakeCharSourceRange(const LangOptions &Features,
FullSourceLoc TokLoc,
const char *TokBegin,
const char *TokRangeBegin,
const char *TokRangeEnd) {
SourceLocation Begin =
Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
TokLoc.getManager(), Features);
SourceLocation End =
Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin,
TokLoc.getManager(), Features);
return CharSourceRange::getCharRange(Begin, End);
}
/// Produce a diagnostic highlighting some portion of a literal.
///
/// Emits the diagnostic \p DiagID, highlighting the range of characters from
/// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be
/// a substring of a spelling buffer for the token beginning at \p TokBegin.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags,
const LangOptions &Features, FullSourceLoc TokLoc,
const char *TokBegin, const char *TokRangeBegin,
const char *TokRangeEnd, unsigned DiagID) {
SourceLocation Begin =
Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
TokLoc.getManager(), Features);
return Diags->Report(Begin, DiagID) <<
MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd);
}
/// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
/// either a character or a string literal.
static unsigned ProcessCharEscape(const char *ThisTokBegin,
const char *&ThisTokBuf,
const char *ThisTokEnd, bool &HadError,
FullSourceLoc Loc, unsigned CharWidth,
DiagnosticsEngine *Diags,
const LangOptions &Features) {
const char *EscapeBegin = ThisTokBuf;
// Skip the '\' char.
++ThisTokBuf;
// We know that this character can't be off the end of the buffer, because
// that would have been \", which would not have been the end of string.
unsigned ResultChar = *ThisTokBuf++;
switch (ResultChar) {
// These map to themselves.
case '\\': case '\'': case '"': case '?': break;
// These have fixed mappings.
case 'a':
// TODO: K&R: the meaning of '\\a' is different in traditional C
ResultChar = 7;
break;
case 'b':
ResultChar = 8;
break;
case 'e':
if (Diags)
Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
diag::ext_nonstandard_escape) << "e";
ResultChar = 27;
break;
case 'E':
if (Diags)
Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
diag::ext_nonstandard_escape) << "E";
ResultChar = 27;
break;
case 'f':
ResultChar = 12;
break;
case 'n':
ResultChar = 10;
break;
case 'r':
ResultChar = 13;
break;
case 't':
ResultChar = 9;
break;
case 'v':
ResultChar = 11;
break;
case 'x': { // Hex escape.
ResultChar = 0;
if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
if (Diags)
Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
diag::err_hex_escape_no_digits) << "x";
HadError = true;
break;
}
// Hex escapes are a maximal series of hex digits.
bool Overflow = false;
for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
if (CharVal == -1) break;
// About to shift out a digit?
if (ResultChar & 0xF0000000)
Overflow = true;
ResultChar <<= 4;
ResultChar |= CharVal;
}
// See if any bits will be truncated when evaluated as a character.
if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
Overflow = true;
ResultChar &= ~0U >> (32-CharWidth);
}
// Check for overflow.
if (Overflow && Diags) // Too many digits to fit in
Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
diag::err_escape_too_large) << 0;
break;
}
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7': {
// Octal escapes.
--ThisTokBuf;
ResultChar = 0;
// Octal escapes are a series of octal digits with maximum length 3.
// "\0123" is a two digit sequence equal to "\012" "3".
unsigned NumDigits = 0;
do {
ResultChar <<= 3;
ResultChar |= *ThisTokBuf++ - '0';
++NumDigits;
} while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
// Check for overflow. Reject '\777', but not L'\777'.
if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
if (Diags)
Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
diag::err_escape_too_large) << 1;
ResultChar &= ~0U >> (32-CharWidth);
}
break;
}
// Otherwise, these are not valid escapes.
case '(': case '{': case '[': case '%':
// GCC accepts these as extensions. We warn about them as such though.
if (Diags)
Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
diag::ext_nonstandard_escape)
<< std::string(1, ResultChar);
break;
default:
if (!Diags)
break;
if (isPrintable(ResultChar))
Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
diag::ext_unknown_escape)
<< std::string(1, ResultChar);
else
Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
diag::ext_unknown_escape)
<< "x" + llvm::utohexstr(ResultChar);
break;
}
return ResultChar;
}
static void appendCodePoint(unsigned Codepoint,
llvm::SmallVectorImpl<char> &Str) {
char ResultBuf[4];
char *ResultPtr = ResultBuf;
bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr);
(void)Res;
assert(Res && "Unexpected conversion failure");
Str.append(ResultBuf, ResultPtr);
}
void clang::expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) {
for (StringRef::iterator I = Input.begin(), E = Input.end(); I != E; ++I) {
if (*I != '\\') {
Buf.push_back(*I);
continue;
}
++I;
assert(*I == 'u' || *I == 'U');
unsigned NumHexDigits;
if (*I == 'u')
NumHexDigits = 4;
else
NumHexDigits = 8;
assert(I + NumHexDigits <= E);
uint32_t CodePoint = 0;
for (++I; NumHexDigits != 0; ++I, --NumHexDigits) {
unsigned Value = llvm::hexDigitValue(*I);
assert(Value != -1U);
CodePoint <<= 4;
CodePoint += Value;
}
appendCodePoint(CodePoint, Buf);
--I;
}
}
/// ProcessUCNEscape - Read the Universal Character Name, check constraints and
/// return the UTF32.
static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
const char *ThisTokEnd,
uint32_t &UcnVal, unsigned short &UcnLen,
FullSourceLoc Loc, DiagnosticsEngine *Diags,
const LangOptions &Features,
bool in_char_string_literal = false) {
const char *UcnBegin = ThisTokBuf;
// Skip the '\u' char's.
ThisTokBuf += 2;
if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
if (Diags)
Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
diag::err_hex_escape_no_digits) << StringRef(&ThisTokBuf[-1], 1);
return false;
}
UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
unsigned short UcnLenSave = UcnLen;
for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) {
int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
if (CharVal == -1) break;
UcnVal <<= 4;
UcnVal |= CharVal;
}
// If we didn't consume the proper number of digits, there is a problem.
if (UcnLenSave) {
if (Diags)
Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
diag::err_ucn_escape_incomplete);
return false;
}
// Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
UcnVal > 0x10FFFF) { // maximum legal UTF32 value
if (Diags)
Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
diag::err_ucn_escape_invalid);
return false;
}
// C++11 allows UCNs that refer to control characters and basic source
// characters inside character and string literals
if (UcnVal < 0xa0 &&
(UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) { // $, @, `
bool IsError = (!Features.CPlusPlus11 || !in_char_string_literal);
if (Diags) {
char BasicSCSChar = UcnVal;
if (UcnVal >= 0x20 && UcnVal < 0x7f)
Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
IsError ? diag::err_ucn_escape_basic_scs :
diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
<< StringRef(&BasicSCSChar, 1);
else
Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
IsError ? diag::err_ucn_control_character :
diag::warn_cxx98_compat_literal_ucn_control_character);
}
if (IsError)
return false;
}
if (!Features.CPlusPlus && !Features.C99 && Diags)
Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
diag::warn_ucn_not_valid_in_c89_literal);
return true;
}
/// MeasureUCNEscape - Determine the number of bytes within the resulting string
/// which this UCN will occupy.
static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
const char *ThisTokEnd, unsigned CharByteWidth,
const LangOptions &Features, bool &HadError) {
// UTF-32: 4 bytes per escape.
if (CharByteWidth == 4)
return 4;
uint32_t UcnVal = 0;
unsigned short UcnLen = 0;
FullSourceLoc Loc;
if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
UcnLen, Loc, nullptr, Features, true)) {
HadError = true;
return 0;
}
// UTF-16: 2 bytes for BMP, 4 bytes otherwise.
if (CharByteWidth == 2)
return UcnVal <= 0xFFFF ? 2 : 4;
// UTF-8.
if (UcnVal < 0x80)
return 1;
if (UcnVal < 0x800)
return 2;
if (UcnVal < 0x10000)
return 3;
return 4;
}
/// EncodeUCNEscape - Read the Universal Character Name, check constraints and
/// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
/// StringLiteralParser. When we decide to implement UCN's for identifiers,
/// we will likely rework our support for UCN's.
static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
const char *ThisTokEnd,
char *&ResultBuf, bool &HadError,
FullSourceLoc Loc, unsigned CharByteWidth,
DiagnosticsEngine *Diags,
const LangOptions &Features) {
typedef uint32_t UTF32;
UTF32 UcnVal = 0;
unsigned short UcnLen = 0;
if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
Loc, Diags, Features, true)) {
HadError = true;
return;
}
assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
"only character widths of 1, 2, or 4 bytes supported");
(void)UcnLen;
assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
if (CharByteWidth == 4) {
// FIXME: Make the type of the result buffer correct instead of
// using reinterpret_cast.
llvm::UTF32 *ResultPtr = reinterpret_cast<llvm::UTF32*>(ResultBuf);
*ResultPtr = UcnVal;
ResultBuf += 4;
return;
}
if (CharByteWidth == 2) {
// FIXME: Make the type of the result buffer correct instead of
// using reinterpret_cast.
llvm::UTF16 *ResultPtr = reinterpret_cast<llvm::UTF16*>(ResultBuf);
if (UcnVal <= (UTF32)0xFFFF) {
*ResultPtr = UcnVal;
ResultBuf += 2;
return;
}
// Convert to UTF16.
UcnVal -= 0x10000;
*ResultPtr = 0xD800 + (UcnVal >> 10);
*(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
ResultBuf += 4;
return;
}
assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
// Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
// The conversion below was inspired by:
// http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
// First, we determine how many bytes the result will require.
typedef uint8_t UTF8;
unsigned short bytesToWrite = 0;
if (UcnVal < (UTF32)0x80)
bytesToWrite = 1;
else if (UcnVal < (UTF32)0x800)
bytesToWrite = 2;
else if (UcnVal < (UTF32)0x10000)
bytesToWrite = 3;
else
bytesToWrite = 4;
const unsigned byteMask = 0xBF;
const unsigned byteMark = 0x80;
// Once the bits are split out into bytes of UTF8, this is a mask OR-ed
// into the first byte, depending on how many bytes follow.
static const UTF8 firstByteMark[5] = {
0x00, 0x00, 0xC0, 0xE0, 0xF0
};
// Finally, we write the bytes into ResultBuf.
ResultBuf += bytesToWrite;
switch (bytesToWrite) { // note: everything falls through.
case 4:
*--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
LLVM_FALLTHROUGH;
case 3:
*--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
LLVM_FALLTHROUGH;
case 2:
*--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
LLVM_FALLTHROUGH;
case 1:
*--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
}
// Update the buffer.
ResultBuf += bytesToWrite;
}
/// integer-constant: [C99 6.4.4.1]
/// decimal-constant integer-suffix
/// octal-constant integer-suffix
/// hexadecimal-constant integer-suffix
/// binary-literal integer-suffix [GNU, C++1y]
/// user-defined-integer-literal: [C++11 lex.ext]
/// decimal-literal ud-suffix
/// octal-literal ud-suffix
/// hexadecimal-literal ud-suffix
/// binary-literal ud-suffix [GNU, C++1y]
/// decimal-constant:
/// nonzero-digit
/// decimal-constant digit
/// octal-constant:
/// 0
/// octal-constant octal-digit
/// hexadecimal-constant:
/// hexadecimal-prefix hexadecimal-digit
/// hexadecimal-constant hexadecimal-digit
/// hexadecimal-prefix: one of
/// 0x 0X
/// binary-literal:
/// 0b binary-digit
/// 0B binary-digit
/// binary-literal binary-digit
/// integer-suffix:
/// unsigned-suffix [long-suffix]
/// unsigned-suffix [long-long-suffix]
/// long-suffix [unsigned-suffix]
/// long-long-suffix [unsigned-sufix]
/// nonzero-digit:
/// 1 2 3 4 5 6 7 8 9
/// octal-digit:
/// 0 1 2 3 4 5 6 7
/// hexadecimal-digit:
/// 0 1 2 3 4 5 6 7 8 9
/// a b c d e f
/// A B C D E F
/// binary-digit:
/// 0
/// 1
/// unsigned-suffix: one of
/// u U
/// long-suffix: one of
/// l L
/// long-long-suffix: one of
/// ll LL
///
/// floating-constant: [C99 6.4.4.2]
/// TODO: add rules...
///
NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
SourceLocation TokLoc,
Preprocessor &PP)
: PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
// This routine assumes that the range begin/end matches the regex for integer
// and FP constants (specifically, the 'pp-number' regex), and assumes that
// the byte at "*end" is both valid and not part of the regex. Because of
// this, it doesn't have to check for 'overscan' in various places.
assert(!isPreprocessingNumberBody(*ThisTokEnd) && "didn't maximally munch?");
s = DigitsBegin = ThisTokBegin;
saw_exponent = false;
saw_period = false;
saw_ud_suffix = false;
saw_fixed_point_suffix = false;
isLong = false;
isUnsigned = false;
isLongLong = false;
isHalf = false;
isFloat = false;
isImaginary = false;
isFloat16 = false;
isFloat128 = false;
MicrosoftInteger = 0;
isFract = false;
isAccum = false;
hadError = false;
if (*s == '0') { // parse radix
ParseNumberStartingWithZero(TokLoc);
if (hadError)
return;
} else { // the first digit is non-zero
radix = 10;
s = SkipDigits(s);
if (s == ThisTokEnd) {
// Done.
} else {
ParseDecimalOrOctalCommon(TokLoc);
if (hadError)
return;
}
}
SuffixBegin = s;
checkSeparator(TokLoc, s, CSK_AfterDigits);
// Initial scan to lookahead for fixed point suffix.
if (PP.getLangOpts().FixedPoint) {
for (const char *c = s; c != ThisTokEnd; ++c) {
if (*c == 'r' || *c == 'k' || *c == 'R' || *c == 'K') {
saw_fixed_point_suffix = true;
break;
}
}
}
// Parse the suffix. At this point we can classify whether we have an FP or
// integer constant.
bool isFPConstant = isFloatingLiteral();
// Loop over all of the characters of the suffix. If we see something bad,
// we break out of the loop.
for (; s != ThisTokEnd; ++s) {
switch (*s) {
case 'R':
case 'r':
if (!PP.getLangOpts().FixedPoint) break;
if (isFract || isAccum) break;
if (!(saw_period || saw_exponent)) break;
isFract = true;
continue;
case 'K':
case 'k':
if (!PP.getLangOpts().FixedPoint) break;
if (isFract || isAccum) break;
if (!(saw_period || saw_exponent)) break;
isAccum = true;
continue;
case 'h': // FP Suffix for "half".
case 'H':
// OpenCL Extension v1.2 s9.5 - h or H suffix for half type.
if (!(PP.getLangOpts().Half || PP.getLangOpts().FixedPoint)) break;
if (isIntegerLiteral()) break; // Error for integer constant.
if (isHalf || isFloat || isLong) break; // HH, FH, LH invalid.
isHalf = true;
continue; // Success.
case 'f': // FP Suffix for "float"
case 'F':
if (!isFPConstant) break; // Error for integer constant.
if (isHalf || isFloat || isLong || isFloat128)
break; // HF, FF, LF, QF invalid.
// CUDA host and device may have different _Float16 support, therefore
// allows f16 literals to avoid false alarm.
// ToDo: more precise check for CUDA.
if ((PP.getTargetInfo().hasFloat16Type() || PP.getLangOpts().CUDA) &&
s + 2 < ThisTokEnd && s[1] == '1' && s[2] == '6') {
s += 2; // success, eat up 2 characters.
isFloat16 = true;
continue;
}
isFloat = true;
continue; // Success.
case 'q': // FP Suffix for "__float128"
case 'Q':
if (!isFPConstant) break; // Error for integer constant.
if (isHalf || isFloat || isLong || isFloat128)
break; // HQ, FQ, LQ, QQ invalid.
isFloat128 = true;
continue; // Success.
case 'u':
case 'U':
if (isFPConstant) break; // Error for floating constant.
if (isUnsigned) break; // Cannot be repeated.
isUnsigned = true;
continue; // Success.
case 'l':
case 'L':
if (isLong || isLongLong) break; // Cannot be repeated.
if (isHalf || isFloat || isFloat128) break; // LH, LF, LQ invalid.
// Check for long long. The L's need to be adjacent and the same case.
if (s[1] == s[0]) {
assert(s + 1 < ThisTokEnd && "didn't maximally munch?");
if (isFPConstant) break; // long long invalid for floats.
isLongLong = true;
++s; // Eat both of them.
} else {
isLong = true;
}
continue; // Success.
case 'i':
case 'I':
if (PP.getLangOpts().MicrosoftExt) {
if (isLong || isLongLong || MicrosoftInteger)
break;
if (!isFPConstant) {
// Allow i8, i16, i32, and i64.
switch (s[1]) {
case '8':
s += 2; // i8 suffix
MicrosoftInteger = 8;
break;
case '1':
if (s[2] == '6') {
s += 3; // i16 suffix
MicrosoftInteger = 16;
}
break;
case '3':
if (s[2] == '2') {
s += 3; // i32 suffix
MicrosoftInteger = 32;
}
break;
case '6':
if (s[2] == '4') {
s += 3; // i64 suffix
MicrosoftInteger = 64;
}
break;
default:
break;
}
}
if (MicrosoftInteger) {
assert(s <= ThisTokEnd && "didn't maximally munch?");
break;
}
}
LLVM_FALLTHROUGH;
case 'j':
case 'J':
if (isImaginary) break; // Cannot be repeated.
isImaginary = true;
continue; // Success.
}
// If we reached here, there was an error or a ud-suffix.
break;
}
// "i", "if", and "il" are user-defined suffixes in C++1y.
if (s != ThisTokEnd || isImaginary) {
// FIXME: Don't bother expanding UCNs if !tok.hasUCN().
expandUCNs(UDSuffixBuf, StringRef(SuffixBegin, ThisTokEnd - SuffixBegin));
if (isValidUDSuffix(PP.getLangOpts(), UDSuffixBuf)) {
if (!isImaginary) {
// Any suffix pieces we might have parsed are actually part of the
// ud-suffix.
isLong = false;
isUnsigned = false;
isLongLong = false;
isFloat = false;
isFloat16 = false;
isHalf = false;
isImaginary = false;
MicrosoftInteger = 0;
saw_fixed_point_suffix = false;
isFract = false;
isAccum = false;
}
saw_ud_suffix = true;
return;
}
if (s != ThisTokEnd) {
// Report an error if there are any.
PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
diag::err_invalid_suffix_constant)
<< StringRef(SuffixBegin, ThisTokEnd - SuffixBegin) << isFPConstant;
hadError = true;
}
}
if (!hadError && saw_fixed_point_suffix) {
assert(isFract || isAccum);
}
}
/// ParseDecimalOrOctalCommon - This method is called for decimal or octal
/// numbers. It issues an error for illegal digits, and handles floating point
/// parsing. If it detects a floating point number, the radix is set to 10.
void NumericLiteralParser::ParseDecimalOrOctalCommon(SourceLocation TokLoc){
assert((radix == 8 || radix == 10) && "Unexpected radix");
// If we have a hex digit other than 'e' (which denotes a FP exponent) then
// the code is using an incorrect base.
if (isHexDigit(*s) && *s != 'e' && *s != 'E' &&
!isValidUDSuffix(PP.getLangOpts(), StringRef(s, ThisTokEnd - s))) {
PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
diag::err_invalid_digit) << StringRef(s, 1) << (radix == 8 ? 1 : 0);
hadError = true;
return;
}
if (*s == '.') {
checkSeparator(TokLoc, s, CSK_AfterDigits);
s++;
radix = 10;
saw_period = true;
checkSeparator(TokLoc, s, CSK_BeforeDigits);
s = SkipDigits(s); // Skip suffix.
}
if (*s == 'e' || *s == 'E') { // exponent
checkSeparator(TokLoc, s, CSK_AfterDigits);
const char *Exponent = s;
s++;
radix = 10;
saw_exponent = true;
if (s != ThisTokEnd && (*s == '+' || *s == '-')) s++; // sign
const char *first_non_digit = SkipDigits(s);
if (containsDigits(s, first_non_digit)) {
checkSeparator(TokLoc, s, CSK_BeforeDigits);
s = first_non_digit;
} else {
if (!hadError) {
PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
diag::err_exponent_has_no_digits);
hadError = true;
}
return;
}
}
}
/// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
/// suffixes as ud-suffixes, because the diagnostic experience is better if we
/// treat it as an invalid suffix.
bool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
StringRef Suffix) {
if (!LangOpts.CPlusPlus11 || Suffix.empty())
return false;
// By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid.
if (Suffix[0] == '_')
return true;
// In C++11, there are no library suffixes.
if (!LangOpts.CPlusPlus14)
return false;
// In C++14, "s", "h", "min", "ms", "us", and "ns" are used in the library.
// Per tweaked N3660, "il", "i", and "if" are also used in the library.
// In C++2a "d" and "y" are used in the library.
return llvm::StringSwitch<bool>(Suffix)
.Cases("h", "min", "s", true)
.Cases("ms", "us", "ns", true)
.Cases("il", "i", "if", true)
.Cases("d", "y", LangOpts.CPlusPlus2a)
.Default(false);
}
void NumericLiteralParser::checkSeparator(SourceLocation TokLoc,
const char *Pos,
CheckSeparatorKind IsAfterDigits) {
if (IsAfterDigits == CSK_AfterDigits) {
if (Pos == ThisTokBegin)
return;
--Pos;
} else if (Pos == ThisTokEnd)
return;
if (isDigitSeparator(*Pos)) {
PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin),
diag::err_digit_separator_not_between_digits)
<< IsAfterDigits;
hadError = true;
}
}
/// ParseNumberStartingWithZero - This method is called when the first character
/// of the number is found to be a zero. This means it is either an octal
/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
/// a floating point number (01239.123e4). Eat the prefix, determining the
/// radix etc.
void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
assert(s[0] == '0' && "Invalid method call");
s++;
int c1 = s[0];
// Handle a hex number like 0x1234.
if ((c1 == 'x' || c1 == 'X') && (isHexDigit(s[1]) || s[1] == '.')) {
s++;
assert(s < ThisTokEnd && "didn't maximally munch?");
radix = 16;
DigitsBegin = s;
s = SkipHexDigits(s);
bool HasSignificandDigits = containsDigits(DigitsBegin, s);
if (s == ThisTokEnd) {
// Done.
} else if (*s == '.') {
s++;
saw_period = true;
const char *floatDigitsBegin = s;
s = SkipHexDigits(s);
if (containsDigits(floatDigitsBegin, s))
HasSignificandDigits = true;
if (HasSignificandDigits)
checkSeparator(TokLoc, floatDigitsBegin, CSK_BeforeDigits);
}
if (!HasSignificandDigits) {
PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
diag::err_hex_constant_requires)
<< PP.getLangOpts().CPlusPlus << 1;
hadError = true;
return;
}
// A binary exponent can appear with or with a '.'. If dotted, the
// binary exponent is required.
if (*s == 'p' || *s == 'P') {
checkSeparator(TokLoc, s, CSK_AfterDigits);
const char *Exponent = s;
s++;
saw_exponent = true;
if (s != ThisTokEnd && (*s == '+' || *s == '-')) s++; // sign
const char *first_non_digit = SkipDigits(s);
if (!containsDigits(s, first_non_digit)) {
if (!hadError) {
PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
diag::err_exponent_has_no_digits);
hadError = true;
}
return;
}
checkSeparator(TokLoc, s, CSK_BeforeDigits);
s = first_non_digit;
if (!PP.getLangOpts().HexFloats)
PP.Diag(TokLoc, PP.getLangOpts().CPlusPlus
? diag::ext_hex_literal_invalid
: diag::ext_hex_constant_invalid);
else if (PP.getLangOpts().CPlusPlus17)
PP.Diag(TokLoc, diag::warn_cxx17_hex_literal);
} else if (saw_period) {
PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
diag::err_hex_constant_requires)
<< PP.getLangOpts().CPlusPlus << 0;
hadError = true;
}
return;
}
// Handle simple binary numbers 0b01010
if ((c1 == 'b' || c1 == 'B') && (s[1] == '0' || s[1] == '1')) {
// 0b101010 is a C++1y / GCC extension.
PP.Diag(TokLoc,
PP.getLangOpts().CPlusPlus14
? diag::warn_cxx11_compat_binary_literal
: PP.getLangOpts().CPlusPlus
? diag::ext_binary_literal_cxx14
: diag::ext_binary_literal);
++s;
assert(s < ThisTokEnd && "didn't maximally munch?");
radix = 2;
DigitsBegin = s;
s = SkipBinaryDigits(s);
if (s == ThisTokEnd) {
// Done.
} else if (isHexDigit(*s) &&
!isValidUDSuffix(PP.getLangOpts(),
StringRef(s, ThisTokEnd - s))) {
PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
diag::err_invalid_digit) << StringRef(s, 1) << 2;
hadError = true;
}
// Other suffixes will be diagnosed by the caller.
return;
}
// For now, the radix is set to 8. If we discover that we have a
// floating point constant, the radix will change to 10. Octal floating
// point constants are not permitted (only decimal and hexadecimal).
radix = 8;
DigitsBegin = s;
s = SkipOctalDigits(s);
if (s == ThisTokEnd)
return; // Done, simple octal number like 01234
// If we have some other non-octal digit that *is* a decimal digit, see if
// this is part of a floating point number like 094.123 or 09e1.
if (isDigit(*s)) {
const char *EndDecimal = SkipDigits(s);
if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
s = EndDecimal;
radix = 10;
}
}
ParseDecimalOrOctalCommon(TokLoc);
}
static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
switch (Radix) {
case 2:
return NumDigits <= 64;
case 8:
return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
case 10:
return NumDigits <= 19; // floor(log10(2^64))
case 16:
return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
default:
llvm_unreachable("impossible Radix");
}
}
/// GetIntegerValue - Convert this numeric literal value to an APInt that
/// matches Val's input width. If there is an overflow, set Val to the low bits
/// of the result and return true. Otherwise, return false.
bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
// Fast path: Compute a conservative bound on the maximum number of
// bits per digit in this radix. If we can't possibly overflow a
// uint64 based on that bound then do the simple conversion to
// integer. This avoids the expensive overflow checking below, and
// handles the common cases that matter (small decimal integers and
// hex/octal values which don't overflow).
const unsigned NumDigits = SuffixBegin - DigitsBegin;
if (alwaysFitsInto64Bits(radix, NumDigits)) {
uint64_t N = 0;
for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
if (!isDigitSeparator(*Ptr))
N = N * radix + llvm::hexDigitValue(*Ptr);
// This will truncate the value to Val's input width. Simply check
// for overflow by comparing.
Val = N;
return Val.getZExtValue() != N;
}
Val = 0;
const char *Ptr = DigitsBegin;
llvm::APInt RadixVal(Val.getBitWidth(), radix);
llvm::APInt CharVal(Val.getBitWidth(), 0);
llvm::APInt OldVal = Val;
bool OverflowOccurred = false;
while (Ptr < SuffixBegin) {
if (isDigitSeparator(*Ptr)) {
++Ptr;
continue;
}
unsigned C = llvm::hexDigitValue(*Ptr++);
// If this letter is out of bound for this radix, reject it.
assert(C < radix && "NumericLiteralParser ctor should have rejected this");
CharVal = C;
// Add the digit to the value in the appropriate radix. If adding in digits
// made the value smaller, then this overflowed.
OldVal = Val;
// Multiply by radix, did overflow occur on the multiply?
Val *= RadixVal;
OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
// Add value, did overflow occur on the value?
// (a + b) ult b <=> overflow
Val += CharVal;
OverflowOccurred |= Val.ult(CharVal);
}
return OverflowOccurred;
}
llvm::APFloat::opStatus
NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
using llvm::APFloat;
unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
llvm::SmallString<16> Buffer;
StringRef Str(ThisTokBegin, n);
if (Str.find('\'') != StringRef::npos) {
Buffer.reserve(n);
std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer),
&isDigitSeparator);
Str = Buffer;
}
auto StatusOrErr =
Result.convertFromString(Str, APFloat::rmNearestTiesToEven);
assert(StatusOrErr && "Invalid floating point representation");
return !errorToBool(StatusOrErr.takeError()) ? *StatusOrErr
: APFloat::opInvalidOp;
}
static inline bool IsExponentPart(char c) {
return c == 'p' || c == 'P' || c == 'e' || c == 'E';
}
bool NumericLiteralParser::GetFixedPointValue(llvm::APInt &StoreVal, unsigned Scale) {
assert(radix == 16 || radix == 10);
// Find how many digits are needed to store the whole literal.
unsigned NumDigits = SuffixBegin - DigitsBegin;
if (saw_period) --NumDigits;
// Initial scan of the exponent if it exists
bool ExpOverflowOccurred = false;
bool NegativeExponent = false;
const char *ExponentBegin;
uint64_t Exponent = 0;
int64_t BaseShift = 0;
if (saw_exponent) {
const char *Ptr = DigitsBegin;
while (!IsExponentPart(*Ptr)) ++Ptr;
ExponentBegin = Ptr;
++Ptr;
NegativeExponent = *Ptr == '-';
if (NegativeExponent) ++Ptr;
unsigned NumExpDigits = SuffixBegin - Ptr;
if (alwaysFitsInto64Bits(radix, NumExpDigits)) {
llvm::StringRef ExpStr(Ptr, NumExpDigits);
llvm::APInt ExpInt(/*numBits=*/64, ExpStr, /*radix=*/10);
Exponent = ExpInt.getZExtValue();
} else {
ExpOverflowOccurred = true;
}
if (NegativeExponent) BaseShift -= Exponent;
else BaseShift += Exponent;
}
// Number of bits needed for decimal literal is
// ceil(NumDigits * log2(10)) Integral part
// + Scale Fractional part
// + ceil(Exponent * log2(10)) Exponent
// --------------------------------------------------
// ceil((NumDigits + Exponent) * log2(10)) + Scale
//
// But for simplicity in handling integers, we can round up log2(10) to 4,
// making:
// 4 * (NumDigits + Exponent) + Scale
//
// Number of digits needed for hexadecimal literal is
// 4 * NumDigits Integral part
// + Scale Fractional part
// + Exponent Exponent
// --------------------------------------------------
// (4 * NumDigits) + Scale + Exponent
uint64_t NumBitsNeeded;
if (radix == 10)
NumBitsNeeded = 4 * (NumDigits + Exponent) + Scale;
else
NumBitsNeeded = 4 * NumDigits + Exponent + Scale;
if (NumBitsNeeded > std::numeric_limits<unsigned>::max())
ExpOverflowOccurred = true;
llvm::APInt Val(static_cast<unsigned>(NumBitsNeeded), 0, /*isSigned=*/false);
bool FoundDecimal = false;
int64_t FractBaseShift = 0;
const char *End = saw_exponent ? ExponentBegin : SuffixBegin;
for (const char *Ptr = DigitsBegin; Ptr < End; ++Ptr) {
if (*Ptr == '.') {
FoundDecimal = true;
continue;
}
// Normal reading of an integer
unsigned C = llvm::hexDigitValue(*Ptr);
assert(C < radix && "NumericLiteralParser ctor should have rejected this");
Val *= radix;
Val += C;
if (FoundDecimal)
// Keep track of how much we will need to adjust this value by from the
// number of digits past the radix point.
--FractBaseShift;
}
// For a radix of 16, we will be multiplying by 2 instead of 16.
if (radix == 16) FractBaseShift *= 4;
BaseShift += FractBaseShift;
Val <<= Scale;
uint64_t Base = (radix == 16) ? 2 : 10;
if (BaseShift > 0) {
for (int64_t i = 0; i < BaseShift; ++i) {
Val *= Base;
}
} else if (BaseShift < 0) {
for (int64_t i = BaseShift; i < 0 && !Val.isNullValue(); ++i)
Val = Val.udiv(Base);
}
bool IntOverflowOccurred = false;
auto MaxVal = llvm::APInt::getMaxValue(StoreVal.getBitWidth());
if (Val.getBitWidth() > StoreVal.getBitWidth()) {
IntOverflowOccurred |= Val.ugt(MaxVal.zext(Val.getBitWidth()));
StoreVal = Val.trunc(StoreVal.getBitWidth());
} else if (Val.getBitWidth() < StoreVal.getBitWidth()) {
IntOverflowOccurred |= Val.zext(MaxVal.getBitWidth()).ugt(MaxVal);
StoreVal = Val.zext(StoreVal.getBitWidth());
} else {
StoreVal = Val;
}
return IntOverflowOccurred || ExpOverflowOccurred;
}
/// \verbatim
/// user-defined-character-literal: [C++11 lex.ext]
/// character-literal ud-suffix
/// ud-suffix:
/// identifier
/// character-literal: [C++11 lex.ccon]
/// ' c-char-sequence '
/// u' c-char-sequence '
/// U' c-char-sequence '
/// L' c-char-sequence '
/// u8' c-char-sequence ' [C++1z lex.ccon]
/// c-char-sequence:
/// c-char
/// c-char-sequence c-char
/// c-char:
/// any member of the source character set except the single-quote ',
/// backslash \, or new-line character
/// escape-sequence
/// universal-character-name
/// escape-sequence:
/// simple-escape-sequence
/// octal-escape-sequence
/// hexadecimal-escape-sequence
/// simple-escape-sequence:
/// one of \' \" \? \\ \a \b \f \n \r \t \v
/// octal-escape-sequence:
/// \ octal-digit
/// \ octal-digit octal-digit
/// \ octal-digit octal-digit octal-digit
/// hexadecimal-escape-sequence:
/// \x hexadecimal-digit
/// hexadecimal-escape-sequence hexadecimal-digit
/// universal-character-name: [C++11 lex.charset]
/// \u hex-quad
/// \U hex-quad hex-quad
/// hex-quad:
/// hex-digit hex-digit hex-digit hex-digit
/// \endverbatim
///
CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
SourceLocation Loc, Preprocessor &PP,
tok::TokenKind kind) {
// At this point we know that the character matches the regex "(L|u|U)?'.*'".
HadError = false;
Kind = kind;
const char *TokBegin = begin;
// Skip over wide character determinant.
if (Kind != tok::char_constant)
++begin;
if (Kind == tok::utf8_char_constant)
++begin;
// Skip over the entry quote.
assert(begin[0] == '\'' && "Invalid token lexed");
++begin;
// Remove an optional ud-suffix.
if (end[-1] != '\'') {
const char *UDSuffixEnd = end;
do {
--end;
} while (end[-1] != '\'');
// FIXME: Don't bother with this if !tok.hasUCN().
expandUCNs(UDSuffixBuf, StringRef(end, UDSuffixEnd - end));
UDSuffixOffset = end - TokBegin;
}
// Trim the ending quote.
assert(end != begin && "Invalid token lexed");
--end;
// FIXME: The "Value" is an uint64_t so we can handle char literals of
// up to 64-bits.
// FIXME: This extensively assumes that 'char' is 8-bits.
assert(PP.getTargetInfo().getCharWidth() == 8 &&
"Assumes char is 8 bits");
assert(PP.getTargetInfo().getIntWidth() <= 64 &&
(PP.getTargetInfo().getIntWidth() & 7) == 0 &&
"Assumes sizeof(int) on target is <= 64 and a multiple of char");
assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
"Assumes sizeof(wchar) on target is <= 64");
SmallVector<uint32_t, 4> codepoint_buffer;
codepoint_buffer.resize(end - begin);
uint32_t *buffer_begin = &codepoint_buffer.front();
uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
// Unicode escapes representing characters that cannot be correctly
// represented in a single code unit are disallowed in character literals
// by this implementation.
uint32_t largest_character_for_kind;
if (tok::wide_char_constant == Kind) {
largest_character_for_kind =
0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
} else if (tok::utf8_char_constant == Kind) {
largest_character_for_kind = 0x7F;
} else if (tok::utf16_char_constant == Kind) {
largest_character_for_kind = 0xFFFF;
} else if (tok::utf32_char_constant == Kind) {
largest_character_for_kind = 0x10FFFF;
} else {
largest_character_for_kind = 0x7Fu;
}
while (begin != end) {
// Is this a span of non-escape characters?
if (begin[0] != '\\') {
char const *start = begin;
do {
++begin;
} while (begin != end && *begin != '\\');
char const *tmp_in_start = start;
uint32_t *tmp_out_start = buffer_begin;
llvm::ConversionResult res =
llvm::ConvertUTF8toUTF32(reinterpret_cast<llvm::UTF8 const **>(&start),
reinterpret_cast<llvm::UTF8 const *>(begin),
&buffer_begin, buffer_end, llvm::strictConversion);
if (res != llvm::conversionOK) {
// If we see bad encoding for unprefixed character literals, warn and
// simply copy the byte values, for compatibility with gcc and
// older versions of clang.
bool NoErrorOnBadEncoding = isAscii();
unsigned Msg = diag::err_bad_character_encoding;
if (NoErrorOnBadEncoding)
Msg = diag::warn_bad_character_encoding;
PP.Diag(Loc, Msg);
if (NoErrorOnBadEncoding) {
start = tmp_in_start;
buffer_begin = tmp_out_start;
for (; start != begin; ++start, ++buffer_begin)
*buffer_begin = static_cast<uint8_t>(*start);
} else {
HadError = true;
}
} else {
for (; tmp_out_start < buffer_begin; ++tmp_out_start) {
if (*tmp_out_start > largest_character_for_kind) {
HadError = true;
PP.Diag(Loc, diag::err_character_too_large);
}
}
}
continue;
}
// Is this a Universal Character Name escape?
if (begin[1] == 'u' || begin[1] == 'U') {
unsigned short UcnLen = 0;
if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
FullSourceLoc(Loc, PP.getSourceManager()),
&PP.getDiagnostics(), PP.getLangOpts(), true)) {
HadError = true;
} else if (*buffer_begin > largest_character_for_kind) {
HadError = true;
PP.Diag(Loc, diag::err_character_too_large);
}
++buffer_begin;
continue;
}
unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
uint64_t result =
ProcessCharEscape(TokBegin, begin, end, HadError,
FullSourceLoc(Loc,PP.getSourceManager()),
CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
*buffer_begin++ = result;
}
unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front();
if (NumCharsSoFar > 1) {
if (isWide())
PP.Diag(Loc, diag::warn_extraneous_char_constant);
else if (isAscii() && NumCharsSoFar == 4)
PP.Diag(Loc, diag::ext_four_char_character_literal);
else if (isAscii())
PP.Diag(Loc, diag::ext_multichar_character_literal);
else
PP.Diag(Loc, diag::err_multichar_utf_character_literal);
IsMultiChar = true;
} else {
IsMultiChar = false;
}
llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
// Narrow character literals act as though their value is concatenated
// in this implementation, but warn on overflow.
bool multi_char_too_long = false;
if (isAscii() && isMultiChar()) {
LitVal = 0;
for (size_t i = 0; i < NumCharsSoFar; ++i) {
// check for enough leading zeros to shift into
multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
LitVal <<= 8;
LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
}
} else if (NumCharsSoFar > 0) {
// otherwise just take the last character
LitVal = buffer_begin[-1];
}
if (!HadError && multi_char_too_long) {
PP.Diag(Loc, diag::warn_char_constant_too_large);
}
// Transfer the value from APInt to uint64_t
Value = LitVal.getZExtValue();
// If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
// if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
// character constants are not sign extended in the this implementation:
// '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
PP.getLangOpts().CharIsSigned)
Value = (signed char)Value;
}
/// \verbatim
/// string-literal: [C++0x lex.string]
/// encoding-prefix " [s-char-sequence] "
/// encoding-prefix R raw-string
/// encoding-prefix:
/// u8
/// u
/// U
/// L
/// s-char-sequence:
/// s-char
/// s-char-sequence s-char
/// s-char:
/// any member of the source character set except the double-quote ",
/// backslash \, or new-line character
/// escape-sequence
/// universal-character-name
/// raw-string:
/// " d-char-sequence ( r-char-sequence ) d-char-sequence "
/// r-char-sequence:
/// r-char
/// r-char-sequence r-char
/// r-char:
/// any member of the source character set, except a right parenthesis )
/// followed by the initial d-char-sequence (which may be empty)
/// followed by a double quote ".
/// d-char-sequence:
/// d-char
/// d-char-sequence d-char
/// d-char:
/// any member of the basic source character set except:
/// space, the left parenthesis (, the right parenthesis ),
/// the backslash \, and the control characters representing horizontal
/// tab, vertical tab, form feed, and newline.
/// escape-sequence: [C++0x lex.ccon]
/// simple-escape-sequence
/// octal-escape-sequence
/// hexadecimal-escape-sequence
/// simple-escape-sequence:
/// one of \' \" \? \\ \a \b \f \n \r \t \v
/// octal-escape-sequence:
/// \ octal-digit
/// \ octal-digit octal-digit
/// \ octal-digit octal-digit octal-digit
/// hexadecimal-escape-sequence:
/// \x hexadecimal-digit
/// hexadecimal-escape-sequence hexadecimal-digit
/// universal-character-name:
/// \u hex-quad
/// \U hex-quad hex-quad
/// hex-quad:
/// hex-digit hex-digit hex-digit hex-digit
/// \endverbatim
///
StringLiteralParser::
StringLiteralParser(ArrayRef<Token> StringToks,
Preprocessor &PP, bool Complain)
: SM(PP.getSourceManager()), Features(PP.getLangOpts()),
Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() :nullptr),
MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
init(StringToks);
}
void StringLiteralParser::init(ArrayRef<Token> StringToks){
// The literal token may have come from an invalid source location (e.g. due
// to a PCH error), in which case the token length will be 0.
if (StringToks.empty() || StringToks[0].getLength() < 2)
return DiagnoseLexingError(SourceLocation());
// Scan all of the string portions, remember the max individual token length,
// computing a bound on the concatenated string length, and see whether any
// piece is a wide-string. If any of the string portions is a wide-string
// literal, the result is a wide-string literal [C99 6.4.5p4].
assert(!StringToks.empty() && "expected at least one token");
MaxTokenLength = StringToks[0].getLength();
assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
SizeBound = StringToks[0].getLength()-2; // -2 for "".
Kind = StringToks[0].getKind();
hadError = false;
// Implement Translation Phase #6: concatenation of string literals
/// (C99 5.1.1.2p1). The common case is only one string fragment.
for (unsigned i = 1; i != StringToks.size(); ++i) {
if (StringToks[i].getLength() < 2)
return DiagnoseLexingError(StringToks[i].getLocation());
// The string could be shorter than this if it needs cleaning, but this is a
// reasonable bound, which is all we need.
assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
SizeBound += StringToks[i].getLength()-2; // -2 for "".
// Remember maximum string piece length.
if (StringToks[i].getLength() > MaxTokenLength)
MaxTokenLength = StringToks[i].getLength();
// Remember if we see any wide or utf-8/16/32 strings.
// Also check for illegal concatenations.
if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
if (isAscii()) {
Kind = StringToks[i].getKind();
} else {
if (Diags)
Diags->Report(StringToks[i].getLocation(),
diag::err_unsupported_string_concat);
hadError = true;
}
}
}
// Include space for the null terminator.
++SizeBound;
// TODO: K&R warning: "traditional C rejects string constant concatenation"
// Get the width in bytes of char/wchar_t/char16_t/char32_t
CharByteWidth = getCharWidth(Kind, Target);
assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
CharByteWidth /= 8;
// The output buffer size needs to be large enough to hold wide characters.
// This is a worst-case assumption which basically corresponds to L"" "long".
SizeBound *= CharByteWidth;
// Size the temporary buffer to hold the result string data.
ResultBuf.resize(SizeBound);
// Likewise, but for each string piece.
SmallString<512> TokenBuf;
TokenBuf.resize(MaxTokenLength);
// Loop over all the strings, getting their spelling, and expanding them to
// wide strings as appropriate.
ResultPtr = &ResultBuf[0]; // Next byte to fill in.
Pascal = false;
SourceLocation UDSuffixTokLoc;
for (unsigned i = 0, e = StringToks.size(); i != e; ++i) {
const char *ThisTokBuf = &TokenBuf[0];
// Get the spelling of the token, which eliminates trigraphs, etc. We know
// that ThisTokBuf points to a buffer that is big enough for the whole token
// and 'spelled' tokens can only shrink.
bool StringInvalid = false;
unsigned ThisTokLen =
Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
&StringInvalid);
if (StringInvalid)
return DiagnoseLexingError(StringToks[i].getLocation());
const char *ThisTokBegin = ThisTokBuf;
const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
// Remove an optional ud-suffix.
if (ThisTokEnd[-1] != '"') {
const char *UDSuffixEnd = ThisTokEnd;
do {
--ThisTokEnd;
} while (ThisTokEnd[-1] != '"');
StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
if (UDSuffixBuf.empty()) {
if (StringToks[i].hasUCN())
expandUCNs(UDSuffixBuf, UDSuffix);
else
UDSuffixBuf.assign(UDSuffix);
UDSuffixToken = i;
UDSuffixOffset = ThisTokEnd - ThisTokBuf;
UDSuffixTokLoc = StringToks[i].getLocation();
} else {
SmallString<32> ExpandedUDSuffix;
if (StringToks[i].hasUCN()) {
expandUCNs(ExpandedUDSuffix, UDSuffix);
UDSuffix = ExpandedUDSuffix;
}
// C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
// result of a concatenation involving at least one user-defined-string-
// literal, all the participating user-defined-string-literals shall
// have the same ud-suffix.
if (UDSuffixBuf != UDSuffix) {
if (Diags) {
SourceLocation TokLoc = StringToks[i].getLocation();
Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
<< UDSuffixBuf << UDSuffix
<< SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
<< SourceRange(TokLoc, TokLoc);
}
hadError = true;
}
}
}
// Strip the end quote.
--ThisTokEnd;
// TODO: Input character set mapping support.
// Skip marker for wide or unicode strings.
if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
++ThisTokBuf;
// Skip 8 of u8 marker for utf8 strings.
if (ThisTokBuf[0] == '8')
++ThisTokBuf;
}
// Check for raw string
if (ThisTokBuf[0] == 'R') {
ThisTokBuf += 2; // skip R"
const char *Prefix = ThisTokBuf;
while (ThisTokBuf[0] != '(')
++ThisTokBuf;
++ThisTokBuf; // skip '('
// Remove same number of characters from the end
ThisTokEnd -= ThisTokBuf - Prefix;
assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
// C++14 [lex.string]p4: A source-file new-line in a raw string literal
// results in a new-line in the resulting execution string-literal.
StringRef RemainingTokenSpan(ThisTokBuf, ThisTokEnd - ThisTokBuf);
while (!RemainingTokenSpan.empty()) {
// Split the string literal on \r\n boundaries.
size_t CRLFPos = RemainingTokenSpan.find("\r\n");
StringRef BeforeCRLF = RemainingTokenSpan.substr(0, CRLFPos);
StringRef AfterCRLF = RemainingTokenSpan.substr(CRLFPos);
// Copy everything before the \r\n sequence into the string literal.
if (CopyStringFragment(StringToks[i], ThisTokBegin, BeforeCRLF))
hadError = true;
// Point into the \n inside the \r\n sequence and operate on the
// remaining portion of the literal.
RemainingTokenSpan = AfterCRLF.substr(1);
}
} else {
if (ThisTokBuf[0] != '"') {
// The file may have come from PCH and then changed after loading the
// PCH; Fail gracefully.
return DiagnoseLexingError(StringToks[i].getLocation());
}
++ThisTokBuf; // skip "
// Check if this is a pascal string
if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
// If the \p sequence is found in the first token, we have a pascal string
// Otherwise, if we already have a pascal string, ignore the first \p
if (i == 0) {
++ThisTokBuf;
Pascal = true;
} else if (Pascal)
ThisTokBuf += 2;
}
while (ThisTokBuf != ThisTokEnd) {
// Is this a span of non-escape characters?
if (ThisTokBuf[0] != '\\') {
const char *InStart = ThisTokBuf;
do {
++ThisTokBuf;
} while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
// Copy the character span over.
if (CopyStringFragment(StringToks[i], ThisTokBegin,
StringRef(InStart, ThisTokBuf - InStart)))
hadError = true;
continue;
}
// Is this a Universal Character Name escape?
if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
ResultPtr, hadError,
FullSourceLoc(StringToks[i].getLocation(), SM),
CharByteWidth, Diags, Features);
continue;
}
// Otherwise, this is a non-UCN escape character. Process it.
unsigned ResultChar =
ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
FullSourceLoc(StringToks[i].getLocation(), SM),
CharByteWidth*8, Diags, Features);
if (CharByteWidth == 4) {
// FIXME: Make the type of the result buffer correct instead of
// using reinterpret_cast.
llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultPtr);
*ResultWidePtr = ResultChar;
ResultPtr += 4;
} else if (CharByteWidth == 2) {
// FIXME: Make the type of the result buffer correct instead of
// using reinterpret_cast.
llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultPtr);
*ResultWidePtr = ResultChar & 0xFFFF;
ResultPtr += 2;
} else {
assert(CharByteWidth == 1 && "Unexpected char width");
*ResultPtr++ = ResultChar & 0xFF;
}
}
}
}
if (Pascal) {
if (CharByteWidth == 4) {
// FIXME: Make the type of the result buffer correct instead of
// using reinterpret_cast.
llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultBuf.data());
ResultWidePtr[0] = GetNumStringChars() - 1;
} else if (CharByteWidth == 2) {
// FIXME: Make the type of the result buffer correct instead of
// using reinterpret_cast.
llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultBuf.data());
ResultWidePtr[0] = GetNumStringChars() - 1;
} else {
assert(CharByteWidth == 1 && "Unexpected char width");
ResultBuf[0] = GetNumStringChars() - 1;
}
// Verify that pascal strings aren't too large.
if (GetStringLength() > 256) {
if (Diags)
Diags->Report(StringToks.front().getLocation(),
diag::err_pascal_string_too_long)
<< SourceRange(StringToks.front().getLocation(),
StringToks.back().getLocation());
hadError = true;
return;
}
} else if (Diags) {
// Complain if this string literal has too many characters.
unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
if (GetNumStringChars() > MaxChars)
Diags->Report(StringToks.front().getLocation(),
diag::ext_string_too_long)
<< GetNumStringChars() << MaxChars
<< (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
<< SourceRange(StringToks.front().getLocation(),
StringToks.back().getLocation());
}
}
static const char *resyncUTF8(const char *Err, const char *End) {
if (Err == End)
return End;
End = Err + std::min<unsigned>(llvm::getNumBytesForUTF8(*Err), End-Err);
while (++Err != End && (*Err & 0xC0) == 0x80)
;
return Err;
}
/// This function copies from Fragment, which is a sequence of bytes
/// within Tok's contents (which begin at TokBegin) into ResultPtr.
/// Performs widening for multi-byte characters.
bool StringLiteralParser::CopyStringFragment(const Token &Tok,
const char *TokBegin,
StringRef Fragment) {
const llvm::UTF8 *ErrorPtrTmp;
if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
return false;
// If we see bad encoding for unprefixed string literals, warn and
// simply copy the byte values, for compatibility with gcc and older
// versions of clang.
bool NoErrorOnBadEncoding = isAscii();
if (NoErrorOnBadEncoding) {
memcpy(ResultPtr, Fragment.data(), Fragment.size());
ResultPtr += Fragment.size();
}
if (Diags) {
const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
FullSourceLoc SourceLoc(Tok.getLocation(), SM);
const DiagnosticBuilder &Builder =
Diag(Diags, Features, SourceLoc, TokBegin,
ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
: diag::err_bad_string_encoding);
const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
StringRef NextFragment(NextStart, Fragment.end()-NextStart);
// Decode into a dummy buffer.
SmallString<512> Dummy;
Dummy.reserve(Fragment.size() * CharByteWidth);
char *Ptr = Dummy.data();
while (!ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
NextStart = resyncUTF8(ErrorPtr, Fragment.end());
Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
ErrorPtr, NextStart);
NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
}
}
return !NoErrorOnBadEncoding;
}
void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
hadError = true;
if (Diags)
Diags->Report(Loc, diag::err_lexing_string);
}
/// getOffsetOfStringByte - This function returns the offset of the
/// specified byte of the string data represented by Token. This handles
/// advancing over escape sequences in the string.
unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
unsigned ByteNo) const {
// Get the spelling of the token.
SmallString<32> SpellingBuffer;
SpellingBuffer.resize(Tok.getLength());
bool StringInvalid = false;
const char *SpellingPtr = &SpellingBuffer[0];
unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
&StringInvalid);
if (StringInvalid)
return 0;
const char *SpellingStart = SpellingPtr;
const char *SpellingEnd = SpellingPtr+TokLen;
// Handle UTF-8 strings just like narrow strings.
if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
SpellingPtr += 2;
assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
// For raw string literals, this is easy.
if (SpellingPtr[0] == 'R') {
assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
// Skip 'R"'.
SpellingPtr += 2;
while (*SpellingPtr != '(') {
++SpellingPtr;
assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
}
// Skip '('.
++SpellingPtr;
return SpellingPtr - SpellingStart + ByteNo;
}
// Skip over the leading quote
assert(SpellingPtr[0] == '"' && "Should be a string literal!");
++SpellingPtr;
// Skip over bytes until we find the offset we're looking for.
while (ByteNo) {
assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
// Step over non-escapes simply.
if (*SpellingPtr != '\\') {
++SpellingPtr;
--ByteNo;
continue;
}
// Otherwise, this is an escape character. Advance over it.
bool HadError = false;
if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
const char *EscapePtr = SpellingPtr;
unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1, Features, HadError);
if (Len > ByteNo) {
// ByteNo is somewhere within the escape sequence.
SpellingPtr = EscapePtr;
break;
}
ByteNo -= Len;
} else {
ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
FullSourceLoc(Tok.getLocation(), SM),
CharByteWidth*8, Diags, Features);
--ByteNo;
}
assert(!HadError && "This method isn't valid on erroneous strings");
}
return SpellingPtr-SpellingStart;
}
/// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
/// suffixes as ud-suffixes, because the diagnostic experience is better if we
/// treat it as an invalid suffix.
bool StringLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
StringRef Suffix) {
return NumericLiteralParser::isValidUDSuffix(LangOpts, Suffix) ||
Suffix == "sv";
}
|
epiqc/ScaffCC
|
clang/lib/Lex/LiteralSupport.cpp
|
C++
|
bsd-2-clause
| 66,118 |
// This file was procedurally generated from the following sources:
// - src/spread/obj-mult-spread.case
// - src/spread/default/super-call.template
/*---
description: Multiple Object Spread operation (SuperCall)
esid: sec-super-keyword-runtime-semantics-evaluation
es6id: 12.3.5.1
features: [object-spread]
flags: [generated]
info: |
SuperCall : super Arguments
1. Let newTarget be GetNewTarget().
2. If newTarget is undefined, throw a ReferenceError exception.
3. Let func be GetSuperConstructor().
4. ReturnIfAbrupt(func).
5. Let argList be ArgumentListEvaluation of Arguments.
[...]
Pending Runtime Semantics: PropertyDefinitionEvaluation
PropertyDefinition:...AssignmentExpression
1. Let exprValue be the result of evaluating AssignmentExpression.
2. Let fromValue be GetValue(exprValue).
3. ReturnIfAbrupt(fromValue).
4. Let excludedNames be a new empty List.
5. Return CopyDataProperties(object, fromValue, excludedNames).
---*/
let o = {a: 2, b: 3};
let o2 = {c: 4, d: 5};
var callCount = 0;
class Test262ParentClass {
constructor(obj) {
assert.sameValue(obj.a, 2);
assert.sameValue(obj.b, 3);
assert.sameValue(obj.c, 4);
assert.sameValue(obj.d, 5);
assert.sameValue(Object.keys(obj).length, 4);
callCount += 1;
}
}
class Test262ChildClass extends Test262ParentClass {
constructor() {
super({...o, ...o2});
}
}
new Test262ChildClass();
assert.sameValue(callCount, 1);
|
sebastienros/jint
|
Jint.Tests.Test262/test/language/expressions/super/call-spread-obj-mult-spread.js
|
JavaScript
|
bsd-2-clause
| 1,479 |
from speakeasy import app
app.run(debug=True)
|
TinnedTuna/speakeasyspeeches
|
wsgi/run.py
|
Python
|
bsd-2-clause
| 46 |
package geom
import "math"
type geom0 struct {
layout Layout
stride int
flatCoords []float64
srid int
}
type geom1 struct {
geom0
}
type geom2 struct {
geom1
ends []int
}
type geom3 struct {
geom1
endss [][]int
}
// Bounds returns the bounds of g.
func (g *geom0) Bounds() *Bounds {
return NewBounds(g.layout).extendFlatCoords(g.flatCoords, 0, len(g.flatCoords), g.stride)
}
// Coords returns all the coordinates in g, i.e. a single coordinate.
func (g *geom0) Coords() Coord {
return inflate0(g.flatCoords, 0, len(g.flatCoords), g.stride)
}
// Empty returns true if g contains no coordinates.
func (g *geom0) Empty() bool {
return len(g.flatCoords) == 0
}
// Ends returns the end indexes of sub-structures of g, i.e. an empty slice.
func (g *geom0) Ends() []int {
return nil
}
// Endss returns the end indexes of sub-sub-structures of g, i.e. an empty
// slice.
func (g *geom0) Endss() [][]int {
return nil
}
// FlatCoords returns the flat coordinates of g.
func (g *geom0) FlatCoords() []float64 {
return g.flatCoords
}
// Layout returns g's layout.
func (g *geom0) Layout() Layout {
return g.layout
}
// NumCoords returns the number of coordinates in g, i.e. 1.
func (g *geom0) NumCoords() int {
return 1
}
// Reserve reserves space in g for n coordinates.
func (g *geom0) Reserve(n int) {
if cap(g.flatCoords) < n*g.stride {
fcs := make([]float64, len(g.flatCoords), n*g.stride)
copy(fcs, g.flatCoords)
g.flatCoords = fcs
}
}
// SRID returns g's SRID.
func (g *geom0) SRID() int {
return g.srid
}
func (g *geom0) setCoords(coords0 []float64) error {
var err error
g.flatCoords, err = deflate0(nil, coords0, g.stride)
return err
}
// Stride returns g's stride.
func (g *geom0) Stride() int {
return g.stride
}
func (g *geom0) verify() error {
if g.stride != g.layout.Stride() {
return errStrideLayoutMismatch
}
if g.stride == 0 {
if len(g.flatCoords) != 0 {
return errNonEmptyFlatCoords
}
return nil
}
if len(g.flatCoords) != g.stride {
return errLengthStrideMismatch
}
return nil
}
// Coord returns the ith coord of g.
func (g *geom1) Coord(i int) Coord {
return g.flatCoords[i*g.stride : (i+1)*g.stride]
}
// Coords unpacks and returns all of g's coordinates.
func (g *geom1) Coords() []Coord {
return inflate1(g.flatCoords, 0, len(g.flatCoords), g.stride)
}
// NumCoords returns the number of coordinates in g.
func (g *geom1) NumCoords() int {
return len(g.flatCoords) / g.stride
}
// Reverse reverses the order of g's coordinates.
func (g *geom1) Reverse() {
reverse1(g.flatCoords, 0, len(g.flatCoords), g.stride)
}
func (g *geom1) setCoords(coords1 []Coord) error {
var err error
g.flatCoords, err = deflate1(nil, coords1, g.stride)
return err
}
func (g *geom1) verify() error {
if g.stride != g.layout.Stride() {
return errStrideLayoutMismatch
}
if g.stride == 0 {
if len(g.flatCoords) != 0 {
return errNonEmptyFlatCoords
}
} else {
if len(g.flatCoords)%g.stride != 0 {
return errLengthStrideMismatch
}
}
return nil
}
// Coords returns all of g's coordinates.
func (g *geom2) Coords() [][]Coord {
return inflate2(g.flatCoords, 0, g.ends, g.stride)
}
// Ends returns the end indexes of all sub-structures in g.
func (g *geom2) Ends() []int {
return g.ends
}
// Reverse reverses the order of coordinates for each sub-structure in g.
func (g *geom2) Reverse() {
reverse2(g.flatCoords, 0, g.ends, g.stride)
}
func (g *geom2) setCoords(coords2 [][]Coord) error {
var err error
g.flatCoords, g.ends, err = deflate2(nil, nil, coords2, g.stride)
return err
}
func (g *geom2) verify() error {
if g.stride != g.layout.Stride() {
return errStrideLayoutMismatch
}
if g.stride == 0 {
if len(g.flatCoords) != 0 {
return errNonEmptyFlatCoords
}
if len(g.ends) != 0 {
return errNonEmptyEnds
}
return nil
}
if len(g.flatCoords)%g.stride != 0 {
return errLengthStrideMismatch
}
offset := 0
for _, end := range g.ends {
if end%g.stride != 0 {
return errMisalignedEnd
}
if end < offset {
return errOutOfOrderEnd
}
offset = end
}
if offset != len(g.flatCoords) {
return errIncorrectEnd
}
return nil
}
// Coords returns all the coordinates in g.
func (g *geom3) Coords() [][][]Coord {
return inflate3(g.flatCoords, 0, g.endss, g.stride)
}
// Endss returns a list of all the sub-sub-structures in g.
func (g *geom3) Endss() [][]int {
return g.endss
}
// Reverse reverses the order of coordinates for each sub-sub-structure in g.
func (g *geom3) Reverse() {
reverse3(g.flatCoords, 0, g.endss, g.stride)
}
func (g *geom3) setCoords(coords3 [][][]Coord) error {
var err error
g.flatCoords, g.endss, err = deflate3(nil, nil, coords3, g.stride)
return err
}
func (g *geom3) verify() error {
if g.stride != g.layout.Stride() {
return errStrideLayoutMismatch
}
if g.stride == 0 {
if len(g.flatCoords) != 0 {
return errNonEmptyFlatCoords
}
if len(g.endss) != 0 {
return errNonEmptyEndss
}
return nil
}
if len(g.flatCoords)%g.stride != 0 {
return errLengthStrideMismatch
}
offset := 0
for _, ends := range g.endss {
for _, end := range ends {
if end%g.stride != 0 {
return errMisalignedEnd
}
if end < offset {
return errOutOfOrderEnd
}
offset = end
}
}
if offset != len(g.flatCoords) {
return errIncorrectEnd
}
return nil
}
func doubleArea1(flatCoords []float64, offset, end, stride int) float64 {
var doubleArea float64
for i := offset + stride; i < end; i += stride {
doubleArea += (flatCoords[i+1] - flatCoords[i+1-stride]) * (flatCoords[i] + flatCoords[i-stride])
}
return doubleArea
}
func doubleArea2(flatCoords []float64, offset int, ends []int, stride int) float64 {
var doubleArea float64
for i, end := range ends {
da := doubleArea1(flatCoords, offset, end, stride)
if i == 0 {
doubleArea = da
} else {
doubleArea -= da
}
offset = end
}
return doubleArea
}
func doubleArea3(flatCoords []float64, offset int, endss [][]int, stride int) float64 {
var doubleArea float64
for _, ends := range endss {
doubleArea += doubleArea2(flatCoords, offset, ends, stride)
offset = ends[len(ends)-1]
}
return doubleArea
}
func deflate0(flatCoords []float64, c Coord, stride int) ([]float64, error) {
if len(c) != stride {
return nil, ErrStrideMismatch{Got: len(c), Want: stride}
}
flatCoords = append(flatCoords, c...)
return flatCoords, nil
}
func deflate1(flatCoords []float64, coords1 []Coord, stride int) ([]float64, error) {
for _, c := range coords1 {
var err error
flatCoords, err = deflate0(flatCoords, c, stride)
if err != nil {
return nil, err
}
}
return flatCoords, nil
}
func deflate2(
flatCoords []float64, ends []int, coords2 [][]Coord, stride int,
) ([]float64, []int, error) {
for _, coords1 := range coords2 {
var err error
flatCoords, err = deflate1(flatCoords, coords1, stride)
if err != nil {
return nil, nil, err
}
ends = append(ends, len(flatCoords))
}
return flatCoords, ends, nil
}
func deflate3(
flatCoords []float64, endss [][]int, coords3 [][][]Coord, stride int,
) ([]float64, [][]int, error) {
for _, coords2 := range coords3 {
var err error
var ends []int
flatCoords, ends, err = deflate2(flatCoords, ends, coords2, stride)
if err != nil {
return nil, nil, err
}
endss = append(endss, ends)
}
return flatCoords, endss, nil
}
func inflate0(flatCoords []float64, offset, end, stride int) Coord {
if offset+stride != end {
panic("geom: stride mismatch")
}
c := make([]float64, stride)
copy(c, flatCoords[offset:end])
return c
}
func inflate1(flatCoords []float64, offset, end, stride int) []Coord {
coords1 := make([]Coord, (end-offset)/stride)
for i := range coords1 {
coords1[i] = inflate0(flatCoords, offset, offset+stride, stride)
offset += stride
}
return coords1
}
func inflate2(flatCoords []float64, offset int, ends []int, stride int) [][]Coord {
coords2 := make([][]Coord, len(ends))
for i := range coords2 {
end := ends[i]
coords2[i] = inflate1(flatCoords, offset, end, stride)
offset = end
}
return coords2
}
func inflate3(flatCoords []float64, offset int, endss [][]int, stride int) [][][]Coord {
coords3 := make([][][]Coord, len(endss))
for i := range coords3 {
ends := endss[i]
coords3[i] = inflate2(flatCoords, offset, ends, stride)
if len(ends) > 0 {
offset = ends[len(ends)-1]
}
}
return coords3
}
func length1(flatCoords []float64, offset, end, stride int) float64 {
var length float64
for i := offset + stride; i < end; i += stride {
dx := flatCoords[i] - flatCoords[i-stride]
dy := flatCoords[i+1] - flatCoords[i+1-stride]
length += math.Sqrt(dx*dx + dy*dy)
}
return length
}
func length2(flatCoords []float64, offset int, ends []int, stride int) float64 {
var length float64
for _, end := range ends {
length += length1(flatCoords, offset, end, stride)
offset = end
}
return length
}
func length3(flatCoords []float64, offset int, endss [][]int, stride int) float64 {
var length float64
for _, ends := range endss {
length += length2(flatCoords, offset, ends, stride)
offset = ends[len(ends)-1]
}
return length
}
func reverse1(flatCoords []float64, offset, end, stride int) {
for i, j := offset+stride, end; i <= j; i, j = i+stride, j-stride {
for k := 0; k < stride; k++ {
flatCoords[i-stride+k], flatCoords[j-stride+k] = flatCoords[j-stride+k], flatCoords[i-stride+k]
}
}
}
func reverse2(flatCoords []float64, offset int, ends []int, stride int) {
for _, end := range ends {
reverse1(flatCoords, offset, end, stride)
offset = end
}
}
func reverse3(flatCoords []float64, offset int, endss [][]int, stride int) {
for _, ends := range endss {
if len(ends) == 0 {
continue
}
reverse2(flatCoords, offset, ends, stride)
offset = ends[len(ends)-1]
}
}
|
twpayne/go-geom
|
flat.go
|
GO
|
bsd-2-clause
| 9,818 |
#pragma once
#include <string>
#include <memory>
#include <deque>
#include "FAST/Object.hpp"
namespace fast {
/**
* @brief A class for runtime measurement
*
* Collect multiple runtimes over time, and calculates running average, running standard deviation,
* sum, max, min etc.
*
* All measurements are in milliseconds
*
*/
class FAST_EXPORT RuntimeMeasurement : public Object {
public:
typedef std::shared_ptr<RuntimeMeasurement> pointer;
RuntimeMeasurement(std::string name, int warmupRounds = 0, int maximumSamples = -1);
void addSample(double runtime);
double getSum() const;
double getAverage() const;
unsigned int getSamples() const;
double getMax() const;
double getMin() const;
double getStdDeviation() const;
std::string print() const;
void reset();
~RuntimeMeasurement() override = default;
private:
RuntimeMeasurement();
double mSum;
unsigned int mSamples;
double mRunningVariance;
double mRunningMean;
double mMin;
double mMax;
double mFirstSample;
std::string mName;
int m_warmupRounds;
int m_maximumSamples;
std::deque<double> m_queueRuntime;
std::deque<double> m_queueAvg;
std::deque<double> m_queueStd;
};
}; // end namespace
|
smistad/FAST
|
source/FAST/RuntimeMeasurement.hpp
|
C++
|
bsd-2-clause
| 1,189 |
# Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
Media::Application.initialize!
|
thomaseger/media
|
config/environment.rb
|
Ruby
|
bsd-2-clause
| 149 |
package me.passtheheadphones.request;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import api.cli.Utils;
import api.requests.Request;
import api.requests.Response;
import api.soup.MySoup;
import me.passtheheadphones.R;
import me.passtheheadphones.PTHApplication;
import me.passtheheadphones.callbacks.LoadingListener;
import me.passtheheadphones.callbacks.ViewTorrentCallbacks;
import me.passtheheadphones.callbacks.ViewUserCallbacks;
import me.passtheheadphones.settings.SettingsActivity;
import me.passtheheadphones.views.ImageDialog;
import java.util.Date;
/**
* Display the details of a request, bounty, artists etc.
*/
public class RequestDetailFragment extends Fragment implements View.OnClickListener, LoadingListener<Request> {
/**
* The request being viewed
*/
private Request request;
private ViewUserCallbacks viewUser;
private ViewTorrentCallbacks viewTorrent;
/**
* Various views displaying the information about the request along with associated headers/text
* so that we can hide any unused views
*/
private ImageView image;
private ProgressBar spinner;
private TextView title, created, recordLabel, catalogueNumber, releaseType, filled, filledBy,
acceptBitrates, acceptFormats, acceptMedia, votes, bounty, tags;
private View recordLabelText, catalogueNumberText, releaseTypeText, filledText, filledByText,
bitratesContainer, formatsContainer, mediaContainer, addVote, artContainer;
/**
* The list shows the artists & top contributors
*/
private ExpandableListView list;
/**
* Use this factory method to create a request fragment displaying the request
*
* @param id request to load
* @return fragment displaying the request
*/
public static RequestDetailFragment newInstance(int id){
RequestDetailFragment fragment = new RequestDetailFragment();
Bundle args = new Bundle();
args.putInt(RequestActivity.REQUEST_ID, id);
fragment.setArguments(args);
return fragment;
}
public RequestDetailFragment(){
//Required empty ctor
}
@Override
public void onAttach(Activity activity){
super.onAttach(activity);
try {
viewTorrent = (ViewTorrentCallbacks)activity;
viewUser = (ViewUserCallbacks)activity;
}
catch (ClassCastException e){
throw new ClassCastException(activity.toString()
+ " must implement ViewUser and ViewTorrent callbacks");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.expandable_list_view, container, false);
list = (ExpandableListView)view.findViewById(R.id.exp_list);
View header = inflater.inflate(R.layout.header_request_info, null);
list.addHeaderView(header, null, false);
image = (ImageView)header.findViewById(R.id.image);
spinner = (ProgressBar)header.findViewById(R.id.loading_indicator);
artContainer = header.findViewById(R.id.art_container);
title = (TextView)header.findViewById(R.id.title);
created = (TextView)header.findViewById(R.id.created);
recordLabelText = header.findViewById(R.id.record_label_text);
recordLabel = (TextView)header.findViewById(R.id.record_label);
catalogueNumberText = header.findViewById(R.id.catalogue_number_text);
catalogueNumber = (TextView)header.findViewById(R.id.catalogue_number);
releaseType = (TextView)header.findViewById(R.id.release_type);
releaseTypeText = header.findViewById(R.id.release_type_text);
filled = (TextView)header.findViewById(R.id.filled_torrent);
filledText = header.findViewById(R.id.filled_torrent_text);
filledBy = (TextView)header.findViewById(R.id.filled_user);
filledByText = header.findViewById(R.id.filled_user_text);
acceptBitrates = (TextView)header.findViewById(R.id.accept_bitrates);
bitratesContainer = header.findViewById(R.id.accept_bitrates_container);
acceptFormats = (TextView)header.findViewById(R.id.accept_formats);
formatsContainer = header.findViewById(R.id.accept_formats_container);
acceptMedia = (TextView)header.findViewById(R.id.accept_media);
mediaContainer = header.findViewById(R.id.accept_media_container);
votes = (TextView)header.findViewById(R.id.votes);
bounty = (TextView)header.findViewById(R.id.bounty);
tags = (TextView)header.findViewById(R.id.tags);
addVote = header.findViewById(R.id.add_vote);
addVote.setOnClickListener(this);
image.setOnClickListener(this);
if (request != null){
populateViews();
}
return view;
}
@Override
public void onClick(View v){
if (v.getId() == R.id.add_vote){
VoteDialog dialog = VoteDialog.newInstance(request);
dialog.show(getChildFragmentManager(), "vote_dialog");
}
else if (v.getId() == R.id.image){
ImageDialog dialog = ImageDialog.newInstance(request.getResponse().getImage());
dialog.show(getChildFragmentManager(), "image_dialog");
}
}
@Override
public void onLoadingComplete(Request data){
request = data;
if (isAdded()){
populateViews();
}
}
/**
* Update the request information being shown
*/
private void populateViews(){
Response response = request.getResponse();
title.setText(response.getTitle());
votes.setText(response.getVoteCount().toString());
bounty.setText(Utils.toHumanReadableSize(response.getTotalBounty().longValue()));
Date createDate = MySoup.parseDate(response.getTimeAdded());
created.setText(DateUtils.getRelativeTimeSpanString(createDate.getTime(),
new Date().getTime(), DateUtils.WEEK_IN_MILLIS));
RequestAdapter adapter = new RequestAdapter(getActivity(), response.getMusicInfo(), response.getTopContributors());
list.setAdapter(adapter);
list.setOnChildClickListener(adapter);
//Requests may be missing any of these fields
String imgUrl = response.getImage();
if (!SettingsActivity.imagesEnabled(getActivity())) {
artContainer.setVisibility(View.GONE);
} else {
artContainer.setVisibility(View.VISIBLE);
PTHApplication.loadImage(getActivity(), imgUrl, image, spinner, null, null);
}
if (response.isFilled()){
addVote.setVisibility(View.GONE);
filled.setText("Yes");
filled.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
viewTorrent.viewTorrent(-1, request.getResponse().getTorrentId().intValue());
}
});
filledBy.setText(response.getFillerName());
filledBy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
viewUser.viewUser(request.getResponse().getFillerId().intValue());
}
});
}
else {
filledText.setVisibility(View.GONE);
filled.setVisibility(View.GONE);
filledByText.setVisibility(View.GONE);
filledBy.setVisibility(View.GONE);
}
if (response.getRecordLabel() != null && !response.getRecordLabel().isEmpty()){
recordLabel.setText(response.getRecordLabel());
}
else {
recordLabelText.setVisibility(View.GONE);
recordLabel.setVisibility(View.GONE);
}
if (response.getCatalogueNumber() != null && !response.getCatalogueNumber().isEmpty()){
catalogueNumber.setText(response.getCatalogueNumber());
}
else {
catalogueNumberText.setVisibility(View.GONE);
catalogueNumber.setVisibility(View.GONE);
}
if (response.getReleaseName() != null && !response.getReleaseName().isEmpty()){
releaseType.setText(response.getReleaseName());
}
else {
releaseTypeText.setVisibility(View.GONE);
releaseType.setVisibility(View.GONE);
}
if (!response.getBitrateList().isEmpty()){
String bitrates = response.getBitrateList().toString();
bitrates = bitrates.substring(bitrates.indexOf('[') + 1, bitrates.lastIndexOf(']'));
acceptBitrates.setText(bitrates);
}
else {
bitratesContainer.setVisibility(View.GONE);
}
if (!response.getFormatList().isEmpty()){
String formats = response.getFormatList().toString();
formats = formats.substring(formats.indexOf('[') + 1, formats.lastIndexOf(']'));
acceptFormats.setText(formats);
}
else {
formatsContainer.setVisibility(View.GONE);
}
if (!response.getMediaList().isEmpty()){
String media = response.getMediaList().toString();
media = media.substring(media.indexOf('[') + 1, media.lastIndexOf(']'));
acceptMedia.setText(media);
}
else {
mediaContainer.setVisibility(View.GONE);
}
String tagString = response.getTags().toString();
tagString = tagString.substring(tagString.indexOf('[') + 1, tagString.lastIndexOf(']'));
tags.setText(tagString);
}
}
|
stuxo/PTHAndroid
|
PTHAndroid/src/main/java/me/passtheheadphones/request/RequestDetailFragment.java
|
Java
|
bsd-2-clause
| 8,720 |
#ifndef FORM_HPP
#define FORM_HPP
#include <CtrlLib/CtrlLib.h>
#include <GridCtrl/GridCtrl.h>
using namespace Upp;
#include "Container.hpp"
#include "FormLayout.hpp"
class Form : public TopWindow
{
typedef Form CLASSNAME;
public:
Form();
~Form();
bool Load(const String& file);
bool Layout(const String& layout, Font font = StdFont());
bool Generate(Font font = StdFont());
bool Exit(const String& action);
bool Acceptor(const String& action);
bool Rejector(const String& action);
Ctrl* GetCtrl(const String& var);
Value GetData(const String& var);
String ExecuteForm();
String Script;
Callback3<const String&, const String&, const String& > SignalHandler;
ArrayMap<String, Ctrl>& GetCtrls() { return _Ctrls; }
const ArrayMap<String, Ctrl>& GetCtrls() const { return _Ctrls; }
void Clear(bool all = true);
bool IsLayout() { return _Current != -1; }
int HasLayout(const String& layout);
void Xmlize(XmlIO xml) { xml("layouts", _Layouts); }
Vector<FormLayout>& GetLayouts() { return _Layouts; }
const Vector<FormLayout>& GetLayouts() const { return _Layouts; }
protected:
void OnAction(const String& action);
bool SetCallback(const String& action, Callback c);
Vector<String> _Acceptors;
Vector<String> _Rejectors;
Vector<FormLayout> _Layouts;
ArrayMap<String, Ctrl> _Ctrls;
private:
int _Current;
String _File;
};
#endif // .. FORM_HPP
|
dreamsxin/ultimatepp
|
bazaar/Form/Form.hpp
|
C++
|
bsd-2-clause
| 1,446 |
"""
OpenVZ containers
=================
"""
from contextlib import contextmanager
import hashlib
import os
import posixpath
import tempfile
from fabric.api import (
env,
hide,
output,
settings,
sudo,
)
from fabric.operations import (
_AttributeString,
_execute,
_prefix_commands,
_prefix_env_vars,
_shell_wrap,
_sudo_prefix,
)
from fabric.state import default_channel
from fabric.utils import error
import fabric.operations
import fabric.sftp
from fabric.context_managers import (
quiet as quiet_manager,
warn_only as warn_only_manager,
)
@contextmanager
def guest(name_or_ctid):
"""
Context manager to run commands inside a guest container.
Supported basic operations are: `run`_, `sudo`_ and `put`_.
.. warning:: commands executed with ``run()`` will be run as
**root** inside the container.
Use ``sudo(command, user='foo')`` to run them as
an unpriviledged user.
Example::
from fabtools.openvz import guest
with guest('foo'):
run('hostname')
sudo('whoami', user='alice')
put('files/hello.txt')
.. _run: http://docs.fabfile.org/en/1.4.3/api/core/operations.html#fabric.operations.run
.. _sudo: http://docs.fabfile.org/en/1.4.3/api/core/operations.html#fabric.operations.sudo
.. _put: http://docs.fabfile.org/en/1.4.3/api/core/operations.html#fabric.operations.put
"""
# Monkey patch fabric operations
_orig_run_command = fabric.operations._run_command
_orig_put = fabric.sftp.SFTP.put
def run_guest_command(command, shell=True, pty=True, combine_stderr=True,
sudo=False, user=None, quiet=False, warn_only=False, stdout=None,
stderr=None, group=None, timeout=None):
"""
Run command inside a guest container
"""
# Use a non-login shell
_orig_shell = env.shell
env.shell = '/bin/bash -c'
# Use double quotes for the sudo prompt
_orig_sudo_prefix = env.sudo_prefix
env.sudo_prefix = 'sudo -S -p "%(sudo_prompt)s" '
# Try to cd to the user's home directory for consistency,
# as the default directory is "/" with "vzctl exec2"
if not env.cwd:
env.command_prefixes.insert(0, 'cd 2>/dev/null || true')
# Build the guest command
guest_command = _shell_wrap_inner(
_prefix_commands(_prefix_env_vars(command), 'remote'),
True,
_sudo_prefix(user) if sudo and user else None
)
host_command = "vzctl exec2 %s '%s'" % (name_or_ctid, guest_command)
# Restore env
env.shell = _orig_shell
env.sudo_prefix = _orig_sudo_prefix
if not env.cwd:
env.command_prefixes.pop(0)
# Run host command as root
return _run_host_command(host_command, shell=shell, pty=pty,
combine_stderr=combine_stderr)
def put_guest(self, local_path, remote_path, use_sudo, mirror_local_mode,
mode, local_is_path):
"""
Upload file to a guest container
"""
pre = self.ftp.getcwd()
pre = pre if pre else ''
if local_is_path and self.isdir(remote_path):
basename = os.path.basename(local_path)
remote_path = posixpath.join(remote_path, basename)
if output.running:
print(("[%s] put: %s -> %s" % (
env.host_string,
local_path if local_is_path else '<file obj>',
posixpath.join(pre, remote_path)
)))
# Have to bounce off FS if doing file-like objects
fd, real_local_path = None, local_path
if not local_is_path:
fd, real_local_path = tempfile.mkstemp()
old_pointer = local_path.tell()
local_path.seek(0)
file_obj = os.fdopen(fd, 'wb')
file_obj.write(local_path.read())
file_obj.close()
local_path.seek(old_pointer)
# Use temporary file with a unique name on the host machine
guest_path = remote_path
hasher = hashlib.sha1()
hasher.update(env.host_string)
hasher.update(name_or_ctid)
hasher.update(guest_path)
host_path = hasher.hexdigest()
# Upload the file to host machine
rattrs = self.ftp.put(real_local_path, host_path)
# Copy file to the guest container
with settings(hide('everything'), cwd=""):
cmd = "cat \"%s\" | vzctl exec \"%s\" 'cat - > \"%s\"'" \
% (host_path, name_or_ctid, guest_path)
_orig_run_command(cmd, sudo=True)
# Revert to original remote_path for return value's sake
remote_path = guest_path
# Clean up
if not local_is_path:
os.remove(real_local_path)
# Handle modes if necessary
if (local_is_path and mirror_local_mode) or (mode is not None):
lmode = os.stat(local_path).st_mode if mirror_local_mode else mode
lmode = lmode & 0o7777
rmode = rattrs.st_mode & 0o7777
if lmode != rmode:
with hide('everything'):
sudo('chmod %o \"%s\"' % (lmode, remote_path))
return remote_path
fabric.operations._run_command = run_guest_command
fabric.sftp.SFTP.put = put_guest
yield
# Monkey unpatch
fabric.operations._run_command = _orig_run_command
fabric.sftp.SFTP.put = _orig_put
@contextmanager
def _noop():
yield
def _run_host_command(command, shell=True, pty=True, combine_stderr=True,
quiet=False, warn_only=False, stdout=None, stderr=None, timeout=None):
"""
Run host wrapper command as root
(Modified from fabric.operations._run_command to ignore prefixes,
path(), cd(), and always use sudo.)
"""
manager = _noop
if warn_only:
manager = warn_only_manager
# Quiet's behavior is a superset of warn_only's, so it wins.
if quiet:
manager = quiet_manager
with manager():
# Set up new var so original argument can be displayed verbatim later.
given_command = command
# Handle context manager modifications, and shell wrapping
wrapped_command = _shell_wrap(
command, # !! removed _prefix_commands() & _prefix_env_vars()
shell,
_sudo_prefix(None) # !! always use sudo
)
# Execute info line
which = 'sudo' # !! always use sudo
if output.debug:
print(("[%s] %s: %s" % (env.host_string, which, wrapped_command)))
elif output.running:
print(("[%s] %s: %s" % (env.host_string, which, given_command)))
# Actual execution, stdin/stdout/stderr handling, and termination
result_stdout, result_stderr, status = _execute(
channel=default_channel(), command=wrapped_command, pty=pty,
combine_stderr=combine_stderr, invoke_shell=False, stdout=stdout,
stderr=stderr, timeout=timeout)
# Assemble output string
out = _AttributeString(result_stdout)
err = _AttributeString(result_stderr)
# Error handling
out.failed = False
out.command = given_command
out.real_command = wrapped_command
if status not in env.ok_ret_codes:
out.failed = True
msg = "%s() received nonzero return code %s while executing" % (
which, status
)
if env.warn_only:
msg += " '%s'!" % given_command
else:
msg += "!\n\nRequested: %s\nExecuted: %s" % (
given_command, wrapped_command
)
error(message=msg, stdout=out, stderr=err)
# Attach return code to output string so users who have set things to
# warn only, can inspect the error code.
out.return_code = status
# Convenience mirror of .failed
out.succeeded = not out.failed
# Attach stderr for anyone interested in that.
out.stderr = err
return out
def _shell_wrap_inner(command, shell=True, sudo_prefix=None):
"""
Conditionally wrap given command in env.shell (while honoring sudo.)
(Modified from fabric.operations._shell_wrap to avoid double escaping,
as the wrapping host command would also get shell escaped.)
"""
# Honor env.shell, while allowing the 'shell' kwarg to override it (at
# least in terms of turning it off.)
if shell and not env.use_shell:
shell = False
# Sudo plus space, or empty string
if sudo_prefix is None:
sudo_prefix = ""
else:
sudo_prefix += " "
# If we're shell wrapping, prefix shell and space, escape the command and
# then quote it. Otherwise, empty string.
if shell:
shell = env.shell + " "
command = '"%s"' % command # !! removed _shell_escape() here
else:
shell = ""
# Resulting string should now have correct formatting
return sudo_prefix + shell + command
|
bitmonk/fabtools
|
fabtools/openvz/contextmanager.py
|
Python
|
bsd-2-clause
| 9,146 |
using System.Collections.Generic;
using System.Linq.Expressions;
using Microsoft.Extensions.Logging;
using Mozlite.Data.Query.Translators.Internal;
using System.Linq;
namespace Mozlite.Data.Query.Translators
{
/// <summary>
/// 方法调用转换实现基类。
/// </summary>
public abstract class RelationalCompositeMethodCallTranslator : IMethodCallTranslator
{
private readonly List<IMethodCallTranslator> _translators;
/// <summary>
/// 初始化类<see cref="RelationalCompositeMethodCallTranslator"/>。
/// </summary>
/// <param name="loggerFactory">日志工厂接口。</param>
protected RelationalCompositeMethodCallTranslator([NotNull] ILoggerFactory loggerFactory)
{
_translators = new List<IMethodCallTranslator>
{
new ContainsTranslator(),
new EndsWithTranslator(),
new EqualsTranslator(),
new StartsWithTranslator(),
new IsNullOrEmptyTranslator(),
new InTranslator(),
};
}
/// <summary>
/// 转换表达式。
/// </summary>
/// <param name="methodCallExpression">方法调用表达式。</param>
/// <returns>返回转换后的表达式。</returns>
public virtual Expression Translate(MethodCallExpression methodCallExpression)
{
return
_translators
.Select(translator => translator.Translate(methodCallExpression))
.FirstOrDefault(translatedMethodCall => translatedMethodCall != null);
}
/// <summary>
/// 添加转换类型。
/// </summary>
/// <param name="translators">转换类型列表。</param>
protected virtual void AddTranslators([NotNull] IEnumerable<IMethodCallTranslator> translators)
{
_translators.InsertRange(0, translators);
}
}
}
|
Mozlite/Mozlite.Core
|
Mozlite.Core/Data/Query/Translators/RelationalCompositeMethodCallTranslator.cs
|
C#
|
bsd-2-clause
| 1,993 |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-29 07:17
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('crimeprediction', '0003_auto_20160406_1610'),
]
operations = [
migrations.RemoveField(
model_name='crimesample',
name='crime',
),
migrations.RemoveField(
model_name='crimesample',
name='grids',
),
migrations.DeleteModel(
name='CrimeSample',
),
]
|
jayArnel/crimemapping
|
crimeprediction/migrations/0004_auto_20160429_0717.py
|
Python
|
bsd-2-clause
| 586 |
#include <ngx_flags.h>
#include <ngx_generator.h>
#include <google/protobuf/descriptor.pb.h>
namespace google {
namespace protobuf {
namespace compiler {
namespace nginx {
void
Generator::GenerateSize(const Descriptor* desc, io::Printer& printer)
{
std::map<std::string, std::string> vars;
vars["name"] = desc->full_name();
vars["root"] = TypedefRoot(desc->full_name());
vars["type"] = StructType(desc->full_name());
// statics for packed field size calcs. this is independent of field
// number and just calculates the payload size (of the actual data).
for (int i = 0; i < desc->field_count(); ++i) {
const FieldDescriptor *field = desc->field(i);
if (field->is_packable() && field->options().packed()) {
bool fixed = false;
vars["ffull"] = field->full_name();
vars["fname"] = field->name();
vars["ftype"] = FieldRealType(field);
printer.Print(vars,
"static size_t\n"
"$root$_$fname$__packed_size(ngx_array_t *a)\n"
"{\n");
Indent(printer);
switch (field->type()) {
case FieldDescriptor::TYPE_FIXED32:
case FieldDescriptor::TYPE_SFIXED32:
case FieldDescriptor::TYPE_FLOAT:
printer.Print("return (a && a->nelts > 0) ? a->nelts * 4 : 0;\n");
fixed = true;
break;
case FieldDescriptor::TYPE_FIXED64:
case FieldDescriptor::TYPE_SFIXED64:
case FieldDescriptor::TYPE_DOUBLE:
printer.Print("return (a && a->nelts > 0) ? a->nelts * 8 : 0;\n");
fixed = true;
break;
default:
// continue with the codegen
break;
}
if (!fixed) {
printer.Print(vars,
"size_t size = 0;\n"
"ngx_uint_t i;\n"
"$ftype$ *fptr;\n"
"\n");
SimpleIf(printer, vars,
"a != NULL && a->nelts > 0");
printer.Print(vars,
"fptr = a->elts;\n"
"for (i = 0; i < a->nelts; ++i) {\n");
Indent(printer);
switch (field->type()) {
case FieldDescriptor::TYPE_BOOL:
case FieldDescriptor::TYPE_ENUM:
case FieldDescriptor::TYPE_UINT32:
case FieldDescriptor::TYPE_INT32:
printer.Print("size += ngx_protobuf_size_uint32(fptr[i]);\n");
break;
case FieldDescriptor::TYPE_SINT32:
printer.Print("size += ngx_protobuf_size_sint32(fptr[i]);\n");
break;
case FieldDescriptor::TYPE_UINT64:
case FieldDescriptor::TYPE_INT64:
printer.Print("size += ngx_protobuf_size_uint32(fptr[i]);\n");
break;
case FieldDescriptor::TYPE_SINT64:
printer.Print("size += ngx_protobuf_size_sint64(fptr[i]);\n");
break;
default:
printer.Print(vars,
"#error $ffull$ cannot be a packed field");
break;
}
CloseBrace(printer);
CloseBrace(printer);
printer.Print("\n"
"return size;\n");
}
CloseBrace(printer);
printer.Print("\n");
}
}
printer.Print(vars,
"size_t\n"
"$root$__size(\n"
" $type$ *obj)\n"
"{\n");
Indent(printer);
Flags flags(desc);
bool iterates = false;
for (int i = 0; i < desc->field_count(); ++i) {
const FieldDescriptor *field = desc->field(i);
if (field->is_repeated() && !IsFixedWidth(field) &&
!(field->is_packable() && field->options().packed())) {
iterates = true;
break;
}
}
printer.Print("size_t size = 0;\n");
if (flags.has_packed() || flags.has_message()) {
printer.Print("size_t n;\n");
}
if (iterates || HasUnknownFields(desc)) {
// we need to iterate any repeated non-fixed field or unknown fields
printer.Print("ngx_uint_t i;\n");
}
printer.Print("\n");
for (int i = 0; i < desc->field_count(); ++i) {
const FieldDescriptor *field = desc->field(i);
vars["fname"] = field->name();
vars["ftype"] = FieldRealType(field);
vars["fnum"] = Number(field->number());
if (field->is_repeated()) {
CuddledIf(printer, vars,
"obj->__has_$fname$",
"&& obj->$fname$ != NULL\n"
"&& obj->$fname$->nelts > 0");
if (field->is_packable() && field->options().packed()) {
printer.Print(vars,
"n = $root$_$fname$__packed_size(\n");
Indented(printer, vars, "obj->$fname$);\n");
printer.Print("\n");
printer.Print(vars,
"size += ngx_protobuf_size_message_field(n, $fnum$);\n");
} else if (IsFixedWidth(field)) {
// size calculation of a non-packed repeated fixed-width field
switch (field->type()) {
case FieldDescriptor::TYPE_FIXED32:
case FieldDescriptor::TYPE_SFIXED32:
case FieldDescriptor::TYPE_FLOAT:
printer.Print(vars,
"size += obj->$fname$->nelts *\n"
" ngx_protobuf_size_fixed32_field($fnum$);\n");
break;
case FieldDescriptor::TYPE_FIXED64:
case FieldDescriptor::TYPE_SFIXED64:
case FieldDescriptor::TYPE_DOUBLE:
printer.Print(vars,
"size += obj->$fname$->nelts *\n"
" ngx_protobuf_size_fixed64_field($fnum$);\n");
break;
default:
break;
}
} else {
// size calculation of a non-packed repeated non-fixed width field
printer.Print(vars,
"$ftype$ *vals = obj->$fname$->elts;\n"
"\n"
"for (i = 0; i < obj->$fname$->nelts; ++i) {\n");
Indent(printer);
switch (field->type()) {
case FieldDescriptor::TYPE_MESSAGE:
vars["froot"] = TypedefRoot(field->message_type()->full_name());
printer.Print(vars,
"n = $froot$__size(vals + i);\n"
"size += ngx_protobuf_size_message_field("
"n, $fnum$);\n");
break;
case FieldDescriptor::TYPE_BYTES:
case FieldDescriptor::TYPE_STRING:
printer.Print(vars,
"size += ngx_protobuf_size_string_field("
"vals + i, $fnum$);\n");
break;
case FieldDescriptor::TYPE_BOOL:
printer.Print(vars,
"size += ngx_protobuf_size_uint32_field("
"(vals[i] != 0), $fnum$);\n");
break;
case FieldDescriptor::TYPE_ENUM:
case FieldDescriptor::TYPE_UINT32:
case FieldDescriptor::TYPE_INT32:
printer.Print(vars,
"size += ngx_protobuf_size_uint32_field("
"vals[i], $fnum$);\n");
break;
case FieldDescriptor::TYPE_SINT32:
printer.Print(vars,
"size += ngx_protobuf_size_sint32_field("
"vals[i], $fnum$);\n");
break;
case FieldDescriptor::TYPE_UINT64:
case FieldDescriptor::TYPE_INT64:
printer.Print(vars,
"size += ngx_protobuf_size_uint64_field("
"vals[i], $fnum$);\n");
break;
case FieldDescriptor::TYPE_SINT64:
printer.Print(vars,
"size += ngx_protobuf_size_sint64_field("
"vals[i], $fnum$);\n");
break;
case FieldDescriptor::TYPE_FIXED32:
case FieldDescriptor::TYPE_SFIXED32:
case FieldDescriptor::TYPE_FLOAT:
printer.Print(vars,
"size += ngx_protobuf_size_fixed32_field($fnum$);\n");
break;
case FieldDescriptor::TYPE_FIXED64:
case FieldDescriptor::TYPE_SFIXED64:
case FieldDescriptor::TYPE_DOUBLE:
printer.Print(vars,
"size += ngx_protobuf_size_fixed64_field($fnum$);\n");
break;
default:
printer.Print(vars,
"size += FIXME; /* size $ftype$ */\n");
break;
}
Outdent(printer);
printer.Print("}\n");
}
Outdent(printer);
printer.Print("}\n");
} else {
switch (field->type()) {
case FieldDescriptor::TYPE_MESSAGE:
vars["froot"] = TypedefRoot(field->message_type()->full_name());
FullCuddledIf(printer, vars,
"obj->__has_$fname$",
"&& obj->$fname$ != NULL",
"n = $froot$__size(obj->$fname$);\n"
"size += ngx_protobuf_size_message_field(n, $fnum$);");
break;
case FieldDescriptor::TYPE_BYTES:
case FieldDescriptor::TYPE_STRING:
FullSimpleIf(printer, vars,
"obj->__has_$fname$",
"size += ngx_protobuf_size_string_field("
"&obj->$fname$, $fnum$);");
break;
case FieldDescriptor::TYPE_BOOL:
FullSimpleIf(printer, vars,
"obj->__has_$fname$",
"size += ngx_protobuf_size_uint32_field("
"(obj->$fname$ != 0), $fnum$);");
break;
case FieldDescriptor::TYPE_ENUM:
case FieldDescriptor::TYPE_UINT32:
case FieldDescriptor::TYPE_INT32:
FullSimpleIf(printer, vars,
"obj->__has_$fname$",
"size += ngx_protobuf_size_uint32_field("
"obj->$fname$, $fnum$);");
break;
case FieldDescriptor::TYPE_SINT32:
FullSimpleIf(printer, vars,
"obj->__has_$fname$",
"size += ngx_protobuf_size_sint32_field("
"obj->$fname$, $fnum$);");
break;
case FieldDescriptor::TYPE_UINT64:
case FieldDescriptor::TYPE_INT64:
FullSimpleIf(printer, vars,
"obj->__has_$fname$",
"size += ngx_protobuf_size_uint64_field("
"obj->$fname$, $fnum$);");
break;
case FieldDescriptor::TYPE_SINT64:
FullSimpleIf(printer, vars,
"obj->__has_$fname$",
"size += ngx_protobuf_size_sint64_field("
"obj->$fname$, $fnum$);");
break;
case FieldDescriptor::TYPE_FIXED32:
case FieldDescriptor::TYPE_SFIXED32:
case FieldDescriptor::TYPE_FLOAT:
FullSimpleIf(printer, vars,
"obj->__has_$fname$",
"size += ngx_protobuf_size_fixed32_field($fnum$);");
break;
case FieldDescriptor::TYPE_FIXED64:
case FieldDescriptor::TYPE_SFIXED64:
case FieldDescriptor::TYPE_DOUBLE:
FullSimpleIf(printer, vars,
"obj->__has_$fname$",
"size += ngx_protobuf_size_fixed64_field($fnum$);");
break;
default:
printer.Print(vars,
"size += FIXME; /* size $ftype$ */\n");
break;
}
}
}
if (desc->extension_range_count() > 0) {
FullSimpleIf(printer, vars,
"obj->__extensions != NULL",
"size += ngx_protobuf_size_extensions(obj->__extensions);");
}
if (HasUnknownFields(desc)) {
printer.Print("\n");
CuddledIf(printer, vars,
"obj->__unknown != NULL",
"&& obj->__unknown->elts != NULL\n"
"&& obj->__unknown->nelts > 0");
printer.Print("ngx_protobuf_unknown_field_t *unk = "
"obj->__unknown->elts;\n"
"\n"
"for (i = 0; i < obj->__unknown->nelts; ++i) ");
OpenBrace(printer);
printer.Print("size += ngx_protobuf_size_unknown_field(unk + i);\n");
CloseBrace(printer);
CloseBrace(printer);
}
printer.Print("\n"
"return size;\n");
CloseBrace(printer);
printer.Print("\n");
}
} // namespace nginx
} // namespace compiler
} // namespace protobuf
} // namespace google
|
dbcode/protobuf-nginx
|
protongx/ngx_size.cc
|
C++
|
bsd-2-clause
| 12,102 |
from django.conf import settings
class Breadcrumb(object):
"""
A single breadcrumb, which is a 1:1 mapping to a view.
This is simply a wrapper class for the template tag.
"""
def __init__(self, name, url):
self.name = name
self.url = url
class Breadcrumbs(object):
"""
The site's breadcrumbs. An instance of this class is added to each
request, and can be called to add breadcrumbs to the template context.
def some_view(request):
request.breadcrumbs('Title', request.path_info)
request.breadcrumbs('Subtitle', ...)
...
You may prevent the 'Home' link being added by setting BREADCRUMBS_ADD_HOME
to False (defaults to True).
This class supports iteration, and is used as such in the template tag.
"""
_bc = []
def __init__(self, request):
self._request = request
# We must clear the list on every request or we will get duplicates
del self._bc[:]
# By default, add a link to the homepage. This can be disabled or
# configured in the project settings.
if getattr(settings, 'BREADCRUMBS_HOME_LINK', True):
home_name = getattr(settings, 'BREADCRUMBS_HOME_LINK_NAME', 'Home')
home_url = getattr(settings, 'BREADCRUMBS_HOME_LINK_URL', '/')
self._add(home_name, home_url)
def __call__(self, *args, **kwargs):
return self._add(*args, **kwargs)
def __iter__(self):
return iter(self._bc)
def __len__(self):
return len(self._bc)
def _add(self, name, url):
self._bc.append(Breadcrumb(name, url))
class BreadcrumbMiddleware(object):
"""
Middleware to add breadcrumbs into every request.
Add 'breadcrumbs3.middleware.BreadcrumbMiddleware' to MIDDLEWARE_CLASSES
and make sure 'django.template.context_processors.request' is in
TEMPLATES.context_processors.
"""
def process_request(self, request):
request.breadcrumbs = Breadcrumbs(request)
|
sjkingo/django-breadcrumbs3
|
breadcrumbs3/middleware.py
|
Python
|
bsd-2-clause
| 2,010 |
package com.pillowdrift.drillergame.entities.menu.buttons;
import com.pillowdrift.drillergame.framework.Scene;
/**
* Button to take you to the RecordsScene
* @author cake_cruncher_7
*
*/
public class RecordsMenuButton extends GenericMenuButton
{
//CONSTRUCTION
public RecordsMenuButton(Scene parent) {
super(parent, "Hi-Scores");
}
//FUNCTION
@Override
protected void onRelease()
{
super.onRelease();
//Activate the records scene
_parent.getOwner().getScene("RecordsScene").activate();
//Deactivate our parent scene
_parent.deactivate();
}
}
|
Pillowdrift/MegaDrillerMole
|
MegaDrillerMole/MDMWorkspace/DrillerGameAndroid/src/com/pillowdrift/drillergame/entities/menu/buttons/RecordsMenuButton.java
|
Java
|
bsd-2-clause
| 600 |
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body style='color:red;'>
Sorry. This page is currently unvailable because your ISP is blocking access to this site!
<br />
The site is available, but your local network is preventing you from accessing it.
You can try using a proxy, or another tool like <a href="https://www.torproject.org">Tor</a>.
Note that getting these tools may also be discouraged by your network.
<br />
You are encouraged to talk publically about this experience. It is instances
of misuse of censorship, maybe like this one, which can be used to advocate
for more transparent laws on Internet policy.
</body>
</html>
|
willscott/activist-wp-plugin
|
views/warning.php
|
PHP
|
bsd-2-clause
| 703 |
# -*- coding: utf-8 -*-
import json
import logging
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import last_modified as cache_last_modified
from django.views.decorators.cache import never_cache as force_cache_validation
from django.core.cache import get_cache
from django.shortcuts import redirect
from mapentity.views import (MapEntityLayer, MapEntityList, MapEntityJsonList,
MapEntityDetail, MapEntityDocument, MapEntityCreate, MapEntityUpdate,
MapEntityDelete, MapEntityFormat,
HttpJSONResponse)
from geotrek.authent.decorators import same_structure_required
from geotrek.common.utils import classproperty
from .models import Path, Trail, Topology
from .forms import PathForm, TrailForm
from .filters import PathFilterSet, TrailFilterSet
from . import graph as graph_lib
logger = logging.getLogger(__name__)
@login_required
def last_list(request):
last = request.session.get('last_list') # set in MapEntityList
if not last:
return redirect('core:path_list')
return redirect(last)
home = last_list
class CreateFromTopologyMixin(object):
def on_topology(self):
pk = self.request.GET.get('topology')
if pk:
try:
return Topology.objects.existing().get(pk=pk)
except Topology.DoesNotExist:
logger.warning("Intervention on unknown topology %s" % pk)
return None
def get_initial(self):
initial = super(CreateFromTopologyMixin, self).get_initial()
# Create intervention with an existing topology as initial data
topology = self.on_topology()
if topology:
initial['topology'] = topology.serialize(with_pk=False)
return initial
class PathLayer(MapEntityLayer):
model = Path
properties = ['name']
class PathList(MapEntityList):
queryset = Path.objects.prefetch_related('networks').select_related('stake')
filterform = PathFilterSet
@classproperty
def columns(cls):
columns = ['id', 'name', 'networks', 'stake']
if settings.TRAIL_MODEL_ENABLED:
columns.append('trails')
return columns
def get_queryset(self):
"""
denormalize ``trail`` column from list.
"""
qs = super(PathList, self).get_queryset()
denormalized = {}
if settings.TRAIL_MODEL_ENABLED:
paths_id = qs.values_list('id', flat=True)
paths_trails = Trail.objects.filter(aggregations__path__id__in=paths_id)
by_id = dict([(trail.id, trail) for trail in paths_trails])
trails_paths_ids = paths_trails.values_list('id', 'aggregations__path__id')
for trail_id, path_id in trails_paths_ids:
denormalized.setdefault(path_id, []).append(by_id[trail_id])
for path in qs:
path_trails = denormalized.get(path.id, [])
setattr(path, '_trails', path_trails)
yield path
class PathJsonList(MapEntityJsonList, PathList):
pass
class PathFormatList(MapEntityFormat, PathList):
pass
class PathDetail(MapEntityDetail):
model = Path
def context_data(self, *args, **kwargs):
context = super(PathDetail, self).context_data(*args, **kwargs)
context['can_edit'] = self.get_object().same_structure(self.request.user)
return context
class PathDocument(MapEntityDocument):
model = Path
def get_context_data(self, *args, **kwargs):
self.get_object().prepare_elevation_chart(self.request.build_absolute_uri('/'))
return super(PathDocument, self).get_context_data(*args, **kwargs)
class PathCreate(MapEntityCreate):
model = Path
form_class = PathForm
class PathUpdate(MapEntityUpdate):
model = Path
form_class = PathForm
@same_structure_required('core:path_detail')
def dispatch(self, *args, **kwargs):
return super(PathUpdate, self).dispatch(*args, **kwargs)
class PathDelete(MapEntityDelete):
model = Path
@same_structure_required('core:path_detail')
def dispatch(self, *args, **kwargs):
return super(PathDelete, self).dispatch(*args, **kwargs)
@login_required
@cache_last_modified(lambda x: Path.latest_updated())
@force_cache_validation
def get_graph_json(request):
cache = get_cache('fat')
key = 'path_graph_json'
result = cache.get(key)
latest = Path.latest_updated()
if result and latest:
cache_latest, json_graph = result
# Not empty and still valid
if cache_latest and cache_latest >= latest:
return HttpJSONResponse(json_graph)
# cache does not exist or is not up to date
# rebuild the graph and cache the json
graph = graph_lib.graph_edges_nodes_of_qs(Path.objects.all())
json_graph = json.dumps(graph)
cache.set(key, (latest, json_graph))
return HttpJSONResponse(json_graph)
class TrailLayer(MapEntityLayer):
queryset = Trail.objects.existing()
properties = ['name']
class TrailList(MapEntityList):
queryset = Trail.objects.existing()
filterform = TrailFilterSet
columns = ['id', 'name', 'departure', 'arrival']
class TrailDetail(MapEntityDetail):
queryset = Trail.objects.existing()
def context_data(self, *args, **kwargs):
context = super(TrailDetail, self).context_data(*args, **kwargs)
context['can_edit'] = self.get_object().same_structure(self.request.user)
return context
class TrailDocument(MapEntityDocument):
queryset = Trail.objects.existing()
class TrailCreate(CreateFromTopologyMixin, MapEntityCreate):
model = Trail
form_class = TrailForm
class TrailUpdate(MapEntityUpdate):
queryset = Trail.objects.existing()
form_class = TrailForm
@same_structure_required('core:trail_detail')
def dispatch(self, *args, **kwargs):
return super(TrailUpdate, self).dispatch(*args, **kwargs)
class TrailDelete(MapEntityDelete):
queryset = Trail.objects.existing()
@same_structure_required('core:trail_detail')
def dispatch(self, *args, **kwargs):
return super(TrailDelete, self).dispatch(*args, **kwargs)
|
camillemonchicourt/Geotrek
|
geotrek/core/views.py
|
Python
|
bsd-2-clause
| 6,257 |
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
HardwareInfo.cpp: Implements the FHardwareInfo class
=============================================================================*/
#include "EnginePrivate.h"
#include "HardwareInfo.h"
static TMap< FName, FString > HardwareDetailsMap;
void FHardwareInfo::RegisterHardwareInfo( const FName SpecIdentifier, const FString& HardwareInfo )
{
// Ensure we are adding a valid identifier to the map
check( SpecIdentifier == NAME_RHI ||
SpecIdentifier == NAME_TextureFormat ||
SpecIdentifier == NAME_DeviceType );
HardwareDetailsMap.Add( SpecIdentifier, HardwareInfo );
}
const FString FHardwareInfo::GetHardwareDetailsString()
{
FString DetailsString;
int32 DetailsAdded = 0;
for( TMap< FName, FString >::TConstIterator SpecIt( HardwareDetailsMap ); SpecIt; ++SpecIt )
{
// Separate all entries with a comma
if( DetailsAdded++ > 0 )
{
DetailsString += TEXT( ", " );
}
FString SpecID = SpecIt.Key().ToString();
FString SpecValue = SpecIt.Value();
DetailsString += ( ( SpecID + TEXT( "=" ) ) + SpecValue );
}
return DetailsString;
}
|
PopCap/GameIdea
|
Engine/Source/Runtime/Engine/Private/HardwareInfo.cpp
|
C++
|
bsd-2-clause
| 1,215 |
// Generated by CoffeeScript 1.9.3
/**
*
* @module cnode/view
* @author vfasky <vfasky@gmail.com>
*/
(function() {
"use strict";
var api, mcore;
mcore = require('mcoreExt');
api = require('./api');
module.exports = mcore.View.subclass({
constructor: mcore.View.prototype.constructor,
beforeInit: function() {
return this.api = api;
}
});
}).call(this);
|
vfasky/mcore
|
example/cnodejs/js/pack/cnode/1.0.0/src/view.js
|
JavaScript
|
bsd-2-clause
| 394 |
// Sorting the columns
/**
* @author zhixin wen <wenzhixin2010@gmail.com>
* version: 1.10.1
* https://github.com/wenzhixin/bootstrap-table/
*/
!function ($) {
'use strict';
// TOOLS DEFINITION
// ======================
var cachedWidth = null;
// it only does '%s', and return '' when arguments are undefined
var sprintf = function (str) {
var args = arguments,
flag = true,
i = 1;
str = str.replace(/%s/g, function () {
var arg = args[i++];
if (typeof arg === 'undefined') {
flag = false;
return '';
}
return arg;
});
return flag ? str : '';
};
var getPropertyFromOther = function (list, from, to, value) {
var result = '';
$.each(list, function (i, item) {
if (item[from] === value) {
result = item[to];
return false;
}
return true;
});
return result;
};
var getFieldIndex = function (columns, field) {
var index = -1;
$.each(columns, function (i, column) {
if (column.field === field) {
index = i;
return false;
}
return true;
});
return index;
};
// http://jsfiddle.net/wenyi/47nz7ez9/3/
var setFieldIndex = function (columns) {
var i, j, k,
totalCol = 0,
flag = [];
for (i = 0; i < columns[0].length; i++) {
totalCol += columns[0][i].colspan || 1;
}
for (i = 0; i < columns.length; i++) {
flag[i] = [];
for (j = 0; j < totalCol; j++) {
flag[i][j] = false;
}
}
for (i = 0; i < columns.length; i++) {
for (j = 0; j < columns[i].length; j++) {
var r = columns[i][j],
rowspan = r.rowspan || 1,
colspan = r.colspan || 1,
index = $.inArray(false, flag[i]);
if (colspan === 1) {
r.fieldIndex = index;
// when field is undefined, use index instead
if (typeof r.field === 'undefined') {
r.field = index;
}
}
for (k = 0; k < rowspan; k++) {
flag[i + k][index] = true;
}
for (k = 0; k < colspan; k++) {
flag[i][index + k] = true;
}
}
}
};
var getScrollBarWidth = function () {
if (cachedWidth === null) {
var inner = $('<p/>').addClass('fixed-table-scroll-inner'),
outer = $('<div/>').addClass('fixed-table-scroll-outer'),
w1, w2;
outer.append(inner);
$('body').append(outer);
w1 = inner[0].offsetWidth;
outer.css('overflow', 'scroll');
w2 = inner[0].offsetWidth;
if (w1 === w2) {
w2 = outer[0].clientWidth;
}
outer.remove();
cachedWidth = w1 - w2;
}
return cachedWidth;
};
var calculateObjectValue = function (self, name, args, defaultValue) {
var func = name;
if (typeof name === 'string') {
// support obj.func1.func2
var names = name.split('.');
if (names.length > 1) {
func = window;
$.each(names, function (i, f) {
func = func[f];
});
} else {
func = window[name];
}
}
if (typeof func === 'object') {
return func;
}
if (typeof func === 'function') {
return func.apply(self, args);
}
if (!func && typeof name === 'string' && sprintf.apply(this, [name].concat(args))) {
return sprintf.apply(this, [name].concat(args));
}
return defaultValue;
};
var compareObjects = function (objectA, objectB, compareLength) {
// Create arrays of property names
var objectAProperties = Object.getOwnPropertyNames(objectA),
objectBProperties = Object.getOwnPropertyNames(objectB),
propName = '';
if (compareLength) {
// If number of properties is different, objects are not equivalent
if (objectAProperties.length !== objectBProperties.length) {
return false;
}
}
for (var i = 0; i < objectAProperties.length; i++) {
propName = objectAProperties[i];
// If the property is not in the object B properties, continue with the next property
if ($.inArray(propName, objectBProperties) > -1) {
// If values of same property are not equal, objects are not equivalent
if (objectA[propName] !== objectB[propName]) {
return false;
}
}
}
// If we made it this far, objects are considered equivalent
return true;
};
var escapeHTML = function (text) {
if (typeof text === 'string') {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/`/g, '`');
}
return text;
};
var getRealHeight = function ($el) {
var height = 0;
$el.children().each(function () {
if (height < $(this).outerHeight(true)) {
height = $(this).outerHeight(true);
}
});
return height;
};
var getRealDataAttr = function (dataAttr) {
for (var attr in dataAttr) {
var auxAttr = attr.split(/(?=[A-Z])/).join('-').toLowerCase();
if (auxAttr !== attr) {
dataAttr[auxAttr] = dataAttr[attr];
delete dataAttr[attr];
}
}
return dataAttr;
};
var getItemField = function (item, field, escape) {
var value = item;
if (typeof field !== 'string' || item.hasOwnProperty(field)) {
return escape ? escapeHTML(item[field]) : item[field];
}
var props = field.split('.');
for (var p in props) {
value = value && value[props[p]];
}
return escape ? escapeHTML(value) : value;
};
var isIEBrowser = function () {
return !!(navigator.userAgent.indexOf("MSIE ") > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./));
};
// BOOTSTRAP TABLE CLASS DEFINITION
// ======================
var BootstrapTable = function (el, options) {
this.options = options;
this.$el = $(el);
this.$el_ = this.$el.clone();
this.timeoutId_ = 0;
this.timeoutFooter_ = 0;
this.init();
};
BootstrapTable.DEFAULTS = {
classes: 'table table-hover',
locale: undefined,
height: undefined,
undefinedText: '-',
sortName: undefined,
sortOrder: 'asc',
striped: false,
columns: [[]],
data: [],
dataField: 'rows',
method: 'get',
url: undefined,
ajax: undefined,
cache: true,
contentType: 'application/json',
dataType: 'json',
ajaxOptions: {},
queryParams: function (params) {
return params;
},
queryParamsType: 'limit', // undefined
responseHandler: function (res) {
return res;
},
pagination: false,
onlyInfoPagination: false,
sidePagination: 'client', // client or server
totalRows: 0, // server side need to set
pageNumber: 1,
pageSize: 10,
pageList: [10, 25, 50, 100],
paginationHAlign: 'right', //right, left
paginationVAlign: 'bottom', //bottom, top, both
paginationDetailHAlign: 'left', //right, left
paginationPreText: '‹',
paginationNextText: '›',
search: false,
searchOnEnterKey: false,
strictSearch: false,
searchAlign: 'right',
selectItemName: 'btSelectItem',
showHeader: true,
showFooter: false,
showColumns: false,
showPaginationSwitch: false,
showRefresh: false,
showToggle: false,
buttonsAlign: 'right',
smartDisplay: true,
escape: false,
minimumCountColumns: 1,
idField: undefined,
uniqueId: undefined,
cardView: false,
detailView: false,
detailFormatter: function (index, row) {
return '';
},
trimOnSearch: true,
clickToSelect: false,
singleSelect: false,
toolbar: undefined,
toolbarAlign: 'left',
checkboxHeader: true,
sortable: true,
silentSort: true,
maintainSelected: false,
searchTimeOut: 500,
searchText: '',
iconSize: undefined,
iconsPrefix: 'glyphicon', // glyphicon of fa (font awesome)
icons: {
paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
refresh: 'glyphicon-refresh icon-refresh',
toggle: 'glyphicon-list-alt icon-list-alt',
columns: 'glyphicon-th icon-th',
detailOpen: 'glyphicon-plus icon-plus',
detailClose: 'glyphicon-minus icon-minus'
},
rowStyle: function (row, index) {
return {};
},
rowAttributes: function (row, index) {
return {};
},
onAll: function (name, args) {
return false;
},
onClickCell: function (field, value, row, $element) {
return false;
},
onDblClickCell: function (field, value, row, $element) {
return false;
},
onClickRow: function (item, $element) {
return false;
},
onDblClickRow: function (item, $element) {
return false;
},
onSort: function (name, order) {
return false;
},
onCheck: function (row) {
return false;
},
onUncheck: function (row) {
return false;
},
onCheckAll: function (rows) {
return false;
},
onUncheckAll: function (rows) {
return false;
},
onCheckSome: function (rows) {
return false;
},
onUncheckSome: function (rows) {
return false;
},
onLoadSuccess: function (data) {
return false;
},
onLoadError: function (status) {
return false;
},
onColumnSwitch: function (field, checked) {
return false;
},
onPageChange: function (number, size) {
return false;
},
onSearch: function (text) {
return false;
},
onToggle: function (cardView) {
return false;
},
onPreBody: function (data) {
return false;
},
onPostBody: function () {
return false;
},
onPostHeader: function () {
return false;
},
onExpandRow: function (index, row, $detail) {
return false;
},
onCollapseRow: function (index, row) {
return false;
},
onRefreshOptions: function (options) {
return false;
},
onResetView: function () {
return false;
}
};
BootstrapTable.LOCALES = [];
BootstrapTable.LOCALES['en-US'] = BootstrapTable.LOCALES['en'] = {
formatLoadingMessage: function () {
return 'Loading, please wait...';
},
formatRecordsPerPage: function (pageNumber) {
return sprintf('%s records per page', pageNumber);
},
formatShowingRows: function (pageFrom, pageTo, totalRows) {
return sprintf('Showing %s to %s of %s rows', pageFrom, pageTo, totalRows);
},
formatDetailPagination: function (totalRows) {
return sprintf('Showing %s rows', totalRows);
},
formatSearch: function () {
return 'Search';
},
formatNoMatches: function () {
return 'No rooms currently available';
},
formatPaginationSwitch: function () {
return 'Hide/Show pagination';
},
formatRefresh: function () {
return 'Refresh';
},
formatToggle: function () {
return 'Toggle';
},
formatColumns: function () {
return 'Columns';
},
formatAllRows: function () {
return 'All';
}
};
$.extend(BootstrapTable.DEFAULTS, BootstrapTable.LOCALES['en-US']);
BootstrapTable.COLUMN_DEFAULTS = {
radio: false,
checkbox: false,
checkboxEnabled: true,
field: undefined,
title: undefined,
titleTooltip: undefined,
'class': undefined,
align: undefined, // left, right, center
halign: undefined, // left, right, center
falign: undefined, // left, right, center
valign: undefined, // top, middle, bottom
width: undefined,
sortable: false,
order: 'asc', // asc, desc
visible: true,
switchable: true,
clickToSelect: true,
formatter: undefined,
footerFormatter: undefined,
events: undefined,
sorter: undefined,
sortName: undefined,
cellStyle: undefined,
searchable: true,
searchFormatter: true,
cardVisible: true
};
BootstrapTable.EVENTS = {
'all.bs.table': 'onAll',
'click-cell.bs.table': 'onClickCell',
'dbl-click-cell.bs.table': 'onDblClickCell',
'click-row.bs.table': 'onClickRow',
'dbl-click-row.bs.table': 'onDblClickRow',
'sort.bs.table': 'onSort',
'check.bs.table': 'onCheck',
'uncheck.bs.table': 'onUncheck',
'check-all.bs.table': 'onCheckAll',
'uncheck-all.bs.table': 'onUncheckAll',
'check-some.bs.table': 'onCheckSome',
'uncheck-some.bs.table': 'onUncheckSome',
'load-success.bs.table': 'onLoadSuccess',
'load-error.bs.table': 'onLoadError',
'column-switch.bs.table': 'onColumnSwitch',
'page-change.bs.table': 'onPageChange',
'search.bs.table': 'onSearch',
'toggle.bs.table': 'onToggle',
'pre-body.bs.table': 'onPreBody',
'post-body.bs.table': 'onPostBody',
'post-header.bs.table': 'onPostHeader',
'expand-row.bs.table': 'onExpandRow',
'collapse-row.bs.table': 'onCollapseRow',
'refresh-options.bs.table': 'onRefreshOptions',
'reset-view.bs.table': 'onResetView'
};
BootstrapTable.prototype.init = function () {
this.initLocale();
this.initContainer();
this.initTable();
this.initHeader();
this.initData();
this.initFooter();
this.initToolbar();
this.initPagination();
this.initBody();
this.initSearchText();
this.initServer();
};
BootstrapTable.prototype.initLocale = function () {
if (this.options.locale) {
var parts = this.options.locale.split(/-|_/);
parts[0].toLowerCase();
parts[1] && parts[1].toUpperCase();
if ($.fn.bootstrapTable.locales[this.options.locale]) {
// locale as requested
$.extend(this.options, $.fn.bootstrapTable.locales[this.options.locale]);
} else if ($.fn.bootstrapTable.locales[parts.join('-')]) {
// locale with sep set to - (in case original was specified with _)
$.extend(this.options, $.fn.bootstrapTable.locales[parts.join('-')]);
} else if ($.fn.bootstrapTable.locales[parts[0]]) {
// short locale language code (i.e. 'en')
$.extend(this.options, $.fn.bootstrapTable.locales[parts[0]]);
}
}
};
BootstrapTable.prototype.initContainer = function () {
this.$container = $([
'<div class="bootstrap-table">',
'<div class="fixed-table-toolbar"></div>',
this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both' ?
'<div class="fixed-table-pagination" style="clear: both;"></div>' :
'',
'<div class="fixed-table-container">',
'<div class="fixed-table-header"><table></table></div>',
'<div class="fixed-table-body">',
'<div class="fixed-table-loading">',
this.options.formatLoadingMessage(),
'</div>',
'</div>',
'<div class="fixed-table-footer"><table><tr></tr></table></div>',
this.options.paginationVAlign === 'bottom' || this.options.paginationVAlign === 'both' ?
'<div class="fixed-table-pagination"></div>' :
'',
'</div>',
'</div>'
].join(''));
this.$container.insertAfter(this.$el);
this.$tableContainer = this.$container.find('.fixed-table-container');
this.$tableHeader = this.$container.find('.fixed-table-header');
this.$tableBody = this.$container.find('.fixed-table-body');
this.$tableLoading = this.$container.find('.fixed-table-loading');
this.$tableFooter = this.$container.find('.fixed-table-footer');
this.$toolbar = this.$container.find('.fixed-table-toolbar');
this.$pagination = this.$container.find('.fixed-table-pagination');
this.$tableBody.append(this.$el);
this.$container.after('<div class="clearfix"></div>');
this.$el.addClass(this.options.classes);
if (this.options.striped) {
this.$el.addClass('table-striped');
}
if ($.inArray('table-no-bordered', this.options.classes.split(' ')) !== -1) {
this.$tableContainer.addClass('table-no-bordered');
}
};
BootstrapTable.prototype.initTable = function () {
var that = this,
columns = [],
data = [];
this.$header = this.$el.find('>thead');
if (!this.$header.length) {
this.$header = $('<thead></thead>').appendTo(this.$el);
}
this.$header.find('tr').each(function () {
var column = [];
$(this).find('th').each(function () {
column.push($.extend({}, {
title: $(this).html(),
'class': $(this).attr('class'),
titleTooltip: $(this).attr('title'),
rowspan: $(this).attr('rowspan') ? +$(this).attr('rowspan') : undefined,
colspan: $(this).attr('colspan') ? +$(this).attr('colspan') : undefined
}, $(this).data()));
});
columns.push(column);
});
if (!$.isArray(this.options.columns[0])) {
this.options.columns = [this.options.columns];
}
this.options.columns = $.extend(true, [], columns, this.options.columns);
this.columns = [];
setFieldIndex(this.options.columns);
$.each(this.options.columns, function (i, columns) {
$.each(columns, function (j, column) {
column = $.extend({}, BootstrapTable.COLUMN_DEFAULTS, column);
if (typeof column.fieldIndex !== 'undefined') {
that.columns[column.fieldIndex] = column;
}
that.options.columns[i][j] = column;
});
});
// if options.data is setting, do not process tbody data
if (this.options.data.length) {
return;
}
this.$el.find('>tbody>tr').each(function () {
var row = {};
// save tr's id, class and data-* attributes
row._id = $(this).attr('id');
row._class = $(this).attr('class');
row._data = getRealDataAttr($(this).data());
$(this).find('td').each(function (i) {
var field = that.columns[i].field;
row[field] = $(this).html();
// save td's id, class and data-* attributes
row['_' + field + '_id'] = $(this).attr('id');
row['_' + field + '_class'] = $(this).attr('class');
row['_' + field + '_rowspan'] = $(this).attr('rowspan');
row['_' + field + '_title'] = $(this).attr('title');
row['_' + field + '_data'] = getRealDataAttr($(this).data());
});
data.push(row);
});
this.options.data = data;
};
BootstrapTable.prototype.initHeader = function () {
var that = this,
visibleColumns = {},
html = [];
this.header = {
fields: [],
styles: [],
classes: [],
formatters: [],
events: [],
sorters: [],
sortNames: [],
cellStyles: [],
searchables: []
};
$.each(this.options.columns, function (i, columns) {
html.push('<tr>');
if (i == 0 && !that.options.cardView && that.options.detailView) {
html.push(sprintf('<th class="detail" rowspan="%s"><div class="fht-cell"></div></th>',
that.options.columns.length));
}
$.each(columns, function (j, column) {
var text = '',
halign = '', // header align style
align = '', // body align style
style = '',
class_ = sprintf(' class="%s"', column['class']),
order = that.options.sortOrder || column.order,
unitWidth = 'px',
width = column.width;
if (column.width !== undefined && (!that.options.cardView)) {
if (typeof column.width === 'string') {
if (column.width.indexOf('%') !== -1) {
unitWidth = '%';
}
}
}
if (column.width && typeof column.width === 'string') {
width = column.width.replace('%', '').replace('px', '');
}
halign = sprintf('text-align: %s; ', column.halign ? column.halign : column.align);
align = sprintf('text-align: %s; ', column.align);
style = sprintf('vertical-align: %s; ', column.valign);
style += sprintf('width: %s; ', (column.checkbox || column.radio) && !width ?
'36px' : (width ? width + unitWidth : undefined));
if (typeof column.fieldIndex !== 'undefined') {
that.header.fields[column.fieldIndex] = column.field;
that.header.styles[column.fieldIndex] = align + style;
that.header.classes[column.fieldIndex] = class_;
that.header.formatters[column.fieldIndex] = column.formatter;
that.header.events[column.fieldIndex] = column.events;
that.header.sorters[column.fieldIndex] = column.sorter;
that.header.sortNames[column.fieldIndex] = column.sortName;
that.header.cellStyles[column.fieldIndex] = column.cellStyle;
that.header.searchables[column.fieldIndex] = column.searchable;
if (!column.visible) {
return;
}
if (that.options.cardView && (!column.cardVisible)) {
return;
}
visibleColumns[column.field] = column;
}
html.push('<th' + sprintf(' title="%s"', column.titleTooltip),
column.checkbox || column.radio ?
sprintf(' class="bs-checkbox %s"', column['class'] || '') :
class_,
sprintf(' style="%s"', halign + style),
sprintf(' rowspan="%s"', column.rowspan),
sprintf(' colspan="%s"', column.colspan),
sprintf(' data-field="%s"', column.field),
"tabindex='0'",
'>');
html.push(sprintf('<div class="th-inner %s">', that.options.sortable && column.sortable ?
'sortable both' : ''));
text = column.title;
if (column.checkbox) {
if (!that.options.singleSelect && that.options.checkboxHeader) {
text = '<input name="btSelectAll" type="checkbox" />';
}
that.header.stateField = column.field;
}
if (column.radio) {
text = '';
that.header.stateField = column.field;
that.options.singleSelect = true;
}
html.push(text);
html.push('</div>');
html.push('<div class="fht-cell"></div>');
html.push('</div>');
html.push('</th>');
});
html.push('</tr>');
});
this.$header.html(html.join(''));
this.$header.find('th[data-field]').each(function (i) {
$(this).data(visibleColumns[$(this).data('field')]);
});
this.$container.off('click', '.th-inner').on('click', '.th-inner', function (event) {
var target = $(this);
if (target.closest('.bootstrap-table')[0] !== that.$container[0])
return false;
if (that.options.sortable && target.parent().data().sortable) {
that.onSort(event);
}
});
this.$header.children().children().off('keypress').on('keypress', function (event) {
if (that.options.sortable && $(this).data().sortable) {
var code = event.keyCode || event.which;
if (code == 13) { //Enter keycode
that.onSort(event);
}
}
});
if (!this.options.showHeader || this.options.cardView) {
this.$header.hide();
this.$tableHeader.hide();
this.$tableLoading.css('top', 0);
} else {
this.$header.show();
this.$tableHeader.show();
this.$tableLoading.css('top', this.$header.outerHeight() + 1);
// Assign the correct sortable arrow
this.getCaret();
}
this.$selectAll = this.$header.find('[name="btSelectAll"]');
this.$selectAll.off('click').on('click', function () {
var checked = $(this).prop('checked');
that[checked ? 'checkAll' : 'uncheckAll']();
that.updateSelected();
});
};
BootstrapTable.prototype.initFooter = function () {
if (!this.options.showFooter || this.options.cardView) {
this.$tableFooter.hide();
} else {
this.$tableFooter.show();
}
};
/**
* @param data
* @param type: append / prepend
*/
BootstrapTable.prototype.initData = function (data, type) {
if (type === 'append') {
this.data = this.data.concat(data);
} else if (type === 'prepend') {
this.data = [].concat(data).concat(this.data);
} else {
this.data = data || this.options.data;
}
// Fix #839 Records deleted when adding new row on filtered table
if (type === 'append') {
this.options.data = this.options.data.concat(data);
} else if (type === 'prepend') {
this.options.data = [].concat(data).concat(this.options.data);
} else {
this.options.data = this.data;
}
if (this.options.sidePagination === 'server') {
return;
}
this.initSort();
};
BootstrapTable.prototype.initSort = function () {
var that = this,
name = this.options.sortName,
order = this.options.sortOrder === 'desc' ? -1 : 1,
index = $.inArray(this.options.sortName, this.header.fields);
if (index !== -1) {
this.data.sort(function (a, b) {
if (that.header.sortNames[index]) {
name = that.header.sortNames[index];
}
var aa = getItemField(a, name, that.options.escape),
bb = getItemField(b, name, that.options.escape),
value = calculateObjectValue(that.header, that.header.sorters[index], [aa, bb]);
if (value !== undefined) {
return order * value;
}
// Fix #161: undefined or null string sort bug.
if (aa === undefined || aa === null) {
aa = '';
}
if (bb === undefined || bb === null) {
bb = '';
}
// IF both values are numeric, do a numeric comparison
if ($.isNumeric(aa) && $.isNumeric(bb)) {
// Convert numerical values form string to float.
aa = parseFloat(aa);
bb = parseFloat(bb);
if (aa < bb) {
return order * -1;
}
return order;
}
if (aa === bb) {
return 0;
}
// If value is not a string, convert to string
if (typeof aa !== 'string') {
aa = aa.toString();
}
if (aa.localeCompare(bb) === -1) {
return order * -1;
}
return order;
});
}
};
BootstrapTable.prototype.onSort = function (event) {
var $this = event.type === "keypress" ? $(event.currentTarget) : $(event.currentTarget).parent(),
$this_ = this.$header.find('th').eq($this.index());
this.$header.add(this.$header_).find('span.order').remove();
if (this.options.sortName === $this.data('field')) {
this.options.sortOrder = this.options.sortOrder === 'asc' ? 'desc' : 'asc';
} else {
this.options.sortName = $this.data('field');
this.options.sortOrder = $this.data('order') === 'asc' ? 'desc' : 'asc';
}
this.trigger('sort', this.options.sortName, this.options.sortOrder);
$this.add($this_).data('order', this.options.sortOrder);
// Assign the correct sortable arrow
this.getCaret();
if (this.options.sidePagination === 'server') {
this.initServer(this.options.silentSort);
return;
}
this.initSort();
this.initBody();
};
BootstrapTable.prototype.initToolbar = function () {
var that = this,
html = [],
timeoutId = 0,
$keepOpen,
$search,
switchableCount = 0;
if (this.$toolbar.find('.bars').children().length) {
$('body').append($(this.options.toolbar));
}
this.$toolbar.html('');
if (typeof this.options.toolbar === 'string' || typeof this.options.toolbar === 'object') {
$(sprintf('<div class="bars pull-%s"></div>', this.options.toolbarAlign))
.appendTo(this.$toolbar)
.append($(this.options.toolbar));
}
// showColumns, showToggle, showRefresh
html = [sprintf('<div class="columns columns-%s btn-group pull-%s">',
this.options.buttonsAlign, this.options.buttonsAlign)];
if (typeof this.options.icons === 'string') {
this.options.icons = calculateObjectValue(null, this.options.icons);
}
if (this.options.showPaginationSwitch) {
html.push(sprintf('<button class="btn btn-default" type="button" name="paginationSwitch" title="%s">',
this.options.formatPaginationSwitch()),
sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.paginationSwitchDown),
'</button>');
}
if (this.options.showRefresh) {
html.push(sprintf('<button class="btn btn-default' +
sprintf(' btn-%s', this.options.iconSize) +
'" type="button" name="refresh" title="%s">',
this.options.formatRefresh()),
sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.refresh),
'</button>');
}
if (this.options.showToggle) {
html.push(sprintf('<button class="btn btn-default' +
sprintf(' btn-%s', this.options.iconSize) +
'" type="button" name="toggle" title="%s">',
this.options.formatToggle()),
sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.toggle),
'</button>');
}
if (this.options.showColumns) {
html.push(sprintf('<div class="keep-open btn-group" title="%s">',
this.options.formatColumns()),
'<button type="button" class="btn btn-default' +
sprintf(' btn-%s', this.options.iconSize) +
' dropdown-toggle" data-toggle="dropdown">',
sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.columns),
' <span class="caret"></span>',
'</button>',
'<ul class="dropdown-menu" role="menu">');
$.each(this.columns, function (i, column) {
if (column.radio || column.checkbox) {
return;
}
if (that.options.cardView && (!column.cardVisible)) {
return;
}
var checked = column.visible ? ' checked="checked"' : '';
if (column.switchable) {
html.push(sprintf('<li>' +
'<label><input type="checkbox" data-field="%s" value="%s"%s> %s</label>' +
'</li>', column.field, i, checked, column.title));
switchableCount++;
}
});
html.push('</ul>',
'</div>');
}
html.push('</div>');
// Fix #188: this.showToolbar is for extensions
if (this.showToolbar || html.length > 2) {
this.$toolbar.append(html.join(''));
}
if (this.options.showPaginationSwitch) {
this.$toolbar.find('button[name="paginationSwitch"]')
.off('click').on('click', $.proxy(this.togglePagination, this));
}
if (this.options.showRefresh) {
this.$toolbar.find('button[name="refresh"]')
.off('click').on('click', $.proxy(this.refresh, this));
}
if (this.options.showToggle) {
this.$toolbar.find('button[name="toggle"]')
.off('click').on('click', function () {
that.toggleView();
});
}
if (this.options.showColumns) {
$keepOpen = this.$toolbar.find('.keep-open');
if (switchableCount <= this.options.minimumCountColumns) {
$keepOpen.find('input').prop('disabled', true);
}
$keepOpen.find('li').off('click').on('click', function (event) {
event.stopImmediatePropagation();
});
$keepOpen.find('input').off('click').on('click', function () {
var $this = $(this);
that.toggleColumn(getFieldIndex(that.columns,
$(this).data('field')), $this.prop('checked'), false);
that.trigger('column-switch', $(this).data('field'), $this.prop('checked'));
});
}
if (this.options.search) {
html = [];
html.push(
'<div class="pull-' + this.options.searchAlign + ' search">',
sprintf('<input class="form-control' +
sprintf(' input-%s', this.options.iconSize) +
'" type="text" placeholder="%s">',
this.options.formatSearch()),
'</div>');
this.$toolbar.append(html.join(''));
$search = this.$toolbar.find('.search input');
$search.off('keyup drop').on('keyup drop', function (event) {
if (that.options.searchOnEnterKey) {
if (event.keyCode !== 13) {
return;
}
}
clearTimeout(timeoutId); // doesn't matter if it's 0
timeoutId = setTimeout(function () {
that.onSearch(event);
}, that.options.searchTimeOut);
});
if (isIEBrowser()) {
$search.off('mouseup').on('mouseup', function (event) {
clearTimeout(timeoutId); // doesn't matter if it's 0
timeoutId = setTimeout(function () {
that.onSearch(event);
}, that.options.searchTimeOut);
});
}
}
};
BootstrapTable.prototype.onSearch = function (event) {
var text = $.trim($(event.currentTarget).val());
// trim search input
if (this.options.trimOnSearch && $(event.currentTarget).val() !== text) {
$(event.currentTarget).val(text);
}
if (text === this.searchText) {
return;
}
this.searchText = text;
this.options.searchText = text;
this.options.pageNumber = 1;
this.initSearch();
this.updatePagination();
this.trigger('search', text);
};
BootstrapTable.prototype.initSearch = function () {
var that = this;
if (this.options.sidePagination !== 'server') {
var s = this.searchText && this.searchText.toLowerCase();
var f = $.isEmptyObject(this.filterColumns) ? null : this.filterColumns;
// Check filter
this.data = f ? $.grep(this.options.data, function (item, i) {
for (var key in f) {
if ($.isArray(f[key])) {
if ($.inArray(item[key], f[key]) === -1) {
return false;
}
} else if (item[key] !== f[key]) {
return false;
}
}
return true;
}) : this.options.data;
this.data = s ? $.grep(this.data, function (item, i) {
for (var key in item) {
key = $.isNumeric(key) ? parseInt(key, 10) : key;
var value = item[key],
column = that.columns[getFieldIndex(that.columns, key)],
j = $.inArray(key, that.header.fields);
// Fix #142: search use formatted data
if (column && column.searchFormatter) {
value = calculateObjectValue(column,
that.header.formatters[j], [value, item, i], value);
}
var index = $.inArray(key, that.header.fields);
if (index !== -1 && that.header.searchables[index] && (typeof value === 'string' || typeof value === 'number')) {
if (that.options.strictSearch) {
if ((value + '').toLowerCase() === s) {
return true;
}
} else {
if ((value + '').toLowerCase().indexOf(s) !== -1) {
return true;
}
}
}
}
return false;
}) : this.data;
}
};
BootstrapTable.prototype.initPagination = function () {
if (!this.options.pagination) {
this.$pagination.hide();
return;
} else {
this.$pagination.show();
}
var that = this,
html = [],
$allSelected = false,
i, from, to,
$pageList,
$first, $pre,
$next, $last,
$number,
data = this.getData();
if (this.options.sidePagination !== 'server') {
this.options.totalRows = data.length;
}
this.totalPages = 0;
if (this.options.totalRows) {
if (this.options.pageSize === this.options.formatAllRows()) {
this.options.pageSize = this.options.totalRows;
$allSelected = true;
} else if (this.options.pageSize === this.options.totalRows) {
// Fix #667 Table with pagination,
// multiple pages and a search that matches to one page throws exception
var pageLst = typeof this.options.pageList === 'string' ?
this.options.pageList.replace('[', '').replace(']', '')
.replace(/ /g, '').toLowerCase().split(',') : this.options.pageList;
if ($.inArray(this.options.formatAllRows().toLowerCase(), pageLst) > -1) {
$allSelected = true;
}
}
this.totalPages = ~~((this.options.totalRows - 1) / this.options.pageSize) + 1;
this.options.totalPages = this.totalPages;
}
if (this.totalPages > 0 && this.options.pageNumber > this.totalPages) {
this.options.pageNumber = this.totalPages;
}
this.pageFrom = (this.options.pageNumber - 1) * this.options.pageSize + 1;
this.pageTo = this.options.pageNumber * this.options.pageSize;
if (this.pageTo > this.options.totalRows) {
this.pageTo = this.options.totalRows;
}
html.push(
'<div class="pull-' + this.options.paginationDetailHAlign + ' pagination-detail">',
'<span class="pagination-info">',
this.options.onlyInfoPagination ? this.options.formatDetailPagination(this.options.totalRows) :
this.options.formatShowingRows(this.pageFrom, this.pageTo, this.options.totalRows),
'</span>');
if (!this.options.onlyInfoPagination) {
html.push('<span class="page-list">');
var pageNumber = [
sprintf('<span class="btn-group %s">',
this.options.paginationVAlign === 'top' || this.options.paginationVAlign === 'both' ?
'dropdown' : 'dropup'),
'<button type="button" class="btn btn-default ' +
sprintf(' btn-%s', this.options.iconSize) +
' dropdown-toggle" data-toggle="dropdown">',
'<span class="page-size">',
$allSelected ? this.options.formatAllRows() : this.options.pageSize,
'</span>',
' <span class="caret"></span>',
'</button>',
'<ul class="dropdown-menu" role="menu">'
],
pageList = this.options.pageList;
if (typeof this.options.pageList === 'string') {
var list = this.options.pageList.replace('[', '').replace(']', '')
.replace(/ /g, '').split(',');
pageList = [];
$.each(list, function (i, value) {
pageList.push(value.toUpperCase() === that.options.formatAllRows().toUpperCase() ?
that.options.formatAllRows() : +value);
});
}
$.each(pageList, function (i, page) {
if (!that.options.smartDisplay || i === 0 || pageList[i - 1] <= that.options.totalRows) {
var active;
if ($allSelected) {
active = page === that.options.formatAllRows() ? ' class="active"' : '';
} else {
active = page === that.options.pageSize ? ' class="active"' : '';
}
pageNumber.push(sprintf('<li%s><a href="javascript:void(0)">%s</a></li>', active, page));
}
});
pageNumber.push('</ul></span>');
html.push(this.options.formatRecordsPerPage(pageNumber.join('')));
html.push('</span>');
html.push('</div>',
'<div class="pull-' + this.options.paginationHAlign + ' pagination">',
'<ul class="pagination' + sprintf(' pagination-%s', this.options.iconSize) + '">',
'<li class="page-pre"><a href="javascript:void(0)">' + this.options.paginationPreText + '</a></li>');
if (this.totalPages < 5) {
from = 1;
to = this.totalPages;
} else {
from = this.options.pageNumber - 2;
to = from + 4;
if (from < 1) {
from = 1;
to = 5;
}
if (to > this.totalPages) {
to = this.totalPages;
from = to - 4;
}
}
if (this.totalPages >= 6) {
if (this.options.pageNumber >= 3) {
html.push('<li class="page-first' + (1 === this.options.pageNumber ? ' active' : '') + '">',
'<a href="javascript:void(0)">', 1, '</a>',
'</li>');
from++;
}
if (this.options.pageNumber >= 4) {
if (this.options.pageNumber == 4 || this.totalPages == 6 || this.totalPages == 7) {
from--;
} else {
html.push('<li class="page-first-separator disabled">',
'<a href="javascript:void(0)">...</a>',
'</li>');
}
to--;
}
}
if (this.totalPages >= 7) {
if (this.options.pageNumber >= (this.totalPages - 2)) {
from--;
}
}
if (this.totalPages == 6) {
if (this.options.pageNumber >= (this.totalPages - 2)) {
to++;
}
} else if (this.totalPages >= 7) {
if (this.totalPages == 7 || this.options.pageNumber >= (this.totalPages - 3)) {
to++;
}
}
for (i = from; i <= to; i++) {
html.push('<li class="page-number' + (i === this.options.pageNumber ? ' active' : '') + '">',
'<a href="javascript:void(0)">', i, '</a>',
'</li>');
}
if (this.totalPages >= 8) {
if (this.options.pageNumber <= (this.totalPages - 4)) {
html.push('<li class="page-last-separator disabled">',
'<a href="javascript:void(0)">...</a>',
'</li>');
}
}
if (this.totalPages >= 6) {
if (this.options.pageNumber <= (this.totalPages - 3)) {
html.push('<li class="page-last' + (this.totalPages === this.options.pageNumber ? ' active' : '') + '">',
'<a href="javascript:void(0)">', this.totalPages, '</a>',
'</li>');
}
}
html.push(
'<li class="page-next"><a href="javascript:void(0)">' + this.options.paginationNextText + '</a></li>',
'</ul>',
'</div>');
}
this.$pagination.html(html.join(''));
if (!this.options.onlyInfoPagination) {
$pageList = this.$pagination.find('.page-list a');
$first = this.$pagination.find('.page-first');
$pre = this.$pagination.find('.page-pre');
$next = this.$pagination.find('.page-next');
$last = this.$pagination.find('.page-last');
$number = this.$pagination.find('.page-number');
if (this.options.smartDisplay) {
if (this.totalPages <= 1) {
this.$pagination.find('div.pagination').hide();
}
if (pageList.length < 2 || this.options.totalRows <= pageList[0]) {
this.$pagination.find('span.page-list').hide();
}
// when data is empty, hide the pagination
this.$pagination[this.getData().length ? 'show' : 'hide']();
}
if ($allSelected) {
this.options.pageSize = this.options.formatAllRows();
}
$pageList.off('click').on('click', $.proxy(this.onPageListChange, this));
$first.off('click').on('click', $.proxy(this.onPageFirst, this));
$pre.off('click').on('click', $.proxy(this.onPagePre, this));
$next.off('click').on('click', $.proxy(this.onPageNext, this));
$last.off('click').on('click', $.proxy(this.onPageLast, this));
$number.off('click').on('click', $.proxy(this.onPageNumber, this));
}
};
BootstrapTable.prototype.updatePagination = function (event) {
// Fix #171: IE disabled button can be clicked bug.
if (event && $(event.currentTarget).hasClass('disabled')) {
return;
}
if (!this.options.maintainSelected) {
this.resetRows();
}
this.initPagination();
if (this.options.sidePagination === 'server') {
this.initServer();
} else {
this.initBody();
}
this.trigger('page-change', this.options.pageNumber, this.options.pageSize);
};
BootstrapTable.prototype.onPageListChange = function (event) {
var $this = $(event.currentTarget);
$this.parent().addClass('active').siblings().removeClass('active');
this.options.pageSize = $this.text().toUpperCase() === this.options.formatAllRows().toUpperCase() ?
this.options.formatAllRows() : +$this.text();
this.$toolbar.find('.page-size').text(this.options.pageSize);
this.updatePagination(event);
};
BootstrapTable.prototype.onPageFirst = function (event) {
this.options.pageNumber = 1;
this.updatePagination(event);
};
BootstrapTable.prototype.onPagePre = function (event) {
if ((this.options.pageNumber - 1) == 0) {
this.options.pageNumber = this.options.totalPages;
} else {
this.options.pageNumber--;
}
this.updatePagination(event);
};
BootstrapTable.prototype.onPageNext = function (event) {
if ((this.options.pageNumber + 1) > this.options.totalPages) {
this.options.pageNumber = 1;
} else {
this.options.pageNumber++;
}
this.updatePagination(event);
};
BootstrapTable.prototype.onPageLast = function (event) {
this.options.pageNumber = this.totalPages;
this.updatePagination(event);
};
BootstrapTable.prototype.onPageNumber = function (event) {
if (this.options.pageNumber === +$(event.currentTarget).text()) {
return;
}
this.options.pageNumber = +$(event.currentTarget).text();
this.updatePagination(event);
};
BootstrapTable.prototype.initBody = function (fixedScroll) {
var that = this,
html = [],
data = this.getData();
this.trigger('pre-body', data);
this.$body = this.$el.find('>tbody');
if (!this.$body.length) {
this.$body = $('<tbody></tbody>').appendTo(this.$el);
}
//Fix #389 Bootstrap-table-flatJSON is not working
if (!this.options.pagination || this.options.sidePagination === 'server') {
this.pageFrom = 1;
this.pageTo = data.length;
}
for (var i = this.pageFrom - 1; i < this.pageTo; i++) {
var key,
item = data[i],
style = {},
csses = [],
data_ = '',
attributes = {},
htmlAttributes = [];
style = calculateObjectValue(this.options, this.options.rowStyle, [item, i], style);
if (style && style.css) {
for (key in style.css) {
csses.push(key + ': ' + style.css[key]);
}
}
attributes = calculateObjectValue(this.options,
this.options.rowAttributes, [item, i], attributes);
if (attributes) {
for (key in attributes) {
htmlAttributes.push(sprintf('%s="%s"', key, escapeHTML(attributes[key])));
}
}
if (item._data && !$.isEmptyObject(item._data)) {
$.each(item._data, function (k, v) {
// ignore data-index
if (k === 'index') {
return;
}
data_ += sprintf(' data-%s="%s"', k, v);
});
}
html.push('<tr',
sprintf(' %s', htmlAttributes.join(' ')),
sprintf(' id="%s"', $.isArray(item) ? undefined : item._id),
sprintf(' class="%s"', style.classes || ($.isArray(item) ? undefined : item._class)),
sprintf(' data-index="%s"', i),
sprintf(' data-uniqueid="%s"', item[this.options.uniqueId]),
sprintf('%s', data_),
'>'
);
if (this.options.cardView) {
html.push(sprintf('<td colspan="%s">', this.header.fields.length));
}
if (!this.options.cardView && this.options.detailView) {
html.push('<td>',
'<a class="detail-icon" href="javascript:">',
sprintf('<i class="%s %s"></i>', this.options.iconsPrefix, this.options.icons.detailOpen),
'</a>',
'</td>');
}
$.each(this.header.fields, function (j, field) {
var text = '',
value = getItemField(item, field, that.options.escape),
type = '',
cellStyle = {},
id_ = '',
class_ = that.header.classes[j],
data_ = '',
rowspan_ = '',
title_ = '',
column = that.columns[getFieldIndex(that.columns, field)];
if (!column.visible) {
return;
}
style = sprintf('style="%s"', csses.concat(that.header.styles[j]).join('; '));
value = calculateObjectValue(column,
that.header.formatters[j], [value, item, i], value);
// handle td's id and class
if (item['_' + field + '_id']) {
id_ = sprintf(' id="%s"', item['_' + field + '_id']);
}
if (item['_' + field + '_class']) {
class_ = sprintf(' class="%s"', item['_' + field + '_class']);
}
if (item['_' + field + '_rowspan']) {
rowspan_ = sprintf(' rowspan="%s"', item['_' + field + '_rowspan']);
}
if (item['_' + field + '_title']) {
title_ = sprintf(' title="%s"', item['_' + field + '_title']);
}
cellStyle = calculateObjectValue(that.header,
that.header.cellStyles[j], [value, item, i], cellStyle);
if (cellStyle.classes) {
class_ = sprintf(' class="%s"', cellStyle.classes);
}
if (cellStyle.css) {
var csses_ = [];
for (var key in cellStyle.css) {
csses_.push(key + ': ' + cellStyle.css[key]);
}
style = sprintf('style="%s"', csses_.concat(that.header.styles[j]).join('; '));
}
if (item['_' + field + '_data'] && !$.isEmptyObject(item['_' + field + '_data'])) {
$.each(item['_' + field + '_data'], function (k, v) {
// ignore data-index
if (k === 'index') {
return;
}
data_ += sprintf(' data-%s="%s"', k, v);
});
}
if (column.checkbox || column.radio) {
type = column.checkbox ? 'checkbox' : type;
type = column.radio ? 'radio' : type;
text = [sprintf(that.options.cardView ?
'<div class="card-view %s">' : '<td class="bs-checkbox %s">', column['class'] || ''),
'<input' +
sprintf(' data-index="%s"', i) +
sprintf(' name="%s"', that.options.selectItemName) +
sprintf(' type="%s"', type) +
sprintf(' value="%s"', item[that.options.idField]) +
sprintf(' checked="%s"', value === true ||
(value && value.checked) ? 'checked' : undefined) +
sprintf(' disabled="%s"', !column.checkboxEnabled ||
(value && value.disabled) ? 'disabled' : undefined) +
' />',
that.header.formatters[j] && typeof value === 'string' ? value : '',
that.options.cardView ? '</div>' : '</td>'
].join('');
item[that.header.stateField] = value === true || (value && value.checked);
} else {
value = typeof value === 'undefined' || value === null ?
that.options.undefinedText : value;
text = that.options.cardView ? ['<div class="card-view">',
that.options.showHeader ? sprintf('<span class="title" %s>%s</span>', style,
getPropertyFromOther(that.columns, 'field', 'title', field)) : '',
sprintf('<span class="value">%s</span>', value),
'</div>'
].join('') : [sprintf('<td%s %s %s %s %s %s>', id_, class_, style, data_, rowspan_, title_),
value,
'</td>'
].join('');
// Hide empty data on Card view when smartDisplay is set to true.
if (that.options.cardView && that.options.smartDisplay && value === '') {
// Should set a placeholder for event binding correct fieldIndex
text = '<div class="card-view"></div>';
}
}
html.push(text);
});
if (this.options.cardView) {
html.push('</td>');
}
html.push('</tr>');
}
// show no records
if (!html.length) {
html.push('<tr class="no-records-found">',
sprintf('<td colspan="%s">%s</td>',
this.$header.find('th').length, this.options.formatNoMatches()),
'</tr>');
}
this.$body.html(html.join(''));
if (!fixedScroll) {
this.scrollTo(0);
}
// click to select by column
this.$body.find('> tr[data-index] > td').off('click dblclick').on('click dblclick', function (e) {
var $td = $(this),
$tr = $td.parent(),
item = that.data[$tr.data('index')],
index = $td[0].cellIndex,
field = that.header.fields[that.options.detailView && !that.options.cardView ? index - 1 : index],
column = that.columns[getFieldIndex(that.columns, field)],
value = getItemField(item, field, that.options.escape);
if ($td.find('.detail-icon').length) {
return;
}
that.trigger(e.type === 'click' ? 'click-cell' : 'dbl-click-cell', field, value, item, $td);
that.trigger(e.type === 'click' ? 'click-row' : 'dbl-click-row', item, $tr);
// if click to select - then trigger the checkbox/radio click
if (e.type === 'click' && that.options.clickToSelect && column.clickToSelect) {
var $selectItem = $tr.find(sprintf('[name="%s"]', that.options.selectItemName));
if ($selectItem.length) {
$selectItem[0].click(); // #144: .trigger('click') bug
}
}
});
this.$body.find('> tr[data-index] > td > .detail-icon').off('click').on('click', function () {
var $this = $(this),
$tr = $this.parent().parent(),
index = $tr.data('index'),
row = data[index]; // Fix #980 Detail view, when searching, returns wrong row
// remove and update
if ($tr.next().is('tr.detail-view')) {
$this.find('i').attr('class', sprintf('%s %s', that.options.iconsPrefix, that.options.icons.detailOpen));
$tr.next().remove();
that.trigger('collapse-row', index, row);
} else {
$this.find('i').attr('class', sprintf('%s %s', that.options.iconsPrefix, that.options.icons.detailClose));
$tr.after(sprintf('<tr class="detail-view"><td colspan="%s"></td></tr>', $tr.find('td').length));
var $element = $tr.next().find('td');
var content = calculateObjectValue(that.options, that.options.detailFormatter, [index, row, $element], '');
if($element.length === 1) {
$element.append(content);
}
that.trigger('expand-row', index, row, $element);
}
that.resetView();
});
this.$selectItem = this.$body.find(sprintf('[name="%s"]', this.options.selectItemName));
this.$selectItem.off('click').on('click', function (event) {
event.stopImmediatePropagation();
var $this = $(this),
checked = $this.prop('checked'),
row = that.data[$this.data('index')];
if (that.options.maintainSelected && $(this).is(':radio')) {
$.each(that.options.data, function (i, row) {
row[that.header.stateField] = false;
});
}
row[that.header.stateField] = checked;
if (that.options.singleSelect) {
that.$selectItem.not(this).each(function () {
that.data[$(this).data('index')][that.header.stateField] = false;
});
that.$selectItem.filter(':checked').not(this).prop('checked', false);
}
that.updateSelected();
that.trigger(checked ? 'check' : 'uncheck', row, $this);
});
$.each(this.header.events, function (i, events) {
if (!events) {
return;
}
// fix bug, if events is defined with namespace
if (typeof events === 'string') {
events = calculateObjectValue(null, events);
}
var field = that.header.fields[i],
fieldIndex = $.inArray(field, that.getVisibleFields());
if (that.options.detailView && !that.options.cardView) {
fieldIndex += 1;
}
for (var key in events) {
that.$body.find('>tr:not(.no-records-found)').each(function () {
var $tr = $(this),
$td = $tr.find(that.options.cardView ? '.card-view' : 'td').eq(fieldIndex),
index = key.indexOf(' '),
name = key.substring(0, index),
el = key.substring(index + 1),
func = events[key];
$td.find(el).off(name).on(name, function (e) {
var index = $tr.data('index'),
row = that.data[index],
value = row[field];
func.apply(this, [e, value, row, index]);
});
});
}
});
this.updateSelected();
this.resetView();
this.trigger('post-body');
};
BootstrapTable.prototype.initServer = function (silent, query) {
var that = this,
data = {},
params = {
searchText: this.searchText,
sortName: this.options.sortName,
sortOrder: this.options.sortOrder
},
request;
if(this.options.pagination) {
params.pageSize = this.options.pageSize === this.options.formatAllRows() ?
this.options.totalRows : this.options.pageSize;
params.pageNumber = this.options.pageNumber;
}
if (!this.options.url && !this.options.ajax) {
return;
}
if (this.options.queryParamsType === 'limit') {
params = {
search: params.searchText,
sort: params.sortName,
order: params.sortOrder
};
if (this.options.pagination) {
params.limit = this.options.pageSize === this.options.formatAllRows() ?
this.options.totalRows : this.options.pageSize;
params.offset = this.options.pageSize === this.options.formatAllRows() ?
0 : this.options.pageSize * (this.options.pageNumber - 1);
}
}
if (!($.isEmptyObject(this.filterColumnsPartial))) {
params['filter'] = JSON.stringify(this.filterColumnsPartial, null);
}
data = calculateObjectValue(this.options, this.options.queryParams, [params], data);
$.extend(data, query || {});
// false to stop request
if (data === false) {
return;
}
if (!silent) {
this.$tableLoading.show();
}
request = $.extend({}, calculateObjectValue(null, this.options.ajaxOptions), {
type: this.options.method,
url: this.options.url,
data: this.options.contentType === 'application/json' && this.options.method === 'post' ?
JSON.stringify(data) : data,
cache: this.options.cache,
contentType: this.options.contentType,
dataType: this.options.dataType,
success: function (res) {
res = calculateObjectValue(that.options, that.options.responseHandler, [res], res);
that.load(res);
that.trigger('load-success', res);
if (!silent) that.$tableLoading.hide();
},
error: function (res) {
that.trigger('load-error', res.status, res);
if (!silent) that.$tableLoading.hide();
}
});
if (this.options.ajax) {
calculateObjectValue(this, this.options.ajax, [request], null);
} else {
$.ajax(request);
}
};
BootstrapTable.prototype.initSearchText = function () {
if (this.options.search) {
if (this.options.searchText !== '') {
var $search = this.$toolbar.find('.search input');
$search.val(this.options.searchText);
this.onSearch({currentTarget: $search});
}
}
};
BootstrapTable.prototype.getCaret = function () {
var that = this;
$.each(this.$header.find('th'), function (i, th) {
$(th).find('.sortable').removeClass('desc asc').addClass($(th).data('field') === that.options.sortName ? that.options.sortOrder : 'both');
});
};
BootstrapTable.prototype.updateSelected = function () {
var checkAll = this.$selectItem.filter(':enabled').length &&
this.$selectItem.filter(':enabled').length ===
this.$selectItem.filter(':enabled').filter(':checked').length;
this.$selectAll.add(this.$selectAll_).prop('checked', checkAll);
this.$selectItem.each(function () {
$(this).closest('tr')[$(this).prop('checked') ? 'addClass' : 'removeClass']('selected');
});
};
BootstrapTable.prototype.updateRows = function () {
var that = this;
this.$selectItem.each(function () {
that.data[$(this).data('index')][that.header.stateField] = $(this).prop('checked');
});
};
BootstrapTable.prototype.resetRows = function () {
var that = this;
$.each(this.data, function (i, row) {
that.$selectAll.prop('checked', false);
that.$selectItem.prop('checked', false);
if (that.header.stateField) {
row[that.header.stateField] = false;
}
});
};
BootstrapTable.prototype.trigger = function (name) {
var args = Array.prototype.slice.call(arguments, 1);
name += '.bs.table';
this.options[BootstrapTable.EVENTS[name]].apply(this.options, args);
this.$el.trigger($.Event(name), args);
this.options.onAll(name, args);
this.$el.trigger($.Event('all.bs.table'), [name, args]);
};
BootstrapTable.prototype.resetHeader = function () {
// fix #61: the hidden table reset header bug.
// fix bug: get $el.css('width') error sometime (height = 500)
clearTimeout(this.timeoutId_);
this.timeoutId_ = setTimeout($.proxy(this.fitHeader, this), this.$el.is(':hidden') ? 100 : 0);
};
BootstrapTable.prototype.fitHeader = function () {
var that = this,
fixedBody,
scrollWidth,
focused,
focusedTemp;
if (that.$el.is(':hidden')) {
that.timeoutId_ = setTimeout($.proxy(that.fitHeader, that), 100);
return;
}
fixedBody = this.$tableBody.get(0);
scrollWidth = fixedBody.scrollWidth > fixedBody.clientWidth &&
fixedBody.scrollHeight > fixedBody.clientHeight + this.$header.outerHeight() ?
getScrollBarWidth() : 0;
this.$el.css('margin-top', -this.$header.outerHeight());
focused = $(':focus');
if (focused.length > 0) {
var $th = focused.parents('th');
if ($th.length > 0) {
var dataField = $th.attr('data-field');
if (dataField !== undefined) {
var $headerTh = this.$header.find("[data-field='" + dataField + "']");
if ($headerTh.length > 0) {
$headerTh.find(":input").addClass("focus-temp");
}
}
}
}
this.$header_ = this.$header.clone(true, true);
this.$selectAll_ = this.$header_.find('[name="btSelectAll"]');
this.$tableHeader.css({
'margin-right': scrollWidth
}).find('table').css('width', this.$el.outerWidth())
.html('').attr('class', this.$el.attr('class'))
.append(this.$header_);
focusedTemp = $('.focus-temp:visible:eq(0)');
if (focusedTemp.length > 0) {
focusedTemp.focus();
this.$header.find('.focus-temp').removeClass('focus-temp');
}
// fix bug: $.data() is not working as expected after $.append()
this.$header.find('th[data-field]').each(function (i) {
that.$header_.find(sprintf('th[data-field="%s"]', $(this).data('field'))).data($(this).data());
});
var visibleFields = this.getVisibleFields();
this.$body.find('>tr:first-child:not(.no-records-found) > *').each(function (i) {
var $this = $(this),
index = i;
if (that.options.detailView && !that.options.cardView) {
if (i === 0) {
that.$header_.find('th.detail').find('.fht-cell').width($this.innerWidth());
}
index = i - 1;
}
that.$header_.find(sprintf('th[data-field="%s"]', visibleFields[index]))
.find('.fht-cell').width($this.innerWidth());
});
// horizontal scroll event
// TODO: it's probably better improving the layout than binding to scroll event
this.$tableBody.off('scroll').on('scroll', function () {
that.$tableHeader.scrollLeft($(this).scrollLeft());
if (that.options.showFooter && !that.options.cardView) {
that.$tableFooter.scrollLeft($(this).scrollLeft());
}
});
that.trigger('post-header');
};
BootstrapTable.prototype.resetFooter = function () {
var that = this,
data = that.getData(),
html = [];
if (!this.options.showFooter || this.options.cardView) { //do nothing
return;
}
if (!this.options.cardView && this.options.detailView) {
html.push('<td><div class="th-inner"> </div><div class="fht-cell"></div></td>');
}
$.each(this.columns, function (i, column) {
var falign = '', // footer align style
style = '',
class_ = sprintf(' class="%s"', column['class']);
if (!column.visible) {
return;
}
if (that.options.cardView && (!column.cardVisible)) {
return;
}
falign = sprintf('text-align: %s; ', column.falign ? column.falign : column.align);
style = sprintf('vertical-align: %s; ', column.valign);
html.push('<td', class_, sprintf(' style="%s"', falign + style), '>');
html.push('<div class="th-inner">');
html.push(calculateObjectValue(column, column.footerFormatter, [data], ' ') || ' ');
html.push('</div>');
html.push('<div class="fht-cell"></div>');
html.push('</div>');
html.push('</td>');
});
this.$tableFooter.find('tr').html(html.join(''));
clearTimeout(this.timeoutFooter_);
this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this),
this.$el.is(':hidden') ? 100 : 0);
};
BootstrapTable.prototype.fitFooter = function () {
var that = this,
$footerTd,
elWidth,
scrollWidth;
clearTimeout(this.timeoutFooter_);
if (this.$el.is(':hidden')) {
this.timeoutFooter_ = setTimeout($.proxy(this.fitFooter, this), 100);
return;
}
elWidth = this.$el.css('width');
scrollWidth = elWidth > this.$tableBody.width() ? getScrollBarWidth() : 0;
this.$tableFooter.css({
'margin-right': scrollWidth
}).find('table').css('width', elWidth)
.attr('class', this.$el.attr('class'));
$footerTd = this.$tableFooter.find('td');
this.$body.find('>tr:first-child:not(.no-records-found) > *').each(function (i) {
var $this = $(this);
$footerTd.eq(i).find('.fht-cell').width($this.innerWidth());
});
};
BootstrapTable.prototype.toggleColumn = function (index, checked, needUpdate) {
if (index === -1) {
return;
}
this.columns[index].visible = checked;
this.initHeader();
this.initSearch();
this.initPagination();
this.initBody();
if (this.options.showColumns) {
var $items = this.$toolbar.find('.keep-open input').prop('disabled', false);
if (needUpdate) {
$items.filter(sprintf('[value="%s"]', index)).prop('checked', checked);
}
if ($items.filter(':checked').length <= this.options.minimumCountColumns) {
$items.filter(':checked').prop('disabled', true);
}
}
};
BootstrapTable.prototype.toggleRow = function (index, uniqueId, visible) {
if (index === -1) {
return;
}
this.$body.find(typeof index !== 'undefined' ?
sprintf('tr[data-index="%s"]', index) :
sprintf('tr[data-uniqueid="%s"]', uniqueId))
[visible ? 'show' : 'hide']();
};
BootstrapTable.prototype.getVisibleFields = function () {
var that = this,
visibleFields = [];
$.each(this.header.fields, function (j, field) {
var column = that.columns[getFieldIndex(that.columns, field)];
if (!column.visible) {
return;
}
visibleFields.push(field);
});
return visibleFields;
};
// PUBLIC FUNCTION DEFINITION
// =======================
BootstrapTable.prototype.resetView = function (params) {
var padding = 0;
if (params && params.height) {
this.options.height = params.height;
}
this.$selectAll.prop('checked', this.$selectItem.length > 0 &&
this.$selectItem.length === this.$selectItem.filter(':checked').length);
if (this.options.height) {
var toolbarHeight = getRealHeight(this.$toolbar),
paginationHeight = getRealHeight(this.$pagination),
height = this.options.height - toolbarHeight - paginationHeight;
this.$tableContainer.css('height', height + 'px');
}
if (this.options.cardView) {
// remove the element css
this.$el.css('margin-top', '0');
this.$tableContainer.css('padding-bottom', '0');
return;
}
if (this.options.showHeader && this.options.height) {
this.$tableHeader.show();
this.resetHeader();
padding += this.$header.outerHeight();
} else {
this.$tableHeader.hide();
this.trigger('post-header');
}
if (this.options.showFooter) {
this.resetFooter();
if (this.options.height) {
padding += this.$tableFooter.outerHeight() + 1;
}
}
// Assign the correct sortable arrow
this.getCaret();
this.$tableContainer.css('padding-bottom', padding + 'px');
this.trigger('reset-view');
};
BootstrapTable.prototype.getData = function (useCurrentPage) {
return (this.searchText || !$.isEmptyObject(this.filterColumns) || !$.isEmptyObject(this.filterColumnsPartial)) ?
(useCurrentPage ? this.data.slice(this.pageFrom - 1, this.pageTo) : this.data) :
(useCurrentPage ? this.options.data.slice(this.pageFrom - 1, this.pageTo) : this.options.data);
};
BootstrapTable.prototype.load = function (data) {
var fixedScroll = false;
// #431: support pagination
if (this.options.sidePagination === 'server') {
this.options.totalRows = data.total;
fixedScroll = data.fixedScroll;
data = data[this.options.dataField];
} else if (!$.isArray(data)) { // support fixedScroll
fixedScroll = data.fixedScroll;
data = data.data;
}
this.initData(data);
this.initSearch();
this.initPagination();
this.initBody(fixedScroll);
};
BootstrapTable.prototype.append = function (data) {
this.initData(data, 'append');
this.initSearch();
this.initPagination();
this.initSort();
this.initBody(true);
};
BootstrapTable.prototype.prepend = function (data) {
this.initData(data, 'prepend');
this.initSearch();
this.initPagination();
this.initSort();
this.initBody(true);
};
BootstrapTable.prototype.remove = function (params) {
var len = this.options.data.length,
i, row;
if (!params.hasOwnProperty('field') || !params.hasOwnProperty('values')) {
return;
}
for (i = len - 1; i >= 0; i--) {
row = this.options.data[i];
if (!row.hasOwnProperty(params.field)) {
continue;
}
if ($.inArray(row[params.field], params.values) !== -1) {
this.options.data.splice(i, 1);
}
}
if (len === this.options.data.length) {
return;
}
this.initSearch();
this.initPagination();
this.initSort();
this.initBody(true);
};
BootstrapTable.prototype.removeAll = function () {
if (this.options.data.length > 0) {
this.options.data.splice(0, this.options.data.length);
this.initSearch();
this.initPagination();
this.initBody(true);
}
};
BootstrapTable.prototype.getRowByUniqueId = function (id) {
var uniqueId = this.options.uniqueId,
len = this.options.data.length,
dataRow = null,
i, row, rowUniqueId;
for (i = len - 1; i >= 0; i--) {
row = this.options.data[i];
if (row.hasOwnProperty(uniqueId)) { // uniqueId is a column
rowUniqueId = row[uniqueId];
} else if(row._data.hasOwnProperty(uniqueId)) { // uniqueId is a row data property
rowUniqueId = row._data[uniqueId];
} else {
continue;
}
if (typeof rowUniqueId === 'string') {
id = id.toString();
} else if (typeof rowUniqueId === 'number') {
if ((Number(rowUniqueId) === rowUniqueId) && (rowUniqueId % 1 === 0)) {
id = parseInt(id);
} else if ((rowUniqueId === Number(rowUniqueId)) && (rowUniqueId !== 0)) {
id = parseFloat(id);
}
}
if (rowUniqueId === id) {
dataRow = row;
break;
}
}
return dataRow;
};
BootstrapTable.prototype.removeByUniqueId = function (id) {
var len = this.options.data.length,
row = this.getRowByUniqueId(id);
if (row) {
this.options.data.splice(this.options.data.indexOf(row), 1);
}
if (len === this.options.data.length) {
return;
}
this.initSearch();
this.initPagination();
this.initBody(true);
};
BootstrapTable.prototype.updateByUniqueId = function (params) {
var rowId;
if (!params.hasOwnProperty('id') || !params.hasOwnProperty('row')) {
return;
}
rowId = $.inArray(this.getRowByUniqueId(params.id), this.options.data);
if (rowId === -1) {
return;
}
$.extend(this.data[rowId], params.row);
this.initSort();
this.initBody(true);
};
BootstrapTable.prototype.insertRow = function (params) {
if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
return;
}
this.data.splice(params.index, 0, params.row);
this.initSearch();
this.initPagination();
this.initSort();
this.initBody(true);
};
BootstrapTable.prototype.updateRow = function (params) {
if (!params.hasOwnProperty('index') || !params.hasOwnProperty('row')) {
return;
}
$.extend(this.data[params.index], params.row);
this.initSort();
this.initBody(true);
};
BootstrapTable.prototype.showRow = function (params) {
if (!params.hasOwnProperty('index') && !params.hasOwnProperty('uniqueId')) {
return;
}
this.toggleRow(params.index, params.uniqueId, true);
};
BootstrapTable.prototype.hideRow = function (params) {
if (!params.hasOwnProperty('index') && !params.hasOwnProperty('uniqueId')) {
return;
}
this.toggleRow(params.index, params.uniqueId, false);
};
BootstrapTable.prototype.getRowsHidden = function (show) {
var rows = $(this.$body[0]).children().filter(':hidden'),
i = 0;
if (show) {
for (; i < rows.length; i++) {
$(rows[i]).show();
}
}
return rows;
};
BootstrapTable.prototype.mergeCells = function (options) {
var row = options.index,
col = $.inArray(options.field, this.getVisibleFields()),
rowspan = options.rowspan || 1,
colspan = options.colspan || 1,
i, j,
$tr = this.$body.find('>tr'),
$td;
if (this.options.detailView && !this.options.cardView) {
col += 1;
}
$td = $tr.eq(row).find('>td').eq(col);
if (row < 0 || col < 0 || row >= this.data.length) {
return;
}
for (i = row; i < row + rowspan; i++) {
for (j = col; j < col + colspan; j++) {
$tr.eq(i).find('>td').eq(j).hide();
}
}
$td.attr('rowspan', rowspan).attr('colspan', colspan).show();
};
BootstrapTable.prototype.updateCell = function (params) {
if (!params.hasOwnProperty('index') ||
!params.hasOwnProperty('field') ||
!params.hasOwnProperty('value')) {
return;
}
this.data[params.index][params.field] = params.value;
if (params.reinit === false) {
return;
}
this.initSort();
this.initBody(true);
};
BootstrapTable.prototype.getOptions = function () {
return this.options;
};
BootstrapTable.prototype.getSelections = function () {
var that = this;
return $.grep(this.data, function (row) {
return row[that.header.stateField];
});
};
BootstrapTable.prototype.getAllSelections = function () {
var that = this;
return $.grep(this.options.data, function (row) {
return row[that.header.stateField];
});
};
BootstrapTable.prototype.checkAll = function () {
this.checkAll_(true);
};
BootstrapTable.prototype.uncheckAll = function () {
this.checkAll_(false);
};
BootstrapTable.prototype.checkInvert = function () {
var that = this;
var rows = that.$selectItem.filter(':enabled');
var checked = rows.filter(':checked');
rows.each(function() {
$(this).prop('checked', !$(this).prop('checked'));
});
that.updateRows();
that.updateSelected();
that.trigger('uncheck-some', checked);
checked = that.getSelections();
that.trigger('check-some', checked);
};
BootstrapTable.prototype.checkAll_ = function (checked) {
var rows;
if (!checked) {
rows = this.getSelections();
}
this.$selectAll.add(this.$selectAll_).prop('checked', checked);
this.$selectItem.filter(':enabled').prop('checked', checked);
this.updateRows();
if (checked) {
rows = this.getSelections();
}
this.trigger(checked ? 'check-all' : 'uncheck-all', rows);
};
BootstrapTable.prototype.check = function (index) {
this.check_(true, index);
};
BootstrapTable.prototype.uncheck = function (index) {
this.check_(false, index);
};
BootstrapTable.prototype.check_ = function (checked, index) {
var $el = this.$selectItem.filter(sprintf('[data-index="%s"]', index)).prop('checked', checked);
this.data[index][this.header.stateField] = checked;
this.updateSelected();
this.trigger(checked ? 'check' : 'uncheck', this.data[index], $el);
};
BootstrapTable.prototype.checkBy = function (obj) {
this.checkBy_(true, obj);
};
BootstrapTable.prototype.uncheckBy = function (obj) {
this.checkBy_(false, obj);
};
BootstrapTable.prototype.checkBy_ = function (checked, obj) {
if (!obj.hasOwnProperty('field') || !obj.hasOwnProperty('values')) {
return;
}
var that = this,
rows = [];
$.each(this.options.data, function (index, row) {
if (!row.hasOwnProperty(obj.field)) {
return false;
}
if ($.inArray(row[obj.field], obj.values) !== -1) {
var $el = that.$selectItem.filter(':enabled')
.filter(sprintf('[data-index="%s"]', index)).prop('checked', checked);
row[that.header.stateField] = checked;
rows.push(row);
that.trigger(checked ? 'check' : 'uncheck', row, $el);
}
});
this.updateSelected();
this.trigger(checked ? 'check-some' : 'uncheck-some', rows);
};
BootstrapTable.prototype.destroy = function () {
this.$el.insertBefore(this.$container);
$(this.options.toolbar).insertBefore(this.$el);
this.$container.next().remove();
this.$container.remove();
this.$el.html(this.$el_.html())
.css('margin-top', '0')
.attr('class', this.$el_.attr('class') || ''); // reset the class
};
BootstrapTable.prototype.showLoading = function () {
this.$tableLoading.show();
};
BootstrapTable.prototype.hideLoading = function () {
this.$tableLoading.hide();
};
BootstrapTable.prototype.togglePagination = function () {
this.options.pagination = !this.options.pagination;
var button = this.$toolbar.find('button[name="paginationSwitch"] i');
if (this.options.pagination) {
button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchDown);
} else {
button.attr("class", this.options.iconsPrefix + " " + this.options.icons.paginationSwitchUp);
}
this.updatePagination();
};
BootstrapTable.prototype.refresh = function (params) {
if (params && params.url) {
this.options.url = params.url;
this.options.pageNumber = 1;
}
this.initServer(params && params.silent, params && params.query);
};
BootstrapTable.prototype.resetWidth = function () {
if (this.options.showHeader && this.options.height) {
this.fitHeader();
}
if (this.options.showFooter) {
this.fitFooter();
}
};
BootstrapTable.prototype.showColumn = function (field) {
this.toggleColumn(getFieldIndex(this.columns, field), true, true);
};
BootstrapTable.prototype.hideColumn = function (field) {
this.toggleColumn(getFieldIndex(this.columns, field), false, true);
};
BootstrapTable.prototype.getHiddenColumns = function () {
return $.grep(this.columns, function (column) {
return !column.visible;
});
};
BootstrapTable.prototype.filterBy = function (columns) {
this.filterColumns = $.isEmptyObject(columns) ? {} : columns;
this.options.pageNumber = 1;
this.initSearch();
this.updatePagination();
};
BootstrapTable.prototype.scrollTo = function (value) {
if (typeof value === 'string') {
value = value === 'bottom' ? this.$tableBody[0].scrollHeight : 0;
}
if (typeof value === 'number') {
this.$tableBody.scrollTop(value);
}
if (typeof value === 'undefined') {
return this.$tableBody.scrollTop();
}
};
BootstrapTable.prototype.getScrollPosition = function () {
return this.scrollTo();
};
BootstrapTable.prototype.selectPage = function (page) {
if (page > 0 && page <= this.options.totalPages) {
this.options.pageNumber = page;
this.updatePagination();
}
};
BootstrapTable.prototype.prevPage = function () {
if (this.options.pageNumber > 1) {
this.options.pageNumber--;
this.updatePagination();
}
};
BootstrapTable.prototype.nextPage = function () {
if (this.options.pageNumber < this.options.totalPages) {
this.options.pageNumber++;
this.updatePagination();
}
};
BootstrapTable.prototype.toggleView = function () {
this.options.cardView = !this.options.cardView;
this.initHeader();
// Fixed remove toolbar when click cardView button.
//that.initToolbar();
this.initBody();
this.trigger('toggle', this.options.cardView);
};
BootstrapTable.prototype.refreshOptions = function (options) {
//If the objects are equivalent then avoid the call of destroy / init methods
if (compareObjects(this.options, options, true)) {
return;
}
this.options = $.extend(this.options, options);
this.trigger('refresh-options', this.options);
this.destroy();
this.init();
};
BootstrapTable.prototype.resetSearch = function (text) {
var $search = this.$toolbar.find('.search input');
$search.val(text || '');
this.onSearch({currentTarget: $search});
};
BootstrapTable.prototype.expandRow_ = function (expand, index) {
var $tr = this.$body.find(sprintf('> tr[data-index="%s"]', index));
if ($tr.next().is('tr.detail-view') === (expand ? false : true)) {
$tr.find('> td > .detail-icon').click();
}
};
BootstrapTable.prototype.expandRow = function (index) {
this.expandRow_(true, index);
};
BootstrapTable.prototype.collapseRow = function (index) {
this.expandRow_(false, index);
};
BootstrapTable.prototype.expandAllRows = function (isSubTable) {
if (isSubTable) {
var $tr = this.$body.find(sprintf('> tr[data-index="%s"]', 0)),
that = this,
detailIcon = null,
executeInterval = false,
idInterval = -1;
if (!$tr.next().is('tr.detail-view')) {
$tr.find('> td > .detail-icon').click();
executeInterval = true;
} else if (!$tr.next().next().is('tr.detail-view')) {
$tr.next().find(".detail-icon").click();
executeInterval = true;
}
if (executeInterval) {
try {
idInterval = setInterval(function () {
detailIcon = that.$body.find("tr.detail-view").last().find(".detail-icon");
if (detailIcon.length > 0) {
detailIcon.click();
} else {
clearInterval(idInterval);
}
}, 1);
} catch (ex) {
clearInterval(idInterval);
}
}
} else {
var trs = this.$body.children();
for (var i = 0; i < trs.length; i++) {
this.expandRow_(true, $(trs[i]).data("index"));
}
}
};
BootstrapTable.prototype.collapseAllRows = function (isSubTable) {
if (isSubTable) {
this.expandRow_(false, 0);
} else {
var trs = this.$body.children();
for (var i = 0; i < trs.length; i++) {
this.expandRow_(false, $(trs[i]).data("index"));
}
}
};
BootstrapTable.prototype.updateFormatText = function (name, text) {
if (this.options[sprintf('format%s', name)]) {
if (typeof text === 'string') {
this.options[sprintf('format%s', name)] = function () {
return text;
};
} else if (typeof text === 'function') {
this.options[sprintf('format%s', name)] = text;
}
}
this.initToolbar();
this.initPagination();
this.initBody();
};
// BOOTSTRAP TABLE PLUGIN DEFINITION
// =======================
var allowedMethods = [
'getOptions',
'getSelections', 'getAllSelections', 'getData',
'load', 'append', 'prepend', 'remove', 'removeAll',
'insertRow', 'updateRow', 'updateCell', 'updateByUniqueId', 'removeByUniqueId',
'getRowByUniqueId', 'showRow', 'hideRow', 'getRowsHidden',
'mergeCells',
'checkAll', 'uncheckAll', 'checkInvert',
'check', 'uncheck',
'checkBy', 'uncheckBy',
'refresh',
'resetView',
'resetWidth',
'destroy',
'showLoading', 'hideLoading',
'showColumn', 'hideColumn', 'getHiddenColumns',
'filterBy',
'scrollTo',
'getScrollPosition',
'selectPage', 'prevPage', 'nextPage',
'togglePagination',
'toggleView',
'refreshOptions',
'resetSearch',
'expandRow', 'collapseRow', 'expandAllRows', 'collapseAllRows',
'updateFormatText'
];
$.fn.bootstrapTable = function (option) {
var value,
args = Array.prototype.slice.call(arguments, 1);
this.each(function () {
var $this = $(this),
data = $this.data('bootstrap.table'),
options = $.extend({}, BootstrapTable.DEFAULTS, $this.data(),
typeof option === 'object' && option);
if (typeof option === 'string') {
if ($.inArray(option, allowedMethods) < 0) {
throw new Error("Unknown method: " + option);
}
if (!data) {
return;
}
value = data[option].apply(data, args);
if (option === 'destroy') {
$this.removeData('bootstrap.table');
}
}
if (!data) {
$this.data('bootstrap.table', (data = new BootstrapTable(this, options)));
}
});
return typeof value === 'undefined' ? this : value;
};
$.fn.bootstrapTable.Constructor = BootstrapTable;
$.fn.bootstrapTable.defaults = BootstrapTable.DEFAULTS;
$.fn.bootstrapTable.columnDefaults = BootstrapTable.COLUMN_DEFAULTS;
$.fn.bootstrapTable.locales = BootstrapTable.LOCALES;
$.fn.bootstrapTable.methods = allowedMethods;
$.fn.bootstrapTable.utils = {
sprintf: sprintf,
getFieldIndex: getFieldIndex,
compareObjects: compareObjects,
calculateObjectValue: calculateObjectValue
};
// BOOTSTRAP TABLE INIT
// =======================
$(function () {
$('[data-toggle="table"]').bootstrapTable();
});
}(jQuery);
|
ZombieHippie/cream
|
public/script/tablesorting.js
|
JavaScript
|
bsd-2-clause
| 100,297 |
/*
* (C) 2011 Billy Brumley (billy.brumley@aalto.fi)
* (C) 2021 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/zfec.h>
#include <botan/internal/simd_32.h>
#if defined(BOTAN_SIMD_USE_SSE2)
#include <tmmintrin.h>
#endif
namespace Botan {
namespace {
/*
* these tables are for the linear map bx^4 + a -> y(bx^4 + a)
* implemented as two maps:
* a -> y(a)
* b -> y(bx^4)
* and the final output is the sum of these two outputs.
*/
alignas(256) const uint8_t GFTBL[256*32] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0,
0x00, 0x02, 0x04, 0x06, 0x08, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16, 0x18, 0x1a, 0x1c, 0x1e,
0x00, 0x20, 0x40, 0x60, 0x80, 0xa0, 0xc0, 0xe0, 0x1d, 0x3d, 0x5d, 0x7d, 0x9d, 0xbd, 0xdd, 0xfd,
0x00, 0x03, 0x06, 0x05, 0x0c, 0x0f, 0x0a, 0x09, 0x18, 0x1b, 0x1e, 0x1d, 0x14, 0x17, 0x12, 0x11,
0x00, 0x30, 0x60, 0x50, 0xc0, 0xf0, 0xa0, 0x90, 0x9d, 0xad, 0xfd, 0xcd, 0x5d, 0x6d, 0x3d, 0x0d,
0x00, 0x04, 0x08, 0x0c, 0x10, 0x14, 0x18, 0x1c, 0x20, 0x24, 0x28, 0x2c, 0x30, 0x34, 0x38, 0x3c,
0x00, 0x40, 0x80, 0xc0, 0x1d, 0x5d, 0x9d, 0xdd, 0x3a, 0x7a, 0xba, 0xfa, 0x27, 0x67, 0xa7, 0xe7,
0x00, 0x05, 0x0a, 0x0f, 0x14, 0x11, 0x1e, 0x1b, 0x28, 0x2d, 0x22, 0x27, 0x3c, 0x39, 0x36, 0x33,
0x00, 0x50, 0xa0, 0xf0, 0x5d, 0x0d, 0xfd, 0xad, 0xba, 0xea, 0x1a, 0x4a, 0xe7, 0xb7, 0x47, 0x17,
0x00, 0x06, 0x0c, 0x0a, 0x18, 0x1e, 0x14, 0x12, 0x30, 0x36, 0x3c, 0x3a, 0x28, 0x2e, 0x24, 0x22,
0x00, 0x60, 0xc0, 0xa0, 0x9d, 0xfd, 0x5d, 0x3d, 0x27, 0x47, 0xe7, 0x87, 0xba, 0xda, 0x7a, 0x1a,
0x00, 0x07, 0x0e, 0x09, 0x1c, 0x1b, 0x12, 0x15, 0x38, 0x3f, 0x36, 0x31, 0x24, 0x23, 0x2a, 0x2d,
0x00, 0x70, 0xe0, 0x90, 0xdd, 0xad, 0x3d, 0x4d, 0xa7, 0xd7, 0x47, 0x37, 0x7a, 0x0a, 0x9a, 0xea,
0x00, 0x08, 0x10, 0x18, 0x20, 0x28, 0x30, 0x38, 0x40, 0x48, 0x50, 0x58, 0x60, 0x68, 0x70, 0x78,
0x00, 0x80, 0x1d, 0x9d, 0x3a, 0xba, 0x27, 0xa7, 0x74, 0xf4, 0x69, 0xe9, 0x4e, 0xce, 0x53, 0xd3,
0x00, 0x09, 0x12, 0x1b, 0x24, 0x2d, 0x36, 0x3f, 0x48, 0x41, 0x5a, 0x53, 0x6c, 0x65, 0x7e, 0x77,
0x00, 0x90, 0x3d, 0xad, 0x7a, 0xea, 0x47, 0xd7, 0xf4, 0x64, 0xc9, 0x59, 0x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5, 0x33, 0xba, 0x22, 0xab, 0x2d, 0xa4,
0x00, 0x78, 0xf0, 0x88, 0xfd, 0x85, 0x0d, 0x75, 0xe7, 0x9f, 0x17, 0x6f, 0x1a, 0x62, 0xea, 0x92,
0x00, 0x8a, 0x09, 0x83, 0x12, 0x98, 0x1b, 0x91, 0x24, 0xae, 0x2d, 0xa7, 0x36, 0xbc, 0x3f, 0xb5,
0x00, 0x48, 0x90, 0xd8, 0x3d, 0x75, 0xad, 0xe5, 0x7a, 0x32, 0xea, 0xa2, 0x47, 0x0f, 0xd7, 0x9f,
0x00, 0x8b, 0x0b, 0x80, 0x16, 0x9d, 0x1d, 0x96, 0x2c, 0xa7, 0x27, 0xac, 0x3a, 0xb1, 0x31, 0xba,
0x00, 0x58, 0xb0, 0xe8, 0x7d, 0x25, 0xcd, 0x95, 0xfa, 0xa2, 0x4a, 0x12, 0x87, 0xdf, 0x37, 0x6f,
0x00, 0x8c, 0x05, 0x89, 0x0a, 0x86, 0x0f, 0x83, 0x14, 0x98, 0x11, 0x9d, 0x1e, 0x92, 0x1b, 0x97,
0x00, 0x28, 0x50, 0x78, 0xa0, 0x88, 0xf0, 0xd8, 0x5d, 0x75, 0x0d, 0x25, 0xfd, 0xd5, 0xad, 0x85,
0x00, 0x8d, 0x07, 0x8a, 0x0e, 0x83, 0x09, 0x84, 0x1c, 0x91, 0x1b, 0x96, 0x12, 0x9f, 0x15, 0x98,
0x00, 0x38, 0x70, 0x48, 0xe0, 0xd8, 0x90, 0xa8, 0xdd, 0xe5, 0xad, 0x95, 0x3d, 0x05, 0x4d, 0x75,
0x00, 0x8e, 0x01, 0x8f, 0x02, 0x8c, 0x03, 0x8d, 0x04, 0x8a, 0x05, 0x8b, 0x06, 0x88, 0x07, 0x89,
0x00, 0x08, 0x10, 0x18, 0x20, 0x28, 0x30, 0x38, 0x40, 0x48, 0x50, 0x58, 0x60, 0x68, 0x70, 0x78,
0x00, 0x8f, 0x03, 0x8c, 0x06, 0x89, 0x05, 0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x5c, 0xa1, 0x68, 0x95, 0x8f, 0x72,
0x00, 0x6b, 0xd6, 0xbd, 0xb1, 0xda, 0x67, 0x0c, 0x7f, 0x14, 0xa9, 0xc2, 0xce, 0xa5, 0x18, 0x73,
0x00, 0xfe, 0xe1, 0x1f, 0xdf, 0x21, 0x3e, 0xc0, 0xa3, 0x5d, 0x42, 0xbc, 0x7c, 0x82, 0x9d, 0x63,
0x00, 0x5b, 0xb6, 0xed, 0x71, 0x2a, 0xc7, 0x9c, 0xe2, 0xb9, 0x54, 0x0f, 0x93, 0xc8, 0x25, 0x7e,
0x00, 0xff, 0xe3, 0x1c, 0xdb, 0x24, 0x38, 0xc7, 0xab, 0x54, 0x48, 0xb7, 0x70, 0x8f, 0x93, 0x6c,
0x00, 0x4b, 0x96, 0xdd, 0x31, 0x7a, 0xa7, 0xec, 0x62, 0x29, 0xf4, 0xbf, 0x53, 0x18, 0xc5, 0x8e };
inline SIMD_4x32 BOTAN_FUNC_ISA(BOTAN_VPERM_ISA) table_lookup(SIMD_4x32 t, SIMD_4x32 v)
{
#if defined(BOTAN_SIMD_USE_SSE2)
return SIMD_4x32(_mm_shuffle_epi8(t.raw(), v.raw()));
#elif defined(BOTAN_SIMD_USE_NEON)
const uint8x16_t tbl = vreinterpretq_u8_u32(t.raw());
const uint8x16_t idx = vreinterpretq_u8_u32(v.raw());
#if defined(BOTAN_TARGET_ARCH_IS_ARM32)
const uint8x8x2_t tbl2 = { vget_low_u8(tbl), vget_high_u8(tbl) };
return SIMD_4x32(vreinterpretq_u32_u8(
vcombine_u8(vtbl2_u8(tbl2, vget_low_u8(idx)),
vtbl2_u8(tbl2, vget_high_u8(idx)))));
#else
return SIMD_4x32(vreinterpretq_u32_u8(vqtbl1q_u8(tbl, idx)));
#endif
#endif
}
}
BOTAN_FUNC_ISA(BOTAN_VPERM_ISA)
size_t ZFEC::addmul_vperm(uint8_t z[], const uint8_t x[], uint8_t y, size_t size)
{
const auto mask = SIMD_4x32::splat_u8(0x0F);
// fetch the lookup tables for the given y
const auto t_lo = SIMD_4x32::load_le(GFTBL + 32*y);
const auto t_hi = SIMD_4x32::load_le(GFTBL + 32*y + 16);
const size_t orig_size = size;
while(size >= 16)
{
const auto x_1 = SIMD_4x32::load_le(x);
auto z_1 = SIMD_4x32::load_le(z);
// mask to get LO nibble for LO LUT input
const auto x_lo = x_1 & mask;
// mask to get HI nibble for HI LUT input
const auto x_hi = x_1.shr<4>() & mask;
// 16x parallel lookups
const auto r_lo = table_lookup(t_lo, x_lo);
const auto r_hi = table_lookup(t_hi, x_hi);
// sum the outputs.
z_1 ^= r_lo;
z_1 ^= r_hi;
z_1.store_le(z);
x += 16;
z += 16;
size -= 16;
}
return orig_size - size;
}
}
|
randombit/botan
|
src/lib/misc/zfec/zfec_vperm/zfec_vperm.cpp
|
C++
|
bsd-2-clause
| 51,390 |
class LimeError(Exception):
"""Raise for errors"""
|
marcotcr/lime
|
lime/exceptions.py
|
Python
|
bsd-2-clause
| 55 |
/**
* @module ol/layer/MapboxVector
*/
import BaseEvent from '../events/Event.js';
import EventType from '../events/EventType.js';
import GeometryType from '../geom/GeometryType.js';
import MVT from '../format/MVT.js';
import RenderFeature from '../render/Feature.js';
import SourceState from '../source/State.js';
import TileEventType from '../source/TileEventType.js';
import VectorTileLayer from '../layer/VectorTile.js';
import VectorTileSource from '../source/VectorTile.js';
import {Fill, Style} from '../style.js';
import {applyStyle, setupVectorSource} from 'ol-mapbox-style';
import {fromExtent} from '../geom/Polygon.js';
import {getValue} from 'ol-mapbox-style/dist/stylefunction.js';
const mapboxBaseUrl = 'https://api.mapbox.com';
/**
* Gets the path from a mapbox:// URL.
* @param {string} url The Mapbox URL.
* @return {string} The path.
* @private
*/
export function getMapboxPath(url) {
const startsWith = 'mapbox://';
if (url.indexOf(startsWith) !== 0) {
return '';
}
return url.slice(startsWith.length);
}
/**
* Turns mapbox:// sprite URLs into resolvable URLs.
* @param {string} url The sprite URL.
* @param {string} token The access token.
* @return {string} A resolvable URL.
* @private
*/
export function normalizeSpriteUrl(url, token) {
const mapboxPath = getMapboxPath(url);
if (!mapboxPath) {
return url;
}
const startsWith = 'sprites/';
if (mapboxPath.indexOf(startsWith) !== 0) {
throw new Error(`unexpected sprites url: ${url}`);
}
const sprite = mapboxPath.slice(startsWith.length);
return `${mapboxBaseUrl}/styles/v1/${sprite}/sprite?access_token=${token}`;
}
/**
* Turns mapbox:// glyphs URLs into resolvable URLs.
* @param {string} url The glyphs URL.
* @param {string} token The access token.
* @return {string} A resolvable URL.
* @private
*/
export function normalizeGlyphsUrl(url, token) {
const mapboxPath = getMapboxPath(url);
if (!mapboxPath) {
return url;
}
const startsWith = 'fonts/';
if (mapboxPath.indexOf(startsWith) !== 0) {
throw new Error(`unexpected fonts url: ${url}`);
}
const font = mapboxPath.slice(startsWith.length);
return `${mapboxBaseUrl}/fonts/v1/${font}/0-255.pbf?access_token=${token}`;
}
/**
* Turns mapbox:// style URLs into resolvable URLs.
* @param {string} url The style URL.
* @param {string} token The access token.
* @return {string} A resolvable URL.
* @private
*/
export function normalizeStyleUrl(url, token) {
const mapboxPath = getMapboxPath(url);
if (!mapboxPath) {
return url;
}
const startsWith = 'styles/';
if (mapboxPath.indexOf(startsWith) !== 0) {
throw new Error(`unexpected style url: ${url}`);
}
const style = mapboxPath.slice(startsWith.length);
return `${mapboxBaseUrl}/styles/v1/${style}?&access_token=${token}`;
}
/**
* Turns mapbox:// source URLs into vector tile URL templates.
* @param {string} url The source URL.
* @param {string} token The access token.
* @param {string} tokenParam The access token key.
* @return {string} A vector tile template.
* @private
*/
export function normalizeSourceUrl(url, token, tokenParam) {
const mapboxPath = getMapboxPath(url);
if (!mapboxPath) {
if (!token) {
return url;
}
const urlObject = new URL(url, location.href);
urlObject.searchParams.set(tokenParam, token);
return decodeURI(urlObject.href);
}
return `https://{a-d}.tiles.mapbox.com/v4/${mapboxPath}/{z}/{x}/{y}.vector.pbf?access_token=${token}`;
}
/**
* @classdesc
* Event emitted on configuration or loading error.
*/
class ErrorEvent extends BaseEvent {
/**
* @param {Error} error error object.
*/
constructor(error) {
super(EventType.ERROR);
/**
* @type {Error}
*/
this.error = error;
}
}
/**
* @typedef {Object} StyleObject
* @property {Object<string, SourceObject>} sources The style sources.
* @property {string} sprite The sprite URL.
* @property {string} glyphs The glyphs URL.
* @property {Array<LayerObject>} layers The style layers.
*/
/**
* @typedef {Object} SourceObject
* @property {string} url The source URL.
* @property {SourceType} type The source type.
* @property {Array<string>} [tiles] TileJSON tiles.
*/
/**
* The Mapbox source type.
* @enum {string}
*/
const SourceType = {
VECTOR: 'vector',
};
/**
* @typedef {Object} LayerObject
* @property {string} id The layer id.
* @property {string} type The layer type.
* @property {string} source The source id.
* @property {Object} layout The layout.
* @property {Object} paint The paint.
*/
/**
* @typedef {Object} Options
* @property {string} styleUrl The URL of the Mapbox style object to use for this layer. For a
* style created with Mapbox Studio and hosted on Mapbox, this will look like
* 'mapbox://styles/you/your-style'.
* @property {string} [accessToken] The access token for your Mapbox style. This has to be provided
* for `mapbox://` style urls. For `https://` and other urls, any access key must be the last query
* parameter of the style url.
* @property {string} [source] If your style uses more than one source, you need to use either the
* `source` property or the `layers` property to limit rendering to a single vector source. The
* `source` property corresponds to the id of a vector source in your Mapbox style.
* @property {Array<string>} [layers] Limit rendering to the list of included layers. All layers
* must share the same vector source. If your style uses more than one source, you need to use
* either the `source` property or the `layers` property to limit rendering to a single vector
* source.
* @property {boolean} [declutter=true] Declutter images and text. Decluttering is applied to all
* image and text styles of all Vector and VectorTile layers that have set this to `true`. The priority
* is defined by the z-index of the layer, the `zIndex` of the style and the render order of features.
* Higher z-index means higher priority. Within the same z-index, a feature rendered before another has
* higher priority.
* @property {string} [className='ol-layer'] A CSS class name to set to the layer element.
* @property {number} [opacity=1] Opacity (0, 1).
* @property {boolean} [visible=true] Visibility.
* @property {import("../extent.js").Extent} [extent] The bounding extent for layer rendering. The layer will not be
* rendered outside of this extent.
* @property {number} [zIndex] The z-index for layer rendering. At rendering time, the layers
* will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed
* for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`
* method was used.
* @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be
* visible.
* @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will
* be visible.
* @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be
* visible.
* @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will
* be visible.
* @property {import("../render.js").OrderFunction} [renderOrder] Render order. Function to be used when sorting
* features before rendering. By default features are drawn in the order that they are created. Use
* `null` to avoid the sort, but get an undefined draw order.
* @property {number} [renderBuffer=100] The buffer in pixels around the tile extent used by the
* renderer when getting features from the vector tile for the rendering or hit-detection.
* Recommended value: Vector tiles are usually generated with a buffer, so this value should match
* the largest possible buffer of the used tiles. It should be at least the size of the largest
* point symbol or line width.
* @property {import("./VectorTileRenderType.js").default|string} [renderMode='hybrid'] Render mode for vector tiles:
* * `'hybrid'`: Polygon and line elements are rendered as images, so pixels are scaled during zoom
* animations. Point symbols and texts are accurately rendered as vectors and can stay upright on
* rotated views.
* * `'vector'`: Everything is rendered as vectors. Use this mode for improved performance on vector
* tile layers with only a few rendered features (e.g. for highlighting a subset of features of
* another layer with the same source).
* @property {import("../PluggableMap.js").default} [map] Sets the layer as overlay on a map. The map will not manage
* this layer in its layers collection, and the layer will be rendered on top. This is useful for
* temporary layers. The standard way to add a layer to a map and have it managed by the map is to
* use {@link import("../PluggableMap.js").default#addLayer map.addLayer()}.
* @property {boolean} [updateWhileAnimating=false] When set to `true`, feature batches will be
* recreated during animations. This means that no vectors will be shown clipped, but the setting
* will have a performance impact for large amounts of vector data. When set to `false`, batches
* will be recreated when no animation is active.
* @property {boolean} [updateWhileInteracting=false] When set to `true`, feature batches will be
* recreated during interactions. See also `updateWhileAnimating`.
* @property {number} [preload=0] Preload. Load low-resolution tiles up to `preload` levels. `0`
* means no preloading.
* @property {boolean} [useInterimTilesOnError=true] Use interim tiles on error.
* @property {Object<string, *>} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.
*/
/**
* @classdesc
* A vector tile layer based on a Mapbox style that uses a single vector source. Configure
* the layer with the `styleUrl` and `accessToken` shown in Mapbox Studio's share panel.
* If the style uses more than one source, use the `source` property to choose a single
* vector source. If you want to render a subset of the layers in the style, use the `layers`
* property (all layers must share the same vector source). See the constructor options for
* more detail.
*
* var map = new Map({
* view: new View({
* center: [0, 0],
* zoom: 1
* }),
* layers: [
* new MapboxVectorLayer({
* styleUrl: 'mapbox://styles/mapbox/bright-v9',
* accessToken: 'your-mapbox-access-token-here'
* })
* ],
* target: 'map'
* });
*
* On configuration or loading error, the layer will trigger an `'error'` event. Listeners
* will receive an object with an `error` property that can be used to diagnose the problem.
*
* @param {Options} options Options.
* @extends {VectorTileLayer}
* @fires module:ol/events/Event~BaseEvent#event:error
* @api
*/
class MapboxVectorLayer extends VectorTileLayer {
/**
* @param {Options} options Layer options. At a minimum, `styleUrl` and `accessToken`
* must be provided.
*/
constructor(options) {
const declutter = 'declutter' in options ? options.declutter : true;
const source = new VectorTileSource({
state: SourceState.LOADING,
format: new MVT(),
});
super({
source: source,
declutter: declutter,
className: options.className,
opacity: options.opacity,
visible: options.visible,
zIndex: options.zIndex,
minResolution: options.minResolution,
maxResolution: options.maxResolution,
minZoom: options.minZoom,
maxZoom: options.maxZoom,
renderOrder: options.renderOrder,
renderBuffer: options.renderBuffer,
renderMode: options.renderMode,
map: options.map,
updateWhileAnimating: options.updateWhileAnimating,
updateWhileInteracting: options.updateWhileInteracting,
preload: options.preload,
useInterimTilesOnError: options.useInterimTilesOnError,
properties: options.properties,
});
this.sourceId = options.source;
this.layers = options.layers;
if (options.accessToken) {
this.accessToken = options.accessToken;
} else {
const url = new URL(options.styleUrl, location.href);
// The last search parameter is the access token
url.searchParams.forEach((value, key) => {
this.accessToken = value;
this.accessTokenParam_ = key;
});
}
this.fetchStyle(options.styleUrl);
}
/**
* Fetch the style object.
* @param {string} styleUrl The URL of the style to load.
* @protected
*/
fetchStyle(styleUrl) {
const url = normalizeStyleUrl(styleUrl, this.accessToken);
fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error(
`unexpected response when fetching style: ${response.status}`
);
}
return response.json();
})
.then((style) => {
this.onStyleLoad(style);
})
.catch((error) => {
this.handleError(error);
});
}
/**
* Handle the loaded style object.
* @param {StyleObject} style The loaded style.
* @protected
*/
onStyleLoad(style) {
let sourceId;
let sourceIdOrLayersList;
if (this.layers) {
// confirm all layers share the same source
const lookup = {};
for (let i = 0; i < style.layers.length; ++i) {
const layer = style.layers[i];
if (layer.source) {
lookup[layer.id] = layer.source;
}
}
let firstSource;
for (let i = 0; i < this.layers.length; ++i) {
const candidate = lookup[this.layers[i]];
if (!candidate) {
this.handleError(
new Error(`could not find source for ${this.layers[i]}`)
);
return;
}
if (!firstSource) {
firstSource = candidate;
} else if (firstSource !== candidate) {
this.handleError(
new Error(
`layers can only use a single source, found ${firstSource} and ${candidate}`
)
);
return;
}
}
sourceId = firstSource;
sourceIdOrLayersList = this.layers;
} else {
sourceId = this.sourceId;
sourceIdOrLayersList = sourceId;
}
if (!sourceIdOrLayersList) {
// default to the first source in the style
sourceId = Object.keys(style.sources)[0];
sourceIdOrLayersList = sourceId;
}
if (style.sprite) {
style.sprite = normalizeSpriteUrl(style.sprite, this.accessToken);
}
if (style.glyphs) {
style.glyphs = normalizeGlyphsUrl(style.glyphs, this.accessToken);
}
const styleSource = style.sources[sourceId];
if (styleSource.type !== SourceType.VECTOR) {
this.handleError(
new Error(`only works for vector sources, found ${styleSource.type}`)
);
return;
}
const source = this.getSource();
if (styleSource.url && styleSource.url.indexOf('mapbox://') === 0) {
// Tile source url, handle it directly
source.setUrl(
normalizeSourceUrl(
styleSource.url,
this.accessToken,
this.accessTokenParam_
)
);
applyStyle(this, style, sourceIdOrLayersList)
.then(() => {
this.configureSource(source, style);
})
.catch((error) => {
this.handleError(error);
});
} else {
// TileJSON url, let ol-mapbox-style handle it
if (styleSource.tiles) {
styleSource.tiles = styleSource.tiles.map((url) =>
normalizeSourceUrl(url, this.accessToken, this.accessTokenParam_)
);
}
setupVectorSource(
styleSource,
styleSource.url
? normalizeSourceUrl(
styleSource.url,
this.accessToken,
this.accessTokenParam_
)
: undefined
).then((source) => {
applyStyle(this, style, sourceIdOrLayersList)
.then(() => {
this.configureSource(source, style);
})
.catch((error) => {
this.configureSource(source, style);
this.handleError(error);
});
});
}
}
/**
* Applies configuration from the provided source to this layer's source,
* and reconfigures the loader to add a feature that renders the background,
* if the style is configured with a background.
* @param {import("../source/VectorTile.js").default} source The source to configure from.
* @param {StyleObject} style The style to configure the background from.
*/
configureSource(source, style) {
const targetSource = this.getSource();
if (source !== targetSource) {
targetSource.setAttributions(source.getAttributions());
targetSource.setTileUrlFunction(source.getTileUrlFunction());
targetSource.setTileLoadFunction(source.getTileLoadFunction());
targetSource.tileGrid = source.tileGrid;
}
const background = style.layers.find(
(layer) => layer.type === 'background'
);
if (
background &&
(!background.layout || background.layout.visibility !== 'none')
) {
const style = new Style({
fill: new Fill(),
});
targetSource.addEventListener(TileEventType.TILELOADEND, (event) => {
const tile = /** @type {import("../VectorTile.js").default} */ (
/** @type {import("../source/Tile.js").TileSourceEvent} */ (event)
.tile
);
const styleFuntion = () => {
const opacity =
/** @type {number} */ (
getValue(
background,
'paint',
'background-opacity',
tile.tileCoord[0]
)
) || 1;
const color = /** @type {*} */ (
getValue(background, 'paint', 'background-color', tile.tileCoord[0])
);
style
.getFill()
.setColor([
color.r * 255,
color.g * 255,
color.b * 255,
color.a * opacity,
]);
return style;
};
const extentGeometry = fromExtent(
targetSource.tileGrid.getTileCoordExtent(tile.tileCoord)
);
const renderFeature = new RenderFeature(
GeometryType.POLYGON,
extentGeometry.getFlatCoordinates(),
extentGeometry.getEnds(),
{layer: background.id},
undefined
);
renderFeature.styleFunction = styleFuntion;
tile.getFeatures().unshift(renderFeature);
});
}
targetSource.setState(SourceState.READY);
}
/**
* Handle configuration or loading error.
* @param {Error} error The error.
* @protected
*/
handleError(error) {
this.dispatchEvent(new ErrorEvent(error));
const source = this.getSource();
source.setState(SourceState.ERROR);
}
}
export default MapboxVectorLayer;
|
ahocevar/ol3
|
src/ol/layer/MapboxVector.js
|
JavaScript
|
bsd-2-clause
| 18,944 |
//
// protocol.hpp
// ~~~~~~~~~~~~
//
// Copyright (c) 2003-2013 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// 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 PORTHOPPER_PROTOCOL_HPP
#define PORTHOPPER_PROTOCOL_HPP
#include <boost/array.hpp>
#include <asio.hpp>
#include <cstring>
#include <iomanip>
#include <string>
#include <strstream>
// This request is sent by the client to the server over a TCP connection.
// The client uses it to perform three functions:
// - To request that data start being sent to a given port.
// - To request that data is no longer sent to a given port.
// - To change the target port to another.
class control_request
{
public:
// Construct an empty request. Used when receiving.
control_request()
{
}
// Create a request to start sending data to a given port.
static const control_request start(unsigned short port)
{
return control_request(0, port);
}
// Create a request to stop sending data to a given port.
static const control_request stop(unsigned short port)
{
return control_request(port, 0);
}
// Create a request to change the port that data is sent to.
static const control_request change(
unsigned short old_port, unsigned short new_port)
{
return control_request(old_port, new_port);
}
// Get the old port. Returns 0 for start requests.
unsigned short old_port() const
{
std::istrstream is(data_, encoded_port_size);
unsigned short port = 0;
is >> std::setw(encoded_port_size) >> std::hex >> port;
return port;
}
// Get the new port. Returns 0 for stop requests.
unsigned short new_port() const
{
std::istrstream is(data_ + encoded_port_size, encoded_port_size);
unsigned short port = 0;
is >> std::setw(encoded_port_size) >> std::hex >> port;
return port;
}
// Obtain buffers for reading from or writing to a socket.
boost::array<asio::mutable_buffer, 1> to_buffers()
{
boost::array<asio::mutable_buffer, 1> buffers
= { { asio::buffer(data_) } };
return buffers;
}
private:
// Construct with specified old and new ports.
control_request(unsigned short old_port_number,
unsigned short new_port_number)
{
std::ostrstream os(data_, control_request_size);
os << std::setw(encoded_port_size) << std::hex << old_port_number;
os << std::setw(encoded_port_size) << std::hex << new_port_number;
}
// The length in bytes of a control_request and its components.
enum
{
encoded_port_size = 4, // 16-bit port in hex.
control_request_size = encoded_port_size * 2
};
// The encoded request data.
char data_[control_request_size];
};
// This frame is sent from the server to subscribed clients over UDP.
class frame
{
public:
// The maximum allowable length of the payload.
enum { payload_size = 32 };
// Construct an empty frame. Used when receiving.
frame()
{
}
// Construct a frame with specified frame number and payload.
frame(unsigned long frame_number, const std::string& payload_data)
{
std::ostrstream os(data_, frame_size);
os << std::setw(encoded_number_size) << std::hex << frame_number;
os << std::setw(payload_size)
<< std::setfill(' ') << payload_data.substr(0, payload_size);
}
// Get the frame number.
unsigned long number() const
{
std::istrstream is(data_, encoded_number_size);
unsigned long frame_number = 0;
is >> std::setw(encoded_number_size) >> std::hex >> frame_number;
return frame_number;
}
// Get the payload data.
const std::string payload() const
{
return std::string(data_ + encoded_number_size, payload_size);
}
// Obtain buffers for reading from or writing to a socket.
boost::array<asio::mutable_buffer, 1> to_buffers()
{
boost::array<asio::mutable_buffer, 1> buffers
= { { asio::buffer(data_) } };
return buffers;
}
private:
// The length in bytes of a frame and its components.
enum
{
encoded_number_size = 8, // Frame number in hex.
frame_size = encoded_number_size + payload_size
};
// The encoded frame data.
char data_[frame_size];
};
#endif // PORTHOPPER_PROTOCOL_HPP
|
laeotropic/HTTP-Proxy
|
deps/asio-1.10.1/src/examples/cpp03/porthopper/protocol.hpp
|
C++
|
bsd-2-clause
| 4,270 |
class Fdclone < Formula
desc "Console-based file manager"
homepage "https://hp.vector.co.jp/authors/VA012337/soft/fd/"
url "http://www.unixusers.net/src/fdclone/FD-3.01h.tar.gz"
sha256 "24be8af52faa48cd6f123d55cfca45d21e5fd1dc16bed24f6686497429f3e2cf"
bottle do
sha256 "84cacf0bc5a76449dc1e0a00999424eed4e580367ff018c26a82a5fd78315896" => :catalina
sha256 "d312c649a0a3691eee27febe3c579250fda9851ae7fe800712b28dfcbd8a6beb" => :mojave
sha256 "58aa669b9e490b8d744bb22948f1ef37549a35bbff0cbbd216ee76251d4511d9" => :high_sierra
sha256 "0fd727178f488ed0c7f32f5b89aa6d38385ebe8377dc2c8abca84ce9777e6cae" => :sierra
sha256 "c890b9824129c9a4ac969ff4930532841de0cce4f11274f9631029af290561ba" => :el_capitan
end
depends_on "nkf" => :build
uses_from_macos "ncurses"
patch do
url "https://raw.githubusercontent.com/Homebrew/formula-patches/86107cf/fdclone/3.01b.patch"
sha256 "c4159db3052d7e4abec57ca719ff37f5acff626654ab4c1b513d7879dcd1eb78"
end
def install
ENV.deparallelize
system "make", "PREFIX=#{prefix}", "all"
system "make", "MANTOP=#{man}", "install"
%w[README FAQ HISTORY LICENSES TECHKNOW ToAdmin].each do |file|
system "nkf", "-w", "--overwrite", file
prefix.install "#{file}.eng" => file
prefix.install file => "#{file}.ja"
end
pkgshare.install "_fdrc" => "fd2rc.dist"
end
def caveats; <<~EOS
To install the initial config file:
install -c -m 0644 #{opt_pkgshare}/fd2rc.dist ~/.fd2rc
To set application messages to Japanese, edit your .fd2rc:
MESSAGELANG="ja"
EOS
end
end
|
zmwangx/homebrew-core
|
Formula/fdclone.rb
|
Ruby
|
bsd-2-clause
| 1,604 |
class Acpica < Formula
desc "OS-independent implementation of the ACPI specification"
homepage "https://www.acpica.org/"
url "https://acpica.org/sites/acpica/files/acpica-unix-20200717.tar.gz"
sha256 "cb99903ef240732f395af40c23b9b19c7899033f48840743544eebb6da72a828"
license any_of: ["Intel-ACPI", "GPL-2.0-only", "BSD-3-Clause"]
head "https://github.com/acpica/acpica.git"
livecheck do
url "https://acpica.org/downloads"
regex(/current release of ACPICA is version <strong>v?(\d{6,8}) </i)
end
bottle do
cellar :any_skip_relocation
sha256 "e32d0376e072bbe080c114842b0a19b300ad8bd844a046fdd4eeb3894363672f" => :catalina
sha256 "4c61d40a957465fd9d3a90caff51051458beeccf5bac1371c3d1974d0dfeddeb" => :mojave
sha256 "3a1b395d0c4085f054626a808d059317d23614eec01fb011981a9f546366e438" => :high_sierra
sha256 "bac4acbdf59883f7921ebe2467822bfc9228e635735e2c46e07c02ea726f9d5d" => :x86_64_linux
end
uses_from_macos "bison" => :build
uses_from_macos "flex" => :build
uses_from_macos "m4" => :build
def install
ENV.deparallelize
system "make", "PREFIX=#{prefix}"
system "make", "install", "PREFIX=#{prefix}"
end
test do
system "#{bin}/acpihelp", "-u"
end
end
|
maxim-belkin/homebrew-core
|
Formula/acpica.rb
|
Ruby
|
bsd-2-clause
| 1,231 |
<?php
/**
* SorterDropDownColumn class file.
*
* @author Krivtsov Artur (wartur) <gwartur@gmail.com> | Made in Russia
* @copyright Krivtsov Artur © 2014
* @link https://github.com/wartur/yii-sorter-behavior
* @license New BSD license
*/
Yii::import('zii.widgets.grid.CGridColumn', true);
Yii::import('sorter.components.SorterAbstractMoveAction');
/**
* Dropdown column for simple work with SorterActiveRecordBehavior
*
* @author Krivtsov Artur (wartur) <gwartur@gmail.com> | Made in Russia
* @since v1.0.0
*/
class SorterDropDownColumn extends CGridColumn {
const ALGO_MOVE_TO_MODEL = 'sorterMoveToModel';
const ALGO_MOVE_TO_POSITION = 'sorterMoveToPosition';
/**
* @var integer алгоритм работы
*/
public $algo = self::ALGO_MOVE_TO_POSITION;
/**
* @var integer
*/
public $direction = 'up';
/**
* @var array
* Default: array((0), 1, 2, 3, 4, 5, 6, 7, 8, 9);
*/
public $sortValues = null;
/**
* @var string
*/
public $cssDropdownClassPart = null;
/**
* @var type
*/
public $emptyText = null;
/**
* @var string
*/
public $onErrorMoveJsExpression = null;
/**
*
* @var type
*/
public $packToLink = true;
/**
* @var type
*/
protected $renderClass = null;
/**
* @var type
*/
protected $topDivRenderId = null;
/**
* @var type
*/
protected $dropDownRenderId = null;
public function init() {
if ($this->sortValues === null) {
if ($this->algo == self::ALGO_MOVE_TO_MODEL) {
throw new CException(Yii::t('SorterDropDownColumn', 'sortValues is reqired if select algo == ({algo})', array('{algo}' => self::ALGO_MOVE_TO_MODEL)));
} else {
if ($this->direction == SorterAbstractMoveAction::DIRECTION_UP) {
$combine = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
} else {
$combine = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
}
$this->sortValues = array_combine($combine, $combine);
}
}
// only head for optimize css
$this->headerHtmlOptions = CMap::mergeArray(array('style' => 'width: 160px;'), $this->headerHtmlOptions);
if (empty($this->cssDropdownClassPart)) {
$this->cssDropdownClassPart = 'moveDropdown';
}
// set csrf
if (Yii::app()->request->enableCsrfValidation) {
$csrfTokenName = Yii::app()->request->csrfTokenName;
$csrfToken = Yii::app()->request->csrfToken;
$csrf = ", '$csrfTokenName':'$csrfToken'";
} else {
$csrf = '';
}
$paramConst = SorterAbstractMoveAction::PARAM;
$dataParams = "\n\t\tdata:{ '{$paramConst}': $(this).val() {$csrf} },";
$onErrorMoveMessage = isset($this->onErrorMoveMessage) ? $this->onErrorMoveMessage : Yii::t('SorterButtonColumn', 'Move error');
$jsOnChange = <<<EOD
function() {
jQuery('#{$this->grid->id}').yiiGridView('update', {
type: 'POST',
url: $(this).data('url'),$dataParams
success: function(data) {
jQuery('#{$this->grid->id}').yiiGridView('update');
return false;
},
error: function(XHR) {
return '{$onErrorMoveMessage}';
}
});
$(this).attr('disabled', 'disabled');
return false;
}
EOD;
$class = preg_replace('/\s+/', '.', $this->cssDropdownClassPart);
$this->renderClass = "{$class}_{$this->id}";
$this->dropDownRenderId = "dropDown_{$this->id}";
$resultJs = "jQuery(document).on('change','#{$this->grid->id} select.{$this->renderClass}',$jsOnChange);";
if ($this->packToLink) {
$resultJs .= "\n";
$this->topDivRenderId = "topDiv_{$class}_{$this->id}";
$resultJs .= <<<EOD
jQuery(document).on('mousedown','#{$this->grid->id} a.{$this->renderClass}',function() {
_select = $($('#{$this->topDivRenderId}').html()).attr('data-url', $(this).attr("href"));
$(this).after(_select);
$(this).hide();
_select.simulate('mousedown');
return false;
});\n
EOD;
$resultJs .= <<<EOD
jQuery(document).on('focusout','#{$this->grid->id} select.{$this->renderClass}',function(){
$(this).parent().find('a.{$this->renderClass}').show();
$(this).remove();
return false;
});
EOD;
// зарегистриуем либу для поддержки автовыпадения селекта
$am = Yii::app()->assetManager; /* @var $am CAssetManager */
$cs = Yii::app()->clientScript; /* @var $cs CClientScript */
$path = $am->publish(Yii::getPathOfAlias('sorter.assets') . "/jquery.simulate.js");
$cs->registerScriptFile($path);
}
// инициализировать выпадающий список
Yii::app()->getClientScript()->registerScript(__CLASS__ . '#' . $this->id, $resultJs);
}
protected function renderHeaderCellContent() {
parent::renderHeaderCellContent();
if($this->packToLink) {
// расположим динамические данные в хедар
$dropDownHtml = CHtml::dropDownList($this->dropDownRenderId, null, $this->sortValues, array(
'class' => $this->renderClass,
'empty' => $this->getRealEmptyText(),
));
echo CHtml::tag('div', array('style' => 'display: none;', 'id' => $this->topDivRenderId), $dropDownHtml);
}
}
protected function renderDataCellContent($row, $data) {
if ($this->packToLink) {
// тут вывести линк с доп данными которые далее будут резолвиться в селект
echo CHtml::link($this->getRealEmptyText(), Yii::app()->controller->createUrl($this->algo, array('id' => $data->getPrimaryKey(), 'd' => $this->direction)), array(
'class' => $this->renderClass
));
} else {
echo CHtml::dropDownList("{$this->dropDownRenderId}_{$row}", null, $this->sortValues, array(
'class' => $this->renderClass,
'empty' => $this->getRealEmptyText(),
'data-url' => Yii::app()->controller->createUrl($this->algo, array('id' => $data->getPrimaryKey(), 'd' => $this->direction))
));
}
}
public function getRealEmptyText() {
$result = null;
if ($this->algo == self::ALGO_MOVE_TO_MODEL) {
if ($this->direction == 'up') {
$result = isset($this->emptyText) ? $this->emptyText : Yii::t('SorterDropDownColumn', '(move before model)');
} else {
$result = isset($this->emptyText) ? $this->emptyText : Yii::t('SorterDropDownColumn', '(move after model)');
}
} else if ($this->algo == self::ALGO_MOVE_TO_POSITION) {
if ($this->direction == 'up') {
$result = isset($this->emptyText) ? $this->emptyText : Yii::t('SorterDropDownColumn', '(move before position)');
} else {
$result = isset($this->emptyText) ? $this->emptyText : Yii::t('SorterDropDownColumn', '(move after position)');
}
} else {
throw new CException(Yii::t('SorterDropDownColumn', 'Unexpected algo == ({algo})', array('{algo}' => $this->algo)));
}
return $result;
}
}
|
wartur/yii-sorter
|
widgets/SorterDropDownColumn.php
|
PHP
|
bsd-2-clause
| 6,834 |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0">
<context>
<name>dialogWPAPersonal</name>
<message>
<source>WPA Personal Config</source>
<translation>WPA-Personal seadistus</translation>
</message>
<message>
<source>&Close</source>
<translation>&Sulge</translation>
</message>
<message>
<source>Alt+C</source>
<translation>Alt+S</translation>
</message>
<message>
<source>Network Key</source>
<translation>Võrgu võti</translation>
</message>
<message>
<source>Network Key (Repeat)</source>
<translation>Võrgu võti (korrata)</translation>
</message>
<message>
<source>Show Key</source>
<translation>Näita võtit</translation>
</message>
<message>
<source>WPA Personal Configuration</source>
<translation>WPA-Personal seadistus</translation>
</message>
</context>
<context>
<name>wepConfig</name>
<message>
<source>WEP Configuration</source>
<translation>WEP konfiguratsioon</translation>
</message>
<message>
<source>Network Key</source>
<translation>Võrgu võti</translation>
</message>
<message>
<source>Network Key (Repeat)</source>
<translation>Võrgu võti (korrata)</translation>
</message>
<message>
<source>Key Index</source>
<translation>Võtme indeks</translation>
</message>
<message>
<source>&Close</source>
<translation>&Sulge</translation>
</message>
<message>
<source>Alt+C</source>
<translation>Alt+S</translation>
</message>
<message>
<source>Hex Key</source>
<translation>Heksadetsimaalarv</translation>
</message>
<message>
<source>Plaintext</source>
<translation>Lihttekst</translation>
</message>
<message>
<source>Show Key</source>
<translation>Näita võtit</translation>
</message>
<message>
<source>Wireless Network Key</source>
<translation>Traadita võrgu võti</translation>
</message>
</context>
<context>
<name>wificonfigwidgetbase</name>
<message>
<source>Wireless Configuration</source>
<translation>Wi-Fi seadistus</translation>
</message>
<message>
<source>&General</source>
<translation>Ü&ldine</translation>
</message>
<message>
<source>O&btain IP automatically (DHCP)</source>
<translation>Seadista &IP-aadress automaatselt (DHCP)</translation>
</message>
<message>
<source>Alt+B</source>
<translation>Alt+I</translation>
</message>
<message>
<source>Alt+S</source>
<translation>Alt+V</translation>
</message>
<message>
<source>Assign static IP address</source>
<translation>Seadista püsiv IP-aadress</translation>
</message>
<message>
<source>IP:</source>
<translation>IP:</translation>
</message>
<message>
<source>Netmask:</source>
<translation>Võrgumask:</translation>
</message>
<message>
<source>999\.999\.999\.999; </source>
<translation>999\.999\.999\.999;</translation>
</message>
<message>
<source>Advanced</source>
<translation>Täpsemad valikud</translation>
</message>
<message>
<source>Use hardware defau&lt MAC address</source>
<translation>Kasuta võrgukaardi &vaikimisi MAC-aadressi</translation>
</message>
<message>
<source>Alt+L</source>
<translation>Alt+V</translation>
</message>
<message>
<source>Custom MAC address</source>
<translation>Kohandatud MAC-aadress</translation>
</message>
<message>
<source>Info</source>
<translation>Info</translation>
</message>
<message>
<source>Configuration info</source>
<translation>Seadistuse info</translation>
</message>
<message>
<source>Mac/Ether:</source>
<translation>MAC-aadress:</translation>
</message>
<message>
<source>Gateway:</source>
<translation>Lüüs:</translation>
</message>
<message>
<source>IPv6:</source>
<translation>IPv6:</translation>
</message>
<message>
<source>Status:</source>
<translation>Olek:</translation>
</message>
<message>
<source>Media:</source>
<translation>Meedia:</translation>
</message>
<message>
<source>Traffic info</source>
<translation>Võrguliiklus</translation>
</message>
<message>
<source>Packets:</source>
<translation>Pakette:</translation>
</message>
<message>
<source>Errors:</source>
<translation>Vigu:</translation>
</message>
<message>
<source>In:</source>
<translation>Sisse:</translation>
</message>
<message>
<source>Out:</source>
<translation>Välja:</translation>
</message>
<message>
<source>Close</source>
<translation>Sulge</translation>
</message>
<message>
<source>Disable this wireless device</source>
<translation>Lülitada see traadita seade välja</translation>
</message>
<message>
<source>&Apply</source>
<translation>&Rakenda</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+R</translation>
</message>
<message>
<source>&OK</source>
<translation>&Olgu</translation>
</message>
<message>
<source>Alt+O</source>
<translation>Alt+O</translation>
</message>
<message>
<source>Missing Fields</source>
<translation>Puuduvad väljad</translation>
</message>
<message>
<source>You must enter an IP and Netmask to continue!
</source>
<translation>Jätkamiseks on vajalikud on IP-aadress ja võrgumask!
</translation>
</message>
<message>
<source>Warning</source>
<translation>Hoiatus</translation>
</message>
<message>
<source>IP Address is out of range! (</source>
<translation>IP-aadress ei ole lubatud piirides! (</translation>
</message>
<message>
<source>) Fields must be between 0-255.</source>
<translation>) Väljad peavad olema vahemikus 0–255.</translation>
</message>
<message>
<source>Netmask is out of range! (</source>
<translation>Võrgumask ei ole lubatud piirides! (</translation>
</message>
<message>
<source>Remove</source>
<translation>Eemalda</translation>
</message>
<message>
<source>Error</source>
<translation>Viga</translation>
</message>
<message>
<source>You already have a wireless network with this SSID! Please remove it first.
</source>
<translation>Sellise SSID-ga traadita võrk on juba olemas! Palun eemalda see kõigepealt.
</translation>
</message>
<message>
<source>Edit</source>
<translation>Muuda</translation>
</message>
<message>
<source>Unknown Wireless Device</source>
<translation>Tundmatu traadita seade</translation>
</message>
<message>
<source>(Higher connections are given priority)</source>
<translation>(Kõrgematele ühendustele antakse suurem prioriteet)</translation>
</message>
<message>
<source>Available Wireless Networks</source>
<translation>Saadaval traadita võrgud</translation>
</message>
<message>
<source>Scan</source>
<translation>Skaneeri</translation>
</message>
<message>
<source>Add Selected</source>
<translation>Lisa valitud</translation>
</message>
<message>
<source>Add Hidden</source>
<translation>Lisa peidetud võrk</translation>
</message>
<message>
<source>Network Name</source>
<translation>Võrgu nimi</translation>
</message>
<message>
<source>Please enter the name of the network you wish to add</source>
<translation>Palun sisesta võrgu nimi, mille soovid lisada </translation>
</message>
<message>
<source>Configured Network Profiles</source>
<translation>Seadistatud võrguprofiilid</translation>
</message>
<message>
<source>Add &network</source>
<translation>&Lisa võrk</translation>
</message>
<message>
<source>WPA Configuration</source>
<translation>WPA seadistus</translation>
</message>
<message>
<source>Set Country Code</source>
<translation>Määra maakood</translation>
</message>
</context>
<context>
<name>wifiscanssid</name>
<message>
<source>Scan for Wireless networks</source>
<translation>Otsi traadita võrke</translation>
</message>
<message>
<source>Available wireless networks</source>
<translation>Kättesaadavad WiFi võrgud</translation>
</message>
<message>
<source>&Rescan</source>
<translation>Skanee&ri uuesti</translation>
</message>
<message>
<source>Alt+R</source>
<translation>Alt+R</translation>
</message>
<message>
<source>Select</source>
<translation>Vali</translation>
</message>
<message>
<source>Alt+C</source>
<translation>Alt+C</translation>
</message>
<message>
<source>Cancel</source>
<translation>Katkesta</translation>
</message>
<message>
<source>Scanning for wireless networks...</source>
<translation>Wi-Fi võrkude skaneerimine...</translation>
</message>
<message>
<source>Select a wireless network to connect.</source>
<translation>Vali traadita võrk, millega soovid ühenduda.</translation>
</message>
<message>
<source>No wireless networks found!</source>
<translation>Ühtegi traadita võrku ei leitud!</translation>
</message>
<message>
<source>No selection</source>
<translation>Valik puudub</translation>
</message>
<message>
<source>Error: You must select a network to connect!
</source>
<translation>Viga: valige võrk, millega liituda!</translation>
</message>
</context>
<context>
<name>wifiselectiondialog</name>
<message>
<source>Select Wireless Network</source>
<translation>Vali traadita võrk</translation>
</message>
<message>
<source>Alt+C</source>
<translation>Alt+N</translation>
</message>
<message>
<source>Cancel</source>
<translation>Katkesta</translation>
</message>
<message>
<source>Selected Wireless Network</source>
<translation>Valitud traadita võrk</translation>
</message>
<message>
<source>Scan</source>
<translation>Skaneeri</translation>
</message>
<message>
<source>Using BSSID</source>
<translation>Kasutatakse BSSID-d</translation>
</message>
<message>
<source>Disabled</source>
<translation>Keelatud</translation>
</message>
<message>
<source>WEP</source>
<translation>WEP</translation>
</message>
<message>
<source>WPA Personal</source>
<translation>WPA-Personal</translation>
</message>
<message>
<source>WPA Enterprise</source>
<translation>WPA-Enterprise</translation>
</message>
<message>
<source>Configure</source>
<translation>Seadista</translation>
</message>
<message>
<source>Add</source>
<translation>Lisa</translation>
</message>
<message>
<source>No SSID!</source>
<translation>SSID puudub!</translation>
</message>
<message>
<source>Error: You must select a wireless network to connect!
</source>
<translation>Viga: tuleb valida traadita võrk, millega ühenduda!
</translation>
</message>
<message>
<source>Invalid BSSID!</source>
<translation>Vigane BSSID!</translation>
</message>
<message>
<source>Error: The specified BSSID appears invalid. It must be in the format xx:xx:xx:xx:xx:xx
</source>
<translation>Viga: valitud BSSID paistab olevat vigane! See peab olema kujul xx:xx:xx:xx:xx:xx
</translation>
</message>
<message>
<source>Warning</source>
<translation>Hoiatus</translation>
</message>
<message>
<source>WEP is selected, but not configured!
Please configure your WEP key before saving!</source>
<translation>WEP on valitud, kuid ei ole seadistatud! Palume seadistada WEP võti enne salvestamist!</translation>
</message>
<message>
<source>WPA-Personal is selected, but not configured!
Please configure your WPA key before saving!</source>
<translation>WPA-Personal on valitud, kuid ei ole seadistatud! Palume seadistada WPA võti enne salvestamist!</translation>
</message>
<message>
<source>WPA-Enterprise is selected, but not configured!
Please configure your WPA settings before saving!</source>
<translation>WPA-Enterprise on valitud, kuid ei ole seadistatud! Palume seadistada WPA võti enne salvestamist!</translation>
</message>
<message>
<source>WEP (Configured)</source>
<translation>WEP (seadistatud)</translation>
</message>
<message>
<source>WPA Personal (Configured)</source>
<translation>WPA-Personal (seadistatud)</translation>
</message>
<message>
<source>WPA Enterprise (Configured)</source>
<translation>WPA-Enterprise (seadistatud)</translation>
</message>
<message>
<source>Save</source>
<translation>Salvesta</translation>
</message>
<message>
<source>Network Security</source>
<translation>Võrgu turvalisus</translation>
</message>
</context>
</TS>
|
NorwegianRockCat/pc-networkmanager
|
src/wificonfig/i18n/wificonfig_et.ts
|
TypeScript
|
bsd-2-clause
| 14,175 |
/*
* Copyright (c) 2017, Loic Blot <loic.blot@unix-experience.fr>
* All rights reserved.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "amqp/connection.h"
#include <iostream>
#include <cstring>
#include "utils/log.h"
#include "amqp/exception.h"
#include "amqp/channel.h"
#include "amqp/envelope.h"
#include "amqp/log.h"
#include "amqp/message.h"
namespace winterwind
{
namespace amqp
{
Connection::Connection(const std::string &url, uint64_t wait_timeout) :
m_wait_timeout_ms(wait_timeout)
{
amqp_connection_info info{};
amqp_default_connection_info(&info);
if (!url.empty()) {
char url_buf[1024];
memset(url_buf, 0, sizeof(url_buf));
memcpy(url_buf, url.data(), url.size());
if (amqp_parse_url(url_buf, &info) != AMQP_STATUS_OK) {
throw amqp::exception("Unable to parse AMQP URL.");
}
}
connect(info.host, (uint16_t) info.port, info.user, info.password, info.vhost);
}
Connection::Connection(const std::string &host, uint16_t port,
const std::string &username, const std::string &password, const std::string &vhost,
int32_t frame_max, uint64_t wait_timeout) :
m_frame_max(frame_max),
m_wait_timeout_ms(wait_timeout)
{
connect(host.c_str(), port, username.c_str(), password.c_str(), vhost.c_str());
}
Connection::~Connection()
{
// Invalidate channels
for (auto &channel: m_channels) {
channel.second->invalidate();
}
amqp_connection_close(m_conn, AMQP_REPLY_SUCCESS);
if (amqp_destroy_connection(m_conn) != AMQP_STATUS_OK) {
log_error(amqp_log, "Failed to destroy AMQP connection.");
}
}
void Connection::connect(const char *host, uint16_t port,
const char *username, const char *password, const char *vhost)
{
m_conn = amqp_new_connection();
if (!m_conn) {
log_error(amqp_log, "Unable to allocate a new AMQP connection.");
throw amqp::exception("Unable to allocate a new AMQP connection.");
}
socket = amqp_tcp_socket_new(m_conn);
if (!socket) {
log_error(amqp_log, "Unable to allocate a new AMQP socket.");
throw amqp::exception("Unable to allocate a new AMQP socket.");
}
if (!open(host, port)) {
throw amqp::exception("Unable to open AMQP connection");
}
if (!login(username, password, vhost, m_frame_max)) {
throw amqp::exception("Unable to login to AMQP connection");
}
}
bool Connection::open(const char *host, uint16_t port)
{
int status = amqp_socket_open(socket, host, port);
if (status != AMQP_STATUS_OK) {
log_error(amqp_log, "Failed to open AMQP connection (code: " +
std::to_string(status) + ")");
return false;
}
return true;
}
bool Connection::login(const std::string &user, const std::string &password,
const std::string &vhost, int32_t frame_max)
{
amqp_rpc_reply_t result = amqp_login(m_conn, vhost.c_str(), 0, frame_max,
m_heartbeat_interval, AMQP_SASL_METHOD_PLAIN, user.c_str(), password.c_str());
if (result.reply_type != AMQP_RESPONSE_NORMAL) {
std::stringstream ss;
ss << "login failure (reply_type: " << result.reply_type << ").";
if (result.reply_type == AMQP_RESPONSE_SERVER_EXCEPTION) {
auto login_exception = (amqp_channel_close_t *)result.reply.decoded;
ss << " Reply ID: " << result.reply.id << ", exception was: "
<< std::string((const char *) login_exception->reply_text.bytes,
login_exception->reply_text.len) << std::endl;
}
log_error(amqp_log, ss.str());
}
return result.reply_type == AMQP_RESPONSE_NORMAL;
}
bool Connection::set_heartbeat_interval(uint32_t interval)
{
if (amqp_tune_connection(m_conn, 0, m_frame_max, interval) != AMQP_STATUS_OK) {
return false;
}
m_heartbeat_interval = interval;
return true;
}
int32_t Connection::get_channel_max()
{
return amqp_get_channel_max(m_conn);
}
std::shared_ptr<Channel> Connection::create_channel()
{
if (m_channels.size() == get_channel_max()) {
log_error(amqp_log, "Unable to open AMQP channel: max channel reached");
return nullptr;
}
// @TODO handle offsets properly
++m_next_channel_id;
std::shared_ptr<Channel> new_channel = std::make_shared<Channel>(m_next_channel_id,
shared_from_this());
m_channels[m_next_channel_id] = new_channel;
return new_channel;
}
void Connection::destroy_channel(std::shared_ptr<Channel> channel)
{
auto channel_it = m_channels.find(channel->m_id);
if (channel_it != m_channels.end()) {
m_channels.erase(channel_it);
}
channel->close();
}
std::shared_ptr<Channel> Connection::find_channel(uint16_t channel_id)
{
auto channel_it = m_channels.find(channel_id);
if (channel_it == m_channels.end()) {
return nullptr;
}
return channel_it->second;
}
bool Connection::start_consuming()
{
while (!m_stop) {
if (!consume_one()) {
return false;
}
}
return true;
}
bool Connection::consume_one()
{
amqp_frame_t frame{};
amqp_envelope_t envelope{};
amqp_rpc_reply_t ret;
amqp_maybe_release_buffers(m_conn);
if (m_wait_timeout_ms) {
timeval tv;
tv.tv_sec = 0;
tv.tv_usec = m_wait_timeout_ms;
ret = amqp_consume_message(m_conn, &envelope, &tv, 0);
}
else {
ret = amqp_consume_message(m_conn, &envelope, nullptr, 0);
}
if (AMQP_RESPONSE_NORMAL != ret.reply_type) {
if (AMQP_RESPONSE_LIBRARY_EXCEPTION == ret.reply_type &&
AMQP_STATUS_UNEXPECTED_STATE == ret.library_error) {
if (AMQP_STATUS_OK != amqp_simple_wait_frame(m_conn, &frame)) {
log_error(amqp_log, "amqp_simple_wait_frame consuming error")
return false;
}
if (AMQP_FRAME_METHOD == frame.frame_type) {
switch (frame.payload.method.id) {
case AMQP_BASIC_ACK_METHOD:
/*
* if we've turned publisher confirms on, and we've published a message
* here is a message being confirmed
*/
// @TODO callback the ack
break;
case AMQP_BASIC_RETURN_METHOD: {
/*
* if a published message couldn't be routed and the mandatory flag was set
* this is what would be returned. The message then needs to be read.
*/
amqp_message_t raw_message{};
ret = amqp_read_message(m_conn, frame.channel, &raw_message, 0);
if (AMQP_RESPONSE_NORMAL != ret.reply_type) {
return false;
}
std::shared_ptr<Channel> channel = find_channel(frame.channel);
if (channel == nullptr) {
log_error(amqp_log, "failed to reroute unsent message to "
"channel id " + std::to_string(frame.channel))
return false;
}
// Request channel to handle unsent message
channel->on_unsent_message(std::make_shared<Message>(&raw_message));
amqp_destroy_message(&raw_message);
break;
}
case AMQP_CHANNEL_CLOSE_METHOD:
/*
* a channel.close method happens when a channel exception occurs, this
* can happen by publishing to an exchange that doesn't exist for example
*
* In this case you would need to open another channel redeclare any queues
* that were declared auto-delete, and restart any consumers that were attached
* to the previous channel
*/
return false;
case AMQP_CONNECTION_CLOSE_METHOD:
/*
* a connection.close method happens when a connection exception occurs,
* this can happen by trying to use a channel that isn't open for example.
*
* In this case the whole connection must be restarted.
*/
return false;
default:
log_error(amqp_log, "An unexpected method was received "
+ std::to_string(frame.payload.method.id));
return false;
}
}
}
} else {
std::stringstream ss;
ss << "Message received on channel " << envelope.channel << std::endl;
log_info(amqp_log, ss.str())
distribute_envelope(std::make_shared<Envelope>(&envelope), envelope.channel);
amqp_destroy_envelope(&envelope);
}
return true;
}
bool Connection::distribute_envelope(EnvelopePtr envelope, uint16_t channel_id)
{
std::shared_ptr<Channel> channel = find_channel(channel_id);
if (channel == nullptr) {
log_error(amqp_log, "failed to distribute envelope to channel id "
+ std::to_string(channel_id))
return false;
}
return channel->on_envelope_received(std::move(envelope));
}
}
}
|
WinterWind/WinterWind
|
src/core/amqp/connection.cpp
|
C++
|
bsd-2-clause
| 9,314 |
#nullable enable
using System;
using Esprima;
using Jint.Native;
using Jint.Native.Error;
using Jint.Native.Object;
using Jint.Pooling;
namespace Jint.Runtime
{
public class JavaScriptException : JintException
{
private string? _callStack;
public JavaScriptException(ErrorConstructor errorConstructor) : base("")
{
Error = errorConstructor.Construct(Arguments.Empty);
}
public JavaScriptException(ErrorConstructor errorConstructor, string? message, Exception? innerException)
: base(message, innerException)
{
Error = errorConstructor.Construct(new JsValue[] { message });
}
public JavaScriptException(ErrorConstructor errorConstructor, string? message)
: base(message)
{
Error = errorConstructor.Construct(new JsValue[] { message });
}
public JavaScriptException(JsValue error)
{
Error = error;
}
// Copy constructors
public JavaScriptException(JavaScriptException exception, Exception? innerException) : base(exception.Message, exception.InnerException)
{
Error = exception.Error;
Location = exception.Location;
}
public JavaScriptException(JavaScriptException exception) : base(exception.Message)
{
Error = exception.Error;
Location = exception.Location;
}
internal JavaScriptException SetLocation(Location location)
{
Location = location;
return this;
}
internal JavaScriptException SetCallstack(Engine engine, Location location)
{
Location = location;
var value = engine.CallStack.BuildCallStackString(location);
_callStack = value;
if (Error.IsObject())
{
Error.AsObject()
.FastAddProperty(CommonProperties.Stack, new JsString(value), false, false, false);
}
return this;
}
private string? GetErrorMessage()
{
if (Error is ObjectInstance oi)
{
return oi.Get(CommonProperties.Message).ToString();
}
return null;
}
public JsValue Error { get; }
public override string Message => GetErrorMessage() ?? TypeConverter.ToString(Error);
/// <summary>
/// Returns the call stack of the exception. Requires that engine was built using
/// <see cref="Options.CollectStackTrace"/>.
/// </summary>
public override string? StackTrace
{
get
{
if (_callStack is not null)
{
return _callStack;
}
if (Error is not ObjectInstance oi)
{
return null;
}
var callstack = oi.Get(CommonProperties.Stack, Error);
return callstack.IsUndefined()
? null
: callstack.AsString();
}
}
public Location Location { get; protected set; }
public int LineNumber => Location.Start.Line;
public int Column => Location.Start.Column;
public override string ToString()
{
// adapted custom version as logic differs between full framework and .NET Core
var className = GetType().ToString();
var message = Message;
var innerExceptionString = InnerException?.ToString() ?? "";
const string endOfInnerExceptionResource = "--- End of inner exception stack trace ---";
var stackTrace = StackTrace;
using var rent = StringBuilderPool.Rent();
var sb = rent.Builder;
sb.Append(className);
if (!string.IsNullOrEmpty(message))
{
sb.Append(": ");
sb.Append(message);
}
if (InnerException != null)
{
sb.Append(Environment.NewLine);
sb.Append(" ---> ");
sb.Append(innerExceptionString);
sb.Append(Environment.NewLine);
sb.Append(" ");
sb.Append(endOfInnerExceptionResource);
}
if (stackTrace != null)
{
sb.Append(Environment.NewLine);
sb.Append(stackTrace);
}
return rent.ToString();
}
}
}
|
sebastienros/jint
|
Jint/Runtime/JavaScriptException.cs
|
C#
|
bsd-2-clause
| 4,591 |
import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import validate
YOUTUBE_URL = "https://www.youtube.com/watch?v={0}"
_url_re = re.compile(r'http(s)?://www\.skai.gr/.*')
_youtube_id = re.compile(r'<span\s+itemprop="contentUrl"\s+href="(.*)"></span>', re.MULTILINE)
_youtube_url_schema = validate.Schema(
validate.all(
validate.transform(_youtube_id.search),
validate.any(
None,
validate.all(
validate.get(1),
validate.text
)
)
)
)
class Skai(Plugin):
@classmethod
def can_handle_url(cls, url):
return _url_re.match(url)
def _get_streams(self):
channel_id = self.session.http.get(self.url, schema=_youtube_url_schema)
if channel_id:
return self.session.streams(YOUTUBE_URL.format(channel_id))
__plugin__ = Skai
|
back-to/streamlink
|
src/streamlink/plugins/skai.py
|
Python
|
bsd-2-clause
| 889 |
/*
* Copyright (c) 2019, Kyle Sergio <https://github.com/ksergio39>
* Copyright (c) 2019, Bryce Altomare <https://github.com/Twinkiel0ver>
* Copyright (c) 2019, Kyle Stead <http://github.com/kyle1elyk>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.worldmap;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.runelite.api.coords.WorldPoint;
import javax.annotation.Nullable;
@Getter
@AllArgsConstructor
enum TransportationPointLocation
{
//Ships
ARDOUGNE_TO_BRIMHAVEN("Ship to Brimhaven / Rimmington", new WorldPoint(2675, 3275, 0)),
ARDOUGNE_TO_FISHINGPLAT("Ship to Fishing Platform", new WorldPoint(2722, 3304, 0), new WorldPoint(2779, 3271, 0)),
BRIMHAVEN_TO_ARDOUGNE("Ship to Ardougne / Rimmington", new WorldPoint(2772, 3234, 0)),
RIMMINGTON_TO_ARDOUGNE("Ship to Ardougne / Brimhaven", new WorldPoint(2915, 3224, 0)),
CATHERBY_TO_KEEP_LE_FAYE("Ship to Keep Le Faye", new WorldPoint(2804, 3421, 0), new WorldPoint(2769, 3402, 0)),
CORSAIR_TO_RIMMINGTON("Ship to Rimmington", new WorldPoint(2577, 2839, 0), new WorldPoint(2909, 3227, 0 )),
DRAGONTOOTH_TO_PHASMATYS("Ship to Port Phasmatys", new WorldPoint(3791, 3561, 0), new WorldPoint(3703, 3487, 0)),
DIGSITE_TO_FOSSIL("Ship to Fossil Island", new WorldPoint(3361, 3448, 0), new WorldPoint(3723, 3807, 0)),
ENTRANA_TO_PORTSARIM("Ship to Port Sarim", new WorldPoint(2833, 3334, 0), new WorldPoint(3046, 3233, 0)),
FISHINGPLAT_TO_ARDOUGNE("Ship to Ardougne", new WorldPoint(2779, 3271, 0), new WorldPoint(2722, 3304, 0)),
HARMLESS_TO_PORT_PHASMATYS("Ship to Port Phasmatys", new WorldPoint(3682, 2951, 0), new WorldPoint(3709, 3497, 0)),
ICEBERG_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2657, 3988, 0), new WorldPoint(2707, 3735, 0)),
ISLAND_OF_STONE_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2470, 3994, 0), new WorldPoint(2621, 3692, 0)),
ISLAND_TO_APE_ATOLL("Ship to Ape Atoll", new WorldPoint(2891, 2726, 0), new WorldPoint(2802, 2706, 0)),
JATIZSO_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2420, 3780, 0), new WorldPoint(2639, 3710, 0)),
KARAMJA_TO_PORT_SARIM("Ship to Port Sarim", new WorldPoint(2955, 3145, 0), new WorldPoint(3029, 3218, 0)),
KARAMJA_TO_PORT_KHAZARD("Ship to Port Khazard", new WorldPoint(2763, 2957, 0), new WorldPoint(2653, 3166, 0)),
LANDSEND_TO_PORTSARIM_PORTPISCARILIUS("Ship to Port Sarim/Port Piscarilius", new WorldPoint(1503, 3398, 0)),
LUNAR_ISLE_TO_PIRATES_COVE("Ship to Pirates' Cove", new WorldPoint(2137, 3899, 0), new WorldPoint(2223, 3796, 0)),
MISCELLANIA_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2579, 3846, 0), new WorldPoint(2627, 3692, 0)),
NEITIZNOT_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2310, 3779, 0), new WorldPoint(2639, 3710, 0)),
PESTCONTROL_TO_PORTSARIM("Ship to Port Sarim", new WorldPoint(2659, 2675, 0), new WorldPoint(3039, 3201, 0)),
PIRATES_COVE_TO_LUNAR_ISLE("Ship to Lunar Isle", new WorldPoint(2223, 3796, 0), new WorldPoint(2137, 3899, 0)),
PIRATES_COVE_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2212, 3794, 0), new WorldPoint(2620, 3695, 0)),
PORT_PHASMATYS_TO_DRAGONTOOTH("Ship to Dragontooth Island", new WorldPoint(3703, 3487, 0), new WorldPoint(3791, 3561, 0)),
PORT_PHASMATYS_TO_HARMLESS("Ship to Mos Le'Harmless", new WorldPoint(3709, 3497, 0), new WorldPoint(3682, 2951, 0)),
PORT_PISCARILIUS_TO_PORTSARIM_LANDSEND("Ship to Port Sarim/Land's End", new WorldPoint(1823, 3692, 0)),
PORTSARIM_TO_GREAT_KOUREND("Ship to Great Kourend", new WorldPoint(3054, 3244, 0), new WorldPoint(1823, 3692, 0)),
PORTSARIM_TO_ENTRANA("Ship to Entrana", new WorldPoint(3046, 3233, 0), new WorldPoint(2833, 3334, 0)),
PORTSARIM_TO_KARAMJA("Ship to Karamja", new WorldPoint(3029, 3218, 0), new WorldPoint(2955, 3144, 0)),
PORTSARIM_TO_CRANDOR("Ship to Crandor", new WorldPoint(3045, 3205, 0), new WorldPoint(2839, 3261, 0)),
PORTSARIM_TO_PEST_CONTROL("Ship to Pest Control", new WorldPoint(3039, 3201, 0), new WorldPoint(2659, 2675, 0)),
RELLEKKA_TO_JATIZSO_NEITIZNOT("Ship to Jatizso/Neitiznot", new WorldPoint(2639, 3710, 0)),
RELLEKKA_TO_MISCELLANIA("Ship to Miscellania", new WorldPoint(2627, 3692, 0), new WorldPoint(2579, 3846, 0)),
RELLEKKA_TO_PIRATES_COVE("Ship to Pirates' Cove", new WorldPoint(2620, 3695, 0), new WorldPoint(2212, 3794, 0)),
RELLEKKA_TO_WATERBIRTH("Ship to Waterbirth", new WorldPoint(2618, 3685, 0), new WorldPoint(2549, 3758, 0)),
RELLEKKA_TO_WEISS_ICEBERG("Ship to Weiss/Iceberg", new WorldPoint(2707, 3735, 0)),
RELLEKKA_TO_UNGAEL("Ship to Ungael", new WorldPoint(2638, 3698, 0), new WorldPoint(2276, 4034, 0)),
RIMMINGTON_TO_CORSAIR_COVE("Ship to Corsair Cove", new WorldPoint(2909, 3227, 0 ), new WorldPoint(2577, 2839, 0)),
WATERBIRTH_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2549, 3758, 0), new WorldPoint(2618, 3685, 0)),
WEISS_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2847, 3967, 0), new WorldPoint(2707, 3735, 0)),
UNGAEL_TO_RELLEKKA("Ship to Rellekka", new WorldPoint(2276, 4034, 0), new WorldPoint(2638, 3698, 0)),
//Row Boats
ROW_BOAT_BATTLEFRONT("Rowboat to Molch/Molch Island/Shayzien", new WorldPoint(1383, 3663, 0)),
ROW_BOAT_BRAIN_DEATH("Rowboat to Port Phasmatys", new WorldPoint(2161, 5117, 0), new WorldPoint(3680, 3538, 0)),
ROW_BOAT_BURGH_DE_ROTT("Rowboat to Meiyerditch", new WorldPoint(3522, 3168, 0), new WorldPoint(3589, 3172, 0)),
ROW_BOAT_CRABCLAW("Rowboat to Hosidius", new WorldPoint(1780, 3417, 0), new WorldPoint(1779, 3457, 0)),
ROW_BOAT_DIVING_ISLAND("Rowboat to Barge/Camp/North of Island", new WorldPoint(3764, 3901, 0)),
ROW_BOAT_FISHING_GUILD("Rowboat to Hemenster", new WorldPoint(2598, 3426, 0), new WorldPoint(2613, 3439, 0)),
ROW_BOAT_GNOME_STRONGHOLD("Rowboat to Fishing Colony", new WorldPoint(2368, 3487, 0), new WorldPoint(2356, 3641, 0)),
ROW_BOAT_FISHING_COLONY("Rowboat to Gnome Stronghold", new WorldPoint(2356, 3641, 0), new WorldPoint(2368, 3487, 0)),
ROW_BOAT_HEMENSTER("Rowboat to Fishing Guild", new WorldPoint(2613, 3439, 0), new WorldPoint(2598, 3426, 0)),
ROW_BOAT_HOSIDIUS("Rowboat to Crabclaw Isle", new WorldPoint(1779, 3457, 0), new WorldPoint(1780, 3417, 0)),
ROW_BOAT_LITHKREN("Rowboat to Mushroom Forest", new WorldPoint(3582, 3973, 0), new WorldPoint(3659, 3849, 0)),
ROW_BOAT_LUMBRIDGE("Rowboat to Misthalin Mystery", new WorldPoint(3238, 3141, 0)),
ROW_BOAT_MOLCH("Rowboat to Molch Island/Shayzien/Battlefront", new WorldPoint(1343, 3646, 0)),
ROW_BOAT_MOLCH_ISLAND("Rowboat to Molch/Shayzien/Battlefront", new WorldPoint(1368, 3641, 0)),
ROW_BOAT_MORT("Rowboat to Mort Myre", new WorldPoint(3518, 3284, 0), new WorldPoint(3498, 3380, 0)),
ROW_BOAT_MORT_SWAMP("Rowboat to Mort'ton", new WorldPoint(3498, 3380, 0), new WorldPoint(3518, 3284, 0)),
ROW_BOAT_MUSEUM_CAMP("Rowboat to Barge/Digsite/North of Island", new WorldPoint(3723, 3807, 0)),
ROW_BOAT_MUSHROOM_FOREST_WEST("Rowboat to Lithkren", new WorldPoint(3659, 3849, 0), new WorldPoint(3582, 3973, 0)),
ROW_BOAT_MUSHROOM_FOREST_NE("Rowboat to Barge/Camp/Sea", new WorldPoint(3733, 3894, 0)),
ROW_BOAT_PORT_PHASMATYS_NORTH("Rowboat to Slepe", new WorldPoint(3670, 3545, 0), new WorldPoint(3661, 3279, 0)),
ROW_BOAT_PORT_PHASMATYS_EAST("Rowboat to Braindeath Island", new WorldPoint(3680, 3538, 0), new WorldPoint(2161, 5117, 0)),
ROW_BOAT_SHAYZIEN("Rowboat to Molch/Molch Island/Battlefront", new WorldPoint(1405, 3612, 0)),
ROW_BOAT_SLEPE("Rowboat to Port Phasmatys", new WorldPoint(3661, 3279, 0), new WorldPoint(3670, 3545, 0)),
OGRE_BOAT_FELDIP("Ogre Boat to Karamja", new WorldPoint(2653, 2964, 0), new WorldPoint(2757, 3085, 0)),
OGRE_BOAT_KARAMJA("Ogre Boat to Feldip", new WorldPoint(2757, 3085, 0), new WorldPoint(2653, 2964, 0)),
//Charter ships
CHARTER_BRIMHAVEN("Charter Ship", new WorldPoint(2760, 3238, 0)),
CHARTER_CATHERBY("Charter Ship", new WorldPoint(2791, 3415, 0)),
CHARTER_CORSAIR_("Charter Ship", new WorldPoint(2589, 2851, 0)),
CHARTER_KARAMJA_NORTH("Charter Ship", new WorldPoint(2954, 3158, 0)),
CHARTER_KARAMJA_EAST("Charter Ship", new WorldPoint(2999, 3032, 0)),
CHARTER_KHAZARD("Charter Ship", new WorldPoint(2673, 3143, 0)),
CHARTER_MOSLE_HARMLESS("Charter Ship", new WorldPoint(3669, 2931, 0)),
CHARTER_PORT_PHASMATYS("Charter Ship", new WorldPoint(3702, 3503, 0)),
CHARTER_PORTSARIM("Charter Ship", new WorldPoint(3037, 3191, 0)),
CHARTER_TYRAS("Charter Ship", new WorldPoint(2141, 3123, 0)),
CHARTER_PRIFDDINAS("Charter Ship", new WorldPoint(2156, 3331, 0)),
CHARTER_PRIFDDINAS_INSTANCE("Charter Ship", new WorldPoint(3180, 6083, 0)),
//Ferries
FERRY_AL_KHARID("Ferry to Ruins of Unkah", new WorldPoint(3269, 3142, 0), new WorldPoint(3145, 2843, 0)),
FERRY_RUINS_OF_UNKAH("Ferry to Al Kharid", new WorldPoint(3145, 2843, 0), new WorldPoint(3269, 3142, 0)),
//Minecarts/Carts
MINE_CART_ARCEUUS("Lovakengj Minecart Network", new WorldPoint(1673, 3832, 0)),
MINE_CART_GRANDEXCHANGE("Minecart to Keldagrim", new WorldPoint(3139, 3504, 0)),
MINE_CART_HOSIDIUS("Lovakengj Minecart Network", new WorldPoint(1656, 3542, 0)),
MINE_CART_ICE_MOUNTAIN("Minecart to Keldagrim", new WorldPoint(2995, 9836, 0)),
MINE_CART_KELDAGRIM("Keldagrim Minecart System", new WorldPoint(2908, 10170, 0)),
MINE_CART_LOVAKENGJ("Lovakengj Minecart Network", new WorldPoint(1524, 3721, 0)),
MINE_CART_PORT_PISCARILIUS("Lovakengj Minecart Network", new WorldPoint(1760, 3708, 0)),
MINE_CART_QUIDAMORTEM("Lovakengj Minecart Network", new WorldPoint(1253, 3550, 0)),
MINE_CART_SHAYZIEN("Lovakengj Minecart Network", new WorldPoint(1586, 3622, 0)),
MINE_CART_WHITE_WOLF_MOUNTAIN("Minecart to Keldagrim", new WorldPoint(2874, 9870, 0)),
CART_TO_BRIMHAVEN("Cart to Brimhaven", new WorldPoint(2833, 2958, 0), new WorldPoint(2780, 3214, 0)),
CART_TO_SHILO("Cart to Shilo Village", new WorldPoint(2780, 3214, 0), new WorldPoint(2833, 2958, 0)),
//Canoes
CANOE_BARBVILLAGE("Canoe", new WorldPoint(3111, 3409, 0)),
CANOE_CHAMPIONSGUILD("Canoe", new WorldPoint(3202, 3344, 0)),
CANOE_EDGEVILLE("Canoe", new WorldPoint(3130, 3509, 0)),
CANOE_LUMBRIDGE("Canoe", new WorldPoint(3241, 3238, 0)),
CANOE_FEROXENCLAVE("Canoe", new WorldPoint(3155, 3630, 0)),
//Gnome Gliders
GNOME_GLIDER_KHARID("Gnome Glider", new WorldPoint(3278, 3213, 0)),
GNOME_GLIDER_APE_ATOLL("Gnome Glider", new WorldPoint(2712, 2804, 0)),
GNOME_GLIDER_KARAMJA("Gnome Glider", new WorldPoint(2971, 2974, 0)),
GNOME_GLIDER_FELDIP("Gnome Glider", new WorldPoint(2540, 2969, 0)),
GNOME_GLIDER_GNOMESTRONGHOLD("Gnome Glider", new WorldPoint(2460, 3502, 0)),
GNOME_GLIDER_WHITEWOLF("Gnome Glider", new WorldPoint(2845, 3501, 0)),
//Balloons
BALLOON_VARROCK("Hot Air Balloon", new WorldPoint(3298, 3480, 0)),
BALLOON_YANILLE("Hot Air Balloon", new WorldPoint(2458, 3108, 0)),
BALLOON_GNOMESTRONGHOLD("Hot Air Balloon", new WorldPoint(2478, 3459, 0)),
BALLOON_TAVERLEY("Hot Air Balloon", new WorldPoint(2936, 3422, 0)),
BALLOON_FALADOR("Hot Air Balloon", new WorldPoint(2921, 3301, 0)),
//Spirit Tree
SPIRITTREE_ARDOUGNE("Spirit Tree", new WorldPoint(2554, 3259, 0)),
SPIRITTREE_CORSAIR("Spirit Tree", new WorldPoint(2485, 2850, 0)),
SPIRITTREE_GNOMESTRONGHOLD("Spirit Tree", new WorldPoint(2459, 3446, 0)),
SPIRITTREE_GNOMEVILLAGE("Spirit Tree", new WorldPoint(2538, 3166, 0)),
SPIRITTREE_GRANDEXCHANGE("Spirit Tree", new WorldPoint(3184, 3510, 0)),
SPIRITTREE_PRIFDDINAS("Spirit Tree", new WorldPoint(3274, 6124, 0)),
//Carpets
CARPET_KHARID("Carpet to Bedabin/Pollnivneach/Uzer", new WorldPoint(3311, 3107, 0)),
CARPET_BEDABIN("Carpet to Shantay Pass", new WorldPoint(3183, 3042, 0), new WorldPoint(3311, 3107, 0)),
CARPET_POLLNIVNEACH_NORTH("Carpet to Shantay Pass", new WorldPoint(3351, 3001, 0), new WorldPoint(3311, 3107, 0)),
CARPET_POLLNIVNEACH_SOUTH("Carpet to Nardah/Sophanem/Menaphos", new WorldPoint(3345, 2943, 0)),
CARPET_NARDAH("Carpet to Pollnivneach", new WorldPoint(3399, 2916, 0), new WorldPoint(3345, 2943, 0)),
CARPET_SOPHANEM("Carpet to Pollnivneach", new WorldPoint(3288, 2814, 0), new WorldPoint(3345, 2943, 0)),
CARPET_MENAPHOS("Carpet to Pollnivneach", new WorldPoint(3244, 2812, 0), new WorldPoint(3345, 2943, 0)),
CARPET_UZER("Carpet to Shantay Pass", new WorldPoint(3468, 3111, 0), new WorldPoint(3311, 3107, 0)),
//Teleports
TELEPORT_ARCHIVE_FROM_ARCEUUS("Teleport to Library Archive", new WorldPoint(1623, 3808, 0)),
TELEPORT_HARMLESS_FROM_HARMONY("Teleport to Mos Le'Harmless", new WorldPoint(3784, 2828, 0)),
TELEPORT_RUNE_ARDOUGNE("Teleport to Rune Essence", new WorldPoint(2681, 3325, 0)),
TELEPORT_RUNE_YANILLE("Teleport to Rune Essence", new WorldPoint(2592, 3089, 0)),
TELEPORT_SORCERESS_GARDEN("Teleport to Sorceress's Garden", new WorldPoint(3320, 3141, 0)),
TELEPORT_PRIFDDINAS_LIBRARY("Teleport to Prifddinas Library", new WorldPoint(3254, 6082, 2)),
//Other
ALTER_KOUREND_UNDERGROUND("Altar to Skotizo", new WorldPoint(1662, 10047, 0)),
FAIRY_RING_ZANARIS_TO_KHARID("Fairy Ring to Al Kharid", new WorldPoint(2483, 4471, 0)),
FAIRY_RING_ZANARIS_TO_SHACK("Fairy Ring to Shack", new WorldPoint(2451, 4471, 0)),
MOUNTAIN_GUIDE_QUIDAMORTEM("Mountain Guide", new WorldPoint(1275, 3559, 0)),
MOUNTAIN_GUIDE_WALL("Mountain Guide", new WorldPoint(1400, 3538, 0)),
MUSHTREE_MUSHROOM_FOREST("Mushtree", new WorldPoint(3674, 3871, 0)),
MUSHTREE_TAR_SWAMP("Mushtree", new WorldPoint(3676, 3755, 0)),
MUSHTREE_VERDANT_VALLEY("Mushtree", new WorldPoint(3757, 3756, 0)),
MYTHS_GUILD_PORTAL("Portal to Guilds", new WorldPoint(2456, 2856, 0)),
SOUL_WARS_PORTAL("Portal to Edgeville/Ferox Enclave", new WorldPoint(2204, 2858, 0)),
TRAIN_KELDAGRIM("Railway Station", new WorldPoint(2941, 10179, 0)),
WILDERNESS_LEVER_ARDOUGNE("Wilderness Lever to Deserted Keep", new WorldPoint(2559, 3309, 0), new WorldPoint(3154, 3924, 0)),
WILDERNESS_LEVER_EDGEVILLE("Wilderness Lever to Deserted Keep", new WorldPoint(3088, 3474, 0), new WorldPoint(3154, 3924, 0)),
WILDERNESS_LEVER_WILDERNESS("Wilderness Lever to Ardougne/Edgeville", new WorldPoint(3154, 3924, 0));
private final String tooltip;
private final WorldPoint location;
@Nullable
private final WorldPoint target;
TransportationPointLocation(String tooltip, WorldPoint worldPoint)
{
this(tooltip, worldPoint, null);
}
}
|
runelite/runelite
|
runelite-client/src/main/java/net/runelite/client/plugins/worldmap/TransportationPointLocation.java
|
Java
|
bsd-2-clause
| 15,466 |
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import redirect, render
from users.forms import UserCreationForm
def create_user_account(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
primary_email = form.cleaned_data['primary_email']
password = form.cleaned_data['password1']
user = authenticate(username=primary_email, password=password)
login(request, user)
return redirect('/')
else:
form = UserCreationForm()
return render(request, 'users/create_user_account.html', {'form': form})
|
kbarnes3/BaseDjangoSite
|
web/users/views.py
|
Python
|
bsd-2-clause
| 696 |
/* Software SPAMS v2.1 - Copyright 2009-2011 Julien Mairal
*
* This file is part of SPAMS.
*
* SPAMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SPAMS 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 SPAMS. If not, see <http://www.gnu.org/licenses/>.
*/
/*!
* \file
* toolbox dictLearn
*
* by Julien Mairal
* julien.mairal@inria.fr
*
* File mexTrainDL.h
* \brief mex-file, function mexTrainDL
* Usage: [D model] = mexTrainDL(X,param);
* Usage: [D model] = mexTrainDL(X,param,model);
* output model is optional
* */
#include <mexutils.h>
#include <dicts.h>
template <typename T>
inline void callFunction(mxArray* plhs[], const mxArray*prhs[],
const int nlhs,const int nrhs) {
if (!mexCheckType<T>(prhs[0]))
mexErrMsgTxt("type of argument 1 is not consistent");
if (!mxIsStruct(prhs[1]))
mexErrMsgTxt("argument 2 should be struct");
if (nrhs == 3)
if (!mxIsStruct(prhs[2]))
mexErrMsgTxt("argument 3 should be struct");
Data<T> *X;
const mwSize* dimsX=mxGetDimensions(prhs[0]);
int n=static_cast<int>(dimsX[0]);
int M=static_cast<int>(dimsX[1]);
if (mxIsSparse(prhs[0])) {
double * X_v=static_cast<double*>(mxGetPr(prhs[0]));
mwSize* X_r=mxGetIr(prhs[0]);
mwSize* X_pB=mxGetJc(prhs[0]);
mwSize* X_pE=X_pB+1;
int* X_r2, *X_pB2, *X_pE2;
T* X_v2;
createCopySparse<T>(X_v2,X_r2,X_pB2,X_pE2,
X_v,X_r,X_pB,X_pE,M);
X = new SpMatrix<T>(X_v2,X_r2,X_pB2,X_pE2,n,M,X_pB2[M]);
} else {
T* prX = reinterpret_cast<T*>(mxGetPr(prhs[0]));
X= new Matrix<T>(prX,n,M);
}
int NUM_THREADS = getScalarStructDef<int>(prhs[1],"numThreads",-1);
#ifdef _OPENMP
NUM_THREADS = NUM_THREADS == -1 ? omp_get_num_procs() : NUM_THREADS;
#else
NUM_THREADS=1;
#endif
int batch_size = getScalarStructDef<int>(prhs[1],"batchsize",
256*(NUM_THREADS+1));
mxArray* pr_D = mxGetField(prhs[1],0,"D");
Trainer<T>* trainer;
if (!pr_D) {
int K = getScalarStruct<int>(prhs[1],"K");
trainer = new Trainer<T>(K,batch_size,NUM_THREADS);
} else {
T* prD = reinterpret_cast<T*>(mxGetPr(pr_D));
const mwSize* dimsD=mxGetDimensions(pr_D);
int nD=static_cast<int>(dimsD[0]);
int K=static_cast<int>(dimsD[1]);
if (n != nD) mexErrMsgTxt("sizes of D are not consistent");
Matrix<T> D1(prD,n,K);
if (nrhs == 3) {
mxArray* pr_A = mxGetField(prhs[2],0,"A");
if (!pr_A) mexErrMsgTxt("field A is not provided");
T* prA = reinterpret_cast<T*>(mxGetPr(pr_A));
const mwSize* dimsA=mxGetDimensions(pr_A);
int xA=static_cast<int>(dimsA[0]);
int yA=static_cast<int>(dimsA[1]);
if (xA != K || yA != K) mexErrMsgTxt("Size of A is not consistent");
Matrix<T> A(prA,K,K);
mxArray* pr_B = mxGetField(prhs[2],0,"B");
if (!pr_B) mexErrMsgTxt("field B is not provided");
T* prB = reinterpret_cast<T*>(mxGetPr(pr_B));
const mwSize* dimsB=mxGetDimensions(pr_B);
int xB=static_cast<int>(dimsB[0]);
int yB=static_cast<int>(dimsB[1]);
if (xB != n || yB != K) mexErrMsgTxt("Size of B is not consistent");
Matrix<T> B(prB,n,K);
int iter = getScalarStruct<int>(prhs[2],"iter");
trainer = new Trainer<T>(A,B,D1,iter,batch_size,NUM_THREADS);
} else {
trainer = new Trainer<T>(D1,batch_size,NUM_THREADS);
}
}
ParamDictLearn<T> param;
param.lambda = getScalarStruct<T>(prhs[1],"lambda");
param.lambda2 = getScalarStructDef<T>(prhs[1],"lambda2",10e-10);
param.iter=getScalarStruct<int>(prhs[1],"iter");
param.t0 = getScalarStructDef<T>(prhs[1],"t0",1e-5);
param.mode =(constraint_type)getScalarStructDef<int>(prhs[1],"mode",PENALTY);
param.posAlpha = getScalarStructDef<bool>(prhs[1],"posAlpha",false);
param.posD = getScalarStructDef<bool>(prhs[1],"posD",false);
param.expand= getScalarStructDef<bool>(prhs[1],"expand",false);
param.modeD=(constraint_type_D)getScalarStructDef<int>(prhs[1],"modeD",L2);
param.whiten = getScalarStructDef<bool>(prhs[1],"whiten",false);
param.clean = getScalarStructDef<bool>(prhs[1],"clean",true);
param.verbose = getScalarStructDef<bool>(prhs[1],"verbose",true);
param.gamma1 = getScalarStructDef<T>(prhs[1],"gamma1",0);
param.gamma2 = getScalarStructDef<T>(prhs[1],"gamma2",0);
param.rho = getScalarStructDef<T>(prhs[1],"rho",T(1.0));
param.stochastic =
getScalarStructDef<bool>(prhs[1],"stochastic_deprecated",
false);
param.modeParam = static_cast<mode_compute>(getScalarStructDef<int>(prhs[1],"modeParam",0));
param.batch = getScalarStructDef<bool>(prhs[1],"batch",false);
param.iter_updateD = getScalarStructDef<T>(prhs[1],"iter_updateD",param.batch ? 5 : 1);
param.log = getScalarStructDef<bool>(prhs[1],"log_deprecated",
false);
if (param.log) {
mxArray *stringData = mxGetField(prhs[1],0,
"logName_deprecated");
if (!stringData)
mexErrMsgTxt("Missing field logName_deprecated");
int stringLength = mxGetN(stringData)+1;
param.logName= new char[stringLength];
mxGetString(stringData,param.logName,stringLength);
}
trainer->train(*X,param);
if (param.log)
mxFree(param.logName);
Matrix<T> D;
trainer->getD(D);
int K = D.n();
plhs[0] = createMatrix<T>(n,K);
T* prD2 = reinterpret_cast<T*>(mxGetPr(plhs[0]));
Matrix<T> D2(prD2,n,K);
D2.copy(D);
if (nlhs == 2) {
mwSize dims[1] = {1};
int nfields=3;
const char *names[] = {"A", "B", "iter"};
plhs[1]=mxCreateStructArray(1, dims,nfields, names);
mxArray* prA = createMatrix<T>(K,K);
T* pr_A= reinterpret_cast<T*>(mxGetPr(prA));
Matrix<T> A(pr_A,K,K);
trainer->getA(A);
mxSetField(plhs[1],0,"A",prA);
mxArray* prB = createMatrix<T>(n,K);
T* pr_B= reinterpret_cast<T*>(mxGetPr(prB));
Matrix<T> B(pr_B,n,K);
trainer->getB(B);
mxSetField(plhs[1],0,"B",prB);
mxArray* priter = createScalar<T>();
*mxGetPr(priter) = static_cast<T>(trainer->getIter());
mxSetField(plhs[1],0,"iter",priter);
}
delete(trainer);
delete(X);
}
void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[]) {
if (nrhs < 2 || nrhs > 3)
mexErrMsgTxt("Bad number of inputs arguments");
if ((nlhs < 1) || (nlhs > 2))
mexErrMsgTxt("Bad number of output arguments");
if (mxGetClassID(prhs[0]) == mxDOUBLE_CLASS) {
callFunction<double>(plhs,prhs,nlhs,nrhs);
} else {
callFunction<float>(plhs,prhs,nlhs,nrhs);
}
}
|
wjbeksi/rgbd-covariance-descriptors
|
spams/dictLearn/mex/mexTrainDL.cpp
|
C++
|
bsd-2-clause
| 7,630 |
# The Nexus software is licensed under the BSD 2-Clause license.
#
# You should have recieved a copy of this license with the software.
# If you did not, you can find one at the following link.
#
# http://opensource.org/licenses/bsd-license.php
entitylist.append(["confetti",(x,y,z),6,6])
|
TheArchives/Nexus
|
core/entities/confetti_create.py
|
Python
|
bsd-2-clause
| 291 |
/* A Pseudo Random Number Generator - Mersenne twister
* http://en.wikipedia.org/wiki/Mersenne_twister
* http://my.opera.com/metrallik/blog/2013/04/19/c-class-for-random-generation-with-mersenne-twister-method
*/
#ifndef PSEUDORNG_HPP
#define PSEUDORNG_HPP
class PseudoRNG {
private:
static const unsigned int length=624;
static const unsigned int bitMask_32=0xffffffff;
static const unsigned int bitPow_31=1<<31;
unsigned int mt[length];
unsigned int idx;
public:
PseudoRNG(unsigned int seed);
unsigned int get();
void gen();
~PseudoRNG();
};
#endif
|
codeape/eye-engine
|
engine/PseudoRNG.hpp
|
C++
|
bsd-2-clause
| 637 |
/*
* Copyright (c) 2011-2022, The DART development contributors
* All rights reserved.
*
* The list of contributors can be found at:
* https://github.com/dartsim/dart/blob/master/LICENSE
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DART_DYNAMICS_WELDJOINT_HPP_
#define DART_DYNAMICS_WELDJOINT_HPP_
#include <string>
#include <Eigen/Dense>
#include "dart/dynamics/ZeroDofJoint.hpp"
namespace dart {
namespace dynamics {
/// class WeldJoint
class WeldJoint : public ZeroDofJoint
{
public:
friend class Skeleton;
struct Properties : ZeroDofJoint::Properties
{
DART_DEFINE_ALIGNED_SHARED_OBJECT_CREATOR(Properties)
Properties(const Joint::Properties& _properties = Joint::Properties());
virtual ~Properties() = default;
};
WeldJoint(const WeldJoint&) = delete;
/// Destructor
virtual ~WeldJoint();
/// Get the Properties of this WeldJoint
Properties getWeldJointProperties() const;
// Documentation inherited
const std::string& getType() const override;
/// Get joint type for this class
static const std::string& getStaticType();
// Documentation inherited
bool isCyclic(std::size_t _index) const override;
// Documentation inherited
void setTransformFromParentBodyNode(const Eigen::Isometry3d& _T) override;
// Documentation inherited
void setTransformFromChildBodyNode(const Eigen::Isometry3d& _T) override;
protected:
/// Constructor called by Skeleton class
WeldJoint(const Properties& properties);
// Documentation inherited
Joint* clone() const override;
//----------------------------------------------------------------------------
// Recursive algorithms
//----------------------------------------------------------------------------
// Documentation inherited
void updateRelativeTransform() const override;
// Documentation inherited
void updateRelativeSpatialVelocity() const override;
// Documentation inherited
void updateRelativeSpatialAcceleration() const override;
// Documentation inherited
void updateRelativePrimaryAcceleration() const override;
// Documentation inherited
void updateRelativeJacobian(bool = true) const override;
// Documentation inherited
void updateRelativeJacobianTimeDeriv() const override;
};
} // namespace dynamics
} // namespace dart
#endif // DART_DYNAMICS_WELDJOINT_HPP_
|
dartsim/dart
|
dart/dynamics/WeldJoint.hpp
|
C++
|
bsd-2-clause
| 3,722 |
from confduino.boardlist import boards_txt
from entrypoint2 import entrypoint
import logging
log = logging.getLogger(__name__)
@entrypoint
def remove_board(board_id):
"""remove board.
:param board_id: board id (e.g. 'diecimila')
:rtype: None
"""
log.debug('remove %s', board_id)
lines = boards_txt().lines()
lines = filter(lambda x: not x.strip().startswith(board_id + '.'), lines)
boards_txt().write_lines(lines)
|
ponty/confduino
|
confduino/boardremove.py
|
Python
|
bsd-2-clause
| 452 |
/*
* Copyright (c) 2019, Dmitriy Shchekotin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package ru.silverhammer.processor;
import java.lang.annotation.Annotation;
import java.util.List;
import ru.junkie.IInjector;
import ru.reflexio.IFieldReflection;
import ru.reflexio.IInstanceFieldReflection;
import ru.reflexio.MetaAnnotation;
import ru.sanatio.conversion.IStringConverter;
import ru.silverhammer.initializer.InitializerReference;
import ru.silverhammer.model.CategoryModel;
import ru.silverhammer.model.ControlModel;
import ru.silverhammer.model.GroupModel;
import ru.silverhammer.model.UiModel;
import ru.silverhammer.control.IControl;
import ru.silverhammer.decorator.IDecorator;
import ru.silverhammer.initializer.IInitializer;
import ru.silverhammer.resolver.IControlResolver;
public class ControlProcessor implements IProcessor<IInstanceFieldReflection, Annotation> {
private final IStringConverter converter;
private final IInjector injector;
private final IControlResolver controlResolver;
private final UiModel model;
public ControlProcessor(IInjector injector, IStringConverter converter, IControlResolver controlResolver, UiModel model) {
this.injector = injector;
this.converter = converter;
this.controlResolver = controlResolver;
this.model = model;
}
@SuppressWarnings("unchecked")
@Override
public void process(Object data, IInstanceFieldReflection reflection, Annotation annotation) {
Class<? extends IControl<?, ?>> controlClass = controlResolver.getControlClass(annotation.annotationType());
if (controlClass != null) {
IControl control = injector.instantiate(controlClass);
decorateControl(control, data, reflection);
addControlAttributes(reflection.getAnnotation(GroupId.class), createControlModel(control, data, reflection));
control.init(annotation);
initializeControl(control, data, reflection);
}
}
@SuppressWarnings("unchecked")
private void decorateControl(IControl<?, ?> control, Object data, IFieldReflection field) {
for (Annotation a : field.getAnnotations()) {
Class<? extends IDecorator<?, ?>> decoratorClass = controlResolver.getDecoratorClass(a.annotationType());
if (decoratorClass != null) {
IDecorator decorator = injector.instantiate(decoratorClass);
decorator.init(a, data);
decorator.setControl(control);
}
}
}
@SuppressWarnings("unchecked")
private void initializeControl(IControl<?, ?> control, Object data, IInstanceFieldReflection field) {
List<MetaAnnotation<InitializerReference>> marked = field.getMetaAnnotations(InitializerReference.class);
for (MetaAnnotation<InitializerReference> ma : marked) {
IInitializer<IControl<?, ?>, Annotation> initializer = (IInitializer<IControl<?, ?>, Annotation>) injector.instantiate(ma.getMetaAnnotation().value());
initializer.init(control, ma.getAnnotation(), data, field);
}
Object value = field.getValue(data);
value = model.getControlValue(value, field);
((IControl<Object, ?>) control).setValue(value);
}
private void addControlAttributes(GroupId gi, ControlModel controlModel) {
String groupId = gi == null ? null : gi.value();
GroupModel groupModel = model.findGroupModel(groupId);
if (groupModel == null) {
groupModel = new GroupModel(groupId);
if (model.getCategories().isEmpty()) {
model.getCategories().add(new CategoryModel()); // TODO: revisit
}
model.getCategories().get(0).getGroups().add(groupModel);
}
groupModel.getControls().add(controlModel);
}
private ControlModel createControlModel(IControl<?, ?> control, Object data, IInstanceFieldReflection field) {
ControlModel result = new ControlModel(control, data, field);
Caption caption = field.getAnnotation(Caption.class);
Description description = field.getAnnotation(Description.class);
if (caption != null) {
result.setCaption(converter.getString(caption.value()));
result.setCaptionLocation(caption.location());
result.setHorizontalAlignment(caption.horizontalAlignment());
result.setVerticalAlignment(caption.verticalAlignment());
}
if (description != null) {
result.setDescription(converter.getString(description.value()));
}
return result;
}
}
|
SupremeBeing/Silver-Hammer
|
silver-hammer-core/src/main/java/ru/silverhammer/processor/ControlProcessor.java
|
Java
|
bsd-2-clause
| 5,459 |
require 'asdf'
require 'cgi'
require 'json'
module SpecTools
def run_server
$stdout.reopen("/dev/null", "a")
$stderr.reopen("/dev/null", "a")
Dir.chdir "./test_files"
Asdf::Server.start
end
def inner_html string
string.gsub(/^<html>/,"").gsub(/<\/html>/,"")
end
def e url
CGI.escape url
end
def error_msg text
{"actionStatus" => "error", "content"=> text}
end
def ok_msg page_body
{"actionStatus" => "ok", "content"=> page_body.gsub("\n", "")}
end
def result_path token
tmp_dir + token
end
def tmp_dir
"/tmp/tofu-kozo/#{@kozo_port}/"
end
# just an alias for better readablitiy in tests
def discard_result token
interpret_result token
end
def interpret_result token, tries=5
if tries < 0
raise "Could not get result file for #{token}."
end
s = File.read(result_path token)
if s.length == 0
sleep 1
return interpret_result(token, tries - 1)
end
dirty = JSON.parse s
if dirty["content"]
clean_content = dirty["content"].gsub("\n","")
else
clean_content = ""
end
{
"actionStatus" => dirty["actionStatus"],
"content" => clean_content
}
end
end
|
ptek/tofu-kozo
|
spec/spec_tools.rb
|
Ruby
|
bsd-2-clause
| 1,231 |
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'moment'})
/**
* Transforms a moment date value to a display value.
*
* @module common
* @class MomentPipe
*/
export class MomentPipe implements PipeTransform {
constructor() { }
/**
* Looks up the input value within the `choices.cfg` section
* for the given topic. If found, then this method returns
* the look-up result, otherwise this method returns the
* input value. If the input value is an array, then this
* method collects the item transformations.
*
* @method transform
* @param value {Object} the moment date input
* @param format {string} the optional date format
* @return {string} the display string
*/
transform(value: Object, format='MM/DD/YYYY'): string {
return value && value.format(format);
}
}
|
ohsu-qin/qiprofile
|
src/common/moment.pipe.ts
|
TypeScript
|
bsd-2-clause
| 834 |
import time
import os
import threading
import collections
from xlog import getLogger
xlog = getLogger("cloudflare_front")
xlog.set_buffer(500)
import simple_http_client
from config import config
import http_dispatcher
import connect_control
import check_ip
class Front(object):
name = "cloudflare_front"
def __init__(self):
self.dispatchs = {}
threading.Thread(target=self.update_front_domains).start()
self.last_success_time = time.time()
self.last_fail_time = 0
self.continue_fail_num = 0
self.success_num = 0
self.fail_num = 0
self.last_host = "center.xx-net.net"
self.rtts = collections.deque([(0, time.time())])
self.rtts_lock = threading.Lock()
self.traffics = collections.deque()
self.traffics_lock = threading.Lock()
self.recent_sent = 0
self.recent_received = 0
self.total_sent = 0
self.total_received = 0
threading.Thread(target=self.debug_data_clearup_thread).start()
@staticmethod
def update_front_domains():
next_update_time = time.time()
while connect_control.keep_running:
if time.time() < next_update_time:
time.sleep(4)
continue
try:
timeout = 30
if config.getint("proxy", "enable", 0):
client = simple_http_client.Client(proxy={
"type": config.get("proxy", "type", ""),
"host": config.get("proxy", "host", ""),
"port": int(config.get("proxy", "port", "0")),
"user": config.get("proxy", "user", ""),
"pass": config.get("proxy", "passwd", ""),
}, timeout=timeout)
else:
client = simple_http_client.Client(timeout=timeout)
url = "https://raw.githubusercontent.com/XX-net/XX-Net/master/code/default/x_tunnel/local/cloudflare_front/front_domains.json"
response = client.request("GET", url)
if response.status != 200:
xlog.warn("update front domains fail:%d", response.status)
raise Exception("status:%r", response.status)
need_update = True
front_domains_fn = os.path.join(config.DATA_PATH, "front_domains.json")
if os.path.exists(front_domains_fn):
with open(front_domains_fn, "r") as fd:
old_content = fd.read()
if response.text == old_content:
need_update = False
if need_update:
with open(front_domains_fn, "w") as fd:
fd.write(response.text)
check_ip.update_front_domains()
next_update_time = time.time() + (4 * 3600)
xlog.info("updated cloudflare front domains from github.")
except Exception as e:
next_update_time = time.time() + (1800)
xlog.debug("updated cloudflare front domains from github fail:%r", e)
def log_debug_data(self, rtt, sent, received):
now = time.time()
self.rtts.append((rtt, now))
with self.traffics_lock:
self.traffics.append((sent, received, now))
self.recent_sent += sent
self.recent_received += received
self.total_sent += sent
self.total_received += received
def get_rtt(self):
now = time.time()
while len(self.rtts) > 1:
with self.rtts_lock:
rtt, log_time = rtt_log = max(self.rtts)
if now - log_time > 5:
self.rtts.remove(rtt_log)
continue
return rtt
return self.rtts[0][0]
def debug_data_clearup_thread(self):
while True:
now = time.time()
with self.rtts_lock:
if len(self.rtts) > 1 and now - self.rtts[0][-1] > 5:
self.rtts.popleft()
with self.traffics_lock:
if self.traffics and now - self.traffics[0][-1] > 60:
sent, received, _ = self.traffics.popleft()
self.recent_sent -= sent
self.recent_received -= received
time.sleep(1)
def worker_num(self):
host = self.last_host
if host not in self.dispatchs:
self.dispatchs[host] = http_dispatcher.HttpsDispatcher(host, self.log_debug_data)
dispatcher = self.dispatchs[host]
return len(dispatcher.workers)
def get_score(self, host=None):
now = time.time()
if now - self.last_fail_time < 60 and \
self.continue_fail_num > 10:
return None
if host is None:
host = self.last_host
if host not in self.dispatchs:
self.dispatchs[host] = http_dispatcher.HttpsDispatcher(host, self.log_debug_data)
dispatcher = self.dispatchs[host]
worker = dispatcher.get_worker(nowait=True)
if not worker:
return None
return worker.get_score()
def request(self, method, host, path="/", headers={}, data="", timeout=120):
if host not in self.dispatchs:
self.dispatchs[host] = http_dispatcher.HttpsDispatcher(host, self.log_debug_data)
self.last_host = host
dispatcher = self.dispatchs[host]
response = dispatcher.request(method, host, path, dict(headers), data, timeout=timeout)
if not response:
xlog.warn("req %s get response timeout", path)
return "", 602, {}
status = response.status
if status not in [200, 405]:
# xlog.warn("front request %s %s%s fail, status:%d", method, host, path, status)
self.fail_num += 1
self.continue_fail_num += 1
self.last_fail_time = time.time()
else:
self.success_num += 1
self.continue_fail_num = 0
content = response.task.read_all()
if status == 200:
xlog.debug("%s %s%s status:%d trace:%s", method, response.worker.ssl_sock.host, path, status,
response.task.get_trace())
else:
xlog.warn("%s %s%s status:%d trace:%s", method, response.worker.ssl_sock.host, path, status,
response.task.get_trace())
return content, status, response
def stop(self):
connect_control.keep_running = False
front = Front()
|
qqzwc/XX-Net
|
code/default/x_tunnel/local/cloudflare_front/front.py
|
Python
|
bsd-2-clause
| 6,638 |
package com.grilledmonkey.niceql.structs;
import java.util.LinkedList;
import java.util.List;
import com.grilledmonkey.niceql.interfaces.SqlMigration;
public class Migration implements SqlMigration {
private final List<String> sql = new LinkedList<String>();
private int version;
public Migration() {
this(1);
}
public Migration(int version) {
this.version = version;
}
@Override
public List<String> getSql() {
return(sql);
}
@Override
public void addStatement(String sql) {
this.sql.add(sql);
}
@Override
public void setVersion(int version) {
this.version = version;
}
@Override
public int getVersion() {
return(version);
}
}
|
Auxx/niceql
|
niceql/src/com/grilledmonkey/niceql/structs/Migration.java
|
Java
|
bsd-2-clause
| 707 |
/**
* Copyright 2015 Fabian Grutschus. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the copyright holders.
*
* @author Fabian Grutschus <f.grutschus@lubyte.de>
* @copyright 2015 Fabian Grutschus. All rights reserved.
* @license BSD-2-Clause
*/
;(function (global, storage) {
var originalOnError = function () {};
if (typeof global.onerror === "function") {
originalOnError = global.onerror;
}
var E = {
storageKey: "fabiang_error_handler",
register: function () {
global.onerror = function () {
var args = Array.prototype.slice.call(arguments);
E.handle.apply(null, args);
originalOnError.apply(null, args);
};
E.registerForjQuery();
},
registerForjQuery: function () {
if (typeof global.jQuery === "function") {
jQuery(global.document).ajaxError(function (e, xhr, settings, message) {
var error = {
message: message.length > 0 ? message : "Unknown error",
method: settings.type,
url: settings.url,
type: "ajaxError"
};
E.store(error);
});
}
},
handle: function (message, file, lineno, column) {
var error = {
message: message,
file: file,
lineno: lineno,
column: column,
type: "error"
};
E.store(error);
},
store: function (error) {
var errors = E.get();
errors.push(error);
storage.setItem(E.storageKey, JSON.stringify(errors));
},
get: function () {
if (null !== storage.getItem(E.storageKey)) {
return JSON.parse(storage.getItem(E.storageKey));
}
return [];
},
clear: function () {
storage.setItem(E.storageKey, "[]");
}
};
global.ErrorHandler = E;
E.register();
}(this, localStorage));
|
fabiang/mink-javascript-errors
|
src/ErrorHandler.js
|
JavaScript
|
bsd-2-clause
| 3,639 |
using System;
using System.Runtime.Serialization;
namespace Entr.Domain
{
[Serializable]
public class EntityNotFoundException : Exception
{
public EntityNotFoundException()
{
}
public EntityNotFoundException(string message) : base(message)
{
}
public EntityNotFoundException(string message, Exception inner) : base(message, inner)
{
}
protected EntityNotFoundException(
SerializationInfo info,
StreamingContext context) : base(info, context)
{
}
}
}
|
bradleyjford/entr
|
src/Entr.Domain/EntityNotFoundException.cs
|
C#
|
bsd-2-clause
| 594 |