text stringlengths 2 1.04M | meta dict |
|---|---|
package com.google.security.zynamics.binnavi.API.debug;
import com.google.security.zynamics.binnavi.debug.connection.packets.replies.QueryDebuggerEventSettingsReply;
public class DebuggerQueryDebuggerEventSettingsReply extends DebuggerReply {
public DebuggerQueryDebuggerEventSettingsReply(final QueryDebuggerEventSettingsReply reply) {
super(reply);
}
}
| {
"content_hash": "11b33fd3e42bec2d87c807187be7648a",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 109,
"avg_line_length": 36.6,
"alnum_prop": 0.8497267759562842,
"repo_name": "google/binnavi",
"id": "a691adcc35e9719ec94c84cf0aaa822d5b4d8864",
"size": "955",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/com/google/security/zynamics/binnavi/API/debug/DebuggerQueryDebuggerEventSettingsReply.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1489"
},
{
"name": "C",
"bytes": "8997"
},
{
"name": "C++",
"bytes": "982064"
},
{
"name": "CMake",
"bytes": "1953"
},
{
"name": "CSS",
"bytes": "12843"
},
{
"name": "GAP",
"bytes": "3637"
},
{
"name": "HTML",
"bytes": "437459"
},
{
"name": "Java",
"bytes": "21714625"
},
{
"name": "Makefile",
"bytes": "3498"
},
{
"name": "PLpgSQL",
"bytes": "180849"
},
{
"name": "Python",
"bytes": "23981"
},
{
"name": "Shell",
"bytes": "713"
}
],
"symlink_target": ""
} |
#ifndef __avmplus_Namespace__
#define __avmplus_Namespace__
namespace avmplus
{
/**
* a namespace is a primitive value in the system, similar to String
*/
class Namespace : public AvmPlusScriptableObject
{
private:
friend class AvmCore;
// Should these be Stringp's?
Atom m_prefix;
uintptr m_uri; // Uses 3 bits for flags, but otherwise is really a Stringp
public:
enum NamespaceType
{
NS_Public = 0,
NS_Protected = 1,
NS_PackageInternal = 2,
NS_Private = 3,
NS_Explicit = 4,
NS_StaticProtected = 5
};
Namespace(Atom prefix, Stringp uri, NamespaceType type);
~Namespace();
inline Atom getPrefix() const { return get_prefix(); }
inline Stringp getURI() const { return get_uri(); }
Atom get_prefix() const { return m_prefix; }
Stringp get_uri() const;
Atom atom() const { return AtomConstants::kNamespaceType | (Atom)this; }
/**
* virtual version of atom():
*/
virtual Atom toAtom() const { return atom(); }
// This is called in ONE place in the XML code. The URI of a namespace
// should never change but its prefix can change in this special case
void setPrefix (Atom pre);
bool hasPrefix () const;
bool EqualTo(const Namespace* other) const;
bool isPrivate() const
{
return ISNULL(m_prefix);
}
NamespaceType getType() const
{
return (NamespaceType)(((sint32)m_uri)&7);
}
// Iterator support - for in, for each
Atom nextName(const AvmCore *core, int index);
Atom nextValue(int index);
int nextNameIndex(int index);
#ifdef DEBUGGER
uint64 size() const { return sizeof(Namespace) - sizeof(AvmPlusScriptableObject); }
#endif
//#ifdef AVMPLUS_VERBOSE
public:
Stringp format(AvmCore* core) const;
//#endif
private:
void setUri(Stringp uri, NamespaceType flags);
};
}
#endif /* __avmplus_Namespace__ */
| {
"content_hash": "326ecc13eead83f482bc98d17e2836ff",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 85,
"avg_line_length": 23.679012345679013,
"alnum_prop": 0.6480709071949948,
"repo_name": "zodouglass/PBNetworking",
"id": "26118a5029f45c7c10a0b5c9bdcfb67ab6f9d29c",
"size": "3645",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "server/tamarin-source/tamarin-central/core/Namespace.h",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "896984"
},
{
"name": "Assembly",
"bytes": "318656"
},
{
"name": "C",
"bytes": "925552"
},
{
"name": "C++",
"bytes": "6426725"
},
{
"name": "CSS",
"bytes": "31472"
},
{
"name": "Erlang",
"bytes": "3604"
},
{
"name": "JavaScript",
"bytes": "269603"
},
{
"name": "Objective-C",
"bytes": "108655"
},
{
"name": "PHP",
"bytes": "5110"
},
{
"name": "Perl",
"bytes": "626190"
},
{
"name": "Python",
"bytes": "120912"
},
{
"name": "Racket",
"bytes": "49971"
},
{
"name": "Ruby",
"bytes": "933"
},
{
"name": "Shell",
"bytes": "223491"
},
{
"name": "Smalltalk",
"bytes": "4895"
}
],
"symlink_target": ""
} |
Are there any images that look unusual? List the file name of any unusual images for this night here, with description:
The first 11 Bias images are normal FYI other than #5
+ `Bias-S001-R001-C005-NoFilt.fit` - Darker horizontal band in lower 3rd
+ `Bias-S001-R001-C012-NoFilt.fit` - Sizeable lighter horizontal bands in the bottom 1/4
+ `Bias-S001-R001-C013-NoFilt.fit` - Horizontal banding, strongest at top
+ `Bias-S001-R001-C014-NoFilt.fit` - Horizontal banding
+ `Bias-S001-R001-C015-NoFilt.fit` - Horizontal and vertical banding both
+ `Bias-S001-R001-C016-NoFilt.fit` - Horizontal banding
+ `Bias-S001-R001-C017-NoFilt.fit` - Horizontal and vertical banding
+ `Bias-S001-R001-C018-NoFilt.fit` - Horizontal banding
+ `Bias-S001-R001-C019-NoFilt.fit` - Horizontal banding
+ `Bias-S001-R001-C020-NoFilt.fit` - top 2/3rds of image is light grey, bottom 1/3 is regular darker color
+ `Dark-S001-R001-C001-NoFilt.fit` - Light gray horizontal banding
+ `Dark-S001-R001-C002-NoFilt.fit` - Multiple light gray bands
+ `Dark-S001-R001-C003-NoFilt.fit` - Multiple gray bands
+ `Dark-S001-R001-C007-NoFilt.fit` - Multiple gray bands
+ `HD37387-S004-R001-C001-B.fit` - Large light gray horizontal band at top
+ `M1-S002-R001-C001-540bp30.fit` - Target not visible or has moved drastically to left side of image?
+ `M1-S003-R001-C001-540bp30.fit` - Target not visible or has moved drastically to left side of image
+ `M1-S003-R001-C003-540bp30.fit` - white scratches/blotches above target
+ `M1-S004-R001-C001-540bp30.fit` - Target has moved drastically to left side of image
+ `M1-S005-R001-C001-540bp30.fit` - Target has moved drastically to left side of image
+ `M1-S006-R001-C001-540bp30.fit` - Target has moved drastically to left side of image
+ `M1-S007-R001-C001-540bp30.fit` - Target has moved drastically to left side of image
+ `M1-S008-R001-C001-540bp30.fit` - Target has moved drastically to left side of image
+ `M1-S008-R001-C001-rp.fit` - Target has moved drastically to left side of image
+ `M1-S008-R001-C002-540bp30.fit` - Target has moved drastically to left side of image
+ `M1-S008-R001-C003-540bp30.fit` - Target has moved drastically to left side of image
+ `M1-S009-R001-C001-540bp30.fit` - Target has moved drastically to left side of image
+ `M1-S009-R001-C001-rp.fit` - Target has moved drastically to left side of image
+ `M1-S009-R001-C002-540bp30.fit` - Target has moved drastically to left side of image
+ `M1-S009-R001-C003-540bp30.fit` - Target has moved drastically to left side of image
+ `SDSSJ052053.80+175228.2-S001-R001-C001-rp.fit` - Light gray band at top of image
+ `SDSSJ052053.80+175228.2-S001-R001-C002-540bp30.fit` - Light gray band at top of image
+ `SDSSJ052053.80+175228.2-S001-R001-C003-540bp30.fit` - Horizontal banding
+ `SDSSJ052053.80+175228.2-S003-R001-C001-gp.fit` - Horizontal banding plus material to be removed via flat correction
+ `SDSSJ052053.80+175228.2-S003-R001-C002-540bp30.fit` - Lots of horizontal banding in the lower half
+ `SDSSJ052053.80+175228.2-S008-R001-C001-rp.fit` - Seems to be out of focus even though we don't have a focusing lens
+ `TIC241076290.01-S001-R001-C001-rp.fit` - Image has shifted significantly
+ `TIC241076290.01-S001-R022-C001-rp.fit` - Significant horizontal banding in upper half
+ `TIC241076290.01-S001-R025-C001-rp.fit` - Horizontal banding visible in dust
+ `ey-uma-S001-R001-C001-rp.fit` - Image has shifted significantly
+ `ey-uma-S001-R001-C002-rp.fit` - Centering is off slightly, 2nd image in sequence
## Many of the M1 images have varying clarity - in some M1 is super faded out, some have it super strong. It seems to be a cycle, similar to how it seems that every R001 image for M1 has the target at the far left side of the image instead of centered. There is also periodic "flare ups" of dust etc on images to be removed via flat correcting, so I didn't mention those specifically.
Delete this list if there are no unusual images.
## Missing information?
Check these off if they are true:
- [x] No images are missing filter information (except BIAS and DARK, which need no filter).
- [x] No images are missing pointing information (RA/Dec and WCS)
- [x] No images are missing object names (only applies to science images)
If any images are missing information and you have been unable to fix them please list
them below with a short description of the problem.
## What, if anything, did you have to do to fix images on this night?
Remember, you should do your changes with scripts that you number and place in the
directory along with the data so the procedure could be repeated if needed or
desired.
Here, explain in English (not code) what you fixed, if anything.
| {
"content_hash": "b5f9aeb5e65965f139fe7d8cbd66c35c",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 384,
"avg_line_length": 69.83582089552239,
"alnum_prop": 0.761701218209019,
"repo_name": "feder-observatory/processed_images",
"id": "a9c4d23b03f65a22c31f68511b0b78ed26acea1a",
"size": "4819",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "nights/2020-01-05-README.md",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
module.exports = function () {
return function (req, res, next) {
if (req.context.user.github_id + '' !== req.user.github_id + '') return res.boom.unauthorized();
next();
};
}; | {
"content_hash": "f07fcd65827d4c813e39871cd4c8cff7",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 100,
"avg_line_length": 31.333333333333332,
"alnum_prop": 0.601063829787234,
"repo_name": "divshot/ele-api",
"id": "6dd26486ee41e2b5782525cecf1348528a3336a5",
"size": "188",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/middleware/current-user-package.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "72652"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
Acta Phys. -Med. Acad. Caes. Leop. -Carol. Nat. Cur. 4:136,t. 3. 1770
#### Original name
null
### Remarks
null | {
"content_hash": "44b96ebecd0837b4f05b4b8b957fc750",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 69,
"avg_line_length": 14.692307692307692,
"alnum_prop": 0.675392670157068,
"repo_name": "mdoering/backbone",
"id": "6849e5e5ca78a52e4d2c4a1529133fe7158803c8",
"size": "241",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Cleomaceae/Cleome/Cleome viridiflora/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package dao;
import java.util.List;
import model.Shop;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
@Repository
public interface ShopDao extends JpaRepository<Shop, Long> {
@Query("SELECT s FROM Shop s WHERE s.isArchived = false")
public List<Shop> findAllShops();
@Query("SELECT s.shopKey FROM Shop s WHERE s.isArchived = false")
public List<Long> findAllShopKeys();
@Modifying
@Transactional
@Query("UPDATE Shop s SET s.isArchived = true, s.modifiedAt = :modifiedAtUtcTime WHERE s.shopKey = :shopKey")
public void archiveShop(@Param("shopKey") long shopKey,
@Param("modifiedAtUtcTime") long modifiedAtUtcTime);
@Query("SELECT s FROM Shop s WHERE s.modifiedAt >= :utcTime")
public List<Shop> findShopsNewerThan(@Param("utcTime") long utcTime);
}
| {
"content_hash": "b67ae9c797d9213c30ce7402abddf116",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 110,
"avg_line_length": 33.40625,
"alnum_prop": 0.784845650140318,
"repo_name": "h920526/jaBenDon",
"id": "b260ab204509f9111184badff04d69a25e76a79d",
"size": "1069",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/dao/ShopDao.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3219"
},
{
"name": "Java",
"bytes": "47519"
},
{
"name": "JavaScript",
"bytes": "62899"
}
],
"symlink_target": ""
} |
NS_ASSUME_NONNULL_BEGIN
/// The view that displays native ads. A minimum implementation to get an ad from within a
/// UIViewController class is:
///
/// <pre>
/// // Create and setup the ad view, specifying the size and origin at {0, 0}.
/// GADNativeExpressAdView *adView =
/// [[GADNativeExpressAdView alloc] initWithAdSize:kGADAdSizeBanner];
/// adView.rootViewController = self;
/// adView.adUnitID = @"ID created when registering your app";
/// // Place the ad view onto the screen.
/// [self.view addSubview:adView];
/// // Request an ad without any additional targeting information.
/// [adView loadRequest:[GADRequest request]];
/// </pre>
GAD_DEPRECATED_ATTRIBUTE
@interface GADNativeExpressAdView : UIView
#pragma mark - Initialization
/// Returns an initialized GADNativeExpressAdView instance set to |adSize| and positioned at
/// |origin| relative to its superview bounds. Returns nil if |adSize| is an invalid ad size.
- (nullable instancetype)initWithAdSize:(GADAdSize)adSize origin:(CGPoint)origin;
/// Returns an initialized GADNativeExpressAdView instance set to |adSize| and positioned at the
/// top left of its superview. Returns nil if |adSize| is an invalid ad size.
- (nullable instancetype)initWithAdSize:(GADAdSize)adSize;
/// Video controller for controlling video rendered by this native express ad view.
@property(nonatomic, strong, readonly) GADVideoController *videoController;
#pragma mark - Pre-Request
/// Required value created on the AdMob website. Create a new ad unit for every unique placement of
/// an ad in your application. Set this to the ID assigned for this placement. Ad units are
/// important for targeting and statistics.
///
/// Example AdMob ad unit ID: @"ca-app-pub-0123456789012345/0123456789"
@property(nonatomic, copy, nullable) IBInspectable NSString *adUnitID;
/// Required reference to the current root view controller. For example, the root view controller in
/// a tab-based application would be the UITabViewController.
@property(nonatomic, weak, nullable) IBOutlet UIViewController *rootViewController;
/// Required to set this native ad view to a proper size. Never create your own GADAdSize directly.
/// Use one of the predefined standard ad sizes (such as kGADAdSizeBanner), or create one using the
/// GADAdSizeFromCGSize method. If you are not using mediation, changing the adSize after an ad has
/// been shown will cause a new request (for an ad of the new size) to be sent. If you are using
/// mediation, then a new request may not be sent.
@property(nonatomic, assign) GADAdSize adSize;
/// Optional delegate object that receives state change notifications from this
/// GADNativeExpressAdView. Typically this is a UIViewController.
@property(nonatomic, weak, nullable) IBOutlet id<GADNativeExpressAdViewDelegate> delegate;
/// A Boolean value that determines whether autoloading of ads in the receiver is enabled. If
/// enabled, you do not need to call the loadRequest: method to load ads.
@property(nonatomic, assign, getter=isAutoloadEnabled) IBInspectable BOOL autoloadEnabled;
/// Sets options that configure ad loading.
///
/// @param adOptions An array of GADAdLoaderOptions objects. The array is deep copied and option
/// objects cannot be modified after calling this method.
- (void)setAdOptions:(NSArray *)adOptions;
#pragma mark - Making an Ad Request
/// Makes an ad request. The request object supplies targeting information.
- (void)loadRequest:(nullable GADRequest *)request;
#pragma mark - Mediation
/// The name of the ad network adapter class that fetched the current ad. Returns nil while the
/// latest ad request is in progress or if the latest ad request failed. For both standard and
/// mediated Google AdMob ads, this method returns @"GADMAdapterGoogleAdMobAds". For ads fetched
/// via mediation custom events, this method returns @"GADMAdapterCustomEvents".
@property(nonatomic, readonly, weak, nullable) NSString *adNetworkClassName;
@end
NS_ASSUME_NONNULL_END
| {
"content_hash": "7c6e541c2ba257fe4cdd973832ee3608",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 100,
"avg_line_length": 48.90243902439025,
"alnum_prop": 0.7665835411471321,
"repo_name": "sagittarius-90/conwaysgameoflife",
"id": "1a0c48f1d51eedfc114d552df579dbed3de83294",
"size": "4386",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Pods/Google-Mobile-Ads-SDK/Frameworks/frameworks/GoogleMobileAds.framework/Headers/GADNativeExpressAdView.h",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Ruby",
"bytes": "259"
},
{
"name": "Swift",
"bytes": "27197"
}
],
"symlink_target": ""
} |
package com.planet_ink.coffee_mud.Commands;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
@SuppressWarnings("unchecked")
public class Credits extends StdCommand
{
public Credits(){}
private String[] access={"CREDITS"};
public String[] getAccessWords(){return access;}
public boolean execute(MOB mob, Vector commands, int metaFlags)
throws java.io.IOException
{
StringBuffer credits=new CMFile(Resources.buildResourcePath("text")+"credits.txt",null,true).text();
try { credits = CMLib.httpUtils().doVirtualPage(credits);}catch(Exception ex){}
if((credits!=null)&&(mob.session()!=null)&&(credits.length()>0))
mob.session().colorOnlyPrintln(credits.toString());
else
mob.tell("CoffeeMud is (C)2000-2010 by Bo Zimmerman");
return false;
}
public boolean canBeOrdered(){return true;}
}
| {
"content_hash": "f0248fec9a9aa9689fb54761712ce315",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 102,
"avg_line_length": 37.24390243902439,
"alnum_prop": 0.7380484610347086,
"repo_name": "robjcaskey/Unofficial-Coffee-Mud-Upstream",
"id": "40ec76354f91029597e0c5c4a2c231c5a7f9cd88",
"size": "2135",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "com/planet_ink/coffee_mud/Commands/Credits.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "21082141"
},
{
"name": "JavaScript",
"bytes": "16596"
},
{
"name": "Shell",
"bytes": "7865"
}
],
"symlink_target": ""
} |
git clone https://github.com/pyenv/pyenv.git ~/.pyenv
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.bash_profile
# Install python dependencies
sudo apt-get update
sudo apt-get install --no-install-recommends make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev
| {
"content_hash": "ad423c995bfa5ffde7843ecad0b47627",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 226,
"avg_line_length": 55.7,
"alnum_prop": 0.7378815080789947,
"repo_name": "caesar0301/warp-drive",
"id": "51b67d7275ebd6095ebf16d18670d1d00d72ab87",
"size": "573",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "utilities/pyenv.sh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AutoHotkey",
"bytes": "1977"
},
{
"name": "C",
"bytes": "591"
},
{
"name": "JavaScript",
"bytes": "611288"
},
{
"name": "Python",
"bytes": "13762"
},
{
"name": "Shell",
"bytes": "93068"
},
{
"name": "Vim Script",
"bytes": "50489"
}
],
"symlink_target": ""
} |
/*global define */
/*jslint browser:true,sloppy:true,nomen:true,unparam:true,plusplus:true,indent:4 */
/*
| Copyright 2013 Esri
|
| 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.
*/
define({
root: {
okButtonText: "OK",
webpageDispalyText: "Copy/paste HTML into your web page",
bufferDistance: "Enter buffer distance (feet)",
findNotify: "Who do you want to Notify?",
propertyOwners: "Property Owners",
propertyOccupants: "Property Occupants",
occupantLabel: "Occupant Label",
averyLabelsFormat: "Avery labels in PDF format ",
csvFormat: "Download in CSV format",
downloadNotification: "Download",
clickToLocate: "Click To Locate",
unableToLoadPDF: "Internet Explorer may fail to load the pdf document sometimes, please try a different browser if the pdf fails to load.",
errorMessages: {
invalidSearch: "No results found",
falseConfigParams: "Required configuration key values are either null or not exactly matching with layer attributes, This message may appear multiple times.",
invalidLocation: "Current Location not found.",
invalidExtent: "Selected feature is out of basemap extent",
invalidProjection: "Unable to plot current location on the map.",
widgetNotLoaded: "Fail to load widgets.",
shareLoadingFailed: "Unable to shorten URL, Bit.ly failed to load",
shareFailed: "Unable to share.",
noParcel: "Parcel not found at current location",
noRoad: "Road not found at current location",
unableToPerform: "Unable to perform operation: invalid geometry.",
enterNumeric: "Please enter numeric value.",
createBuffer: "Geometry for buffer is null in create buffer.",
selectProperty: "Select Property Owners or Occupants to notify.",
enterBufferDist: "Please enter the buffer distance.",
inValidAveryFormat: "Invalid Avery format. Please select a valid format from the dropdown list.",
inValidOccupantLabel: "Invalid format. Please select a valid option from the dropdown list.",
fileSelect: "Select at least one file format to download.",
noDataAvailable: "Data not available for this particular location.",
bufferRange: "Valid buffer range is between 0 to ${0} feet."
},
buttons: {
embedding: "Embedding", //Shown next to icon for sharing the map embedding in website
email: "Email", // Shown next to icon for sharing the current map extents via email; works with shareViaEmail tooltip
facebook: "Facebook", // Shown next to icon for sharing the current map extents via a Facebook post; works with shareViaFacebook tooltip
twitter: "Twitter" // Shown next to icon for sharing the current map extents via a Twitter tweet; works with shareViaTwitter tooltip
},
tooltips: {
locate: "Locate",
share: "Share",
help: "Help",
clear: "Clear",
search: "Search",
exit: "Exit",
locateAddress: "Locate Address",
polygon:"Polygon Tool"
}
},
es: true,
fr: true,
it: true
});
| {
"content_hash": "fef111eb6d9eae0189aa2938d85a4328",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 170,
"avg_line_length": 51.689189189189186,
"alnum_prop": 0.6556862745098039,
"repo_name": "Esri/land-use-public-notification",
"id": "5e5df81ae0d2b8e25262648cd9625d02d94472ff",
"size": "3827",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/library/nls/localizedStrings.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "45017"
},
{
"name": "CSS",
"bytes": "35434"
},
{
"name": "HTML",
"bytes": "22158"
},
{
"name": "JavaScript",
"bytes": "336201"
}
],
"symlink_target": ""
} |
package org.apache.cassandra.cql3.functions;
import java.nio.ByteBuffer;
import java.util.List;
import com.google.common.base.Objects;
import org.apache.cassandra.cql3.AssignmentTestable;
import org.apache.cassandra.cql3.CQL3Type;
import org.apache.cassandra.cql3.ColumnSpecification;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.commons.lang3.text.StrBuilder;
import static java.util.stream.Collectors.toList;
/**
* Base class for our native/hardcoded functions.
*/
public abstract class AbstractFunction implements Function
{
protected final FunctionName name;
protected final List<AbstractType<?>> argTypes;
protected final AbstractType<?> returnType;
protected AbstractFunction(FunctionName name, List<AbstractType<?>> argTypes, AbstractType<?> returnType)
{
this.name = name;
this.argTypes = argTypes;
this.returnType = returnType;
}
public FunctionName name()
{
return name;
}
public List<AbstractType<?>> argTypes()
{
return argTypes;
}
public AbstractType<?> returnType()
{
return returnType;
}
public List<String> argumentsList()
{
return argTypes().stream()
.map(AbstractType::asCQL3Type)
.map(CQL3Type::toString)
.collect(toList());
}
@Override
public boolean equals(Object o)
{
if (!(o instanceof AbstractFunction))
return false;
AbstractFunction that = (AbstractFunction)o;
return Objects.equal(this.name, that.name)
&& Objects.equal(this.argTypes, that.argTypes)
&& Objects.equal(this.returnType, that.returnType);
}
public void addFunctionsTo(List<Function> functions)
{
functions.add(this);
}
public boolean referencesUserType(ByteBuffer name)
{
return false;
}
@Override
public int hashCode()
{
return Objects.hashCode(name, argTypes, returnType);
}
public final AssignmentTestable.TestResult testAssignment(String keyspace, ColumnSpecification receiver)
{
// We should ignore the fact that the receiver type is frozen in our comparison as functions do not support
// frozen types for return type
AbstractType<?> returnType = returnType();
if (receiver.type.isFreezable() && !receiver.type.isMultiCell())
returnType = returnType.freeze();
if (receiver.type.equals(returnType))
return AssignmentTestable.TestResult.EXACT_MATCH;
if (receiver.type.isValueCompatibleWith(returnType))
return AssignmentTestable.TestResult.WEAKLY_ASSIGNABLE;
return AssignmentTestable.TestResult.NOT_ASSIGNABLE;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(name).append(" : (");
for (int i = 0; i < argTypes.size(); i++)
{
if (i > 0)
sb.append(", ");
sb.append(argTypes.get(i).asCQL3Type());
}
sb.append(") -> ").append(returnType.asCQL3Type());
return sb.toString();
}
@Override
public String columnName(List<String> columnNames)
{
return new StrBuilder(name().toString()).append('(')
.appendWithSeparators(columnNames, ", ")
.append(')')
.toString();
}
}
| {
"content_hash": "bd411c4431569a64a3be2cc06dd8e5a2",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 115,
"avg_line_length": 28.584,
"alnum_prop": 0.612650433809124,
"repo_name": "clohfink/cassandra",
"id": "aea0d01b877c8ad788ff1a1fb60e55130dc53d3f",
"size": "4378",
"binary": false,
"copies": "20",
"ref": "refs/heads/trunk",
"path": "src/java/org/apache/cassandra/cql3/functions/AbstractFunction.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AMPL",
"bytes": "801"
},
{
"name": "Batchfile",
"bytes": "38885"
},
{
"name": "GAP",
"bytes": "86159"
},
{
"name": "Groovy",
"bytes": "11484"
},
{
"name": "HTML",
"bytes": "264240"
},
{
"name": "Java",
"bytes": "23505441"
},
{
"name": "Lex",
"bytes": "10151"
},
{
"name": "PowerShell",
"bytes": "39040"
},
{
"name": "Python",
"bytes": "528715"
},
{
"name": "Shell",
"bytes": "91870"
}
],
"symlink_target": ""
} |
<!--
Copyright (C) 2012 Red Hat, Inc.
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.
-->
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.commonjava.maven.ext.integration-test</groupId>
<artifactId>project-version-child-property-version</artifactId>
<version>1.0</version>
<packaging>pom</packaging>
<name>ProjectVersionRemoval</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<mychildversion>1.1</mychildversion>
</properties>
<modules>
<module>child</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>\${project.version}</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>2.0</version>
</dependency>
</dependencies>
</dependencyManagement>
<repositories>
<repository>
<id>jboss-public-repository-group</id>
<name>JBoss Public Maven Repository Group</name>
<url>https://repository.jboss.org/nexus/content/groups/public/</url>
<layout>default</layout>
<releases>
<enabled>false</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
<updatePolicy>never</updatePolicy>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>jboss-public-repository-group</id>
<name>JBoss Public Maven Repository Group</name>
<url>https://repository.jboss.org/nexus/content/groups/public/</url>
<layout>default</layout>
<releases>
<enabled>false</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
<updatePolicy>never</updatePolicy>
</snapshots>
</pluginRepository>
</pluginRepositories>
<profiles>
<profile>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>\${project.version}</version>
</dependency>
</dependencies>
</profile>
</profiles>
</project>
| {
"content_hash": "c06635e83f6c31b557f4366243597882",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 108,
"avg_line_length": 33.61904761904762,
"alnum_prop": 0.5875354107648725,
"repo_name": "rnc/pom-manipulation-ext",
"id": "0b98689bacdc9e749790d00e0236542ee228ea7b",
"size": "3530",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "integration-test/src/it/project-version-child-property-version/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "289281"
},
{
"name": "Java",
"bytes": "1584108"
}
],
"symlink_target": ""
} |
fhc-admin-users(1) -- Administer FeedHenry Users
================================================
## SYNOPSIS
fhc admin-users list
fhc admin-users create username=<username> [password=<password>] [email=<email>] [name=<name>] [roles=<roles>] [authpolicies=<authpolicies>] [invite=<invitation>]
fhc admin-users delete <username>
fhc admin-users read <username>
fhc admin-users update username=<username> [password=<password>] [email=<email>] [name=<name>] [roles=<roles>] [authpolicies=<authpolicies>] [inviation=<invitation>] [enabled=<enabled>]
fhc admin-users enable <username>
fhc admin-users disable <username>
fhc admin-users changeroles <username> <roles>
fhc admin-users changeauthpolicies <username> <authpolicies>
fhc admin-users listdevices <username>
fhc admin-users listinstallapps <username>
fhc admin-users import <path-to-csv-file> [invite] [<roles> <authpolicies>]
## DESCRIPTION
This command allows you to Administer Users on the FeedHenry Platform. For more information, see http://docs.feedhenry.com/v2/useradmin.html.
| {
"content_hash": "568264a0402aa9647850121abb796916",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 189,
"avg_line_length": 49.77272727272727,
"alnum_prop": 0.6958904109589041,
"repo_name": "david-martin/fh-fhc",
"id": "e739ae71e6ef54f7e472cde7a797df058ec367a1",
"size": "1095",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "doc/common/admin-users.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "484265"
},
{
"name": "Smarty",
"bytes": "566"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Web.Razor.Generator;
using System.Web.Razor.Parser.SyntaxTree;
using System.Web.Razor.Resources;
using System.Web.Razor.Text;
using System.Web.Razor.Tokenizer;
using System.Web.Razor.Tokenizer.Symbols;
namespace System.Web.Razor.Parser
{
public partial class VBCodeParser : TokenizerBackedParser<VBTokenizer, VBSymbol, VBSymbolType>
{
private void SetUpKeywords()
{
MapKeyword(VBKeyword.Using, EndTerminatedStatement(VBKeyword.Using, supportsExit: false, supportsContinue: false)); // http://msdn.microsoft.com/en-us/library/htd05whh.aspx
MapKeyword(VBKeyword.While, EndTerminatedStatement(VBKeyword.While, supportsExit: true, supportsContinue: true)); // http://msdn.microsoft.com/en-us/library/zh1f56zs.aspx
MapKeyword(VBKeyword.If, EndTerminatedStatement(VBKeyword.If, supportsExit: false, supportsContinue: false)); // http://msdn.microsoft.com/en-us/library/752y8abs.aspx
MapKeyword(VBKeyword.Select, EndTerminatedStatement(VBKeyword.Select, supportsExit: true, supportsContinue: false, blockName: SyntaxConstants.VB.SelectCaseKeyword)); // http://msdn.microsoft.com/en-us/library/cy37t14y.aspx
MapKeyword(VBKeyword.Try, EndTerminatedStatement(VBKeyword.Try, supportsExit: true, supportsContinue: false)); // http://msdn.microsoft.com/en-us/library/fk6t46tz.aspx
MapKeyword(VBKeyword.With, EndTerminatedStatement(VBKeyword.With, supportsExit: false, supportsContinue: false)); // http://msdn.microsoft.com/en-us/library/wc500chb.aspx
MapKeyword(VBKeyword.SyncLock, EndTerminatedStatement(VBKeyword.SyncLock, supportsExit: false, supportsContinue: false)); // http://msdn.microsoft.com/en-us/library/3a86s51t.aspx
// http://msdn.microsoft.com/en-us/library/5z06z1kb.aspx
// http://msdn.microsoft.com/en-us/library/5ebk1751.aspx
MapKeyword(VBKeyword.For, KeywordTerminatedStatement(VBKeyword.For, VBKeyword.Next, supportsExit: true, supportsContinue: true));
MapKeyword(VBKeyword.Do, KeywordTerminatedStatement(VBKeyword.Do, VBKeyword.Loop, supportsExit: true, supportsContinue: true)); // http://msdn.microsoft.com/en-us/library/eked04a7.aspx
MapKeyword(VBKeyword.Imports, ImportsStatement);
MapKeyword(VBKeyword.Option, OptionStatement);
MapKeyword(VBKeyword.Inherits, InheritsStatement);
MapKeyword(VBKeyword.Class, ReservedWord);
MapKeyword(VBKeyword.Namespace, ReservedWord);
}
protected virtual bool InheritsStatement()
{
Assert(VBKeyword.Inherits);
Span.CodeGenerator = SpanCodeGenerator.Null;
Context.CurrentBlock.Type = BlockType.Directive;
AcceptAndMoveNext();
SourceLocation endInherits = CurrentLocation;
if (At(VBSymbolType.WhiteSpace))
{
Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;
}
AcceptWhile(VBSymbolType.WhiteSpace);
Output(SpanKind.MetaCode);
if (EndOfFile || At(VBSymbolType.WhiteSpace) || At(VBSymbolType.NewLine))
{
Context.OnError(endInherits, RazorResources.ParseError_InheritsKeyword_Must_Be_Followed_By_TypeName);
}
// Just accept to a newline
AcceptUntil(VBSymbolType.NewLine);
if (!Context.DesignTimeMode)
{
// We want the newline to be treated as code, but it causes issues at design-time.
Optional(VBSymbolType.NewLine);
}
string baseType = Span.GetContent();
Span.CodeGenerator = new SetBaseTypeCodeGenerator(baseType.Trim());
Output(SpanKind.Code);
return false;
}
protected virtual bool OptionStatement()
{
try
{
Context.CurrentBlock.Type = BlockType.Directive;
Assert(VBKeyword.Option);
AcceptAndMoveNext();
AcceptWhile(VBSymbolType.WhiteSpace);
if (!At(VBSymbolType.Identifier))
{
if (CurrentSymbol != null)
{
Context.OnError(CurrentLocation, String.Format(CultureInfo.CurrentCulture,
RazorResources.ParseError_Unexpected,
CurrentSymbol.Content));
}
return false;
}
SourceLocation optionLoc = CurrentLocation;
string option = CurrentSymbol.Content;
AcceptAndMoveNext();
AcceptWhile(VBSymbolType.WhiteSpace);
bool boolVal;
if (At(VBKeyword.On))
{
AcceptAndMoveNext();
boolVal = true;
}
else if (At(VBSymbolType.Identifier))
{
if (String.Equals(CurrentSymbol.Content, SyntaxConstants.VB.OffKeyword, StringComparison.OrdinalIgnoreCase))
{
AcceptAndMoveNext();
boolVal = false;
}
else
{
Context.OnError(CurrentLocation, String.Format(CultureInfo.CurrentCulture,
RazorResources.ParseError_InvalidOptionValue,
option,
CurrentSymbol.Content));
AcceptAndMoveNext();
return false;
}
}
else
{
if (!EndOfFile)
{
Context.OnError(CurrentLocation, String.Format(CultureInfo.CurrentCulture,
RazorResources.ParseError_Unexpected,
CurrentSymbol.Content));
AcceptAndMoveNext();
}
return false;
}
if (String.Equals(option, SyntaxConstants.VB.StrictKeyword, StringComparison.OrdinalIgnoreCase))
{
Span.CodeGenerator = SetVBOptionCodeGenerator.Strict(boolVal);
}
else if (String.Equals(option, SyntaxConstants.VB.ExplicitKeyword, StringComparison.OrdinalIgnoreCase))
{
Span.CodeGenerator = SetVBOptionCodeGenerator.Explicit(boolVal);
}
else
{
Span.CodeGenerator = new SetVBOptionCodeGenerator(option, boolVal);
Context.OnError(optionLoc, RazorResources.ParseError_UnknownOption, option);
}
}
finally
{
if (Span.Symbols.Count > 0)
{
Output(SpanKind.MetaCode);
}
}
return true;
}
protected virtual bool ImportsStatement()
{
Context.CurrentBlock.Type = BlockType.Directive;
Assert(VBKeyword.Imports);
AcceptAndMoveNext();
AcceptVBSpaces();
if (At(VBSymbolType.WhiteSpace) || At(VBSymbolType.NewLine))
{
Context.OnError(CurrentLocation, RazorResources.ParseError_NamespaceOrTypeAliasExpected);
}
// Just accept to a newline
AcceptUntil(VBSymbolType.NewLine);
Optional(VBSymbolType.NewLine);
string ns = String.Concat(Span.Symbols.Skip(1).Select(s => s.Content));
Span.CodeGenerator = new AddImportCodeGenerator(ns, SyntaxConstants.VB.ImportsKeywordLength);
Output(SpanKind.MetaCode);
return false;
}
protected virtual Func<bool> EndTerminatedStatement(VBKeyword keyword, bool supportsExit, bool supportsContinue)
{
return EndTerminatedStatement(keyword, supportsExit, supportsContinue, blockName: keyword.ToString());
}
protected virtual Func<bool> EndTerminatedStatement(VBKeyword keyword, bool supportsExit, bool supportsContinue, string blockName)
{
return () =>
{
using (PushSpanConfig(StatementBlockSpanConfiguration(new StatementCodeGenerator())))
{
SourceLocation blockStart = CurrentLocation;
Assert(keyword);
AcceptAndMoveNext();
while (!EndOfFile)
{
VBSymbol lastWhitespace = AcceptWhiteSpaceInLines();
if (IsAtEmbeddedTransition(allowTemplatesAndComments: true, allowTransitions: true))
{
HandleEmbeddedTransition(lastWhitespace);
}
else
{
Accept(lastWhitespace);
if ((supportsExit && At(VBKeyword.Exit)) || (supportsContinue && At(VBKeyword.Continue)))
{
HandleExitOrContinue(keyword);
}
else if (At(VBKeyword.End))
{
AcceptAndMoveNext();
AcceptVBSpaces();
if (At(keyword))
{
AcceptAndMoveNext();
if (!Context.DesignTimeMode)
{
Optional(VBSymbolType.NewLine);
}
Span.EditHandler.AcceptedCharacters = AcceptedCharacters.None;
return false;
}
}
else if (At(keyword))
{
// Parse nested statement
EndTerminatedStatement(keyword, supportsExit, supportsContinue)();
}
else if (!EndOfFile)
{
AcceptAndMoveNext();
}
}
}
Context.OnError(blockStart,
RazorResources.ParseError_BlockNotTerminated,
blockName,
// This is a language keyword, so it does not need to be localized
String.Concat(VBKeyword.End, " ", keyword));
return false;
}
};
}
protected virtual Func<bool> KeywordTerminatedStatement(VBKeyword start, VBKeyword terminator, bool supportsExit, bool supportsContinue)
{
return () =>
{
using (PushSpanConfig(StatementBlockSpanConfiguration(new StatementCodeGenerator())))
{
SourceLocation blockStart = CurrentLocation;
Assert(start);
AcceptAndMoveNext();
while (!EndOfFile)
{
VBSymbol lastWhitespace = AcceptWhiteSpaceInLines();
if (IsAtEmbeddedTransition(allowTemplatesAndComments: true, allowTransitions: true))
{
HandleEmbeddedTransition(lastWhitespace);
}
else
{
Accept(lastWhitespace);
if ((supportsExit && At(VBKeyword.Exit)) || (supportsContinue && At(VBKeyword.Continue)))
{
HandleExitOrContinue(start);
}
else if (At(start))
{
// Parse nested statement
KeywordTerminatedStatement(start, terminator, supportsExit, supportsContinue)();
}
else if (At(terminator))
{
AcceptUntil(VBSymbolType.NewLine);
Optional(VBSymbolType.NewLine);
Span.EditHandler.AcceptedCharacters = AcceptedCharacters.AnyExceptNewline;
return false;
}
else if (!EndOfFile)
{
AcceptAndMoveNext();
}
}
}
Context.OnError(blockStart,
RazorResources.ParseError_BlockNotTerminated,
start, terminator);
return false;
}
};
}
protected void HandleExitOrContinue(VBKeyword keyword)
{
Assert(VBSymbolType.Keyword);
Debug.Assert(CurrentSymbol.Keyword == VBKeyword.Continue || CurrentSymbol.Keyword == VBKeyword.Exit);
// Accept, read whitespace and look for the next keyword
AcceptAndMoveNext();
AcceptWhile(VBSymbolType.WhiteSpace);
// If this is the start keyword, skip it and continue (to avoid starting a nested statement block)
Optional(keyword);
}
}
}
| {
"content_hash": "d615f8caa485c98cebaf2300d59b3456",
"timestamp": "",
"source": "github",
"line_count": 314,
"max_line_length": 234,
"avg_line_length": 45.761146496815286,
"alnum_prop": 0.5035145104043427,
"repo_name": "Terminator-Aaron/Katana_Diagram",
"id": "b5bb00dd13f88e247b3b5b68d2ec3bf1c78573c4",
"size": "14371",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "aspnetwebsrc/System.Web.Razor/Parser/VBCodeParser.Statements.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "10480"
},
{
"name": "C#",
"bytes": "9816488"
},
{
"name": "CSS",
"bytes": "19810"
},
{
"name": "HTML",
"bytes": "1720"
},
{
"name": "JavaScript",
"bytes": "11545"
},
{
"name": "PowerShell",
"bytes": "20946"
},
{
"name": "Shell",
"bytes": "11193"
},
{
"name": "Smalltalk",
"bytes": "50876"
},
{
"name": "Visual Basic",
"bytes": "157681"
}
],
"symlink_target": ""
} |
package com.example.quartz.example15;
import org.quartz.DateBuilder.IntervalUnit;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.quartz.DateBuilder.futureDate;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;
/**
* Used to test/show the clustering features of TC JobStore.
* <p>
* All instances MUST use a different properties file, because their instance Ids must be different, however all other
* properties should be the same.
* </p>
* <p>
* If you want it to clear out existing jobs & triggers, pass a command-line argument called "clearJobs".
* </p>
* <p>
* You should probably start with a "fresh" set of tables (assuming you may have some data lingering in it from other
* tests), since mixing data from a non-clustered setup with a clustered one can be bad.
* </p>
* <p>
* Try killing one of the cluster instances while they are running, and see that the remaining instance(s) recover the
* in-progress jobs. Note that detection of the failure may take up to 15 or so seconds with the default settings.
* </p>
* <p>
* Also try running it with/without the shutdown-hook plugin registered with the scheduler.
* (org.quartz.plugins.management.ShutdownHookPlugin).
* </p>
* <p>
* <i>Note:</i> Never run clustering on separate machines, unless their clocks are synchronized using some form of
* time-sync service (daemon).
* </p>
*
* @author James House
*/
public class ClusterExample {
private static Logger _log = LoggerFactory.getLogger(ClusterExample.class);
public void run(boolean inClearJobs, boolean inScheduleJobs) throws Exception {
// First we must get a reference to a scheduler
SchedulerFactory sf = new StdSchedulerFactory();
Scheduler sched = sf.getScheduler();
if (inClearJobs) {
_log.warn("***** Deleting existing jobs/triggers *****");
sched.clear();
}
_log.info("------- Initialization Complete -----------");
if (inScheduleJobs) {
_log.info("------- Scheduling Jobs ------------------");
String schedId = sched.getSchedulerInstanceId();
int count = 1;
JobDetail job = newJob(SimpleRecoveryJob.class).withIdentity("job_" + count, schedId) // put triggers in group
// named after the cluster
// node instance just to
// distinguish (in logging)
// what was scheduled from
// where
.requestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went
// down...
.build();
SimpleTrigger trigger = newTrigger().withIdentity("triger_" + count, schedId)
.startAt(futureDate(1, IntervalUnit.SECOND))
.withSchedule(simpleSchedule().withRepeatCount(20).withIntervalInSeconds(5)).build();
_log.info(job.getKey() + " will run at: " + trigger.getNextFireTime() + " and repeat: "
+ trigger.getRepeatCount() + " times, every " + trigger.getRepeatInterval() / 1000 + " seconds");
sched.scheduleJob(job, trigger);
count++;
job = newJob(SimpleRecoveryJob.class).withIdentity("job_" + count, schedId) // put triggers in group named after
// the cluster node instance just to
// distinguish (in logging) what was
// scheduled from where
.requestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went
// down...
.build();
trigger = newTrigger().withIdentity("triger_" + count, schedId).startAt(futureDate(2, IntervalUnit.SECOND))
.withSchedule(simpleSchedule().withRepeatCount(20).withIntervalInSeconds(5)).build();
_log.info(job.getKey() + " will run at: " + trigger.getNextFireTime() + " and repeat: "
+ trigger.getRepeatCount() + " times, every " + trigger.getRepeatInterval() / 1000 + " seconds");
sched.scheduleJob(job, trigger);
count++;
job = newJob(SimpleRecoveryStatefulJob.class).withIdentity("job_" + count, schedId) // put triggers in group named
// after the cluster node
// instance just to
// distinguish (in logging)
// what was scheduled from
// where
.requestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went
// down...
.build();
trigger = newTrigger().withIdentity("triger_" + count, schedId).startAt(futureDate(1, IntervalUnit.SECOND))
.withSchedule(simpleSchedule().withRepeatCount(20).withIntervalInSeconds(3)).build();
_log.info(job.getKey() + " will run at: " + trigger.getNextFireTime() + " and repeat: "
+ trigger.getRepeatCount() + " times, every " + trigger.getRepeatInterval() / 1000 + " seconds");
sched.scheduleJob(job, trigger);
count++;
job = newJob(SimpleRecoveryJob.class).withIdentity("job_" + count, schedId) // put triggers in group named after
// the cluster node instance just to
// distinguish (in logging) what was
// scheduled from where
.requestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went
// down...
.build();
trigger = newTrigger().withIdentity("triger_" + count, schedId).startAt(futureDate(1, IntervalUnit.SECOND))
.withSchedule(simpleSchedule().withRepeatCount(20).withIntervalInSeconds(4)).build();
_log.info(job.getKey() + " will run at: " + trigger.getNextFireTime() + " & repeat: " + trigger.getRepeatCount()
+ "/" + trigger.getRepeatInterval());
sched.scheduleJob(job, trigger);
count++;
job = newJob(SimpleRecoveryJob.class).withIdentity("job_" + count, schedId) // put triggers in group named after
// the cluster node instance just to
// distinguish (in logging) what was
// scheduled from where
.requestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went
// down...
.build();
trigger = newTrigger().withIdentity("triger_" + count, schedId).startAt(futureDate(1, IntervalUnit.SECOND))
.withSchedule(simpleSchedule().withRepeatCount(20).withIntervalInMilliseconds(4500L)).build();
_log.info(job.getKey() + " will run at: " + trigger.getNextFireTime() + " & repeat: " + trigger.getRepeatCount()
+ "/" + trigger.getRepeatInterval());
sched.scheduleJob(job, trigger);
}
// jobs don't start firing until start() has been called...
_log.info("------- Starting Scheduler ---------------");
sched.start();
_log.info("------- Started Scheduler ----------------");
_log.info("------- Waiting for one hour... ----------");
try {
Thread.sleep(3600L * 1000L);
} catch (Exception e) {
//
}
_log.info("------- Shutting Down --------------------");
sched.shutdown();
_log.info("------- Shutdown Complete ----------------");
}
public static void main(String[] args) throws Exception {
boolean clearJobs = false;
boolean scheduleJobs = true;
for (String arg : args) {
if (arg.equalsIgnoreCase("clearJobs")) {
clearJobs = true;
} else if (arg.equalsIgnoreCase("dontScheduleJobs")) {
scheduleJobs = false;
}
}
ClusterExample example = new ClusterExample();
example.run(clearJobs, scheduleJobs);
}
}
| {
"content_hash": "ccf0b98bf0cee6149300c10ef4e3d829",
"timestamp": "",
"source": "github",
"line_count": 193,
"max_line_length": 120,
"avg_line_length": 48.18652849740933,
"alnum_prop": 0.5351612903225806,
"repo_name": "yuweijun/learning-programming",
"id": "7083665d2807d33b48b0e89fdc855be912baa3d6",
"size": "9973",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "quartz/src/main/java/com/example/quartz/example15/ClusterExample.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "154236"
},
{
"name": "C++",
"bytes": "4553"
},
{
"name": "CMake",
"bytes": "1946"
},
{
"name": "CSS",
"bytes": "160054"
},
{
"name": "Dockerfile",
"bytes": "19619"
},
{
"name": "FreeMarker",
"bytes": "637"
},
{
"name": "Groovy",
"bytes": "12984"
},
{
"name": "HTML",
"bytes": "4187"
},
{
"name": "Java",
"bytes": "3190734"
},
{
"name": "JavaScript",
"bytes": "89565"
},
{
"name": "Makefile",
"bytes": "4844"
},
{
"name": "Objective-C",
"bytes": "115632"
},
{
"name": "Perl",
"bytes": "34453"
},
{
"name": "Perl 6",
"bytes": "251"
},
{
"name": "Python",
"bytes": "9199"
},
{
"name": "Ruby",
"bytes": "245894"
},
{
"name": "Shell",
"bytes": "46710"
},
{
"name": "Thrift",
"bytes": "6327"
}
],
"symlink_target": ""
} |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Framework.Extensions.EnumExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Textures;
using osu.Framework.Utils;
using osuTK;
namespace osu.Game.Storyboards.Drawables
{
public class DrawableStoryboardSprite : CompositeDrawable, IFlippable, IVectorScalable
{
public StoryboardSprite Sprite { get; }
private bool flipH;
public bool FlipH
{
get => flipH;
set
{
if (flipH == value)
return;
flipH = value;
Invalidate(Invalidation.MiscGeometry);
}
}
private bool flipV;
public bool FlipV
{
get => flipV;
set
{
if (flipV == value)
return;
flipV = value;
Invalidate(Invalidation.MiscGeometry);
}
}
private Vector2 vectorScale = Vector2.One;
public Vector2 VectorScale
{
get => vectorScale;
set
{
if (Math.Abs(value.X) < Precision.FLOAT_EPSILON)
value.X = Precision.FLOAT_EPSILON;
if (Math.Abs(value.Y) < Precision.FLOAT_EPSILON)
value.Y = Precision.FLOAT_EPSILON;
if (vectorScale == value)
return;
if (!Validation.IsFinite(value)) throw new ArgumentException($@"{nameof(VectorScale)} must be finite, but is {value}.");
vectorScale = value;
Invalidate(Invalidation.MiscGeometry);
}
}
public override bool RemoveWhenNotAlive => false;
protected override Vector2 DrawScale
=> new Vector2(FlipH ? -base.DrawScale.X : base.DrawScale.X, FlipV ? -base.DrawScale.Y : base.DrawScale.Y) * VectorScale;
public override Anchor Origin
{
get
{
var origin = base.Origin;
if (FlipH)
{
if (origin.HasFlagFast(Anchor.x0))
origin = Anchor.x2 | (origin & (Anchor.y0 | Anchor.y1 | Anchor.y2));
else if (origin.HasFlagFast(Anchor.x2))
origin = Anchor.x0 | (origin & (Anchor.y0 | Anchor.y1 | Anchor.y2));
}
if (FlipV)
{
if (origin.HasFlagFast(Anchor.y0))
origin = Anchor.y2 | (origin & (Anchor.x0 | Anchor.x1 | Anchor.x2));
else if (origin.HasFlagFast(Anchor.y2))
origin = Anchor.y0 | (origin & (Anchor.x0 | Anchor.x1 | Anchor.x2));
}
return origin;
}
}
public override bool IsPresent
=> !float.IsNaN(DrawPosition.X) && !float.IsNaN(DrawPosition.Y) && base.IsPresent;
public DrawableStoryboardSprite(StoryboardSprite sprite)
{
Sprite = sprite;
Origin = sprite.Origin;
Position = sprite.InitialPosition;
LifetimeStart = sprite.StartTime;
LifetimeEnd = sprite.EndTime;
AutoSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader]
private void load(TextureStore textureStore, Storyboard storyboard)
{
var drawable = storyboard.CreateSpriteFromResourcePath(Sprite.Path, textureStore);
if (drawable != null)
InternalChild = drawable;
Sprite.ApplyTransforms(this);
}
}
}
| {
"content_hash": "ac95718a09826077500d9e59361c7eba",
"timestamp": "",
"source": "github",
"line_count": 128,
"max_line_length": 136,
"avg_line_length": 30.2109375,
"alnum_prop": 0.5285751228342385,
"repo_name": "peppy/osu-new",
"id": "eb877f3dffef375af337aecaed347f844af51bf0",
"size": "3869",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "osu.Game/Storyboards/Drawables/DrawableStoryboardSprite.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "281779"
}
],
"symlink_target": ""
} |
{% load i18n %}
<h3>{% trans "Search" %}</h3>
<form id="search" action="{{ satchmo_search_url }}" method="get">
{% if categories %}
<select name="category">
<option value="" selected="selected">{% trans "All Products" %}</option>
{% for cat in categories %}
<option value="{{ cat.slug }}"{% ifequal cat category %} selected="selected"{% endifequal %}>{{ cat.name}}</option>
{% endfor %}
</select><br/>
{% endif %}
<input type="text" size="20" name="keywords" id="search_keywords" /><br/>
<input type="submit" value="{% trans "Search" %}" />
</form>
| {
"content_hash": "6ae36a9a0e90064512cdabcd977d00f0",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 117,
"avg_line_length": 38.13333333333333,
"alnum_prop": 0.5961538461538461,
"repo_name": "grengojbo/satchmo",
"id": "85ed0955149366f361e12b8f1bd93aefa6c6b699",
"size": "572",
"binary": false,
"copies": "16",
"ref": "refs/heads/master",
"path": "satchmo/apps/satchmo_store/shop/templates/shop/_search.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "73898"
},
{
"name": "Python",
"bytes": "1752948"
}
],
"symlink_target": ""
} |
package org.apache.calcite.adapter.enumerable;
import org.apache.calcite.plan.Convention;
import org.apache.calcite.plan.RelTraitSet;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.convert.ConverterRule;
import org.apache.calcite.rel.core.RelFactories;
import org.apache.calcite.rel.logical.LogicalTableFunctionScan;
import org.apache.calcite.tools.RelBuilderFactory;
import java.util.function.Predicate;
/** Planner rule that converts a
* {@link org.apache.calcite.rel.logical.LogicalTableFunctionScan}
* relational expression
* {@link org.apache.calcite.adapter.enumerable.EnumerableConvention enumerable calling convention}. */
public class EnumerableTableFunctionScanRule extends ConverterRule {
@Deprecated // to be removed before 2.0
public EnumerableTableFunctionScanRule() {
this(RelFactories.LOGICAL_BUILDER);
}
/**
* Creates an EnumerableTableFunctionScanRule.
*
* @param relBuilderFactory Builder for relational expressions
*/
public EnumerableTableFunctionScanRule(RelBuilderFactory relBuilderFactory) {
super(LogicalTableFunctionScan.class, (Predicate<RelNode>) r -> true,
Convention.NONE, EnumerableConvention.INSTANCE, relBuilderFactory,
"EnumerableTableFunctionScanRule");
}
@Override public RelNode convert(RelNode rel) {
final RelTraitSet traitSet =
rel.getTraitSet().replace(EnumerableConvention.INSTANCE);
LogicalTableFunctionScan tbl = (LogicalTableFunctionScan) rel;
return new EnumerableTableFunctionScan(rel.getCluster(), traitSet,
tbl.getInputs(), tbl.getElementType(), tbl.getRowType(),
tbl.getCall(), tbl.getColumnMappings());
}
}
// End EnumerableTableFunctionScanRule.java
| {
"content_hash": "3191ab73e0a9bc59c1ec31c4f0a968e3",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 103,
"avg_line_length": 38.266666666666666,
"alnum_prop": 0.7799070847851336,
"repo_name": "dindin5258/calcite",
"id": "a5a4190bf48ae078aa0a4b1efb21e0bf70752a97",
"size": "2519",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableFunctionScanRule.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3037"
},
{
"name": "CSS",
"bytes": "36560"
},
{
"name": "FreeMarker",
"bytes": "16065"
},
{
"name": "HTML",
"bytes": "28465"
},
{
"name": "Java",
"bytes": "15811546"
},
{
"name": "Kotlin",
"bytes": "1157"
},
{
"name": "Python",
"bytes": "1610"
},
{
"name": "Ruby",
"bytes": "1807"
},
{
"name": "Shell",
"bytes": "5326"
}
],
"symlink_target": ""
} |
package org.springframework.security.oauth2.server.resource.introspection;
import java.net.URI;
import java.net.URL;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import com.nimbusds.oauth2.sdk.TokenIntrospectionResponse;
import com.nimbusds.oauth2.sdk.TokenIntrospectionSuccessResponse;
import com.nimbusds.oauth2.sdk.http.HTTPResponse;
import com.nimbusds.oauth2.sdk.id.Audience;
import reactor.core.publisher.Mono;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames;
import org.springframework.util.Assert;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.reactive.function.client.WebClient;
/**
* A Nimbus implementation of {@link ReactiveOpaqueTokenIntrospector} that verifies and
* introspects a token using the configured
* <a href="https://tools.ietf.org/html/rfc7662" target="_blank">OAuth 2.0 Introspection
* Endpoint</a>.
*
* @author Josh Cummings
* @since 5.2
*/
public class NimbusReactiveOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
private final URI introspectionUri;
private final WebClient webClient;
private String authorityPrefix = "SCOPE_";
/**
* Creates a {@code OpaqueTokenReactiveAuthenticationManager} with the provided
* parameters
* @param introspectionUri The introspection endpoint uri
* @param clientId The client id authorized to introspect
* @param clientSecret The client secret for the authorized client
*/
public NimbusReactiveOpaqueTokenIntrospector(String introspectionUri, String clientId, String clientSecret) {
Assert.hasText(introspectionUri, "introspectionUri cannot be empty");
Assert.hasText(clientId, "clientId cannot be empty");
Assert.notNull(clientSecret, "clientSecret cannot be null");
this.introspectionUri = URI.create(introspectionUri);
this.webClient = WebClient.builder().defaultHeaders((h) -> h.setBasicAuth(clientId, clientSecret)).build();
}
/**
* Creates a {@code OpaqueTokenReactiveAuthenticationManager} with the provided
* parameters
* @param introspectionUri The introspection endpoint uri
* @param webClient The client for performing the introspection request
*/
public NimbusReactiveOpaqueTokenIntrospector(String introspectionUri, WebClient webClient) {
Assert.hasText(introspectionUri, "introspectionUri cannot be null");
Assert.notNull(webClient, "webClient cannot be null");
this.introspectionUri = URI.create(introspectionUri);
this.webClient = webClient;
}
@Override
public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
// @formatter:off
return Mono.just(token)
.flatMap(this::makeRequest)
.flatMap(this::adaptToNimbusResponse)
.map(this::parseNimbusResponse)
.map(this::castToNimbusSuccess)
.doOnNext((response) -> validate(token, response))
.map(this::convertClaimsSet)
.onErrorMap((e) -> !(e instanceof OAuth2IntrospectionException), this::onError);
// @formatter:on
}
private Mono<ClientResponse> makeRequest(String token) {
// @formatter:off
return this.webClient.post()
.uri(this.introspectionUri)
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.body(BodyInserters.fromFormData("token", token))
.exchange();
// @formatter:on
}
private Mono<HTTPResponse> adaptToNimbusResponse(ClientResponse responseEntity) {
HTTPResponse response = new HTTPResponse(responseEntity.rawStatusCode());
response.setHeader(HttpHeaders.CONTENT_TYPE, responseEntity.headers().contentType().get().toString());
if (response.getStatusCode() != HTTPResponse.SC_OK) {
// @formatter:off
return responseEntity.bodyToFlux(DataBuffer.class)
.map(DataBufferUtils::release)
.then(Mono.error(new OAuth2IntrospectionException(
"Introspection endpoint responded with " + response.getStatusCode()))
);
// @formatter:on
}
return responseEntity.bodyToMono(String.class).doOnNext(response::setContent).map((body) -> response);
}
private TokenIntrospectionResponse parseNimbusResponse(HTTPResponse response) {
try {
return TokenIntrospectionResponse.parse(response);
}
catch (Exception ex) {
throw new OAuth2IntrospectionException(ex.getMessage(), ex);
}
}
private TokenIntrospectionSuccessResponse castToNimbusSuccess(TokenIntrospectionResponse introspectionResponse) {
if (!introspectionResponse.indicatesSuccess()) {
throw new OAuth2IntrospectionException("Token introspection failed");
}
return (TokenIntrospectionSuccessResponse) introspectionResponse;
}
private void validate(String token, TokenIntrospectionSuccessResponse response) {
// relying solely on the authorization server to validate this token (not checking
// 'exp', for example)
if (!response.isActive()) {
throw new BadOpaqueTokenException("Provided token isn't active");
}
}
private OAuth2AuthenticatedPrincipal convertClaimsSet(TokenIntrospectionSuccessResponse response) {
Map<String, Object> claims = response.toJSONObject();
Collection<GrantedAuthority> authorities = new ArrayList<>();
if (response.getAudience() != null) {
List<String> audiences = new ArrayList<>();
for (Audience audience : response.getAudience()) {
audiences.add(audience.getValue());
}
claims.put(OAuth2TokenIntrospectionClaimNames.AUD, Collections.unmodifiableList(audiences));
}
if (response.getClientID() != null) {
claims.put(OAuth2TokenIntrospectionClaimNames.CLIENT_ID, response.getClientID().getValue());
}
if (response.getExpirationTime() != null) {
Instant exp = response.getExpirationTime().toInstant();
claims.put(OAuth2TokenIntrospectionClaimNames.EXP, exp);
}
if (response.getIssueTime() != null) {
Instant iat = response.getIssueTime().toInstant();
claims.put(OAuth2TokenIntrospectionClaimNames.IAT, iat);
}
if (response.getIssuer() != null) {
claims.put(OAuth2TokenIntrospectionClaimNames.ISS, issuer(response.getIssuer().getValue()));
}
if (response.getNotBeforeTime() != null) {
claims.put(OAuth2TokenIntrospectionClaimNames.NBF, response.getNotBeforeTime().toInstant());
}
if (response.getScope() != null) {
List<String> scopes = Collections.unmodifiableList(response.getScope().toStringList());
claims.put(OAuth2TokenIntrospectionClaimNames.SCOPE, scopes);
for (String scope : scopes) {
authorities.add(new SimpleGrantedAuthority(this.authorityPrefix + scope));
}
}
return new OAuth2IntrospectionAuthenticatedPrincipal(claims, authorities);
}
private URL issuer(String uri) {
try {
return new URL(uri);
}
catch (Exception ex) {
throw new OAuth2IntrospectionException(
"Invalid " + OAuth2TokenIntrospectionClaimNames.ISS + " value: " + uri);
}
}
private OAuth2IntrospectionException onError(Throwable ex) {
return new OAuth2IntrospectionException(ex.getMessage(), ex);
}
}
| {
"content_hash": "22343d4d992b3b8807b178fc107c9a1d",
"timestamp": "",
"source": "github",
"line_count": 193,
"max_line_length": 114,
"avg_line_length": 38.5440414507772,
"alnum_prop": 0.7733566339561769,
"repo_name": "djechelon/spring-security",
"id": "b562c8630874b04dcd91a8f2bac7e1fbd42d0b01",
"size": "8060",
"binary": false,
"copies": "2",
"ref": "refs/heads/bugfix/20214-principal-claim-name-null",
"path": "oauth2/oauth2-resource-server/src/main/java/org/springframework/security/oauth2/server/resource/introspection/NimbusReactiveOpaqueTokenIntrospector.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AspectJ",
"bytes": "3352"
},
{
"name": "Groovy",
"bytes": "87440"
},
{
"name": "HTML",
"bytes": "115"
},
{
"name": "Java",
"bytes": "10726244"
},
{
"name": "JavaScript",
"bytes": "10"
},
{
"name": "PLSQL",
"bytes": "3180"
},
{
"name": "Python",
"bytes": "129"
},
{
"name": "Shell",
"bytes": "809"
},
{
"name": "XSLT",
"bytes": "2344"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en" itemscope itemtype="http://schema.org/WebPage">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<title>observation - Dripping Data</title>
<meta name="author" content="Mike Ching"/><script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "WebSite",
"name": "Dripping Data",
"url": "\/"
}
</script><script type="application/ld+json">
{
"@context": "http://schema.org",
"@type": "Organization",
"name": "",
"url": "\/"
}
</script>
<meta property="og:title" content="observation" />
<meta property="og:image" content="/img/IMG_6557.jpg" />
<meta property="og:url" content="/tags/observation/" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="Dripping Data" />
<meta name="twitter:title" content="observation" />
<meta name="twitter:image" content="/img/IMG_6557.jpg" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:site" content="@mikec2a" />
<meta name="twitter:creator" content="@mikec2a" />
<link href='../../img/favicon.ico' rel='icon' type='image/x-icon'/>
<meta name="generator" content="Hugo 0.88.1" />
<link rel="alternate" href="../../index.xml" type="application/rss+xml" title="Dripping Data"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.10.0/katex.min.css" integrity="sha384-9eLZqc9ds8eNjO3TmqPeYcDj8n+Qfa4nuSiGYa6DjLNcv9BtN69ZIulL9+8CqC9Y" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"><link rel="stylesheet" href="../../css/main.css" /><link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" /><link rel="stylesheet" href="../../css/syntax.css" /><link rel="stylesheet" href="../../css/codeblock.css" /><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe.min.css" integrity="sha384-h/L2W9KefUClHWaty3SLE5F/qvc4djlyR4qY3NUV5HGQBBW7stbcfff1+I/vmsHh" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/default-skin/default-skin.min.css" integrity="sha384-iD0dNku6PYSIQLyfTOpB06F2KCZJAKLOThS5HRe8b3ibhdEQ6eKsFf/EeFxdOt5R" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-default navbar-fixed-top navbar-custom">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-navbar">
<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="../../">Dripping Data</a>
</div>
<div class="collapse navbar-collapse" id="main-navbar">
<ul class="nav navbar-nav navbar-right">
<li>
<a title="Blog" href="../../">Blog</a>
</li>
<li>
<a title="About" href="../../about/">About</a>
</li>
<li>
<a title="LinkedIn" href="https://www.linkedin.com/in/michael-ching-033a5029">LinkedIn</a>
</li>
<li>
<a title="Twitter" href="https://twitter.com/mikec2a">Twitter</a>
</li>
</ul>
</div>
<div class="avatar-container">
<div class="avatar-img-border">
<a title="Dripping Data" href="../../">
<img class="avatar-img" src="../../img/IMG_6557.jpg" alt="Dripping Data" />
</a>
</div>
</div>
</div>
</nav>
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
<div class="pswp__bg"></div>
<div class="pswp__scroll-wrap">
<div class="pswp__container">
<div class="pswp__item"></div>
<div class="pswp__item"></div>
<div class="pswp__item"></div>
</div>
<div class="pswp__ui pswp__ui--hidden">
<div class="pswp__top-bar">
<div class="pswp__counter"></div>
<button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
<button class="pswp__button pswp__button--share" title="Share"></button>
<button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
<button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
<div class="pswp__preloader">
<div class="pswp__preloader__icn">
<div class="pswp__preloader__cut">
<div class="pswp__preloader__donut"></div>
</div>
</div>
</div>
</div>
<div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
<div class="pswp__share-tooltip"></div>
</div>
<button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
</button>
<button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
</button>
<div class="pswp__caption">
<div class="pswp__caption__center"></div>
</div>
</div>
</div>
</div>
<header class="header-section ">
<div class="intro-header no-img">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="tags-heading">
<h1>observation</h1>
<hr class="small">
</div>
</div>
</div>
</div>
</div>
</header>
<div class="container" role="main">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="posts-list">
<article class="post-preview">
<a href="../../2019/03/15/heeia/">
<h2 class="post-title">Effects of Mangrove Clearance on Water Quality at He'eia Fishpond</h2>
</a>
<p class="post-meta">
<span class="post-meta">
<i class="fas fa-calendar"></i> Posted on March 15, 2019
| <i class="fas fa-user"></i> Mike Ching
</span>
</p>
<div class="post-entry">
My daughter started doing a science project on the ecology of the Heeia fishpond. She collected a bunch of data, but since she’s only a 5th grader, I thought she might need some help with the analysis.
The premise is that the fishpond has been overgrown by invasive mangrove plants. The organization that runs the fishpond has been clearing back the mangroves. This helps to restore the water in the pond.
<a href="../../2019/03/15/heeia/" class="post-read-more">[Read More]</a>
</div>
<div class="blog-tags">
<a href="//tags/observation/">observation</a>
<a href="//tags/ecology/">ecology</a>
</div>
</article>
</div>
</div>
</div>
</div>
<footer>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<ul class="list-inline text-center footer-links">
<li>
<a href="https://github.com/mching" title="GitHub">
<span class="fa-stack fa-lg">
<i class="fas fa-circle fa-stack-2x"></i>
<i class="fab fa-github fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li>
<a href="https://twitter.com/mikec2a" title="Twitter">
<span class="fa-stack fa-lg">
<i class="fas fa-circle fa-stack-2x"></i>
<i class="fab fa-twitter fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li>
<a href="https://linkedin.com/in/michael-ching-033a5029" title="LinkedIn">
<span class="fa-stack fa-lg">
<i class="fas fa-circle fa-stack-2x"></i>
<i class="fab fa-linkedin fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li>
<a href="../../tags/observation/index.xml" title="RSS">
<span class="fa-stack fa-lg">
<i class="fas fa-circle fa-stack-2x"></i>
<i class="fas fa-rss fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
</ul>
<p class="credits copyright text-muted">
Mike Ching
• ©
2021
•
<a href="../../">Dripping Data</a>
</p>
<p class="credits theme-by text-muted">
<a href="https://gohugo.io">Hugo v0.88.1</a> powered • Theme <a href="https://github.com/halogenica/beautifulhugo">Beautiful Hugo</a> adapted from <a href="https://deanattali.com/beautiful-jekyll/">Beautiful Jekyll</a>
</p>
</div>
</div>
</div>
</footer><script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.10.0/katex.min.js" integrity="sha384-K3vbOmF2BtaVai+Qk37uypf7VrgBubhQreNQe9aGsz9lB63dIFiQVlJbr92dw2Lx" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.10.0/contrib/auto-render.min.js" integrity="sha384-kmZOZB5ObwgQnS/DuDg6TScgOiWWBiVt0plIRkZCmE6rDZGrEOQeHM5PcHi+nyqe" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script src="../../js/main.js"></script><script> renderMathInElement(document.body); </script><script src="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe.min.js" integrity="sha384-QELNnmcmU8IR9ZAykt67vGr9/rZJdHbiWi64V88fCPaOohUlHCqUD/unNN0BXSqy" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe-ui-default.min.js" integrity="sha384-m67o7SkQ1ALzKZIFh4CiTA8tmadaujiTa9Vu+nqPSwDOqHrDmxLezTdFln8077+q" crossorigin="anonymous"></script><script src="../../js/load-photoswipe.js"></script>
</body>
</html>
| {
"content_hash": "761f245b49f3595355f33854f68a53ca",
"timestamp": "",
"source": "github",
"line_count": 344,
"max_line_length": 476,
"avg_line_length": 33.526162790697676,
"alnum_prop": 0.5795543223792595,
"repo_name": "mching/mching.github.io",
"id": "232af577298f421fabc68c03411d40eda28a538d",
"size": "11535",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tags/observation/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "166406"
},
{
"name": "HTML",
"bytes": "2756923"
},
{
"name": "JavaScript",
"bytes": "31473"
}
],
"symlink_target": ""
} |
using System;
using System.Data;
namespace MyMeta.VistaDB3x
{
#if ENTERPRISE
using System.Runtime.InteropServices;
[ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual), ComDefaultInterface(typeof(IParameters))]
#endif
public class VistaDBParameters : Parameters
{
public VistaDBParameters()
{
}
override internal void LoadAll()
{
try
{
// DataTable metaData = this.LoadData(OleDbSchemaGuid.Procedure_Parameters, new object[]{null, null, this.Procedure.Name});
//
// PopulateArray(metaData);
//
// LoadExtraData();
}
catch {}
}
// private void LoadExtraData()
// {
// try
// {
// string select = "SELECT PARMNAME, TYPENAME, CODEPAGE FROM SYSCAT.PROCPARMS WHERE PROCNAME = '" + this.Procedure.Name + "' ORDER BY ORDINAL";
//
// OleDbDataAdapter adapter = new OleDbDataAdapter(select, this.dbRoot.ConnectionString);
// DataTable dataTable = new DataTable();
//
// adapter.Fill(dataTable);
//
// if(this._array.Count > 0)
// {
// DataRowCollection rows = dataTable.Rows;
// string paramName = "";
//
// int count = this._array.Count;
// Parameter p = null;
//
// foreach(DataRow row in rows)
// {
// paramName = row["PARMNAME"] as string;
// p = this[paramName] as Parameter;
//
// p._row["TYPE_NAME"] = (row["TYPENAME"] as string).Trim();
//
// int codepage = -1;
// try
// {
// codepage = (short)row["CODEPAGE"];
// }
// catch{}
//
// if(codepage == 0)
// {
// // Check for "bit data"
// switch(p.TypeName)
// {
// case "CHARACTER":
// case "VARCHAR":
// case "LONG VARCHAR":
//
// p._row["TYPE_NAME"] = p.TypeName + " FOR BIT DATA";
// break;
// }
// }
// }
// }
// }
// catch {}
// }
}
}
| {
"content_hash": "bace2bfd1ea4fc1e50c311dfbc6e1967",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 146,
"avg_line_length": 22.23170731707317,
"alnum_prop": 0.5765222161272627,
"repo_name": "cafephin/mygeneration",
"id": "b31facec6ae7f0617734d8a360add907894f96e3",
"size": "1823",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/mymeta/VistaDB3x/Parameters.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "4036"
},
{
"name": "C",
"bytes": "38730"
},
{
"name": "C#",
"bytes": "5939427"
},
{
"name": "Common Lisp",
"bytes": "3251"
},
{
"name": "JavaScript",
"bytes": "6202"
},
{
"name": "NSIS",
"bytes": "85526"
},
{
"name": "PLpgSQL",
"bytes": "21332"
},
{
"name": "Perl",
"bytes": "320"
},
{
"name": "Python",
"bytes": "456"
},
{
"name": "Shell",
"bytes": "638"
},
{
"name": "Smalltalk",
"bytes": "24466"
},
{
"name": "Tcl",
"bytes": "2761"
},
{
"name": "Visual Basic",
"bytes": "1266111"
},
{
"name": "XSLT",
"bytes": "26803"
}
],
"symlink_target": ""
} |




Intercepts uploads to WebGL buffers in order to keep track of their expected
value on the GPU.
Designed solely with the intention of testing packages that interact with
WebGL buffers. It's probably not something you should be using in an actual
app/demo, so approach with caution.
## Usage
[](https://nodei.co/npm/gl-buffer-snoop/)
### `snoop(gl)`
Before using your WebGL context at all, you should let `gl-buffer-snoop` do
its thing by passing it the context in question:
``` javascript
var canvas = document.createElement('canvas')
var gl = canvas.getContext('webgl')
require('gl-buffer-snoop')(gl)
```
This will override a few of the context's methods to keep track of outgoing
data, along with providing a new method for you to use to retrieve a buffer's
data:
### `gl.getBufferData(buffer)`
Given an instance of a `WebGLBuffer`, returns our local copy of the data it
should have stored on the GPU. This is returned as a `Uint8Array`, but you
can easily convert it to other types too thanks to the magic of typed arrays.
For example:
``` javascript
var buffer = gl.createBuffer()
// ...
var rawData = gl.getBufferData(buffer)
var floatData = new Float32Array(rawData.buffer)
```
If you're using this with [gl-buffer](http://github.com/stackgl/gl-buffer),
you can just use the `handle` property to access the underlying buffer instance:
``` javascript
var buffer = require('gl-buffer')(gl, [1, 2, 3])
var rawData = gl.getBufferData(buffer.handle)
var floatData = new Float32Array(rawData.buffer)
console.log(floatData) // [1, 2, 3]
```
## License
MIT. See [LICENSE.md](http://github.com/stackgl/gl-buffer-snoop/blob/master/LICENSE.md)
for details.
| {
"content_hash": "621f7e05bb730325814f3e06912592b7",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 89,
"avg_line_length": 32.57377049180328,
"alnum_prop": 0.7413185707096125,
"repo_name": "stackgl/gl-buffer-snoop",
"id": "17be4a380ffda71623b34852944d7eca8f218bb3",
"size": "2005",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "4764"
}
],
"symlink_target": ""
} |
package org.sfm.map.mapper;
import org.sfm.map.FieldKey;
import org.sfm.map.MappingContext;
import org.sfm.map.MappingException;
import org.sfm.map.SetRowMapper;
import org.sfm.utils.ErrorHelper;
import org.sfm.utils.UnaryFactory;
import org.sfm.utils.RowHandler;
import org.sfm.utils.UnaryFactoryWithException;
import java.util.Iterator;
//IFJAVA8_START
import java.util.stream.Stream;
//IFJAVA8_END
public class DynamicSetRowMapper<R, S, T, E extends Exception, K extends FieldKey<K>> implements SetRowMapper<R, S, T, E> {
private final MapperCache<K, SetRowMapper<R, S, T, E>> mapperCache = new MapperCache<K, SetRowMapper<R, S, T, E>>();
private final UnaryFactory<MapperKey<K>, SetRowMapper<R, S, T, E>> mapperFactory;
private final UnaryFactoryWithException<R, MapperKey<K>, E> mapperKeyFromRow;
private final UnaryFactoryWithException<S, MapperKey<K>, E> mapperKeyFromSet;
public DynamicSetRowMapper(
UnaryFactory<MapperKey<K>, SetRowMapper<R, S, T, E>> mapperFactory,
UnaryFactoryWithException<R, MapperKey<K>, E> mapperKeyFromRow,
UnaryFactoryWithException<S, MapperKey<K>, E> mapperKeyFromSet) {
this.mapperFactory = mapperFactory;
this.mapperKeyFromRow = mapperKeyFromRow;
this.mapperKeyFromSet = mapperKeyFromSet;
}
@Override
public final T map(R row) throws MappingException {
try {
return getMapperFromRow(row).map(row);
} catch(Exception e) {
ErrorHelper.rethrow(e);
return null;
}
}
@Override
public final T map(R row, MappingContext<? super R> context) throws MappingException {
try {
return getMapperFromRow(row).map(row, context);
} catch(Exception e) {
ErrorHelper.rethrow(e);
return null;
}
}
@Override
public final void mapTo(R row, T target, MappingContext<? super R> context) throws Exception {
getMapperFromRow(row).mapTo(row, target, context);
}
@Override
public final Iterator<T> iterator(S rs) throws E, MappingException {
return getMapperFromSet(rs).iterator(rs);
}
//IFJAVA8_START
@Override
public final Stream<T> stream(S set) throws E, MappingException {
return getMapperFromSet(set).stream(set);
}
//IFJAVA8_END
@Override
public final <H extends RowHandler<? super T>> H forEach(S set, H handler) throws E, MappingException {
return getMapperFromSet(set).forEach(set, handler);
}
@Override
public final MappingContext<? super R> newMappingContext(R set) throws E {
return getMapperFromRow(set).newMappingContext(set);
}
@Override
public String toString() {
return "DynamicMapper{mapperFactory=" + mapperFactory
+ ", " + mapperCache +
'}';
}
private SetRowMapper<R, S, T, E> getMapperFromSet(S set) throws E {
return getMapper(mapperKeyFromSet.newInstance(set));
}
private SetRowMapper<R, S, T, E> getMapperFromRow(R row) throws E {
return getMapper(mapperKeyFromRow.newInstance(row));
}
public SetRowMapper<R, S, T, E> getMapper(MapperKey<K> key) throws E {
SetRowMapper<R, S, T, E> mapper = mapperCache.get(key);
if (mapper == null) {
mapper = mapperFactory.newInstance(key);
mapperCache.add(key, mapper);
}
return mapper;
}
}
| {
"content_hash": "61b591e0fc18c75529d314640a19c72a",
"timestamp": "",
"source": "github",
"line_count": 109,
"max_line_length": 123,
"avg_line_length": 28.513761467889907,
"alnum_prop": 0.7348777348777349,
"repo_name": "tsdl2013/SimpleFlatMapper",
"id": "3c872cd40cd1749161053d47bc6812ae8c06293d",
"size": "3108",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sfm/src/main/java/org/sfm/map/mapper/DynamicSetRowMapper.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1780759"
},
{
"name": "Shell",
"bytes": "1430"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Sporodum stemonitideum De Not.
### Remarks
null | {
"content_hash": "c29f28f1d67b07b7ef53a20aa15cd8dd",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 30,
"avg_line_length": 10.384615384615385,
"alnum_prop": 0.7111111111111111,
"repo_name": "mdoering/backbone",
"id": "13284145abac24eb205190125992645971823641",
"size": "189",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Dothideomycetes/Pleosporales/Sporodum/Sporodum stemonitideum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
/** section: Ajax
* Ajax.Responders
* includes Enumerable
*
* A repository of global listeners notified about every step of
* Prototype-based Ajax requests.
*
* Sometimes, you need to provide generic behaviors over all Ajax operations
* happening on the page (through [[Ajax.Request]], [[Ajax.Updater]] or
* [[Ajax.PeriodicalUpdater]]).
*
* For instance, you might want to automatically show an indicator when an
* Ajax request is ongoing, and hide it when none are. You may well want to
* factor out exception handling as well, logging those somewhere on the page
* in a custom fashion. The possibilities are myriad.
*
* To achieve this, Prototype provides `Ajax.Responders`, which lets you
* register (and, if you wish, unregister later) _responders_, which are
* objects with specially-named methods. These names come from a set of
* general callbacks corresponding to different points in time (or outcomes)
* of an Ajax request's life cycle.
*
* For instance, Prototype automatically registers a responder that maintains
* a nifty variable: [[Ajax.activeRequestCount]]. This represents, at a given
* time, the number of currently active Ajax requests — by monitoring their
* `onCreate` and `onComplete` events. The code for this is fairly simple:
*
* Ajax.Responders.register({
* onCreate: function() {
* Ajax.activeRequestCount++;
* },
* onComplete: function() {
* Ajax.activeRequestCount--;
* }
* });
*
* ##### Responder callbacks
*
* The callbacks for responders are similar to the callbacks described in
* the [[Ajax section]], but take a different signature. They're invoked with
* three parameters: the requester object (i.e., the corresponding "instance"
* of [[Ajax.Request]]), the `XMLHttpRequest` object, and the result of
* evaluating the `X-JSON` response header, if any (can be `null`). They also
* execute in the context of the responder, bound to the `this` reference.
*
* * `onCreate`: Triggered whenever a requester object from the `Ajax`
* namespace is created, after its parameters are adjusted and before its
* XHR connection is opened. This takes *two* arguments: the requester
* object and the underlying XHR object.
* * `onUninitialized` (*Not guaranteed*): Invoked just after the XHR object
* is created.
* * `onLoading` (*Not guaranteed*): Triggered when the underlying XHR object
* is being setup, and its connection opened.
* * `onLoaded` (*Not guaranteed*): Triggered once the underlying XHR object
* is setup, the connection is open, and it is ready to send its actual
* request.
* * `onInteractive` (*Not guaranteed*): Triggered whenever the requester
* receives a part of the response (but not the final part), should it
* be sent in several packets.
* * `onException`: Triggered whenever an XHR error arises. Has a custom
* signature: the first argument is the requester (i.e. an [[Ajax.Request]]
* instance), and the second is the exception object.
* * `onComplete`: Triggered at the _very end_ of a request's life-cycle, after
* the request completes, status-specific callbacks are called, and possible
* automatic behaviors are processed. Guaranteed to run regardless of what
* happened during the request.
**/
Ajax.Responders = {
responders: [],
_each: function(iterator, context) {
this.responders._each(iterator, context);
},
/**
* Ajax.Responders.register(responder) -> undefined
* - responder (Object): A list of functions with keys corresponding to the
* names of possible callbacks.
*
* Add a group of responders to all Ajax requests.
**/
register: function(responder) {
if (!this.include(responder))
this.responders.push(responder);
},
/**
* Ajax.Responders.unregister(responder) -> undefined
* - responder (Object): A list of functions with keys corresponding to the
* names of possible callbacks.
*
* Remove a previously-added group of responders.
*
* As always, unregistering something requires you to use the very same
* object you used at registration. If you plan to use `unregister`, be sure
* to assign your responder to a _variable_ before passing it into
* [[Ajax.Responders#register]] — don't pass it an object literal.
**/
unregister: function(responder) {
this.responders = this.responders.without(responder);
},
dispatch: function(callback, request, transport, json) {
this.each(function(responder) {
if (Object.isFunction(responder[callback])) {
try {
responder[callback].apply(responder, [request, transport, json]);
} catch (e) { }
}
});
}
};
Object.extend(Ajax.Responders, Enumerable);
Ajax.Responders.register({
onCreate: function() { Ajax.activeRequestCount++ },
onComplete: function() { Ajax.activeRequestCount-- }
});
| {
"content_hash": "9d661871730ccd4b1f2ff5e717ae6caa",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 82,
"avg_line_length": 41.333333333333336,
"alnum_prop": 0.6923387096774194,
"repo_name": "daejunpark/jsaf",
"id": "0f5611e37cd2a114f9b43605ac64b31b6e157b45",
"size": "4960",
"binary": false,
"copies": "22",
"ref": "refs/heads/master",
"path": "tests/clone_detector_tests/prototype/src/prototype/ajax/responders.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "379"
},
{
"name": "C",
"bytes": "59067"
},
{
"name": "C++",
"bytes": "13294"
},
{
"name": "CSS",
"bytes": "9351891"
},
{
"name": "Emacs Lisp",
"bytes": "9812"
},
{
"name": "HTML",
"bytes": "19106074"
},
{
"name": "Jasmin",
"bytes": "46"
},
{
"name": "Java",
"bytes": "375421"
},
{
"name": "JavaScript",
"bytes": "51177272"
},
{
"name": "Makefile",
"bytes": "3558"
},
{
"name": "Objective-C",
"bytes": "345276"
},
{
"name": "Objective-J",
"bytes": "4500028"
},
{
"name": "PHP",
"bytes": "12684"
},
{
"name": "Perl",
"bytes": "5278"
},
{
"name": "Python",
"bytes": "75059"
},
{
"name": "Ruby",
"bytes": "22932"
},
{
"name": "Scala",
"bytes": "5542753"
},
{
"name": "Shell",
"bytes": "91018"
},
{
"name": "VimL",
"bytes": "6985"
},
{
"name": "XML",
"bytes": "1288109"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "c6b374d30c77f66c7a70a11d7326d41e",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "6ee20aac85ed820fcf9f533ff6b9be45f0f8580d",
"size": "181",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Dryopteridaceae/Polystichum/Polystichum nigrospinosum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
'use strict';
// Put simple "helper" functions here for DRY and to keep code clean.
// use e.g.
// var toconcsole =require(Config.libDirectory + 'helpers').toconsole;
module.exports = {
// sends your file stream to the console. Good for debugging file streams
toconsole: function(chunk){
var contents = chunk.contents.toString().trim();
var bufLength = process.stdout.columns;
var hr = '\n\n' + Array(bufLength).join("_") + '\n\n'
if (contents.length > 1) {
process.stdout.write(chunk.path + '\n' + contents + '\n');
process.stdout.write(chunk.path + hr);
}
}
}
| {
"content_hash": "34454be1c76b0b001a60705f6565c194",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 76,
"avg_line_length": 30.476190476190474,
"alnum_prop": 0.6109375,
"repo_name": "dkebler/hugo-sass-bower-gulp-starter",
"id": "442148d5ab3a7f855057739df444c1c86885a77a",
"size": "640",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "lib/helpers.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "27618"
},
{
"name": "HTML",
"bytes": "11792"
},
{
"name": "JavaScript",
"bytes": "24115"
}
],
"symlink_target": ""
} |
module Pling
##
# This module adds support for Google's Cloud to Device Messaging (C2DM) to pling.
# Please refer to {Pling::C2DM::Gateway} for documentation.
#
# @see Pling::C2DM::Gateway
module C2DM
autoload :Gateway, 'pling/c2dm/gateway'
class QuotaExceeded < Pling::DeliveryFailed; end
class DeviceQuotaExceeded < Pling::DeliveryFailed; end
class InvalidRegistration < Pling::DeliveryFailed; end
class NotRegistered < Pling::DeliveryFailed; end
class MessageTooBig < Pling::DeliveryFailed; end
class MissingCollapseKey < Pling::DeliveryFailed; end
end
end | {
"content_hash": "bd623493bf0472ba2f7190efe4e2ca71",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 84,
"avg_line_length": 36.529411764705884,
"alnum_prop": 0.7133655394524959,
"repo_name": "mrnugget/pling",
"id": "dda12233871eab0a6379cba579d5d4e531bd8953",
"size": "621",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/pling/c2dm.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "72423"
}
],
"symlink_target": ""
} |
package io.cattle.platform.token.impl;
import io.cattle.platform.archaius.util.ArchaiusUtil;
import io.cattle.platform.token.TokenDecryptionException;
import io.cattle.platform.token.TokenException;
import io.cattle.platform.token.TokenService;
import java.security.interfaces.RSAPublicKey;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import org.apache.commons.lang.StringUtils;
import com.netflix.config.DynamicLongProperty;
import com.netflix.config.DynamicStringProperty;
import com.nimbusds.jose.EncryptionMethod;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JOSEObject;
import com.nimbusds.jose.JWEAlgorithm;
import com.nimbusds.jose.JWEHeader;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSObject;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.crypto.RSADecrypter;
import com.nimbusds.jose.crypto.RSAEncrypter;
import com.nimbusds.jose.crypto.RSASSASigner;
import com.nimbusds.jose.crypto.RSASSAVerifier;
import com.nimbusds.jwt.EncryptedJWT;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
public class JwtTokenServiceImpl implements TokenService {
private static final String KEY_ID = "kid";
private static final DynamicStringProperty SUBJECT = ArchaiusUtil.getString("jwt.default.subject");
private static final DynamicStringProperty ISSUER = ArchaiusUtil.getString("jwt.default.issuer");
private static final DynamicLongProperty EXPIRATION = ArchaiusUtil.getLong("jwt.default.expiration.seconds");
RSAKeyProvider keyProvider;
@Override
public String generateToken(Map<String, Object> payload) {
return generateToken(payload, new Date(), new Date(System.currentTimeMillis() + EXPIRATION.get() * 1000), false);
}
@Override
public String generateToken(Map<String, Object> payload, Date expireDate) {
return generateToken(payload, new Date(), expireDate, false);
}
@Override
public String generateEncryptedToken(Map<String, Object> payload) {
return generateToken(payload, new Date(), new Date(System.currentTimeMillis() + EXPIRATION.get() * 1000), true);
}
@Override
public String generateEncryptedToken(Map<String, Object> payload, Date expireDate) {
return generateToken(payload, new Date(), expireDate, true);
}
protected String generateToken(Map<String, Object> payload, Date issueTime, Date expireDate, boolean encrypted) {
// Prepare JWT with claims set
JWTClaimsSet claimsSet = new JWTClaimsSet();
Map<String, Object> customClaims = new HashMap<>();
if (payload != null) {
customClaims.putAll(payload);
}
if (expireDate != null) {
claimsSet.setExpirationTime(expireDate);
}
claimsSet.setCustomClaims(customClaims);
claimsSet.setSubject(SUBJECT.get());
claimsSet.setIssueTime(issueTime);
claimsSet.setIssuer(ISSUER.get());
if (!encrypted) {
RSAPrivateKeyHolder privateKey = keyProvider.getPrivateKey();
customClaims.put(KEY_ID, privateKey.getKeyId());
// Create RSA-signer with the private key
JWSSigner signer = new RSASSASigner(privateKey.getKey());
SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet);
// Compute the RSA signature
try {
signedJWT.sign(signer);
} catch (JOSEException e) {
throw new RuntimeException("Failed to generate token", e);
}
return signedJWT.serialize();
}
JWEHeader header = new JWEHeader(JWEAlgorithm.RSA_OAEP, EncryptionMethod.A128GCM);
EncryptedJWT jwt = new EncryptedJWT(header, claimsSet);
RSAEncrypter encrypter = new RSAEncrypter((RSAPublicKey) keyProvider.getDefaultPublicKey());
try {
jwt.encrypt(encrypter);
} catch (JOSEException e) {
throw new RuntimeException("Failed to generate encrypted token", e);
}
return jwt.serialize();
}
public RSAKeyProvider getKeyProvider() {
return keyProvider;
}
@Override
public Map<String, Object> getJsonPayload(String token, boolean encrypted) throws TokenException {
if (StringUtils.isEmpty(token)) {
throw new TokenException("null or empty token");
}
if (encrypted) {
EncryptedJWT jwt = null;
try {
jwt = EncryptedJWT.parse(token);
RSADecrypter decrypter = new RSADecrypter(keyProvider.getPrivateKey().getKey());
jwt.decrypt(decrypter);
} catch (JOSEException | ParseException e) {
throw new TokenDecryptionException("Invalid token", e);
}
return getJSONObject(jwt, encrypted);
}
try {
JWSObject jws = JWSObject.parse(token);
JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) keyProvider.getDefaultPublicKey());
if (!jws.verify(verifier)) {
throw new TokenException("ERROR: Fradulent token");
}
return getJSONObject(jws, encrypted);
} catch (TokenException | ParseException | JOSEException e) {
throw new TokenException("Error: Fradulent token, unrecognized signature", e);
}
}
private Map<String, Object> getJSONObject(JOSEObject jose, boolean encrypted) throws TokenException {
Long exp = (Long) jose.getPayload().toJSONObject().get("exp");
if (exp != null && exp * 1000 <= System.currentTimeMillis()) {
throw new TokenException("Expired Token");
}
return jose.getPayload().toJSONObject();
}
@Inject
public void setKeyProvider(RSAKeyProvider keyProvider) {
this.keyProvider = keyProvider;
}
} | {
"content_hash": "f5647fd6fdd480fb257f28b0acb47588",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 121,
"avg_line_length": 37.12883435582822,
"alnum_prop": 0.6802709847984137,
"repo_name": "alena1108/cattle",
"id": "8fd0be2964aad890e2be982154d2e8bf564ed367",
"size": "6052",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "code/framework/token/src/main/java/io/cattle/platform/token/impl/JwtTokenServiceImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "3287143"
},
{
"name": "Makefile",
"bytes": "6771"
},
{
"name": "Python",
"bytes": "193716"
},
{
"name": "Shell",
"bytes": "54068"
}
],
"symlink_target": ""
} |
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
steamid: { type: String, index: true, unique: true },
steamid32: { type: Number },
_json: Object,
matches: [{type: String, ref: '' }]
});
userSchema.statics.updateUser = function (profile, cb) {
if (!profile || profile == null || !profile.steamid) { return; }
//console.log("Adding: " + profile.steamid);
var newProf = new this(profile);
var prof = this.findOne({ steamid: profile.steamid });
//console.log(prof.count());
prof.exec(function (err, response) {
if (err) { console.log(err); return (err); }
if (response != null) {
/*
this.update(prof, { personaname: profile.personaname }, function (err, response) {
if (err) { return next(err); }
console.log("profile updated");
})
*/
response._json = profile._json;
response.save(function (err) {
if (err) { return err; }
console.log("profile updated: " + profile.steamid);
});
}
else {
newProf.save(cb, function (err) {
if (err) { return next(err); }
console.log("profile created");
})
}
});
/*
newProf.save(cb, function (err) {
if (err) { return next(err); }
console.log("profile created");
})
*/
return prof;
}
mongoose.model('User', userSchema); | {
"content_hash": "914d958dc27ae640666aa423dedd234c",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 94,
"avg_line_length": 31.333333333333332,
"alnum_prop": 0.5186170212765957,
"repo_name": "nicholasmf/nodesteam",
"id": "e9b6f42b1605870adef5f50b114ce57a6dad84a9",
"size": "1504",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "models/userModel.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "326"
},
{
"name": "HTML",
"bytes": "6355"
},
{
"name": "JavaScript",
"bytes": "28899"
}
],
"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.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeGeneration
Imports Microsoft.CodeAnalysis.Host
Imports Microsoft.CodeAnalysis.LanguageServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration
Friend Class VisualBasicCodeGenerationService
Inherits AbstractCodeGenerationService
Public Sub New(provider As HostLanguageServices)
MyBase.New(provider.GetService(Of ISymbolDeclarationService)(),
provider.WorkspaceServices.Workspace)
End Sub
Public Overloads Overrides Function GetDestination(containerNode As SyntaxNode) As CodeGenerationDestination
Return VisualBasicCodeGenerationHelpers.GetDestination(containerNode)
End Function
Protected Overrides Function GetMemberComparer() As IComparer(Of SyntaxNode)
Return VisualBasicDeclarationComparer.WithoutNamesInstance
End Function
Protected Overrides Function GetAvailableInsertionIndices(destination As SyntaxNode, cancellationToken As CancellationToken) As IList(Of Boolean)
' NOTE(cyrusn): We know that the destination overlaps some hidden regions.
If TypeOf destination Is TypeBlockSyntax Then
Return DirectCast(destination, TypeBlockSyntax).GetInsertionIndices(cancellationToken)
End If
If TypeOf destination Is CompilationUnitSyntax Then
Return GetAvailableInsertionIndices(DirectCast(destination, CompilationUnitSyntax), cancellationToken)
End If
' TODO(cyrusn): This will exclude all non-type-blocks if they overlap a hidden region.
' For example, for enums or namespaces. We could consider relaxing that and actually
' attempting to determine where in the destination are viable, if we think it's worth
' it.
Return Nothing
End Function
Private Overloads Function GetAvailableInsertionIndices(destination As CompilationUnitSyntax, cancellationToken As CancellationToken) As IList(Of Boolean)
Dim members = destination.Members
Dim indices = New List(Of Boolean)
If members.Count >= 1 Then
' First, see if we can insert between the start of the typeblock, and it's first
' member.
indices.Add(Not destination.OverlapsHiddenPosition(TextSpan.FromBounds(0, destination.Members.First.SpanStart), cancellationToken))
' Now, walk between each member and see if something can be inserted between it and
' the next member
For i = 0 To members.Count - 2
Dim member1 = members(i)
Dim member2 = members(i + 1)
indices.Add(Not destination.OverlapsHiddenPosition(member1, member2, cancellationToken))
Next
' Last, see if we can insert between the last member and the end of the typeblock
indices.Add(Not destination.OverlapsHiddenPosition(
TextSpan.FromBounds(destination.Members.Last.Span.End, destination.EndOfFileToken.SpanStart), cancellationToken))
End If
Return indices
End Function
Protected Overrides Function AddEvent(Of TDeclarationNode As SyntaxNode)(
destinationType As TDeclarationNode,
[event] As IEventSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TDeclarationNode
CheckDeclarationNode(Of TypeBlockSyntax)(destinationType)
Return Cast(Of TDeclarationNode)(AddEventTo(Cast(Of TypeBlockSyntax)(destinationType), [event], options, availableIndices))
End Function
Protected Overrides Function AddField(Of TDeclarationNode As SyntaxNode)(
destinationType As TDeclarationNode,
field As IFieldSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TDeclarationNode
CheckDeclarationNode(Of EnumBlockSyntax, TypeBlockSyntax, CompilationUnitSyntax)(destinationType)
If TypeOf destinationType Is EnumBlockSyntax Then
Return Cast(Of TDeclarationNode)(EnumMemberGenerator.AddEnumMemberTo(Cast(Of EnumBlockSyntax)(destinationType), field, options))
ElseIf TypeOf destinationType Is TypeBlockSyntax Then
Return Cast(Of TDeclarationNode)(FieldGenerator.AddFieldTo(Cast(Of TypeBlockSyntax)(destinationType), field, options, availableIndices))
Else
Return Cast(Of TDeclarationNode)(FieldGenerator.AddFieldTo(Cast(Of CompilationUnitSyntax)(destinationType), field, options, availableIndices))
End If
End Function
Protected Overrides Function AddProperty(Of TDeclarationNode As SyntaxNode)(
destinationType As TDeclarationNode,
[property] As IPropertySymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TDeclarationNode
CheckDeclarationNode(Of TypeBlockSyntax, CompilationUnitSyntax)(destinationType)
If TypeOf destinationType Is TypeBlockSyntax Then
Return Cast(Of TDeclarationNode)(PropertyGenerator.AddPropertyTo(Cast(Of TypeBlockSyntax)(destinationType), [property], options, availableIndices))
Else
Return Cast(Of TDeclarationNode)(PropertyGenerator.AddPropertyTo(Cast(Of CompilationUnitSyntax)(destinationType), [property], options, availableIndices))
End If
End Function
Protected Overrides Function AddMethod(Of TDeclarationNode As SyntaxNode)(
destination As TDeclarationNode,
method As IMethodSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean)) As TDeclarationNode
CheckDeclarationNode(Of TypeBlockSyntax, CompilationUnitSyntax, NamespaceBlockSyntax)(destination)
' Synthesized methods for properties/events are not things we actually generate
' declarations for.
If method.AssociatedSymbol IsNot Nothing Then
Return destination
End If
Dim typeDeclaration As TypeBlockSyntax = TryCast(destination, TypeBlockSyntax)
If typeDeclaration IsNot Nothing Then
If method.IsConstructor() Then
Return Cast(Of TDeclarationNode)(ConstructorGenerator.AddConstructorTo(typeDeclaration, method, options, availableIndices))
End If
If method.MethodKind = MethodKind.UserDefinedOperator Then
Return Cast(Of TDeclarationNode)(OperatorGenerator.AddOperatorTo(typeDeclaration, method, options, availableIndices))
End If
If method.MethodKind = MethodKind.Conversion Then
Return Cast(Of TDeclarationNode)(ConversionGenerator.AddConversionTo(typeDeclaration, method, options, availableIndices))
End If
Return Cast(Of TDeclarationNode)(MethodGenerator.AddMethodTo(typeDeclaration, method, options, availableIndices))
End If
If method.IsConstructor() Then
Return destination
End If
Dim compilationUnit = TryCast(destination, CompilationUnitSyntax)
If compilationUnit IsNot Nothing Then
Return Cast(Of TDeclarationNode)(MethodGenerator.AddMethodTo(compilationUnit, method, options, availableIndices))
End If
Dim ns = Cast(Of NamespaceBlockSyntax)(destination)
Return Cast(Of TDeclarationNode)(MethodGenerator.AddMethodTo(ns, method, options, availableIndices))
End Function
Protected Overloads Overrides Function AddNamedType(Of TDeclarationNode As SyntaxNode)(
destination As TDeclarationNode,
namedType As INamedTypeSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean),
cancellationToken As CancellationToken) As TDeclarationNode
CheckDeclarationNode(Of TypeBlockSyntax, NamespaceBlockSyntax, CompilationUnitSyntax)(destination)
options = If(options, CodeGenerationOptions.Default)
If TypeOf destination Is TypeBlockSyntax Then
Return Cast(Of TDeclarationNode)(NamedTypeGenerator.AddNamedTypeTo(Me, Cast(Of TypeBlockSyntax)(destination), namedType, options, availableIndices, cancellationToken))
ElseIf TypeOf destination Is NamespaceBlockSyntax Then
Return Cast(Of TDeclarationNode)(NamedTypeGenerator.AddNamedTypeTo(Me, Cast(Of NamespaceBlockSyntax)(destination), namedType, options, availableIndices, cancellationToken))
Else
Return Cast(Of TDeclarationNode)(NamedTypeGenerator.AddNamedTypeTo(Me, Cast(Of CompilationUnitSyntax)(destination), namedType, options, availableIndices, cancellationToken))
End If
End Function
Protected Overrides Function AddNamespace(Of TDeclarationNode As SyntaxNode)(
destination As TDeclarationNode,
[namespace] As INamespaceSymbol,
options As CodeGenerationOptions,
availableIndices As IList(Of Boolean),
cancellationToken As CancellationToken) As TDeclarationNode
CheckDeclarationNode(Of CompilationUnitSyntax, NamespaceBlockSyntax)(destination)
If TypeOf destination Is CompilationUnitSyntax Then
Return Cast(Of TDeclarationNode)(NamespaceGenerator.AddNamespaceTo(Me, Cast(Of CompilationUnitSyntax)(destination), [namespace], options, availableIndices, cancellationToken))
Else
Return Cast(Of TDeclarationNode)(NamespaceGenerator.AddNamespaceTo(Me, Cast(Of NamespaceBlockSyntax)(destination), [namespace], options, availableIndices, cancellationToken))
End If
End Function
Public Overrides Function AddParameters(Of TDeclarationNode As SyntaxNode)(
destinationMember As TDeclarationNode,
parameters As IEnumerable(Of IParameterSymbol),
options As CodeGenerationOptions,
cancellationToken As CancellationToken) As TDeclarationNode
Dim methodBlock = TryCast(destinationMember, MethodBlockBaseSyntax)
Dim methodStatement = If(methodBlock IsNot Nothing,
methodBlock.BlockStatement,
TryCast(destinationMember, MethodBaseSyntax))
If methodStatement IsNot Nothing Then
Select Case methodStatement.Kind
Case SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement
' Don't allow adding parameters to Property Getter/Setter
Return destinationMember
Case Else
Return AddParametersToMethod(Of TDeclarationNode)(methodStatement, methodBlock, parameters, options)
End Select
Else
Dim propertyBlock = TryCast(destinationMember, PropertyBlockSyntax)
If propertyBlock IsNot Nothing Then
Return AddParametersToProperty(Of TDeclarationNode)(propertyBlock, parameters, options)
End If
End If
Return destinationMember
End Function
Protected Overrides Function AddMembers(Of TDeclarationNode As SyntaxNode)(destination As TDeclarationNode, members As IEnumerable(Of SyntaxNode)) As TDeclarationNode
CheckDeclarationNode(Of EnumBlockSyntax, TypeBlockSyntax, NamespaceBlockSyntax, CompilationUnitSyntax)(destination)
If TypeOf destination Is EnumBlockSyntax Then
Return Cast(Of TDeclarationNode)(Cast(Of EnumBlockSyntax)(destination).AddMembers(members.Cast(Of EnumMemberDeclarationSyntax).ToArray()))
ElseIf TypeOf destination Is TypeBlockSyntax Then
Return Cast(Of TDeclarationNode)(Cast(Of TypeBlockSyntax)(destination).AddMembers(members.Cast(Of StatementSyntax).ToArray()))
ElseIf TypeOf destination Is NamespaceBlockSyntax Then
Return Cast(Of TDeclarationNode)(Cast(Of NamespaceBlockSyntax)(destination).AddMembers(members.Cast(Of StatementSyntax).ToArray()))
Else
Return Cast(Of TDeclarationNode)(Cast(Of CompilationUnitSyntax)(destination).AddMembers(members.Cast(Of StatementSyntax).ToArray()))
End If
End Function
Private Overloads Shared Function AddParametersToMethod(Of TDeclarationNode As SyntaxNode)(methodStatement As MethodBaseSyntax,
methodBlock As MethodBlockBaseSyntax,
parameters As IEnumerable(Of IParameterSymbol),
options As CodeGenerationOptions) As TDeclarationNode
Dim newParameterList = AddParameters(methodStatement.ParameterList, parameters, options)
Dim finalStatement = methodStatement.WithParameterList(newParameterList)
Dim result As Object
If methodBlock IsNot Nothing Then
Select Case methodBlock.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock
result = DirectCast(methodBlock, MethodBlockSyntax).WithBlockStatement(DirectCast(finalStatement, MethodStatementSyntax))
Case SyntaxKind.ConstructorBlock
result = DirectCast(methodBlock, ConstructorBlockSyntax).WithBlockStatement(DirectCast(finalStatement, SubNewStatementSyntax))
Case SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
result = DirectCast(methodBlock, AccessorBlockSyntax).WithBlockStatement(DirectCast(finalStatement, AccessorStatementSyntax))
Case Else
result = DirectCast(methodBlock, OperatorBlockSyntax).WithBlockStatement(DirectCast(finalStatement, OperatorStatementSyntax))
End Select
Else
result = finalStatement
End If
Return DirectCast(DirectCast(result, Object), TDeclarationNode)
End Function
Private Overloads Shared Function AddParametersToProperty(Of TDeclarationNode As SyntaxNode)(
propertyBlock As PropertyBlockSyntax,
parameters As IEnumerable(Of IParameterSymbol),
options As CodeGenerationOptions) As TDeclarationNode
Dim propertyStatement = propertyBlock.PropertyStatement
Dim newParameterList = AddParameters(propertyStatement.ParameterList, parameters, options)
Dim newPropertyStatement = propertyStatement.WithParameterList(newParameterList)
Dim newPropertyBlock As SyntaxNode = propertyBlock.WithPropertyStatement(newPropertyStatement)
Return DirectCast(newPropertyBlock, TDeclarationNode)
End Function
Private Overloads Shared Function AddParameters(parameterList As ParameterListSyntax, parameters As IEnumerable(Of IParameterSymbol), options As CodeGenerationOptions) As ParameterListSyntax
Dim nodesAndTokens = If(parameterList IsNot Nothing,
New List(Of SyntaxNodeOrToken)(parameterList.Parameters.GetWithSeparators()),
New List(Of SyntaxNodeOrToken))
Dim currentParamsCount = If(parameterList IsNot Nothing, parameterList.Parameters.Count, 0)
Dim seenOptional = currentParamsCount > 0 AndAlso parameterList.Parameters(currentParamsCount - 1).Default IsNot Nothing
For Each parameter In parameters
If nodesAndTokens.Count > 0 AndAlso nodesAndTokens.Last().Kind() <> SyntaxKind.CommaToken Then
nodesAndTokens.Add(SyntaxFactory.Token(SyntaxKind.CommaToken))
End If
Dim parameterSyntax = ParameterGenerator.GenerateParameter(parameter, seenOptional, options)
nodesAndTokens.Add(parameterSyntax)
seenOptional = seenOptional OrElse parameterSyntax.Default IsNot Nothing
Next
Return If(parameterList IsNot Nothing,
SyntaxFactory.ParameterList(parameterList.OpenParenToken, SyntaxFactory.SeparatedList(Of ParameterSyntax)(nodesAndTokens), parameterList.CloseParenToken),
SyntaxFactory.ParameterList(parameters:=SyntaxFactory.SeparatedList(Of ParameterSyntax)(nodesAndTokens)))
End Function
Public Overrides Function AddAttributes(Of TDeclarationNode As SyntaxNode)(
destination As TDeclarationNode,
attributes As IEnumerable(Of AttributeData),
target As SyntaxToken?,
options As CodeGenerationOptions,
cancellationToken As CancellationToken) As TDeclarationNode
If target.HasValue AndAlso Not target.Value.IsValidAttributeTarget() Then
Throw New ArgumentException(NameOf(target))
End If
Dim attributeSyntaxList = AttributeGenerator.GenerateAttributeBlocks(attributes.ToImmutableArray(), options, target)
' Handle most cases
Dim member = TryCast(destination, StatementSyntax)
If member IsNot Nothing Then
Return Cast(Of TDeclarationNode)(member.AddAttributeLists(attributeSyntaxList.ToArray()))
End If
' Handle global attributes
Dim compilationUnit = TryCast(destination, CompilationUnitSyntax)
If compilationUnit IsNot Nothing Then
Return Cast(Of TDeclarationNode)(compilationUnit.AddAttributes(SyntaxFactory.AttributesStatement(attributeSyntaxList)))
End If
' Handle parameters
Dim parameter = TryCast(destination, ParameterSyntax)
If parameter IsNot Nothing Then
Return Cast(Of TDeclarationNode)(parameter.AddAttributeLists(attributeSyntaxList.ToArray()))
End If
Return destination
End Function
Public Overrides Function RemoveAttribute(Of TDeclarationNode As SyntaxNode)(destination As TDeclarationNode, attributeToRemove As AttributeData, options As CodeGenerationOptions, cancellationToken As CancellationToken) As TDeclarationNode
If attributeToRemove.ApplicationSyntaxReference Is Nothing Then
Throw New ArgumentException(NameOf(attributeToRemove))
End If
Dim attributeSyntaxToRemove = attributeToRemove.ApplicationSyntaxReference.GetSyntax(cancellationToken)
Return RemoveAttribute(destination, attributeSyntaxToRemove, options, cancellationToken)
End Function
Public Overrides Function RemoveAttribute(Of TDeclarationNode As SyntaxNode)(destination As TDeclarationNode, attributeToRemove As SyntaxNode, options As CodeGenerationOptions, cancellationToken As CancellationToken) As TDeclarationNode
If attributeToRemove Is Nothing Then
Throw New ArgumentException(NameOf(attributeToRemove))
End If
' Removed node could be AttributeSyntax or AttributeListSyntax.
Dim attributeRemoved As Boolean = False
Dim positionOfRemovedNode As Integer = -1
Dim triviaOfRemovedNode As SyntaxTriviaList = Nothing
' Handle most cases
Dim member = TryCast(destination, StatementSyntax)
If member IsNot Nothing Then
Dim newAttributeLists = RemoveAttributeFromAttributeLists(member.GetAttributes(), attributeToRemove, options, attributeRemoved, positionOfRemovedNode, triviaOfRemovedNode)
VerifyAttributeRemoved(attributeRemoved)
Dim newMember = member.WithAttributeLists(newAttributeLists)
Return Cast(Of TDeclarationNode)(AppendTriviaAtPosition(newMember, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode))
End If
' Handle global attributes
Dim compilationUnit = TryCast(destination, CompilationUnitSyntax)
If compilationUnit IsNot Nothing Then
Dim attributeStatements = compilationUnit.Attributes
Dim newAttributeStatements = RemoveAttributeFromAttributeStatements(attributeStatements, attributeToRemove, options, attributeRemoved, positionOfRemovedNode, triviaOfRemovedNode)
VerifyAttributeRemoved(attributeRemoved)
Dim newCompilationUnit = compilationUnit.WithAttributes(newAttributeStatements)
Return Cast(Of TDeclarationNode)(AppendTriviaAtPosition(newCompilationUnit, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode))
End If
' Handle parameters
Dim parameter = TryCast(destination, ParameterSyntax)
If parameter IsNot Nothing Then
Dim newAttributeLists = RemoveAttributeFromAttributeLists(parameter.AttributeLists, attributeToRemove, options, attributeRemoved, positionOfRemovedNode, triviaOfRemovedNode)
VerifyAttributeRemoved(attributeRemoved)
Dim newParameter = parameter.WithAttributeLists(newAttributeLists)
Return Cast(Of TDeclarationNode)(AppendTriviaAtPosition(newParameter, positionOfRemovedNode - destination.FullSpan.Start, triviaOfRemovedNode))
End If
Return destination
End Function
Private Shared Function RemoveAttributeFromAttributeLists(attributeLists As SyntaxList(Of AttributeListSyntax), attributeToRemove As SyntaxNode, options As CodeGenerationOptions,
<Out> ByRef attributeRemoved As Boolean, <Out> ByRef positionOfRemovedNode As Integer, <Out> ByRef triviaOfRemovedNode As SyntaxTriviaList) As SyntaxList(Of AttributeListSyntax)
For Each attributeList In attributeLists
Dim attributes = attributeList.Attributes
If attributes.Any(Function(a) a Is attributeToRemove) Then
attributeRemoved = True
Dim trivia As IEnumerable(Of SyntaxTrivia) = Nothing
Dim newAttributeLists As IEnumerable(Of AttributeListSyntax) = Nothing
If attributes.Count = 1 Then
' Remove the entire attribute list.
ComputePositionAndTriviaForRemoveAttributeList(attributeList, Function(t As SyntaxTrivia) t.IsKind(SyntaxKind.EndOfLineTrivia), positionOfRemovedNode, trivia)
newAttributeLists = attributeLists.Where(Function(aList) aList IsNot attributeList)
Else
' Remove just the given attribute from the attribute list.
ComputePositionAndTriviaForRemoveAttributeFromAttributeList(attributeToRemove, Function(t As SyntaxToken) t.IsKind(SyntaxKind.CommaToken), positionOfRemovedNode, trivia)
Dim newAttributes = SyntaxFactory.SeparatedList(attributes.Where(Function(a) a IsNot attributeToRemove))
Dim newAttributeList = attributeList.WithAttributes(newAttributes)
newAttributeLists = attributeLists.Select(Function(attrList) If(attrList Is attributeList, newAttributeList, attrList))
End If
triviaOfRemovedNode = trivia.ToSyntaxTriviaList()
Return SyntaxFactory.List(newAttributeLists)
End If
Next
attributeRemoved = False
Return attributeLists
End Function
Private Shared Function RemoveAttributeFromAttributeStatements(attributeStatements As SyntaxList(Of AttributesStatementSyntax), attributeToRemove As SyntaxNode, options As CodeGenerationOptions,
<Out> ByRef attributeRemoved As Boolean, <Out> ByRef positionOfRemovedNode As Integer, <Out> ByRef triviaOfRemovedNode As SyntaxTriviaList) As SyntaxList(Of AttributesStatementSyntax)
For Each attributeStatement In attributeStatements
Dim attributeLists = attributeStatement.AttributeLists
Dim newAttributeLists = RemoveAttributeFromAttributeLists(attributeLists, attributeToRemove, options, attributeRemoved, positionOfRemovedNode, triviaOfRemovedNode)
If attributeRemoved Then
Dim newAttributeStatement = attributeStatement.WithAttributeLists(newAttributeLists)
Return SyntaxFactory.List(attributeStatements.Select(Function(attrStatement) If(attrStatement Is attributeStatement, newAttributeStatement, attrStatement)))
End If
Next
attributeRemoved = False
Return attributeStatements
End Function
Private Shared Sub VerifyAttributeRemoved(attributeRemoved As Boolean)
If Not attributeRemoved Then
Throw New ArgumentException("attributeToRemove")
End If
End Sub
Public Overrides Function AddStatements(Of TDeclarationNode As SyntaxNode)(
destinationMember As TDeclarationNode,
statements As IEnumerable(Of SyntaxNode),
options As CodeGenerationOptions,
cancellationToken As CancellationToken) As TDeclarationNode
Dim methodBlock = TryCast(destinationMember, MethodBlockBaseSyntax)
If methodBlock IsNot Nothing Then
Dim allStatements = methodBlock.Statements.Concat(StatementGenerator.GenerateStatements(statements))
Dim result As Object
Select Case methodBlock.Kind
Case SyntaxKind.SubBlock,
SyntaxKind.FunctionBlock
result = DirectCast(methodBlock, MethodBlockSyntax).WithStatements(SyntaxFactory.List(allStatements))
Case SyntaxKind.ConstructorBlock
result = DirectCast(methodBlock, ConstructorBlockSyntax).WithStatements(SyntaxFactory.List(allStatements))
Case SyntaxKind.OperatorBlock
result = DirectCast(methodBlock, OperatorBlockSyntax).WithStatements(SyntaxFactory.List(allStatements))
Case Else
result = DirectCast(methodBlock, AccessorBlockSyntax).WithStatements(SyntaxFactory.List(allStatements))
End Select
Return DirectCast(DirectCast(result, Object), TDeclarationNode)
Else
Return AddStatementsWorker(destinationMember, statements, options, cancellationToken)
End If
End Function
Private Function AddStatementsWorker(Of TDeclarationNode As SyntaxNode)(
destinationMember As TDeclarationNode,
statements As IEnumerable(Of SyntaxNode),
options As CodeGenerationOptions,
cancellationToken As CancellationToken) As TDeclarationNode
Dim location = options.BestLocation
CheckLocation(destinationMember, location)
Dim token = location.FindToken(cancellationToken)
Dim oldBlock = token.Parent.GetContainingMultiLineExecutableBlocks().First
Dim oldBlockStatements = oldBlock.GetExecutableBlockStatements()
Dim oldBlockStatementsSet = oldBlockStatements.ToSet()
Dim oldStatement = token.Parent.GetAncestorsOrThis(Of StatementSyntax)().First(AddressOf oldBlockStatementsSet.Contains)
Dim oldStatementIndex = oldBlockStatements.IndexOf(oldStatement)
Dim statementArray = statements.OfType(Of StatementSyntax).ToArray()
Dim newBlock As SyntaxNode
If options.BeforeThisLocation IsNot Nothing Then
Dim strippedTrivia As ImmutableArray(Of SyntaxTrivia) = Nothing
Dim newStatement = VisualBasicSyntaxFactsService.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(
oldStatement, strippedTrivia)
statementArray(0) = statementArray(0).WithLeadingTrivia(strippedTrivia)
newBlock = oldBlock.ReplaceNode(oldStatement, newStatement)
newBlock = newBlock.ReplaceStatements(newBlock.GetExecutableBlockStatements().InsertRange(oldStatementIndex, statementArray))
Else
newBlock = oldBlock.ReplaceStatements(oldBlockStatements.InsertRange(oldStatementIndex + 1, statementArray))
End If
Return destinationMember.ReplaceNode(oldBlock, newBlock)
End Function
Public Overrides Function CreateMethodDeclaration(method As IMethodSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxNode
' Synthesized methods for properties/events are not things we actually generate
' declarations for.
If method.AssociatedSymbol IsNot Nothing Then
Return Nothing
End If
If method.IsConstructor() Then
Return ConstructorGenerator.GenerateConstructorDeclaration(method, destination, options)
ElseIf method.IsUserDefinedOperator() Then
Return OperatorGenerator.GenerateOperatorDeclaration(method, destination, options)
ElseIf method.IsConversion() Then
Return ConversionGenerator.GenerateConversionDeclaration(method, destination, options)
Else
Return MethodGenerator.GenerateMethodDeclaration(method, destination, options)
End If
End Function
Public Overrides Function CreateEventDeclaration([event] As IEventSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxNode
Return EventGenerator.GenerateEventDeclaration([event], destination, options)
End Function
Public Overrides Function CreateFieldDeclaration(field As IFieldSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxNode
If destination = CodeGenerationDestination.EnumType Then
Return EnumMemberGenerator.GenerateEnumMemberDeclaration(field, Nothing, options)
Else
Return FieldGenerator.GenerateFieldDeclaration(field, destination, options)
End If
End Function
Public Overrides Function CreatePropertyDeclaration([property] As IPropertySymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions) As SyntaxNode
Return PropertyGenerator.GeneratePropertyDeclaration([property], destination, options)
End Function
Public Overrides Function CreateNamedTypeDeclaration(namedType As INamedTypeSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions,
cancellationToken As CancellationToken) As SyntaxNode
Return NamedTypeGenerator.GenerateNamedTypeDeclaration(Me, namedType, options, cancellationToken)
End Function
Public Overrides Function CreateNamespaceDeclaration([namespace] As INamespaceSymbol,
destination As CodeGenerationDestination,
options As CodeGenerationOptions,
cancellationToken As CancellationToken) As SyntaxNode
Return NamespaceGenerator.GenerateNamespaceDeclaration(Me, [namespace], options, cancellationToken)
End Function
Private Overloads Shared Function UpdateDeclarationModifiers(Of TDeclarationNode As SyntaxNode)(declaration As TDeclarationNode, computeNewModifiersList As Func(Of SyntaxTokenList, SyntaxTokenList), options As CodeGenerationOptions, cancellationToken As CancellationToken) As TDeclarationNode
' Handle type declarations
Dim typeStatementSyntax = TryCast(declaration, TypeStatementSyntax)
If typeStatementSyntax IsNot Nothing Then
Return Cast(Of TDeclarationNode)(typeStatementSyntax.WithModifiers(computeNewModifiersList(typeStatementSyntax.Modifiers)))
End If
' Handle enum declarations
Dim enumStatementSyntax = TryCast(declaration, EnumStatementSyntax)
If enumStatementSyntax IsNot Nothing Then
Return Cast(Of TDeclarationNode)(enumStatementSyntax.WithModifiers(computeNewModifiersList(enumStatementSyntax.Modifiers)))
End If
' Handle methods
Dim methodBaseSyntax = TryCast(declaration, MethodBaseSyntax)
If methodBaseSyntax IsNot Nothing Then
Return Cast(Of TDeclarationNode)(methodBaseSyntax.WithModifiers(computeNewModifiersList(methodBaseSyntax.Modifiers)))
End If
' Handle Incomplete Members
Dim incompleteMemberSyntax = TryCast(declaration, IncompleteMemberSyntax)
If incompleteMemberSyntax IsNot Nothing Then
Return Cast(Of TDeclarationNode)(incompleteMemberSyntax.WithModifiers(computeNewModifiersList(incompleteMemberSyntax.Modifiers)))
End If
' Handle fields
Dim fieldDeclarationSyntax = TryCast(declaration, FieldDeclarationSyntax)
If fieldDeclarationSyntax IsNot Nothing Then
Return Cast(Of TDeclarationNode)(fieldDeclarationSyntax.WithModifiers(computeNewModifiersList(fieldDeclarationSyntax.Modifiers)))
End If
' Handle parameters
Dim parameterSyntax = TryCast(declaration, ParameterSyntax)
If parameterSyntax IsNot Nothing Then
Return Cast(Of TDeclarationNode)(parameterSyntax.WithModifiers(computeNewModifiersList(parameterSyntax.Modifiers)))
End If
' Handle local declarations
Dim localDeclarationStatementSyntax = TryCast(declaration, LocalDeclarationStatementSyntax)
If localDeclarationStatementSyntax IsNot Nothing Then
Return Cast(Of TDeclarationNode)(localDeclarationStatementSyntax.WithModifiers(computeNewModifiersList(localDeclarationStatementSyntax.Modifiers)))
End If
Return declaration
End Function
Public Overrides Function UpdateDeclarationModifiers(Of TDeclarationNode As SyntaxNode)(declaration As TDeclarationNode, newModifiers As IEnumerable(Of SyntaxToken), options As CodeGenerationOptions, cancellationToken As CancellationToken) As TDeclarationNode
Dim computeNewModifiersList As Func(Of SyntaxTokenList, SyntaxTokenList) = Function(modifiersList As SyntaxTokenList)
Return SyntaxFactory.TokenList(newModifiers)
End Function
Return UpdateDeclarationModifiers(declaration, computeNewModifiersList, options, cancellationToken)
End Function
Public Overrides Function UpdateDeclarationAccessibility(Of TDeclarationNode As SyntaxNode)(declaration As TDeclarationNode, newAccessibility As Accessibility, options As CodeGenerationOptions, cancellationToken As CancellationToken) As TDeclarationNode
Dim computeNewModifiersList As Func(Of SyntaxTokenList, SyntaxTokenList) = Function(modifiersList As SyntaxTokenList)
Return UpdateDeclarationAccessibility(modifiersList, newAccessibility, options)
End Function
Return UpdateDeclarationModifiers(declaration, computeNewModifiersList, options, cancellationToken)
End Function
Private Overloads Shared Function UpdateDeclarationAccessibility(modifiersList As SyntaxTokenList, newAccessibility As Accessibility, options As CodeGenerationOptions) As SyntaxTokenList
Dim newModifierTokens = New List(Of SyntaxToken)()
VisualBasicCodeGenerationHelpers.AddAccessibilityModifiers(newAccessibility, newModifierTokens, CodeGenerationDestination.Unspecified, options, Accessibility.NotApplicable)
If newModifierTokens.Count = 0 Then
Return modifiersList
End If
Return SyntaxFactory.TokenList(GetUpdatedDeclarationAccessibilityModifiers(newModifierTokens, modifiersList, Function(modifier As SyntaxToken) SyntaxFacts.IsAccessibilityModifier(modifier.Kind())))
End Function
Private Function UpdateSimpleAsClause(asClause As SimpleAsClauseSyntax, newType As ITypeSymbol) As SimpleAsClauseSyntax
Dim newTypeSyntax = newType.GenerateTypeSyntax().
WithLeadingTrivia(asClause.GetLeadingTrivia()).
WithTrailingTrivia(asClause.GetTrailingTrivia())
Return DirectCast(asClause, SimpleAsClauseSyntax).WithType(newTypeSyntax)
End Function
Private Function UpdateAsClause(asClause As AsClauseSyntax, newType As ITypeSymbol) As AsClauseSyntax
Dim newTypeSyntax = newType.GenerateTypeSyntax().
WithLeadingTrivia(asClause.GetLeadingTrivia()).
WithTrailingTrivia(asClause.GetTrailingTrivia())
Select Case asClause.Kind
Case SyntaxKind.SimpleAsClause
Return DirectCast(asClause, SimpleAsClauseSyntax).WithType(newTypeSyntax)
Case Else
Dim asNewClause = DirectCast(asClause, AsNewClauseSyntax)
Dim newExpression = asNewClause.NewExpression
Dim updatedNewExpression As NewExpressionSyntax
Select Case newExpression.Kind
Case SyntaxKind.ArrayCreationExpression
updatedNewExpression = DirectCast(newExpression, ArrayCreationExpressionSyntax).WithType(newTypeSyntax)
Case SyntaxKind.ObjectCreationExpression
updatedNewExpression = DirectCast(newExpression, ObjectCreationExpressionSyntax).WithType(newTypeSyntax)
Case Else
Return asClause
End Select
Return asNewClause.WithNewExpression(updatedNewExpression)
End Select
End Function
Public Overrides Function UpdateDeclarationType(Of TDeclarationNode As SyntaxNode)(declaration As TDeclarationNode, newType As ITypeSymbol, options As CodeGenerationOptions, cancellationToken As CancellationToken) As TDeclarationNode
Dim syntaxNode = TryCast(declaration, VisualBasicSyntaxNode)
If syntaxNode Is Nothing Then
Return declaration
End If
Select Case syntaxNode.Kind
Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement
Dim methodStatementSyntax = DirectCast(syntaxNode, MethodStatementSyntax)
Dim newAsClause = UpdateSimpleAsClause(methodStatementSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(methodStatementSyntax.WithAsClause(newAsClause))
Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement
Dim declareStatementSyntax = DirectCast(syntaxNode, DeclareStatementSyntax)
Dim newAsClause = UpdateSimpleAsClause(declareStatementSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(declareStatementSyntax.WithAsClause(newAsClause))
Case SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement
Dim delegateStatementSyntax = DirectCast(syntaxNode, DelegateStatementSyntax)
Dim newAsClause = UpdateSimpleAsClause(delegateStatementSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(delegateStatementSyntax.WithAsClause(newAsClause))
Case SyntaxKind.EventStatement
Dim eventStatementSyntax = DirectCast(syntaxNode, EventStatementSyntax)
Dim newAsClause = UpdateSimpleAsClause(eventStatementSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(eventStatementSyntax.WithAsClause(newAsClause))
Case SyntaxKind.OperatorStatement
Dim operatorStatementSyntax = DirectCast(syntaxNode, OperatorStatementSyntax)
Dim newAsClause = UpdateSimpleAsClause(operatorStatementSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(operatorStatementSyntax.WithAsClause(newAsClause))
Case SyntaxKind.PropertyStatement
Dim propertyStatementSyntax = DirectCast(syntaxNode, PropertyStatementSyntax)
Dim newAsClause = UpdateAsClause(propertyStatementSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(propertyStatementSyntax.WithAsClause(newAsClause))
Case SyntaxKind.VariableDeclarator
Dim variableDeclaratorSyntax = DirectCast(syntaxNode, VariableDeclaratorSyntax)
Dim newAsClause = UpdateAsClause(variableDeclaratorSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(variableDeclaratorSyntax.WithAsClause(newAsClause))
Case SyntaxKind.Parameter
Dim parameterSyntax = DirectCast(syntaxNode, ParameterSyntax)
Dim newAsClause = UpdateSimpleAsClause(parameterSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(parameterSyntax.WithAsClause(newAsClause))
Case SyntaxKind.CatchStatement
Dim catchStatementSyntax = DirectCast(syntaxNode, CatchStatementSyntax)
Dim newAsClause = UpdateSimpleAsClause(catchStatementSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(catchStatementSyntax.WithAsClause(newAsClause))
Case SyntaxKind.FunctionLambdaHeader, SyntaxKind.SubLambdaHeader
Dim lambdaHeaderSyntax = DirectCast(syntaxNode, LambdaHeaderSyntax)
Dim newAsClause = UpdateSimpleAsClause(lambdaHeaderSyntax.AsClause, newType)
Return Cast(Of TDeclarationNode)(lambdaHeaderSyntax.WithAsClause(newAsClause))
Case Else
Return declaration
End Select
End Function
Public Overrides Function UpdateDeclarationMembers(Of TDeclarationNode As SyntaxNode)(declaration As TDeclarationNode, newMembers As IList(Of ISymbol), Optional options As CodeGenerationOptions = Nothing, Optional cancellationToken As CancellationToken = Nothing) As TDeclarationNode
Dim syntaxNode = TryCast(declaration, VisualBasicSyntaxNode)
If syntaxNode IsNot Nothing Then
Select Case syntaxNode.Kind
Case SyntaxKind.EnumBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ClassBlock
Return Cast(Of TDeclarationNode)(NamedTypeGenerator.UpdateNamedTypeDeclaration(Me, DirectCast(syntaxNode, StatementSyntax), newMembers, options, cancellationToken))
Case SyntaxKind.CompilationUnit, SyntaxKind.NamespaceBlock
Return Cast(Of TDeclarationNode)(NamespaceGenerator.UpdateCompilationUnitOrNamespaceDeclaration(Me, syntaxNode, newMembers, options, cancellationToken))
End Select
End If
Return declaration
End Function
End Class
End Namespace
| {
"content_hash": "240f890e66d9f053c231469651b02dfc",
"timestamp": "",
"source": "github",
"line_count": 733,
"max_line_length": 300,
"avg_line_length": 62.346521145975444,
"alnum_prop": 0.6757549234135667,
"repo_name": "abock/roslyn",
"id": "3a81b8bab3db7e16010aef358ecaa1a5a5cb8d3f",
"size": "45702",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Workspaces/VisualBasic/Portable/CodeGeneration/VisualBasicCodeGenerationService.vb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "1C Enterprise",
"bytes": "289100"
},
{
"name": "Batchfile",
"bytes": "9059"
},
{
"name": "C#",
"bytes": "126276814"
},
{
"name": "C++",
"bytes": "5602"
},
{
"name": "CMake",
"bytes": "8276"
},
{
"name": "Dockerfile",
"bytes": "2450"
},
{
"name": "F#",
"bytes": "549"
},
{
"name": "PowerShell",
"bytes": "236203"
},
{
"name": "Shell",
"bytes": "94929"
},
{
"name": "Visual Basic .NET",
"bytes": "70520200"
}
],
"symlink_target": ""
} |
<?php
/* SyliusWebBundle:Backend/Order:index.html.twig */
class __TwigTemplate_4671ea868310fa1a0c6576b6a4ff361f745803c9988e35280e019cdc7433468d extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = $this->env->loadTemplate("SyliusWebBundle:Backend:layout.html.twig");
$this->blocks = array(
'topbar' => array($this, 'block_topbar'),
'content' => array($this, 'block_content'),
);
}
protected function doGetParent(array $context)
{
return "SyliusWebBundle:Backend:layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 3
$context["buttons"] = $this->env->loadTemplate("SyliusResourceBundle:Macros:buttons.html.twig");
// line 4
$context["__internal_27e54d8fd21419afc029892a2b74856e9fccc366006c61d1dc7294c32699ce44"] = $this->env->loadTemplate("SyliusWebBundle:Backend/Macros:misc.html.twig");
// line 5
$context["__internal_5fe40155b1196470a1416ecff9d48c8d5f0509dc9c2e15b968c7448257a2b021"] = $this->env->loadTemplate("SyliusWebBundle:Backend/Order:macros.html.twig");
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 7
public function block_topbar($context, array $blocks = array())
{
// line 8
echo "<ol class=\"breadcrumb\">
<li>";
// line 9
echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("sylius.breadcrumb.sales"), "html", null, true);
echo "</li>
<li>";
// line 10
echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("sylius.breadcrumb.order.index"), "html", null, true);
echo "</li>
</ol>
";
}
// line 14
public function block_content($context, array $blocks = array())
{
// line 15
echo "<div class=\"page-header\">
<div class=\"actions-menu\">
";
// line 17
echo $context["buttons"]->getcreate($this->env->getExtension('routing')->getPath("sylius_backend_order_create"), $this->env->getExtension('translator')->trans("sylius.order.create"));
echo "
</div>
<h1><i class=\"glyphicon glyphicon-shopping-cart\"></i> ";
// line 19
echo $this->env->getExtension('translator')->trans("sylius.order.index_header");
echo "</h1>
</div>
";
// line 22
echo $this->env->getExtension('actions')->renderUri($this->env->getExtension('routing')->getUrl("sylius_backend_order_filter_form", array("criteria" => $this->getAttribute($this->getAttribute($this->getAttribute((isset($context["app"]) ? $context["app"] : $this->getContext($context, "app")), "request"), "query"), "get", array(0 => "criteria"), "method"))), array());
// line 23
echo "
";
// line 24
echo $context["__internal_27e54d8fd21419afc029892a2b74856e9fccc366006c61d1dc7294c32699ce44"]->getpagination((isset($context["orders"]) ? $context["orders"] : $this->getContext($context, "orders")));
echo "
";
// line 25
echo $context["__internal_5fe40155b1196470a1416ecff9d48c8d5f0509dc9c2e15b968c7448257a2b021"]->getlist((isset($context["orders"]) ? $context["orders"] : $this->getContext($context, "orders")));
echo "
";
// line 26
echo $context["__internal_27e54d8fd21419afc029892a2b74856e9fccc366006c61d1dc7294c32699ce44"]->getpagination((isset($context["orders"]) ? $context["orders"] : $this->getContext($context, "orders")));
echo "
";
}
public function getTemplateName()
{
return "SyliusWebBundle:Backend/Order:index.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 83 => 26, 79 => 25, 75 => 24, 72 => 23, 70 => 22, 64 => 19, 59 => 17, 55 => 15, 52 => 14, 45 => 10, 41 => 9, 38 => 8, 35 => 7, 30 => 5, 28 => 4, 26 => 3,);
}
}
| {
"content_hash": "313d36ba38547f8aad7a4ef68b306582",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 376,
"avg_line_length": 39.699029126213595,
"alnum_prop": 0.6138420151626315,
"repo_name": "johnyjamma93/prod_lokisalle",
"id": "7f25732885db519fccc77fe9dd695abeeed5b0bc",
"size": "4089",
"binary": false,
"copies": "1",
"ref": "refs/heads/full",
"path": "app/cache/dev/twig/46/71/ea868310fa1a0c6576b6a4ff361f745803c9988e35280e019cdc7433468d.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": ""
} |
"""Sensor from an SQL Query."""
import datetime
import decimal
import logging
import re
import sqlalchemy
from sqlalchemy.orm import scoped_session, sessionmaker
import voluptuous as vol
from homeassistant.components.recorder import CONF_DB_URL, DEFAULT_DB_FILE, DEFAULT_URL
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.const import CONF_NAME, CONF_UNIT_OF_MEASUREMENT, CONF_VALUE_TEMPLATE
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
CONF_COLUMN_NAME = "column"
CONF_QUERIES = "queries"
CONF_QUERY = "query"
DB_URL_RE = re.compile("//.*:.*@")
def redact_credentials(data):
"""Redact credentials from string data."""
return DB_URL_RE.sub("//****:****@", data)
def validate_sql_select(value):
"""Validate that value is a SQL SELECT query."""
if not value.lstrip().lower().startswith("select"):
raise vol.Invalid("Only SELECT queries allowed")
return value
_QUERY_SCHEME = vol.Schema(
{
vol.Required(CONF_COLUMN_NAME): cv.string,
vol.Required(CONF_NAME): cv.string,
vol.Required(CONF_QUERY): vol.All(cv.string, validate_sql_select),
vol.Optional(CONF_UNIT_OF_MEASUREMENT): cv.string,
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_QUERIES): [_QUERY_SCHEME], vol.Optional(CONF_DB_URL): cv.string}
)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the SQL sensor platform."""
db_url = config.get(CONF_DB_URL)
if not db_url:
db_url = DEFAULT_URL.format(hass_config_path=hass.config.path(DEFAULT_DB_FILE))
sess = None
try:
engine = sqlalchemy.create_engine(db_url)
sessmaker = scoped_session(sessionmaker(bind=engine))
# Run a dummy query just to test the db_url
sess = sessmaker()
sess.execute("SELECT 1;")
except sqlalchemy.exc.SQLAlchemyError as err:
_LOGGER.error(
"Couldn't connect using %s DB_URL: %s",
redact_credentials(db_url),
redact_credentials(str(err)),
)
return
finally:
if sess:
sess.close()
queries = []
for query in config.get(CONF_QUERIES):
name = query.get(CONF_NAME)
query_str = query.get(CONF_QUERY)
unit = query.get(CONF_UNIT_OF_MEASUREMENT)
value_template = query.get(CONF_VALUE_TEMPLATE)
column_name = query.get(CONF_COLUMN_NAME)
if value_template is not None:
value_template.hass = hass
# MSSQL uses TOP and not LIMIT
if not ("LIMIT" in query_str or "SELECT TOP" in query_str):
query_str = (
query_str.replace("SELECT", "SELECT TOP 1")
if "mssql" in db_url
else query_str.replace(";", " LIMIT 1;")
)
sensor = SQLSensor(
name, sessmaker, query_str, column_name, unit, value_template
)
queries.append(sensor)
add_entities(queries, True)
class SQLSensor(SensorEntity):
"""Representation of an SQL sensor."""
def __init__(self, name, sessmaker, query, column, unit, value_template):
"""Initialize the SQL sensor."""
self._name = name
self._query = query
self._unit_of_measurement = unit
self._template = value_template
self._column_name = column
self.sessionmaker = sessmaker
self._state = None
self._attributes = None
@property
def name(self):
"""Return the name of the query."""
return self._name
@property
def native_value(self):
"""Return the query's current state."""
return self._state
@property
def native_unit_of_measurement(self):
"""Return the unit of measurement."""
return self._unit_of_measurement
@property
def extra_state_attributes(self):
"""Return the state attributes."""
return self._attributes
def update(self):
"""Retrieve sensor data from the query."""
data = None
try:
sess = self.sessionmaker()
result = sess.execute(self._query)
self._attributes = {}
if not result.returns_rows or result.rowcount == 0:
_LOGGER.warning("%s returned no results", self._query)
self._state = None
return
for res in result.mappings():
_LOGGER.debug("result = %s", res.items())
data = res[self._column_name]
for key, value in res.items():
if isinstance(value, decimal.Decimal):
value = float(value)
if isinstance(value, datetime.date):
value = str(value)
self._attributes[key] = value
except sqlalchemy.exc.SQLAlchemyError as err:
_LOGGER.error(
"Error executing query %s: %s",
self._query,
redact_credentials(str(err)),
)
return
finally:
sess.close()
if data is not None and self._template is not None:
self._state = self._template.async_render_with_possible_json_value(
data, None
)
else:
self._state = data
| {
"content_hash": "9a4f14e2d508fa1e7bf008a633c25919",
"timestamp": "",
"source": "github",
"line_count": 178,
"max_line_length": 88,
"avg_line_length": 30.528089887640448,
"alnum_prop": 0.5901729849098271,
"repo_name": "sander76/home-assistant",
"id": "1b0ae5a9076af075c29e4ff63678f62c932a33d0",
"size": "5434",
"binary": false,
"copies": "3",
"ref": "refs/heads/dev",
"path": "homeassistant/components/sql/sensor.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "1795"
},
{
"name": "Python",
"bytes": "36548768"
},
{
"name": "Shell",
"bytes": "4910"
}
],
"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="wrap_content"
android:background="@color/info_template_blue_background"
android:paddingBottom="10dp"
android:paddingTop="10dp">
<TextView
android:id="@+id/tv_info_object"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="2dp"
android:padding="2dp"
android:text="test"
android:textColor="@android:color/white" />
</RelativeLayout> | {
"content_hash": "ad6682913f858abcaf6a95df98dbfca5",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 74,
"avg_line_length": 35.94444444444444,
"alnum_prop": 0.6599690880989181,
"repo_name": "amritsinghbains/BuildmLearn-Toolkit-Android",
"id": "47f338ad0fae0656da49bddd47c303bf2a1010fa",
"size": "647",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "source-code/app/src/main/res/layout/info_template_app_list_item.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "283820"
}
],
"symlink_target": ""
} |
var WIDTH = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var HEIGHT = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
// creating instance of Phaser.Game
var game = new Phaser.Game(WIDTH, HEIGHT, Phaser.AUTO, '', { preload: preload, create: create, update: update, render: render});
// loading assets
function preload() {
// loading assets
game.load.image('background', 'assets/background.jpg');
game.load.image('crosshair', 'assets/crosshair.png');
game.load.spritesheet('target', 'assets/target.png', 39, 121);
}
var worldScale = 1;
var snipingCam;
var target;
var cursors;
// phaser function for modifying the UI
function create() {
// setting game bounds
game.world.setBounds(0, 0, 1400, 1000);
// enabling phaser's physics engine
game.physics.startSystem(Phaser.Physics.P2JS);
// adding background to game.world
game.add.image(0, 0, 'background');
// adding shift key and keyboard cursors to game
shiftKey = game.input.keyboard.addKey(Phaser.Keyboard.SHIFT);
cursors = game.input.keyboard.createCursorKeys();
//var c = new Phaser.Circle(150, 150, 300);
// circle that acts as a sniping camera
snipingCam = game.add.graphics(150, 150);
// drawing red border line
snipingCam.lineStyle(3, 0xff0004);
snipingCam.beginFill(0xff0004, 0.2);
snipingCam.drawCircle(0, 0, 300);
snipingCam.drawCircle(0, 0, 2);
snipingCam.endFill();
//game.physics.p2.enable(snipingCam, true);
//snipingCam.body.setCircle(150);
//snipingCam.body.setZeroDamping();
//snipingCam.body.fixedRotation = true;
game.camera.follow(snipingCam);
//target = game.add.sprite(32, game.world.height - 150, 'target');
//game.physics.p2.enable(target, true);
//target.body.gravity.y = 300;
//target.animations.add('left', [13, 6, 7, 8, 9, 10, 11], 10, true);
// target.animations.add('right', [12, 0, 1, 2, 3, 4, 5], 10, true);
game.input.addMoveCallback(moveCam, this);
}
// phaser function that runs every frame and updates the UI
function update() {
// zooming in and out
if (game.input.keyboard.isDown(Phaser.Keyboard.Q)) {
worldScale += 0.05;
}
else if (game.input.keyboard.isDown(Phaser.Keyboard.A)) {
worldScale -= 0.05;
}
// set a minimum and maximum scale value
worldScale = Phaser.Math.clamp(worldScale, 1, 1.5);
// set our world scale as needed
game.world.scale.set(worldScale);
}
function render(game) {
game.debug.text(game.time.fps || '--', 2, 14, "#00ff00");
}
function moveCam(pointer, x, y) {
snipingCam.x = x;
snipingCam.y = y;
}
| {
"content_hash": "29be0c0d75318e1487188bd8b49cc8dd",
"timestamp": "",
"source": "github",
"line_count": 92,
"max_line_length": 128,
"avg_line_length": 28.48913043478261,
"alnum_prop": 0.695154521175124,
"repo_name": "suvingrg/sniper2D",
"id": "03388150c1554b5322d8a25a1fdd63e09ecf4a54",
"size": "2661",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build/v1/v1.2/scripts.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "6953"
},
{
"name": "JavaScript",
"bytes": "163484"
}
],
"symlink_target": ""
} |
package com.callfire.api11.client;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
* Callfire API exception is thrown by client in case of 4xx or 5xx HTTP code
* response
*
* @since 1.0
*/
public class CfApi11ApiException extends RuntimeException {
protected String message;
public CfApi11ApiException(String message) {
this.message = message;
}
/**
* Get detailed error message with HTTP code, help link, etc.
*
* @return detailed message
*/
@Override
public String getMessage() {
return message;
}
/**
* Set detailed error message with HTTP code, help link, etc.
*
* @param message detailed message
*/
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return new ToStringBuilder(this)
.appendSuper(super.toString())
.append("message", message)
.toString();
}
}
| {
"content_hash": "5c9bac80121bb30a5129ac92c768a59b",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 77,
"avg_line_length": 22.75,
"alnum_prop": 0.6253746253746254,
"repo_name": "CallFire/callfire-api-1.1-client-java",
"id": "40456f3c2b197d20be124b175c12d1ef628836c6",
"size": "1001",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "callfire-api-1.1-client-core/src/main/java/com/callfire/api11/client/CfApi11ApiException.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "604279"
}
],
"symlink_target": ""
} |
class ThreadIdValidationThread : public v8::base::Thread {
public:
ThreadIdValidationThread(v8::base::Thread* thread_to_start,
i::List<i::ThreadId>* refs, unsigned int thread_no,
v8::base::Semaphore* semaphore)
: Thread(Options("ThreadRefValidationThread")),
refs_(refs),
thread_no_(thread_no),
thread_to_start_(thread_to_start),
semaphore_(semaphore) {}
void Run() {
i::ThreadId thread_id = i::ThreadId::Current();
for (int i = 0; i < thread_no_; i++) {
CHECK(!(*refs_)[i].Equals(thread_id));
}
CHECK(thread_id.IsValid());
(*refs_)[thread_no_] = thread_id;
if (thread_to_start_ != NULL) {
thread_to_start_->Start();
}
semaphore_->Signal();
}
private:
i::List<i::ThreadId>* refs_;
int thread_no_;
v8::base::Thread* thread_to_start_;
v8::base::Semaphore* semaphore_;
};
TEST(ThreadIdValidation) {
const int kNThreads = 100;
i::List<ThreadIdValidationThread*> threads(kNThreads);
i::List<i::ThreadId> refs(kNThreads);
v8::base::Semaphore semaphore(0);
ThreadIdValidationThread* prev = NULL;
for (int i = kNThreads - 1; i >= 0; i--) {
ThreadIdValidationThread* newThread =
new ThreadIdValidationThread(prev, &refs, i, &semaphore);
threads.Add(newThread);
prev = newThread;
refs.Add(i::ThreadId::Invalid());
}
prev->Start();
for (int i = 0; i < kNThreads; i++) {
semaphore.Wait();
}
for (int i = 0; i < kNThreads; i++) {
delete threads[i];
}
}
| {
"content_hash": "cd0e4eb7270600c0baf737f6bf104c20",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 78,
"avg_line_length": 29.28301886792453,
"alnum_prop": 0.5966494845360825,
"repo_name": "baslr/ArangoDB",
"id": "a9058a523a4b0338f4e5f0df57127721644007e5",
"size": "3270",
"binary": false,
"copies": "6",
"ref": "refs/heads/3.1-silent",
"path": "3rdParty/V8/V8-5.0.71.39/test/cctest/test-threads.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "89080"
},
{
"name": "Assembly",
"bytes": "391227"
},
{
"name": "Awk",
"bytes": "4272"
},
{
"name": "Batchfile",
"bytes": "62892"
},
{
"name": "C",
"bytes": "7932707"
},
{
"name": "C#",
"bytes": "96430"
},
{
"name": "C++",
"bytes": "284363933"
},
{
"name": "CLIPS",
"bytes": "5291"
},
{
"name": "CMake",
"bytes": "681903"
},
{
"name": "CSS",
"bytes": "1036656"
},
{
"name": "CWeb",
"bytes": "174166"
},
{
"name": "Cuda",
"bytes": "52444"
},
{
"name": "DIGITAL Command Language",
"bytes": "259402"
},
{
"name": "Emacs Lisp",
"bytes": "14637"
},
{
"name": "Fortran",
"bytes": "1856"
},
{
"name": "Groovy",
"bytes": "131"
},
{
"name": "HTML",
"bytes": "2318016"
},
{
"name": "Java",
"bytes": "2325801"
},
{
"name": "JavaScript",
"bytes": "67878359"
},
{
"name": "LLVM",
"bytes": "24129"
},
{
"name": "Lex",
"bytes": "1231"
},
{
"name": "Lua",
"bytes": "16189"
},
{
"name": "M4",
"bytes": "600550"
},
{
"name": "Makefile",
"bytes": "509612"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Module Management System",
"bytes": "1545"
},
{
"name": "NSIS",
"bytes": "28404"
},
{
"name": "Objective-C",
"bytes": "19321"
},
{
"name": "Objective-C++",
"bytes": "2503"
},
{
"name": "PHP",
"bytes": "98503"
},
{
"name": "Pascal",
"bytes": "145688"
},
{
"name": "Perl",
"bytes": "720157"
},
{
"name": "Perl 6",
"bytes": "9918"
},
{
"name": "Python",
"bytes": "5859911"
},
{
"name": "QMake",
"bytes": "16692"
},
{
"name": "R",
"bytes": "5123"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Roff",
"bytes": "1010686"
},
{
"name": "Ruby",
"bytes": "922159"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Scheme",
"bytes": "10604"
},
{
"name": "Shell",
"bytes": "511077"
},
{
"name": "Swift",
"bytes": "116"
},
{
"name": "Tcl",
"bytes": "1172"
},
{
"name": "TeX",
"bytes": "32117"
},
{
"name": "Vim script",
"bytes": "4075"
},
{
"name": "Visual Basic",
"bytes": "11568"
},
{
"name": "XSLT",
"bytes": "551977"
},
{
"name": "Yacc",
"bytes": "53005"
}
],
"symlink_target": ""
} |
#import <CorePDF/CPChunk.h>
@interface CPTextObject : CPChunk
{
struct CGPoint anchor;
_Bool metricInfoCalculated;
float maxFontSize;
double maxFontLineHeight;
}
- (void)translateObjectYBy:(double)arg1;
- (void)clearCachedInfo;
- (double)maxFontLineHeight;
- (float)maxFontSize;
- (void)calculateMetrics;
@end
| {
"content_hash": "4f1ab9d5a35739588ec597fa85f0ab21",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 40,
"avg_line_length": 16.6,
"alnum_prop": 0.7349397590361446,
"repo_name": "matthewsot/CocoaSharp",
"id": "6769a21facdd1cb991528b5cdb178b652512d89d",
"size": "472",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Headers/PrivateFrameworks/CorePDF/CPTextObject.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "259784"
},
{
"name": "C#",
"bytes": "2789005"
},
{
"name": "C++",
"bytes": "252504"
},
{
"name": "Objective-C",
"bytes": "24301417"
},
{
"name": "Smalltalk",
"bytes": "167909"
}
],
"symlink_target": ""
} |
// clang-format off
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#include <CoreFoundation/CFBase.h>
#include <CoreFoundation/CFAttributedString.h>
#include "CFRunArray.h"
#include "ForFoundationOnly.h"
#include "CFInternal.h"
#include <Foundation/NSMutableAttributedString.h>
struct __CFAttributedString {
CFRuntimeBase base;
CFStringRef string;
CFRunArrayRef attributeArray;
};
/* Mutability is determined by a bit in the CF base. Mutable if bit 0 is 0. So by default freshly created attributed strings are mutable. Don't change mutability once the object has been created and initialized!
*/
CF_INLINE Boolean __CFAttributedStringIsMutable(CFAttributedStringRef attrStr) {
return __CFBitfieldGetValue(((const CFRuntimeBase *)attrStr)->_cfinfo[CF_INFO_BITS], 0, 0) ? false : true;
}
// WINOBJC: This function is for Foundation's benefit; no one else should use it.
CF_EXPORT Boolean _CFAttributedStringIsMutable(CFAttributedStringRef attrStr) { return __CFAttributedStringIsMutable(attrStr); }
CF_INLINE void __CFAttributedStringSetMutable(CFAttributedStringRef attrStr, Boolean flag) {
__CFBitfieldSetValue(((CFRuntimeBase *)attrStr)->_cfinfo[CF_INFO_BITS], 0, 0, (flag ? 0 : 1));
}
/* Assertions
*/
#define __CFAssertIsAttributedString(cf) __CFGenericValidateType(cf, CFAttributedStringGetTypeID())
#define __CFAssertIndexIsInBounds(cf, idx) CFAssert3((idx) >= 0 && (idx) < CFAttributedStringGetLength(cf), __kCFLogAssertion, "%s(): index %d out of bounds (length %d)", __PRETTY_FUNCTION__, idx, CFAttributedStringGetLength(cf))
#define __CFAssertRangeIsInBounds(cf, idx, count) CFAssert4((idx) >= 0 && (idx + count) <= CFAttributedStringGetLength(cf), __kCFLogAssertion, "%s(): range %d,%d out of bounds (length %d)", __PRETTY_FUNCTION__, idx, count, CFAttributedStringGetLength(cf))
#define __CFAssertRangeIsWithinLength(len, idx, count) CFAssert4((idx) >= 0 && (idx + count) <= len, __kCFLogAssertion, "%s(): range %d,%d out of bounds (length %d)", __PRETTY_FUNCTION__, idx, count, len)
#define __CFAssertIsAttributedStringAndMutable(cf) CFAssert1((CFGetTypeID(cf) == CFAttributedStringGetTypeID()) && __CFAttributedStringIsMutable(cf), __kCFLogAssertion, "%s(): argument not a CFMutableAttributedString", __PRETTY_FUNCTION__)
/*** "Polymorphic" functions ***/
static Boolean __CFAttributedStringEqual(CFTypeRef cf1, CFTypeRef cf2) {
CFAttributedStringRef attrStr = (CFAttributedStringRef)cf1;
CFAttributedStringRef otherAttrStr = (CFAttributedStringRef)cf2;
if (!CFEqual(attrStr->string, CFAttributedStringGetString(otherAttrStr))) return false;
CFIndex len = CFStringGetLength(attrStr->string);
CFIndex curLoc = 0;
CFRange myRange = {0, 0};
CFRange otherRange = {0, 0};
CFDictionaryRef myAttrs = NULL;
CFDictionaryRef otherAttrs = NULL;
while (curLoc < len) {
if (curLoc >= myRange.length + myRange.location) myAttrs = CFAttributedStringGetAttributes(attrStr, curLoc, &myRange);
if (curLoc >= otherRange.length + otherRange.location) otherAttrs = CFAttributedStringGetAttributes(otherAttrStr, curLoc, &otherRange);
if (!CFEqual(myAttrs, otherAttrs)) return false;
curLoc = otherRange.length + otherRange.location;
if (myRange.length + myRange.location < curLoc) curLoc = myRange.length + myRange.location;
}
return true;
}
static CFHashCode __CFAttributedStringHash(CFTypeRef cf) {
CFAttributedStringRef attrStr = (CFAttributedStringRef)cf;
return CFHash(attrStr->string);
}
// Create a stack or malloc'ed array of CFTypeRef
#define localArrayStackSize 256
#define createLocalArray(arrayName, count) \
CFTypeRef arrayName ## Buf[localArrayStackSize]; \
CFTypeRef *arrayName = (CFTypeRef *)((count <= localArrayStackSize) ? (arrayName ## Buf) : ((count < LONG_MAX / sizeof(CFTypeRef)) ? malloc(count * sizeof(CFTypeRef)) : NULL));
#define freeLocalArray(arrayName) \
if (arrayName != arrayName ## Buf) free(arrayName);
static CFStringRef __CFAttributedStringCopyDescription(CFTypeRef cf) {
CFMutableStringRef result = CFStringCreateMutable(kCFAllocatorSystemDefault, 0);
CFAttributedStringRef attrStr = (CFAttributedStringRef)cf;
CFIndex len = CFStringGetLength(attrStr->string);
CFRange range = {0, 0};
while (range.location < len) {
CFDictionaryRef attrs = CFAttributedStringGetAttributes(attrStr, range.location, &range);
CFStringRef substring = CFStringCreateWithSubstring(kCFAllocatorSystemDefault, attrStr->string, range);
CFStringAppend(result, substring);
CFRelease(substring);
CFStringAppendFormat(result, NULL, CFSTR(" %p {"), attrs);
CFIndex cnt = CFDictionaryGetCount(attrs);
createLocalArray(keys, cnt);
createLocalArray(values, cnt);
CFDictionaryGetKeysAndValues(attrs, keys, values);
while (cnt--) CFStringAppendFormat(result, NULL, CFSTR("%@=%@%s"), keys[cnt], values[cnt], ((cnt == 0) ? "" : ", "));
CFStringAppendFormat(result, NULL, CFSTR("} Len %ld\n"), (long)range.length);
range.location += range.length;
freeLocalArray(keys);
freeLocalArray(values);
}
return result;
}
static void __CFAttributedStringDeallocate(CFTypeRef cf) {
CFAttributedStringRef attrStr = (CFAttributedStringRef)cf;
CFRelease(attrStr->string);
CFRelease(attrStr->attributeArray);
}
static CFTypeID __kCFAttributedStringTypeID = _kCFRuntimeNotATypeID;
static const CFRuntimeClass __CFAttributedStringClass = {
0,
"CFAttributedString",
NULL, // init
NULL, // copy
__CFAttributedStringDeallocate,
__CFAttributedStringEqual,
__CFAttributedStringHash,
NULL, //
__CFAttributedStringCopyDescription
};
CFTypeID CFAttributedStringGetTypeID(void) {
static dispatch_once_t initOnce;
dispatch_once(&initOnce, ^{ __kCFAttributedStringTypeID = _CFRuntimeRegisterClass(&__CFAttributedStringClass); });
return __kCFAttributedStringTypeID;
}
/*** Creation and Copy routines ***/
/* Create an "internal" attributes dictionary
*/
static CFMutableDictionaryRef __CFAttributedStringCreateAttributesDictionary(CFAllocatorRef alloc, CFDictionaryRef attrs) {
if (attrs) {
return CFDictionaryCreateMutableCopy(alloc, 0, attrs);
} else {
return CFDictionaryCreateMutable(alloc, 0, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
}
}
/* Does no argument checking; doesn't shortcut to doing a copy if the range is the whole string. (This is used by the other functions to create copies).
*/
CFMutableAttributedStringRef __CFAttributedStringCreateMutableWithSubstring(CFAllocatorRef alloc, CFAttributedStringRef attrStr, CFRange range) {
CFMutableAttributedStringRef newAttrStr = CFAttributedStringCreateMutable(alloc, 0);
// Initialize the string (!!! this should be done more efficiently!)
CFStringRef str = CFStringCreateWithSubstring(alloc, attrStr->string, range);
CFAttributedStringReplaceString(newAttrStr, CFRangeMake(0, 0), str);
CFRelease(str);
CFIndex curLoc = range.location;
CFIndex endLoc = range.location + range.length;
while (curLoc < endLoc) {
CFRange effectiveRange;
CFDictionaryRef attrs = CFAttributedStringGetAttributes(attrStr, curLoc, &effectiveRange);
if (curLoc != effectiveRange.location) effectiveRange.length -= (curLoc - effectiveRange.location);
if (curLoc + effectiveRange.length > endLoc) effectiveRange.length = endLoc - curLoc;
CFAttributedStringSetAttributes(newAttrStr, CFRangeMake(curLoc - range.location, effectiveRange.length), attrs, true);
curLoc += effectiveRange.length;
}
return newAttrStr;
}
CFAttributedStringRef CFAttributedStringCreate(CFAllocatorRef alloc, CFStringRef str, CFDictionaryRef attributes) {
CFIndex size = sizeof(struct __CFAttributedString) - sizeof(CFRuntimeBase);
struct __CFAttributedString *newAttrStr = (struct __CFAttributedString *)_CFRuntimeCreateInstance(alloc, CFAttributedStringGetTypeID(), size, NULL);
if (newAttrStr == NULL) return NULL;
newAttrStr->string = CFStringCreateCopy(alloc, str);
newAttrStr->attributeArray = CFRunArrayCreate(alloc);
CFIndex len = CFStringGetLength(newAttrStr->string);
if (len) {
CFMutableDictionaryRef attrs = __CFAttributedStringCreateAttributesDictionary(alloc, attributes);
CFRunArrayInsert(newAttrStr->attributeArray, CFRangeMake(0, len), attrs);
CFRelease(attrs);
}
__CFAttributedStringSetMutable(newAttrStr, false); // Make it immutable
return (CFAttributedStringRef)newAttrStr;
}
CFAttributedStringRef CFAttributedStringCreateWithSubstring(CFAllocatorRef alloc, CFAttributedStringRef attrStr, CFRange range) {
// CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), CFAttributedStringRef, (NSAttributedString *)attrStr, _createAttributedSubstringWithRange:NSMakeRange(range.location, range.length));
__CFAssertIsAttributedString(attrStr);
__CFAssertRangeIsInBounds(attrStr, range.location, range.length);
CFIndex len = CFAttributedStringGetLength(attrStr);
// !!! Bounds check on range here
if (range.location == 0 && range.length == len) {
return CFAttributedStringCreateCopy(alloc, attrStr); /* This in turn might take a retain shortcut */
} else {
struct __CFAttributedString *newAttrStr = __CFAttributedStringCreateMutableWithSubstring(alloc, attrStr, range);
__CFAttributedStringSetMutable(newAttrStr, false);
return (CFAttributedStringRef)newAttrStr;
}
}
/* CFAttributedStringCreateCopy() will do a refcount bump if the argument is immutable and has the same allocator
*/
CFAttributedStringRef CFAttributedStringCreateCopy(CFAllocatorRef alloc, CFAttributedStringRef attrStr) {
// CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), CFAttributedStringRef, (NSAttributedString *)attrStr, copy);
// WINOBJC: still needed
CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), CFAttributedStringRef, (NSAttributedString *)attrStr, copy);
__CFAssertIsAttributedString(attrStr);
if (!__CFAttributedStringIsMutable(attrStr) && // If the string is not mutable
((alloc ? alloc : __CFGetDefaultAllocator()) == __CFGetAllocator(attrStr))) { // and it has the same allocator as the one we're using
CFRetain(attrStr); // Then just retain instead of making a true copy
return attrStr;
} else {
CFIndex len = CFAttributedStringGetLength(attrStr);
CFMutableAttributedStringRef newAttrStr =__CFAttributedStringCreateMutableWithSubstring(alloc, attrStr, CFRangeMake(0, len));
__CFAttributedStringSetMutable(newAttrStr, false); // Make it immutable
return (CFAttributedStringRef)newAttrStr;
}
}
/* CFAttributedStringCreateWithRuns() creates an attributed string from the specified string and a list of sparse attribute dictionaries. See CFAttributedStringPriv.h for info.
*/
CFAttributedStringRef _CFAttributedStringCreateWithRuns(CFAllocatorRef alloc, CFStringRef str, const CFDictionaryRef *attrDictionaries, const CFRange *runRanges, CFIndex numRuns) {
CFIndex size = sizeof(struct __CFAttributedString) - sizeof(CFRuntimeBase);
struct __CFAttributedString *newAttrStr = (struct __CFAttributedString *)_CFRuntimeCreateInstance(alloc, CFAttributedStringGetTypeID(), size, NULL);
if (newAttrStr == NULL) return NULL;
newAttrStr->string = CFStringCreateCopy(alloc, str);
newAttrStr->attributeArray = CFRunArrayCreate(alloc);
// First fill attributed string with empty attribute dictionary
CFIndex len = CFStringGetLength(newAttrStr->string);
if (len) {
CFMutableDictionaryRef attrs = __CFAttributedStringCreateAttributesDictionary(alloc, NULL);
CFRunArrayInsert(newAttrStr->attributeArray, CFRangeMake(0, len), attrs);
CFRelease(attrs);
}
// Now set the various ranges
CFIndex cnt;
for (cnt = 0; cnt < numRuns; cnt++) {
CFMutableDictionaryRef attrs = __CFAttributedStringCreateAttributesDictionary(alloc, attrDictionaries[cnt]);
__CFAssertRangeIsWithinLength(len, runRanges[cnt].location, runRanges[cnt].length);
CFRunArrayReplace(newAttrStr->attributeArray, runRanges[cnt], attrs, runRanges[cnt].length);
CFRelease(attrs);
}
__CFAttributedStringSetMutable(newAttrStr, false); // Make it immutable
return (CFAttributedStringRef)newAttrStr;
}
CFMutableAttributedStringRef CFAttributedStringCreateMutable(CFAllocatorRef alloc, CFIndex maxLength) {
CFIndex size = sizeof(struct __CFAttributedString) - sizeof(CFRuntimeBase);
struct __CFAttributedString *newAttrStr = (CFMutableAttributedStringRef)_CFRuntimeCreateInstance(alloc, CFAttributedStringGetTypeID(), size, NULL);
if (newAttrStr == NULL) return NULL;
newAttrStr->string = CFStringCreateMutable(alloc, maxLength);
newAttrStr->attributeArray = CFRunArrayCreate(alloc);
return (CFMutableAttributedStringRef)newAttrStr;
}
CFMutableAttributedStringRef CFAttributedStringCreateMutableCopy(CFAllocatorRef alloc, CFIndex maxLength, CFAttributedStringRef attrStr) {
// CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), CFMutableAttributedStringRef, (NSAttributedString *)attrStr, mutableCopy);
// WINOBJC: still needed
CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), CFMutableAttributedStringRef, (NSAttributedString *)attrStr, mutableCopy);
__CFAssertIsAttributedString(attrStr);
// !!! Need to deal with maxLength
return __CFAttributedStringCreateMutableWithSubstring(alloc, attrStr, CFRangeMake(0, CFStringGetLength(attrStr->string)));
}
/*** CFAttributedString functionality ***/
CFStringRef CFAttributedStringGetString(CFAttributedStringRef attrStr) {
CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), CFStringRef, (NSAttributedString *)attrStr, string);
__CFAssertIsAttributedString(attrStr);
return attrStr->string;
}
CFIndex CFAttributedStringGetLength(CFAttributedStringRef attrStr) {
CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), CFIndex, (NSAttributedString *)attrStr, length);
__CFAssertIsAttributedString(attrStr);
return CFStringGetLength(attrStr->string);
}
CFDictionaryRef CFAttributedStringGetAttributes(CFAttributedStringRef attrStr, CFIndex loc, CFRange *effectiveRange) {
CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), CFDictionaryRef, (NSAttributedString *)attrStr, attributesAtIndex:(NSUInteger)loc effectiveRange:(NSRange *)effectiveRange);
__CFAssertIsAttributedString(attrStr);
__CFAssertIndexIsInBounds(attrStr, loc);
return (CFDictionaryRef)CFRunArrayGetValueAtIndex(attrStr->attributeArray, loc, effectiveRange, NULL);
}
CFTypeRef CFAttributedStringGetAttribute(CFAttributedStringRef attrStr, CFIndex loc, CFStringRef attrName, CFRange *effectiveRange) {
CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), CFTypeRef, (NSAttributedString *)attrStr, attribute:(NSString *)attrName atIndex:(NSUInteger)loc effectiveRange:(NSRange *)effectiveRange);
__CFAssertIsAttributedString(attrStr);
__CFAssertIndexIsInBounds(attrStr, loc);
CFDictionaryRef attrs = (CFDictionaryRef)CFRunArrayGetValueAtIndex(attrStr->attributeArray, loc, effectiveRange, NULL);
return CFDictionaryGetValue(attrs, attrName);
}
CFDictionaryRef CFAttributedStringGetAttributesAndLongestEffectiveRange(CFAttributedStringRef attrStr, CFIndex location, CFRange rangeLimit, CFRange *longestEffectiveRange) {
CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), CFDictionaryRef, (NSAttributedString *)attrStr, attributesAtIndex:(NSUInteger)location longestEffectiveRange:(NSRange *)longestEffectiveRange inRange:NSMakeRange(rangeLimit.location, rangeLimit.length));
__CFAssertIsAttributedString(attrStr);
__CFAssertRangeIsInBounds(attrStr, rangeLimit.location, rangeLimit.length);
__CFAssertIndexIsInBounds(attrStr, location);
CFDictionaryRef attrs = CFAttributedStringGetAttributes(attrStr, location, longestEffectiveRange);
if (longestEffectiveRange) { // No need to do any of this if the range isn't desired
CFIndex leftEnd, rightEnd;
CFDictionaryRef other;
CFRange tmpRange;
// First go right and set rightEnd pointing past the end
tmpRange = *longestEffectiveRange;
do {
if ((rightEnd = tmpRange.location + tmpRange.length) >= rangeLimit.location + rangeLimit.length) break;
other = CFAttributedStringGetAttributes(attrStr, rightEnd, &tmpRange);
} while (CFEqual(other, attrs));
// Now go back and set leftEnd
tmpRange = *longestEffectiveRange;
do {
if ((leftEnd = tmpRange.location) <= rangeLimit.location) break;
other = CFAttributedStringGetAttributes(attrStr, leftEnd - 1, &tmpRange);
} while (CFEqual(other, attrs));
// This basically intersects the rangeLimit with leftEnd,rightEnd
longestEffectiveRange->location = (leftEnd < rangeLimit.location) ? rangeLimit.location : leftEnd;
CFIndex rangeEnd = rangeLimit.location + rangeLimit.length;
longestEffectiveRange->length = ((rangeEnd < rightEnd) ? rangeEnd : rightEnd) - longestEffectiveRange->location;
}
return attrs;
}
CFTypeRef CFAttributedStringGetAttributeAndLongestEffectiveRange(CFAttributedStringRef attrStr, CFIndex location, CFStringRef attrName, CFRange rangeLimit, CFRange *longestEffectiveRange) {
CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), CFTypeRef, (NSAttributedString *)attrStr, attribute:(NSString *)attrName atIndex:(NSUInteger)location longestEffectiveRange:(NSRange *)longestEffectiveRange inRange: NSMakeRange(rangeLimit.location, rangeLimit.length));
__CFAssertIsAttributedString(attrStr);
__CFAssertRangeIsInBounds(attrStr, rangeLimit.location, rangeLimit.length);
__CFAssertIndexIsInBounds(attrStr, location);
CFTypeRef attr = CFAttributedStringGetAttribute(attrStr, location, attrName, longestEffectiveRange);
if (longestEffectiveRange) { // No need to do any of this if the range isn't desired
CFIndex leftEnd, rightEnd;
CFTypeRef other;
CFRange tmpRange;
// First go right and set rightEnd pointing past the end
tmpRange = *longestEffectiveRange;
do {
if ((rightEnd = tmpRange.location + tmpRange.length) >= rangeLimit.location + rangeLimit.length) break;
other = CFAttributedStringGetAttribute(attrStr, rightEnd, attrName, &tmpRange);
} while ((other == attr) || (other && attr && CFEqual(other, attr))); // The first check is to catch nil as well
// Now go back and set leftEnd
tmpRange = *longestEffectiveRange;
do {
if ((leftEnd = tmpRange.location) <= rangeLimit.location) break;
other = CFAttributedStringGetAttribute(attrStr, leftEnd - 1, attrName, &tmpRange);
} while ((other == attr) || (other && attr && CFEqual(other, attr))); // The first check is to catch nil as well
// This basically intersects the rangeLimit with leftEnd,rightEnd
longestEffectiveRange->location = (leftEnd < rangeLimit.location) ? rangeLimit.location : leftEnd;
CFIndex rangeEnd = rangeLimit.location + rangeLimit.length;
longestEffectiveRange->length = ((rangeEnd < rightEnd) ? rangeEnd : rightEnd) - longestEffectiveRange->location;
}
return attr;
}
/* The next two functions are SPI which allow return bulk information about attributes. See CFAttributedStringPriv.h for info.
*/
CFIndex _CFAttributedStringGetNumberOfRuns(CFAttributedStringRef attrStr, Boolean includeEmpty) {
CFIndex numRuns = 0;
CFRange remainingRange = CFRangeMake(0, CFAttributedStringGetLength(attrStr));
while (remainingRange.length > 0) {
CFRange thisRange;
CFDictionaryRef dict = CFAttributedStringGetAttributesAndLongestEffectiveRange(attrStr, remainingRange.location, remainingRange, &thisRange);
if (includeEmpty || (CFDictionaryGetCount(dict) > 0)) numRuns++;
remainingRange.length -= thisRange.length;
remainingRange.location += thisRange.length;
}
return numRuns;
}
void _CFAttributedStringGetRuns(CFAttributedStringRef attrStr, Boolean includeEmpty, CFDictionaryRef *attrDictionaries, CFRange *runRanges) {
CFRange remainingRange = CFRangeMake(0, CFAttributedStringGetLength(attrStr));
while (remainingRange.length > 0) {
CFRange thisRange;
CFDictionaryRef dict = CFAttributedStringGetAttributesAndLongestEffectiveRange(attrStr, remainingRange.location, remainingRange, &thisRange);
if (includeEmpty || (CFDictionaryGetCount(dict) > 0)) {
if (attrDictionaries) *attrDictionaries++ = dict;
if (runRanges) *runRanges++ = thisRange;
}
remainingRange.length -= thisRange.length;
remainingRange.location += thisRange.length;
}
}
/*** CFMutableAttributedString functionality ***/
static void __CFDictionaryAddMultiple(CFMutableDictionaryRef dict, CFTypeRef *keys, CFTypeRef *values, CFIndex numAdditionalItems) {
CFIndex cnt;
for (cnt = 0; cnt < numAdditionalItems; cnt++) CFDictionarySetValue(dict, keys[cnt], values[cnt]);
}
/* ??? This is not properly implemented at this point! We need to return a proxy
*/
CFMutableStringRef CFAttributedStringGetMutableString(CFMutableAttributedStringRef attrStr) {
CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), CFMutableStringRef, (NSMutableAttributedString *)attrStr, mutableString);
return NULL; /* (CFMutableStringRef)(attrStr->string); */
}
void CFAttributedStringReplaceString(CFMutableAttributedStringRef attrStr, CFRange range, CFStringRef replacement) {
CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), void, (NSMutableAttributedString *)attrStr, replaceCharactersInRange: NSMakeRange(range.location, range.length) withString:(NSString *)replacement);
__CFAssertIsAttributedStringAndMutable(attrStr);
__CFAssertRangeIsInBounds(attrStr, range.location, range.length);
CFIndex replacementLen = CFStringGetLength(replacement);
CFMutableDictionaryRef attributesToBeUsed = NULL;
if (replacementLen > 0) {
// By default extend replaced attributes, or take them from the previous character
if (range.length > 0) {
attributesToBeUsed = (CFMutableDictionaryRef)CFRunArrayGetValueAtIndex(attrStr->attributeArray, range.location, NULL, NULL);
CFRetain(attributesToBeUsed);
} else if (range.location > 0) {
attributesToBeUsed = (CFMutableDictionaryRef)CFRunArrayGetValueAtIndex(attrStr->attributeArray, range.location - 1, NULL, NULL);
CFRetain(attributesToBeUsed);
} else if (CFStringGetLength(attrStr->string) > 0) {
attributesToBeUsed = (CFMutableDictionaryRef)CFRunArrayGetValueAtIndex(attrStr->attributeArray, 0, NULL, NULL);
CFRetain(attributesToBeUsed);
} else {
attributesToBeUsed = __CFAttributedStringCreateAttributesDictionary(CFGetAllocator(attrStr), NULL);
}
}
if (range.length > 0) {
CFRunArrayReplace(attrStr->attributeArray, range, attributesToBeUsed, replacementLen);
} else if (replacementLen) {
CFRunArrayInsert(attrStr->attributeArray, CFRangeMake(range.location, replacementLen), attributesToBeUsed);
}
if (attributesToBeUsed) CFRelease(attributesToBeUsed);
CFStringReplace((CFMutableStringRef)(attrStr->string), range, replacement);
// !!! [self edited:NSAttributedStringEditedCharacters range:range changeInLength:replacementLen - range.length];
}
void CFAttributedStringSetAttributes(CFMutableAttributedStringRef attrStr, CFRange range, CFDictionaryRef replacementAttrs, Boolean clearOtherAttributes) {
if (clearOtherAttributes) {
CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), void, (NSMutableAttributedString *)attrStr, setAttributes:(NSDictionary *)replacementAttrs range: NSMakeRange(range.location, range.length));
} else {
CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), void, (NSMutableAttributedString *)attrStr, addAttributes:(NSDictionary *)replacementAttrs range: NSMakeRange(range.location, range.length));
}
__CFAssertIsAttributedStringAndMutable(attrStr);
__CFAssertRangeIsInBounds(attrStr, range.location, range.length);
if (clearOtherAttributes) { // Just blast all attribute dictionaries in the specified range
if (range.length) {
CFMutableDictionaryRef attrs = __CFAttributedStringCreateAttributesDictionary(CFGetAllocator(attrStr), replacementAttrs);
CFRunArrayReplace(attrStr->attributeArray, range, attrs, range.length);
CFRelease(attrs);
// !!! [self edited:NSAttributedStringEditedAttributes range:range changeInLength:0];
}
} else { // More difficult --- set specified keys and values on the existing dictionaries in the specified range
CFIndex numAdditionalItems = CFDictionaryGetCount(replacementAttrs);
if (numAdditionalItems) {
// Extract the new keys and values so we don't do it over and over for each range
createLocalArray(additionalKeys, numAdditionalItems);
createLocalArray(additionalValues, numAdditionalItems);
CFDictionaryGetKeysAndValues(replacementAttrs, additionalKeys, additionalValues);
// CFAttributedStringBeginEditing(attrStr);
while (range.length) {
CFRange effectiveRange;
CFMutableDictionaryRef attrs = (CFMutableDictionaryRef)CFRunArrayGetValueAtIndex(attrStr->attributeArray, range.location, &effectiveRange, NULL);
// Intersect effectiveRange and range
if (effectiveRange.location < range.location) {
effectiveRange.length -= (range.location - effectiveRange.location);
effectiveRange.location = range.location;
}
if (effectiveRange.length > range.length) effectiveRange.length = range.length;
// We need to make a new copy
attrs = __CFAttributedStringCreateAttributesDictionary(CFGetAllocator(attrStr), attrs);
__CFDictionaryAddMultiple(attrs, additionalKeys, additionalValues, numAdditionalItems);
CFRunArrayReplace(attrStr->attributeArray, effectiveRange, attrs, effectiveRange.length);
CFRelease(attrs);
range.length -= effectiveRange.length;
range.location += effectiveRange.length;
}
// CFAttributedStringEndEditing(attrStr);
freeLocalArray(additionalKeys);
freeLocalArray(additionalValues);
}
}
}
void CFAttributedStringSetAttribute(CFMutableAttributedStringRef attrStr, CFRange range, CFStringRef attrName, CFTypeRef value) {
CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), void, (NSMutableAttributedString *)attrStr, addAttribute:(NSString *)attrName value:(id) value range:NSMakeRange(range.location, range.length));
__CFAssertIsAttributedStringAndMutable(attrStr);
__CFAssertRangeIsInBounds(attrStr, range.location, range.length);
// CFAttributedStringBeginEditing(attrStr);
while (range.length) {
CFRange effectiveRange;
// effectiveRange.location returned here may be equal to or smaller than range.location
CFMutableDictionaryRef attrs = (CFMutableDictionaryRef)CFRunArrayGetValueAtIndex(attrStr->attributeArray, range.location, &effectiveRange, NULL);
// Intersect effectiveRange and range
if (effectiveRange.location < range.location) {
effectiveRange.length -= (range.location - effectiveRange.location);
effectiveRange.location = range.location;
}
if (effectiveRange.length > range.length) effectiveRange.length = range.length;
// First check to see if the same value already exists; this will avoid a copy
CFTypeRef existingValue = CFDictionaryGetValue(attrs, attrName);
if (!existingValue || !CFEqual(existingValue, value)) {
// We need to make a new copy
attrs = __CFAttributedStringCreateAttributesDictionary(CFGetAllocator(attrStr), attrs);
CFDictionarySetValue(attrs, attrName, value);
CFRunArrayReplace(attrStr->attributeArray, effectiveRange, attrs, effectiveRange.length);
CFRelease(attrs);
}
range.length -= effectiveRange.length;
range.location += effectiveRange.length;
}
// CFAttributedStringEndEditing(attrStr);
}
void CFAttributedStringRemoveAttribute(CFMutableAttributedStringRef attrStr, CFRange range, CFStringRef attrName) {
CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), void, (NSMutableAttributedString *)attrStr, removeAttribute:(NSString *)attrName range:NSMakeRange(range.location, range.length));
__CFAssertIsAttributedStringAndMutable(attrStr);
__CFAssertRangeIsInBounds(attrStr, range.location, range.length);
// CFAttributedStringBeginEditing(attrStr);
while (range.length) {
CFRange effectiveRange;
CFMutableDictionaryRef attrs = (CFMutableDictionaryRef)CFRunArrayGetValueAtIndex(attrStr->attributeArray, range.location, &effectiveRange, NULL);
// Intersect effectiveRange and range
if (effectiveRange.location < range.location) {
effectiveRange.length -= (range.location - effectiveRange.location);
effectiveRange.location = range.location;
}
if (effectiveRange.length > range.length) effectiveRange.length = range.length;
// First check to see if the value is not there; this will avoid a copy
if (CFDictionaryContainsKey(attrs, attrName)) {
// We need to make a new copy
attrs = __CFAttributedStringCreateAttributesDictionary(CFGetAllocator(attrStr), attrs);
CFDictionaryRemoveValue(attrs, attrName);
CFRunArrayReplace(attrStr->attributeArray, effectiveRange, attrs, effectiveRange.length);
CFRelease(attrs);
}
range.length -= effectiveRange.length;
range.location += effectiveRange.length;
}
// CFAttributedStringEndEditing(attrStr);
}
void CFAttributedStringReplaceAttributedString(CFMutableAttributedStringRef attrStr, CFRange range, CFAttributedStringRef replacement) {
CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), void, (NSMutableAttributedString *)attrStr, replaceCharactersInRange:NSMakeRange(range.location, range.length) withAttributedString:(NSAttributedString *)replacement);
__CFAssertIsAttributedStringAndMutable(attrStr);
__CFAssertRangeIsInBounds(attrStr, range.location, range.length);
CFStringRef otherStr = CFAttributedStringGetString(replacement);
CFIndex stringLen = CFStringGetLength(otherStr);
if (stringLen > 0) {
CFAllocatorRef allocator = CFGetAllocator(attrStr);
CFRange attrRange = {0, 0};
while (attrRange.location < stringLen) {
CFDictionaryRef otherAttrs = CFAttributedStringGetAttributes(replacement, attrRange.location, &attrRange);
CFMutableDictionaryRef attrs = __CFAttributedStringCreateAttributesDictionary(allocator, otherAttrs);
CFRunArrayInsert(attrStr->attributeArray, CFRangeMake(attrRange.location + range.location, attrRange.length), attrs);
CFRelease(attrs);
attrRange.location += attrRange.length;
}
}
if (range.length > 0) CFRunArrayDelete(attrStr->attributeArray, CFRangeMake(range.location + stringLen, range.length));
CFStringReplace((CFMutableStringRef)(attrStr->string), range, otherStr);
// [self edited:NSAttributedStringEditedCharacters|NSAttributedStringEditedAttributes range:range changeInLength:stringLen - range.length];
}
void CFAttributedStringBeginEditing(CFMutableAttributedStringRef attrStr) {
CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), void, (NSMutableAttributedString *)attrStr, beginEditing);
}
void CFAttributedStringEndEditing(CFMutableAttributedStringRef attrStr) {
CF_OBJC_FUNCDISPATCHV(CFAttributedStringGetTypeID(), void, (NSMutableAttributedString *)attrStr, endEditing);
}
/*** Functions for NSCFAttributedString usage ***/
CFIndex _CFAttributedStringGetLength(CFAttributedStringRef attrStr) {
return CFStringGetLength(attrStr->string);
}
int _CFAttributedStringCheckAndReplace(CFMutableAttributedStringRef attrStr, CFRange range, CFStringRef replacement) {
CFIndex len = CFStringGetLength(attrStr->string);
if (range.location > len || (range.location + range.length > len)) return _CFStringErrBounds;
if (!__CFAttributedStringIsMutable(attrStr)) return _CFStringErrNotMutable;
CFAttributedStringReplaceString(attrStr, range, replacement); // ??? Do this faster!
return _CFStringErrNone;
}
int _CFAttributedStringCheckAndReplaceAttributed(CFMutableAttributedStringRef attrStr, CFRange range, CFAttributedStringRef replacement) {
CFIndex len = CFStringGetLength(attrStr->string);
if (range.location > len || (range.location + range.length > len)) return _CFStringErrBounds;
if (!__CFAttributedStringIsMutable(attrStr)) return _CFStringErrNotMutable;
if (replacement) { // Special: NULL means delete
CFAttributedStringReplaceAttributedString(attrStr, range, replacement); // ??? Do this faster!
} else {
CFAttributedStringReplaceString(attrStr, range, CFSTR(""));
}
return _CFStringErrNone;
}
int _CFAttributedStringCheckAndSetAttributes(CFMutableAttributedStringRef attrStr, CFRange range, CFTypeRef attrOrAttrs, Boolean clearOthers) {
CFIndex len = CFStringGetLength(attrStr->string);
if (range.location > len || (range.location + range.length > len)) return _CFStringErrBounds;
if (!__CFAttributedStringIsMutable(attrStr)) return _CFStringErrNotMutable;
CFAttributedStringSetAttributes(attrStr, range, (CFDictionaryRef)attrOrAttrs, clearOthers); // ??? Do this faster!
return _CFStringErrNone;
}
int _CFAttributedStringCheckAndSetAttribute(CFMutableAttributedStringRef attrStr, CFRange range, CFStringRef attrName, CFTypeRef attr) {
CFIndex len = CFStringGetLength(attrStr->string);
if (range.location > len || (range.location + range.length > len)) return _CFStringErrBounds;
if (!__CFAttributedStringIsMutable(attrStr)) return _CFStringErrNotMutable;
if (!attrName) return _CFStringErrNilArg;
if (attr) {
CFAttributedStringSetAttribute(attrStr, range, attrName, attr); // ??? Do this faster!
} else {
CFAttributedStringRemoveAttribute(attrStr, range, attrName); // ??? Do this faster!
}
return _CFStringErrNone;
}
// clang-format on
| {
"content_hash": "a10bf77da573decde678ac10389fa26e",
"timestamp": "",
"source": "github",
"line_count": 675,
"max_line_length": 276,
"avg_line_length": 52.97185185185185,
"alnum_prop": 0.7272345899988814,
"repo_name": "rajsesh-msft/WinObjC",
"id": "3dfcc2a57fdd0e9530c4b888c4a72c230b9c2dcf",
"size": "35846",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "Frameworks/CoreFoundation/String.subproj/CFAttributedString.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "13134"
},
{
"name": "C",
"bytes": "6326273"
},
{
"name": "C#",
"bytes": "132853"
},
{
"name": "C++",
"bytes": "3539189"
},
{
"name": "Lex",
"bytes": "4667"
},
{
"name": "M",
"bytes": "77709"
},
{
"name": "Makefile",
"bytes": "3446"
},
{
"name": "Objective-C",
"bytes": "8138616"
},
{
"name": "Objective-C++",
"bytes": "10325585"
},
{
"name": "PowerShell",
"bytes": "15625"
},
{
"name": "Python",
"bytes": "7658"
},
{
"name": "Yacc",
"bytes": "9740"
}
],
"symlink_target": ""
} |
Getting Started
###############
You have installed Elgg and worked through any potential initial issues. What now? Here are some
suggestions on how to to familiarize yourself with Elgg.
Focus first on core functionality
=================================
When you're new to Elgg, it's best to explore the stock features in core and its bundled plugins before installing any third party plugins. It's tempting install every interesting plugin from the community site, but exploring the core features builds a familiarity with Elgg's expected behavior, and prevents introducing any confusing bugs from third party plugin into your new Elgg network.
Elgg installs with a basic set of social network plugins activated: blogs, social bookmarking, files, groups, likes, message boards, wiki-like pages, user profiles, and microblogging. To change the plugins that are activated, log in as an admin user, then use the topbar to browse to Administration, then to Plugins on the right sidebar.
.. note:: The user you create during installation is an admin user.
Create test users
=================
Users can be created two ways in stock Elgg:
#. Complete the signup process using a different email address and username. (Logout first or use a different browser!)
#. Add a user through the Admin section by browsing to Administration -> Users -> Add New User.
.. note:: Users that self-register must validate their account through email before they can log in. Users that an admin creates are already validated.
Explore user functionality
==========================
Use your test users to create blogs, add widgets to your profile or dashboard, post to the Wire (microblogging), and create pages (wiki-like page creation). Investigate the Settings on the topbar. This is where a user sets notification settings and configures tools (which will be blank because none of the default plugins add controls here).
Explore admin functionality
===========================
All of the admin controls are found by clicking Administration in the topbar. The has a dashboard with a widget that explains the various sections. Change options in the Configure menu to change how Elgg looks and acts.
Extending Elgg
==============
After exploring what Elgg can do out of the box, install some themes and plugins. You can find many plugins and themes at the community site that have been developed by third parties. These plugins do everything from changing language strings, to adding chat, to completely redesigning Elgg's interface. Because these plugins are not official, be certain to check the comments to make sure you only install well-written plugins by high quality developers. | {
"content_hash": "f6369a357a9a49ab27222dd935dec546",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 455,
"avg_line_length": 76.34285714285714,
"alnum_prop": 0.7627245508982036,
"repo_name": "miniguez/novadores",
"id": "05e0fbec95518d1f1171f4bce29e78f1a6f26230",
"size": "2672",
"binary": false,
"copies": "20",
"ref": "refs/heads/master",
"path": "elgg/docs/admin/getting_started.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "5021"
},
{
"name": "Batchfile",
"bytes": "6697"
},
{
"name": "CSS",
"bytes": "9308"
},
{
"name": "HTML",
"bytes": "29934"
},
{
"name": "JavaScript",
"bytes": "123742"
},
{
"name": "Makefile",
"bytes": "6738"
},
{
"name": "PHP",
"bytes": "5638516"
},
{
"name": "Python",
"bytes": "8408"
},
{
"name": "Shell",
"bytes": "1127"
}
],
"symlink_target": ""
} |
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.technovalley21.layerlistexample;
public final class R {
public static final class array {
public static final int media_names=0x7f040000;
}
public static final class attr {
}
public static final class dimen {
/** Default screen margins, per the Android Design guidelines.
Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively).
*/
public static final int activity_horizontal_margin=0x7f050000;
public static final int activity_vertical_margin=0x7f050001;
}
public static final class drawable {
public static final int down_arrow=0x7f020000;
public static final int ic_launcher=0x7f020001;
public static final int ic_launcher2=0x7f020002;
public static final int layer_style=0x7f020003;
public static final int spinner_bg_style=0x7f020004;
}
public static final class id {
public static final int action_settings=0x7f090001;
public static final int spinner_outlet_type=0x7f090000;
}
public static final class layout {
public static final int activity_main=0x7f030000;
}
public static final class menu {
public static final int main=0x7f080000;
}
public static final class string {
public static final int action_settings=0x7f060002;
public static final int app_name=0x7f060000;
public static final int hello_world=0x7f060001;
}
public static final class style {
/**
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
Base application theme for API 11+. This theme completely replaces
AppBaseTheme from res/values/styles.xml on API 11+ devices.
API 11 theme customizations can go here.
Base application theme for API 14+. This theme completely replaces
AppBaseTheme from BOTH res/values/styles.xml and
res/values-v11/styles.xml on API 14+ devices.
API 14 theme customizations can go here.
*/
public static final int AppBaseTheme=0x7f070000;
/** Application theme.
All customizations that are NOT specific to a particular API-level can go here.
*/
public static final int AppTheme=0x7f070001;
}
}
| {
"content_hash": "2cec86523b67b073d669fc6d178611fb",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 91,
"avg_line_length": 38.18181818181818,
"alnum_prop": 0.6850340136054421,
"repo_name": "pengzhao001/android-apps",
"id": "5dec3e127235e14188f327f0728f7be522d3c821",
"size": "2940",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "LayerListExample/gen/com/technovalley21/layerlistexample/R.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "165"
},
{
"name": "HTML",
"bytes": "5542"
},
{
"name": "Java",
"bytes": "2987344"
}
],
"symlink_target": ""
} |
namespace Microsoft.ApplicationInsights.DataContracts
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using KellermanSoftware.CompareNetObjects;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.Implementation;
using Microsoft.ApplicationInsights.TestFramework;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class DependencyTelemetryTest
{
/// <summary>
/// The SDKs (and our customers) expect specific default values.
/// This test is to verify that changes to the schema don't unexpectedly change our public api.
/// </summary>
[TestMethod]
public void VerifyExpectedDefaultValue()
{
var defaultDependencyTelemetry = new DependencyTelemetry();
Assert.AreEqual(true, defaultDependencyTelemetry.Success, "Success is expected to be true");
Assert.IsNotNull(defaultDependencyTelemetry.Target);
Assert.IsNotNull(defaultDependencyTelemetry.Name);
Assert.IsNotNull(defaultDependencyTelemetry.Data);
Assert.IsNotNull(defaultDependencyTelemetry.ResultCode);
Assert.IsNotNull(defaultDependencyTelemetry.Type);
Assert.IsNotNull(defaultDependencyTelemetry.Id);
Assert.AreEqual(SamplingDecision.None, defaultDependencyTelemetry.ProactiveSamplingDecision);
Assert.AreEqual(SamplingTelemetryItemTypes.RemoteDependency, defaultDependencyTelemetry.ItemTypeFlag);
Assert.IsTrue(defaultDependencyTelemetry.Id.Length >= 1);
}
[TestMethod]
public void DependencyTelemetryITelemetryContractConsistentlyWithOtherTelemetryTypes()
{
new ITelemetryTest<DependencyTelemetry, AI.RemoteDependencyData>().Run();
}
[TestMethod]
public void DependencyTelemetryPropertiesFromContextAndItemSerializesToPropertiesInJson()
{
var expected = CreateRemoteDependencyTelemetry();
((ITelemetry)expected).Sanitize();
Assert.AreEqual(1, expected.Properties.Count);
Assert.AreEqual(1, expected.Context.GlobalProperties.Count);
Assert.IsTrue(expected.Properties.ContainsKey("TestProperty"));
Assert.IsTrue(expected.Context.GlobalProperties.ContainsKey("TestPropertyGlobal"));
var item = TelemetryItemTestHelper.SerializeDeserializeTelemetryItem<AI.AvailabilityData>(expected);
// Items added to both dependency.Properties, and dependency.Context.GlobalProperties are serialized to properties.
// IExtension object in CreateDependencyTelemetry adds 2 more properties: myIntField and myStringField
Assert.AreEqual(4, item.data.baseData.properties.Count);
Assert.IsTrue(item.data.baseData.properties.ContainsKey("TestPropertyGlobal"));
Assert.IsTrue(item.data.baseData.properties.ContainsKey("TestProperty"));
}
[TestMethod]
public void RemoteDependencyTelemetrySerializesToJson()
{
DependencyTelemetry expected = this.CreateRemoteDependencyTelemetry();
var item = TelemetryItemTestHelper.SerializeDeserializeTelemetryItem<AI.RemoteDependencyData>(expected);
Assert.AreEqual<DateTimeOffset>(expected.Timestamp, DateTimeOffset.Parse(item.time, null, System.Globalization.DateTimeStyles.AssumeUniversal));
Assert.AreEqual(expected.Sequence, item.seq);
Assert.AreEqual(expected.Context.InstrumentationKey, item.iKey);
AssertEx.AreEqual(expected.Context.SanitizedTags.ToArray(), item.tags.ToArray());
Assert.AreEqual(nameof(AI.RemoteDependencyData), item.data.baseType);
Assert.AreEqual(expected.Id, item.data.baseData.id);
Assert.AreEqual(expected.ResultCode, item.data.baseData.resultCode);
Assert.AreEqual(expected.Name, item.data.baseData.name);
Assert.AreEqual(expected.Duration, TimeSpan.Parse(item.data.baseData.duration));
Assert.AreEqual(expected.Type, item.data.baseData.type);
Assert.AreEqual(expected.Success, item.data.baseData.success);
// IExtension is currently flattened into the properties by serialization
Utils.CopyDictionary(((MyTestExtension)expected.Extension).SerializeIntoDictionary(), expected.Properties);
AssertEx.AreEqual(expected.Properties.ToArray(), item.data.baseData.properties.ToArray());
}
[TestMethod]
/// Test validates that if Serialize is called multiple times, and telemetry is modified
/// in between, serialize always gives the latest state.
public void RemoteDependencySerializationPicksUpCorrectState()
{
DependencyTelemetry expected = this.CreateRemoteDependencyTelemetry();
((ITelemetry)expected).Sanitize();
byte[] buf = new byte[1000000];
expected.SerializeData(new JsonSerializationWriter(new StreamWriter(new MemoryStream(buf))));
// Change the telemetry after serialization.
expected.Name = expected.Name + "new";
// Validate that the newly updated Name is picked up.
var item = TelemetryItemTestHelper.SerializeDeserializeTelemetryItem<AI.RemoteDependencyData>(expected);
Assert.AreEqual<DateTimeOffset>(expected.Timestamp, DateTimeOffset.Parse(item.time, null, System.Globalization.DateTimeStyles.AssumeUniversal));
Assert.AreEqual(expected.Sequence, item.seq);
Assert.AreEqual(expected.Context.InstrumentationKey, item.iKey);
AssertEx.AreEqual(expected.Context.SanitizedTags.ToArray(), item.tags.ToArray());
Assert.AreEqual(nameof(AI.RemoteDependencyData), item.data.baseType);
Assert.AreEqual(expected.Id, item.data.baseData.id);
Assert.AreEqual(expected.ResultCode, item.data.baseData.resultCode);
Assert.AreEqual(expected.Name, item.data.baseData.name);
Assert.AreEqual(expected.Duration, TimeSpan.Parse(item.data.baseData.duration));
Assert.AreEqual(expected.Type, item.data.baseData.type);
Assert.AreEqual(expected.Success, item.data.baseData.success);
AssertEx.AreEqual(expected.Properties.ToArray(), item.data.baseData.properties.ToArray());
}
[TestMethod]
public void SerializeWritesNullValuesAsExpectedByEndpoint()
{
DependencyTelemetry original = new DependencyTelemetry();
original.Name = null;
original.Data = null;
original.Type = null;
original.Success = null;
((ITelemetry)original).Sanitize();
var item = TelemetryItemTestHelper.SerializeDeserializeTelemetryItem<AI.RemoteDependencyData>(original);
Assert.AreEqual(2, item.data.baseData.ver);
}
[TestMethod]
public void SerializePopulatesRequiredFieldsOfDependencyTelemetry()
{
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
var depTelemetry = new DependencyTelemetry();
depTelemetry.Context.InstrumentationKey = Guid.NewGuid().ToString();
((ITelemetry)depTelemetry).Sanitize();
var item = TelemetryItemTestHelper.SerializeDeserializeTelemetryItem<AI.RemoteDependencyData>(depTelemetry);
Assert.AreEqual(2, item.data.baseData.ver);
Assert.IsNotNull(item.data.baseData.id);
Assert.IsNotNull(item.time);
Assert.AreEqual(new TimeSpan(), TimeSpan.Parse(item.data.baseData.duration));
Assert.IsTrue(item.data.baseData.success);
}
}
[TestMethod]
public void RemoteDependencyTelemetrySerializesStructuredIKeyToJsonCorrectlyPreservingPrefixCasing()
{
DependencyTelemetry expected = this.CreateRemoteDependencyTelemetry();
expected.Context.InstrumentationKey = "AIC-" + expected.Context.InstrumentationKey;
var item = TelemetryItemTestHelper.SerializeDeserializeTelemetryItem<AI.RemoteDependencyData>(expected);
Assert.AreEqual(expected.Context.InstrumentationKey, item.iKey);
}
[TestMethod]
public void RemoteDependencyTelemetrySerializeCommandNameToJson()
{
DependencyTelemetry expected = this.CreateRemoteDependencyTelemetry("Select * from Customers where CustomerID=@1");
var item = TelemetryItemTestHelper.SerializeDeserializeTelemetryItem<AI.RemoteDependencyData>(expected);
AI.RemoteDependencyData dp = item.data.baseData;
Assert.AreEqual(expected.Data, dp.data);
}
[TestMethod]
public void RemoteDependencyTelemetrySerializeNullCommandNameToJson()
{
DependencyTelemetry expected = this.CreateRemoteDependencyTelemetry(null);
var item = TelemetryItemTestHelper.SerializeDeserializeTelemetryItem<AI.RemoteDependencyData>(expected);
AI.RemoteDependencyData dp = item.data.baseData;
Assert.IsTrue(string.IsNullOrEmpty(dp.data));
}
[TestMethod]
public void RemoteDependencyTelemetrySerializeEmptyCommandNameToJson()
{
DependencyTelemetry expected = this.CreateRemoteDependencyTelemetry(string.Empty);
var item = TelemetryItemTestHelper.SerializeDeserializeTelemetryItem<AI.RemoteDependencyData>(expected);
AI.RemoteDependencyData dp = item.data.baseData;
Assert.IsTrue(string.IsNullOrEmpty(dp.data));
}
[TestMethod]
public void DependencyTypeNameDefaultsToEmptyInConstructor()
{
#pragma warning disable 618
var dependency = new DependencyTelemetry("name", "command name", DateTimeOffset.Now, TimeSpan.FromSeconds(42), false);
AssertEx.IsEmpty(dependency.DependencyKind);
#pragma warning restore 618
AssertEx.IsEmpty(dependency.Type);
}
[TestMethod]
public void SerttingDependencyKindSetsDependencyTypeName()
{
DependencyTelemetry expected = new DependencyTelemetry();
#pragma warning disable 618
expected.DependencyKind = "Http";
Assert.AreEqual("Http", expected.DependencyKind);
Assert.AreEqual("Http", expected.DependencyTypeName);
#pragma warning restore 618
}
[TestMethod]
public void SanitizeWillTrimAppropriateFields()
{
DependencyTelemetry telemetry = new DependencyTelemetry();
telemetry.Name = new string('Z', Property.MaxNameLength + 1);
telemetry.Data = new string('Y', Property.MaxDataLength + 1);
telemetry.Type = new string('D', Property.MaxDependencyTypeLength + 1);
telemetry.Properties.Add(new string('X', Property.MaxDictionaryNameLength) + 'X', new string('X', Property.MaxValueLength + 1));
telemetry.Properties.Add(new string('X', Property.MaxDictionaryNameLength) + 'Y', new string('X', Property.MaxValueLength + 1));
telemetry.Metrics.Add(new string('Y', Property.MaxDictionaryNameLength) + 'X', 42.0);
telemetry.Metrics.Add(new string('Y', Property.MaxDictionaryNameLength) + 'Y', 42.0);
((ITelemetry)telemetry).Sanitize();
Assert.AreEqual(new string('Z', Property.MaxNameLength), telemetry.Name);
Assert.AreEqual(new string('Y', Property.MaxDataLength), telemetry.Data);
Assert.AreEqual(new string('D', Property.MaxDependencyTypeLength), telemetry.Type);
Assert.AreEqual(2, telemetry.Properties.Count);
var t = new SortedList<string, string>(telemetry.Properties);
Assert.AreEqual(new string('X', Property.MaxDictionaryNameLength), t.Keys.ToArray()[1]);
Assert.AreEqual(new string('X', Property.MaxValueLength), t.Values.ToArray()[1]);
Assert.AreEqual(new string('X', Property.MaxDictionaryNameLength - 3) + "1", t.Keys.ToArray()[0]);
Assert.AreEqual(new string('X', Property.MaxValueLength), t.Values.ToArray()[0]);
Assert.AreSame(telemetry.Properties, telemetry.Properties);
Assert.AreEqual(2, telemetry.Metrics.Count);
var keys = telemetry.Metrics.Keys.OrderBy(s => s).ToArray();
Assert.AreEqual(new string('Y', Property.MaxDictionaryNameLength), keys[1]);
Assert.AreEqual(new string('Y', Property.MaxDictionaryNameLength - 3) + "1", keys[0]);
}
[TestMethod]
public void DependencyTelemetryImplementsISupportSamplingContract()
{
var telemetry = new DependencyTelemetry();
Assert.IsNotNull(telemetry as ISupportSampling);
}
[TestMethod]
public void DependencyTelemetryImplementsISupportAdvancedSamplingContract()
{
var telemetry = new DependencyTelemetry();
Assert.IsNotNull(telemetry as ISupportAdvancedSampling);
}
[TestMethod]
public void DependencyTelemetryHasCorrectValueOfSamplingPercentageAfterSerialization()
{
var telemetry = this.CreateRemoteDependencyTelemetry("mycommand");
((ISupportSampling)telemetry).SamplingPercentage = 10;
var item = TelemetryItemTestHelper.SerializeDeserializeTelemetryItem<AI.RemoteDependencyData>(telemetry);
Assert.AreEqual(10, item.sampleRate);
}
[TestMethod]
public void DependencyTelemetrySetGetOperationDetail()
{
const string key = "foo";
const string detail = "bar";
var telemetry = this.CreateRemoteDependencyTelemetry("mycommand");
telemetry.SetOperationDetail(key, detail);
Assert.IsTrue(telemetry.TryGetOperationDetail(key, out object retrievedValue));
Assert.IsNotNull(retrievedValue);
Assert.AreEqual(detail, retrievedValue.ToString());
// Clear and verify the detail is no longer present
new TelemetryClient(TelemetryConfiguration.CreateDefault()).TrackDependency(telemetry);
Assert.IsFalse(telemetry.TryGetOperationDetail(key, out retrievedValue));
}
[TestMethod]
public void DependencyTelemetryGetUnsetOperationDetail()
{
const string key = "foo";
var telemetry = this.CreateRemoteDependencyTelemetry("mycommand");
Assert.IsFalse(telemetry.TryGetOperationDetail(key, out object retrievedValue));
Assert.IsNull(retrievedValue);
// should not throw
new TelemetryClient(TelemetryConfiguration.CreateDefault()).TrackDependency(telemetry);
}
[TestMethod]
public void DependencyTelemetryDeepCloneCopiesAllProperties()
{
DependencyTelemetry telemetry = CreateRemoteDependencyTelemetry();
DependencyTelemetry other = (DependencyTelemetry)telemetry.DeepClone();
ComparisonConfig comparisonConfig = new ComparisonConfig();
CompareLogic deepComparator = new CompareLogic(comparisonConfig);
ComparisonResult result = deepComparator.Compare(telemetry, other);
Assert.IsTrue(result.AreEqual, result.DifferencesString);
}
[TestMethod]
public void DependencyTelemetryDeepCloneWithNullExtensionDoesNotThrow()
{
var telemetry = new DependencyTelemetry();
// Extension is not set, means it'll be null.
// Validate that cloning with null Extension does not throw.
var other = telemetry.DeepClone();
}
private DependencyTelemetry CreateRemoteDependencyTelemetry()
{
DependencyTelemetry item = new DependencyTelemetry
{
Timestamp = DateTimeOffset.Now,
Sequence = "4:2",
Name = "MyWebServer.cloudapp.net",
Duration = TimeSpan.FromMilliseconds(42),
Success = true,
Id = "DepID",
ResultCode = "200",
Type = "external call"
};
item.Context.InstrumentationKey = Guid.NewGuid().ToString();
item.Properties.Add("TestProperty", "TestValue");
item.Context.GlobalProperties.Add("TestPropertyGlobal", "TestValue");
item.Extension = new MyTestExtension() { myIntField = 42, myStringField = "value" };
return item;
}
private DependencyTelemetry CreateRemoteDependencyTelemetry(string commandName)
{
DependencyTelemetry item = this.CreateRemoteDependencyTelemetry();
item.Data = commandName;
return item;
}
}
} | {
"content_hash": "466c5c8c7f2ec2d6ee1eda7c4974e569",
"timestamp": "",
"source": "github",
"line_count": 357,
"max_line_length": 156,
"avg_line_length": 48.87675070028011,
"alnum_prop": 0.6586623875293713,
"repo_name": "pharring/ApplicationInsights-dotnet",
"id": "299d1d6fe78bc021a8d7166996c28f9436822750",
"size": "17451",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "BASE/Test/Microsoft.ApplicationInsights.Test/Microsoft.ApplicationInsights.Tests/DataContracts/DependencyTelemetryTest.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP.NET",
"bytes": "58230"
},
{
"name": "Batchfile",
"bytes": "17529"
},
{
"name": "C#",
"bytes": "8807345"
},
{
"name": "CSS",
"bytes": "30590"
},
{
"name": "Dockerfile",
"bytes": "527"
},
{
"name": "HTML",
"bytes": "45984"
},
{
"name": "JavaScript",
"bytes": "350192"
},
{
"name": "PowerShell",
"bytes": "64561"
},
{
"name": "TSQL",
"bytes": "1733"
}
],
"symlink_target": ""
} |
package org.apache.ignite;
import java.util.ArrayList;
import java.util.List;
import org.apache.ignite.marshaller.Marshaller;
import org.apache.ignite.marshaller.MarshallerContext;
import org.apache.ignite.marshaller.MarshallerContextTestImpl;
import org.apache.ignite.marshaller.jdk.JdkMarshaller;
import org.apache.ignite.internal.marshaller.optimized.OptimizedMarshaller;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
/**
* Base externalizable test class.
*/
public class IgniteExternalizableAbstractTest extends GridCommonAbstractTest {
/** */
private static final MarshallerContext CTX = new MarshallerContextTestImpl();
/**
* @return Marshallers.
*/
protected List<Marshaller> getMarshallers() {
List<Marshaller> marshallers = new ArrayList<>();
OptimizedMarshaller opt = new OptimizedMarshaller();
opt.setContext(CTX);
marshallers.add(new JdkMarshaller());
marshallers.add(opt);
return marshallers;
}
} | {
"content_hash": "161612a0cde16e26bb0ed47a7cfa24c6",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 81,
"avg_line_length": 28.583333333333332,
"alnum_prop": 0.7482993197278912,
"repo_name": "pperalta/ignite",
"id": "de8dfbef59de8f3c8872e77b7253eb3d9e484b75",
"size": "1831",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "modules/core/src/test/java/org/apache/ignite/IgniteExternalizableAbstractTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "39783"
},
{
"name": "C",
"bytes": "7463"
},
{
"name": "C#",
"bytes": "4030613"
},
{
"name": "C++",
"bytes": "2132957"
},
{
"name": "CSS",
"bytes": "98406"
},
{
"name": "Groovy",
"bytes": "15092"
},
{
"name": "HTML",
"bytes": "411123"
},
{
"name": "Java",
"bytes": "24428314"
},
{
"name": "JavaScript",
"bytes": "963263"
},
{
"name": "M4",
"bytes": "5528"
},
{
"name": "Makefile",
"bytes": "99146"
},
{
"name": "PHP",
"bytes": "11079"
},
{
"name": "PowerShell",
"bytes": "6281"
},
{
"name": "Scala",
"bytes": "681399"
},
{
"name": "Shell",
"bytes": "577613"
},
{
"name": "Smalltalk",
"bytes": "1908"
}
],
"symlink_target": ""
} |
package main
import (
"fmt"
"testing"
)
type tcase struct {
apkFile,
certFile,
vendor,
certType string
result bool
}
func TestCheckCert(t *testing.T) {
cases := []struct {
in tcase
}{
{tcase{"test/app-debug.apk", "/dev/null", "android", "release", false}},
{tcase{"/dev/null", "test/android.cert", "", "", false}},
{tcase{"/dev/random", "test/android.cert", "", "", false}},
{tcase{"test/app-debug.apk", "/dev/null", "", "", true}},
{tcase{"test/app-debug.apk", "test/android.cert", "android", "release", false}},
{tcase{"test/app-mediakey.apk", "", "android", "media", true}},
{tcase{"test/app-sharedkey.apk", "", "android", "shared", true}},
{tcase{"test/app-platformkey.apk", "", "android", "platform", true}},
{tcase{"test/app-releasekey.apk", "", "android", "release", true}},
{tcase{"test/app-unsigned.apk", "", "android", "release", false}},
}
for i, c := range cases {
fmt.Printf("Testing #%d case\n", i)
ret := Checkcert(c.in.apkFile, c.in.certFile, c.in.vendor, c.in.certType)
if ret != c.in.result {
t.Errorf("result incorrect in #%d test cases", i)
}
}
}
| {
"content_hash": "fc01dc068f96cbcd72060b637327798b",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 82,
"avg_line_length": 29.342105263157894,
"alnum_prop": 0.6080717488789238,
"repo_name": "ElvisChiang/androidtools",
"id": "7b9372f73a2cefc68ab298dc2cc39b71852a1762",
"size": "1115",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "checkcert_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "7042"
},
{
"name": "Shell",
"bytes": "3602"
}
],
"symlink_target": ""
} |
package org.squbs.stream.javasamples;
import akka.NotUsed;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.model.HttpResponse;
import akka.stream.Materializer;
import akka.stream.javadsl.Flow;
import org.squbs.marshallers.MarshalUnmarshal;
import org.squbs.stream.FlowToPerpetualStream;
import static org.squbs.marshallers.json.JacksonMapperSupport.unmarshaller;
class HttpFlowWithMergeHub extends FlowToPerpetualStream {
private final Materializer mat = Materializer.createMaterializer(context());
private final MarshalUnmarshal mu = new MarshalUnmarshal(context().system().dispatcher(), mat);
@Override
public Flow<HttpRequest, HttpResponse, NotUsed> flow() {
return Flow.<HttpRequest>create()
.mapAsync(1, req -> mu.apply(unmarshaller(MyMessage.class), req.entity()))
.alsoTo(matValue("/user/mycube/perpetualStreamWithMergeHub"))
.map(myMessage -> HttpResponse.create().withEntity("Received Id: " + myMessage.ip));
}
}
| {
"content_hash": "f7a72880390c4ba3c65fa367fa7ce424",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 100,
"avg_line_length": 40.96,
"alnum_prop": 0.7470703125,
"repo_name": "akara/squbs",
"id": "d4a2a8ac616f0798bcc50d9c8bfc3373e43df0e2",
"size": "1024",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "squbs-unicomplex/src/test/java/org/squbs/stream/javasamples/HttpFlowWithMergeHub.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "320007"
},
{
"name": "Scala",
"bytes": "1410957"
}
],
"symlink_target": ""
} |
package procstat
import (
"regexp"
"github.com/shirou/gopsutil/process"
)
//Pattern matches on the process name
func (pg *NativeFinder) Pattern(pattern string) ([]PID, error) {
var pids []PID
regxPattern, err := regexp.Compile(pattern)
if err != nil {
return pids, err
}
procs, err := process.Processes()
if err != nil {
return pids, err
}
for _, p := range procs {
name, err := p.Exe()
if err != nil {
//skip, this can be caused by the pid no longer existing
//or you having no permissions to access it
continue
}
if regxPattern.MatchString(name) {
pids = append(pids, PID(p.Pid))
}
}
return pids, err
}
| {
"content_hash": "a02be8e2c265236016db621aeeb71841",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 64,
"avg_line_length": 20.1875,
"alnum_prop": 0.6547987616099071,
"repo_name": "signalfx/telegraf",
"id": "33275460162d2fcccf9ebae6d23159d11124597c",
"size": "666",
"binary": false,
"copies": "1",
"ref": "refs/heads/signalfx-agent",
"path": "plugins/inputs/procstat/native_finder_notwindows.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "5277215"
},
{
"name": "Makefile",
"bytes": "3578"
},
{
"name": "Python",
"bytes": "37517"
},
{
"name": "Ragel",
"bytes": "7577"
},
{
"name": "Shell",
"bytes": "13945"
}
],
"symlink_target": ""
} |
<!-- title: custom -->
<div class="dev-header">
<a class="btn btn-default btn-sm" disabled style="margin-bottom: 10px;">
Version 6.x.x</a>
<a class="btn btn-default btn-sm" href="https://github.com/frappe/frappe/tree/develop/custom"
target="_blank" style="margin-left: 10px; margin-bottom: 10px;"><i class="octicon octicon-mark-github"></i> Source</a>
</div>
<h3>Package Contents</h3>
{index}
<!-- autodoc --> | {
"content_hash": "632524ad1ff01d5b2774bc1d5b2f4f0e",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 120,
"avg_line_length": 22.210526315789473,
"alnum_prop": 0.6658767772511849,
"repo_name": "jevonearth/frappe",
"id": "4d659752b229b7769e0a7533984f87b8c5454442",
"size": "422",
"binary": false,
"copies": "7",
"ref": "refs/heads/develop",
"path": "frappe/docs/current/api/custom/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "279822"
},
{
"name": "HTML",
"bytes": "1327148"
},
{
"name": "JavaScript",
"bytes": "1089936"
},
{
"name": "Python",
"bytes": "1226972"
},
{
"name": "Shell",
"bytes": "517"
}
],
"symlink_target": ""
} |
/**
* Comments REDUCER
*/
function postComments(state = [], action) {
switch (action.type) {
case 'ADD_COMMENT_DATA_RECEIVED':
return [...state, {
user: action.data.author,
text: action.data.comment
}];
case 'REMOVE_COMMENT_DATA_RECEIVED':
return [
...state.slice(0, action.index),
...state.slice(action.index + 1)
];
default:
return state;
}
return state;
}
function comments(state = [], action) {
console.log("ACTION: " + action.type);
if (typeof action.postId !== 'undefined') {
return {
...state,
[action.postId]: postComments(state[action.postId], action)
}
}
switch(action.type) {
case 'COMMENTS_DATA_RECEIVED':
return action.data;
default:
return state;
}
}
export default comments; | {
"content_hash": "58928b1e17ef5feca0f462857b70a04e",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 65,
"avg_line_length": 18.488888888888887,
"alnum_prop": 0.5805288461538461,
"repo_name": "rabbitfighter81/yodagram",
"id": "cd7bf05789b78c4a9c964f6baf691d3c39483302",
"size": "832",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/reducers/comments.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6130"
},
{
"name": "HTML",
"bytes": "294"
},
{
"name": "JavaScript",
"bytes": "37655"
}
],
"symlink_target": ""
} |
var secretNumber = 7;
var password = 'just open the door';
var allowedIn = false;
var members = ['John','chicken','apple pie','Mary'];
// __________________________________________
// Test Code: Do not alter code below this line.
function assert(test, message, test_number) {
if (!test) {
console.log(test_number + "false");
throw "ERROR: " + message;
}
console.log(test_number + "true");
return true;
}
assert(
(typeof secretNumber === 'number'),
"The value of secretNumber should be a number.",
"1. "
)
assert(
secretNumber === 7,
"The value of secretNumber should be 7.",
"2. "
)
assert(
typeof password === 'string',
"The value of password should be a string.",
"3. "
)
assert(
password === "just open the door",
"The value of password should be 'just open the door'.",
"4. "
)
assert(
typeof allowedIn === 'boolean',
"The value of allowedIn should be a boolean.",
"5. "
)
assert(
allowedIn === false,
"The value of allowedIn should be false.",
"6. "
)
assert(
members instanceof Array,
"The value of members should be an array",
"7. "
)
assert(
members[0] === "John",
"The first element in the value of members should be 'John'.",
"8. "
)
assert(
members[3] === "Mary",
"The fourth element in the value of members should be 'Mary'.",
"9. "
)
| {
"content_hash": "32259c727d1d7a2032f0417244836abf",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 65,
"avg_line_length": 18.246575342465754,
"alnum_prop": 0.6028528528528528,
"repo_name": "ian-kinner/phase-0",
"id": "763b9dda7bfd9a448e3072cba89ff923011b7920",
"size": "1484",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "week-7/variables-objects.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5048"
},
{
"name": "HTML",
"bytes": "24798"
},
{
"name": "JavaScript",
"bytes": "40646"
},
{
"name": "Ruby",
"bytes": "131033"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "2c6f88cba76c8316eb61734ebfa27498",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "a430795635130e605365be55046fbc344fb366cc",
"size": "184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Dryopteridaceae/Dryopteris/Dryopteris mannii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.apache.camel.component.webhook;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.spi.RestConfiguration;
import org.apache.camel.spi.UriParam;
import org.apache.camel.spi.UriParams;
import org.apache.camel.spi.UriPath;
import org.apache.camel.util.HostUtils;
import org.apache.camel.util.ObjectHelper;
/**
* Configuration class for the webhook component.
*/
@UriParams
public class WebhookConfiguration implements Cloneable {
/*
* Note: all properties start with the 'webhook' prefix to avoid collision with the delegate endpoint.
*/
@UriParam(label = "common")
private String webhookComponentName;
@UriParam(label = "common")
private String webhookExternalUrl;
@UriParam(label = "common")
private String webhookBasePath;
@UriParam(label = "common")
private String webhookPath;
@UriParam(label = "common", defaultValue = "true")
private boolean webhookAutoRegister = true;
@UriPath
private String endpointUri;
private RestConfiguration restConfiguration;
public WebhookConfiguration() {
}
public String getWebhookComponentName() {
return webhookComponentName;
}
/**
* Returns a copy of this configuration
*/
public WebhookConfiguration copy() {
try {
return (WebhookConfiguration) clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeCamelException(e);
}
}
/**
* Computes the external URL of the webhook as seen by the remote webhook provider.
*/
public String computeFullExternalUrl() throws UnknownHostException {
String externalServerUrl = this.webhookExternalUrl;
if (externalServerUrl == null) {
externalServerUrl = computeServerUriPrefix();
}
String path = computeFullPath(true);
return externalServerUrl + path;
}
/**
* Computes the URL of the webhook that should be used to bind the REST endpoint locally.
*/
public String computeServerUriPrefix() throws UnknownHostException {
// if no explicit port/host configured, then use port from rest configuration
String scheme = "http";
String host = "";
int port = 80;
if (restConfiguration.getScheme() != null) {
scheme = restConfiguration.getScheme();
}
if (restConfiguration.getHost() != null) {
host = restConfiguration.getHost();
}
int num = restConfiguration.getPort();
if (num > 0) {
port = num;
}
// if no explicit hostname set then resolve the hostname
if (ObjectHelper.isEmpty(host)) {
if (restConfiguration.getHostNameResolver() == RestConfiguration.RestHostNameResolver.allLocalIp) {
host = "0.0.0.0";
} else if (restConfiguration.getHostNameResolver() == RestConfiguration.RestHostNameResolver.localHostName) {
host = HostUtils.getLocalHostName();
} else if (restConfiguration.getHostNameResolver() == RestConfiguration.RestHostNameResolver.localIp) {
host = HostUtils.getLocalIp();
}
}
return scheme + "://" + host + (port != 80 ? ":" + port : "");
}
/**
* Computes the path part of the webhook.
*
* @param external indicates if it's the path seen by the external provider or the internal one.
* @return the webhook full path
*/
public String computeFullPath(boolean external) {
// calculate the url to the rest service
String path = this.webhookPath;
if (path == null) {
path = computeDefaultPath(getEndpointUri());
} else if (!path.startsWith("/")) {
path = "/" + path;
}
if (this.webhookBasePath != null) {
if (!this.webhookBasePath.startsWith("/")) {
path = "/" + this.webhookBasePath + path;
} else {
path = this.webhookBasePath + path;
}
}
if (external) {
String contextPath = restConfiguration.getContextPath();
if (contextPath != null) {
if (!contextPath.startsWith("/")) {
path = "/" + contextPath + path;
} else {
path = contextPath + path;
}
}
}
return path;
}
/**
* A default path is computed for the webhook if not provided by the user.
* It uses a hash of the delegate endpoint in order for it to be reproducible.
*
* This is not random on purpose.
*/
protected static String computeDefaultPath(String uri) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(uri.getBytes(StandardCharsets.UTF_8));
byte[] digest = md.digest();
return "/" + Base64.getUrlEncoder().encodeToString(digest);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeCamelException("Cannot compute default webhook path", e);
}
}
public String getEndpointUri() {
return endpointUri;
}
/**
* The delegate uri. Must belong to a component that supports webhooks.
*/
public void setEndpointUri(String endpointUri) {
this.endpointUri = endpointUri;
}
public RestConfiguration getRestConfiguration() {
return restConfiguration;
}
/**
* The Camel Rest Configuration used by the webhook.
*/
public void setRestConfiguration(RestConfiguration restConfiguration) {
this.restConfiguration = restConfiguration;
}
/**
* The Camel Rest component to use for the REST transport, such as netty-http.
*/
public void setWebhookComponentName(String webhookComponentName) {
this.webhookComponentName = webhookComponentName;
}
public String getWebhookExternalUrl() {
return webhookExternalUrl;
}
/**
* The URL of the current service as seen by the webhook provider
*/
public void setWebhookExternalUrl(String webhookExternalUrl) {
this.webhookExternalUrl = webhookExternalUrl;
}
public String getWebhookBasePath() {
return webhookBasePath;
}
/**
* The first (base) path element where the webhook will be exposed.
* It's a good practice to set it to a random string, so that it cannot be guessed by unauthorized parties.
*/
public void setWebhookBasePath(String webhookBasePath) {
this.webhookBasePath = webhookBasePath;
}
public String getWebhookPath() {
return webhookPath;
}
/**
* The path where the webhook endpoint will be exposed (relative to basePath, if any)
*/
public void setWebhookPath(String webhookPath) {
this.webhookPath = webhookPath;
}
public boolean isWebhookAutoRegister() {
return webhookAutoRegister;
}
/**
* Automatically register the webhook at startup and unregister it on shutdown.
*/
public void setWebhookAutoRegister(boolean webhookAutoRegister) {
this.webhookAutoRegister = webhookAutoRegister;
}
}
| {
"content_hash": "3485a63120dd93fce5e1ba10bc75398b",
"timestamp": "",
"source": "github",
"line_count": 240,
"max_line_length": 121,
"avg_line_length": 30.966666666666665,
"alnum_prop": 0.6332077502691066,
"repo_name": "CodeSmell/camel",
"id": "be3a58ccfc0906089cddc875633d9874bf8aa494",
"size": "8234",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "components/camel-webhook/src/main/java/org/apache/camel/component/webhook/WebhookConfiguration.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Apex",
"bytes": "6521"
},
{
"name": "Batchfile",
"bytes": "2353"
},
{
"name": "CSS",
"bytes": "5472"
},
{
"name": "Elm",
"bytes": "10852"
},
{
"name": "FreeMarker",
"bytes": "8015"
},
{
"name": "Groovy",
"bytes": "20838"
},
{
"name": "HTML",
"bytes": "915679"
},
{
"name": "Java",
"bytes": "80453693"
},
{
"name": "JavaScript",
"bytes": "100326"
},
{
"name": "Makefile",
"bytes": "513"
},
{
"name": "RobotFramework",
"bytes": "8461"
},
{
"name": "Shell",
"bytes": "17295"
},
{
"name": "TSQL",
"bytes": "28835"
},
{
"name": "Tcl",
"bytes": "4974"
},
{
"name": "Thrift",
"bytes": "6979"
},
{
"name": "XQuery",
"bytes": "546"
},
{
"name": "XSLT",
"bytes": "280849"
}
],
"symlink_target": ""
} |
<!--
Copyright 2010 The Kuali Foundation
Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
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.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:dd="http://rice.kuali.org/dd"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://rice.kuali.org/dd
http://rice.kuali.org/dd/dd.xsd">
<bean id="ClassCodeMaintenanceDocument" parent="ClassCodeMaintenanceDocument-parentBean" />
<bean id="ClassCodeMaintenanceDocument-parentBean" abstract="true" parent="MaintenanceDocumentEntry">
<property name="businessObjectClass" value="org.kuali.kfs.module.endow.businessobject.ClassCode" />
<property name="maintainableClass" value="org.kuali.rice.kns.maintenance.KualiMaintainableImpl" />
<property name="maintainableSections" >
<list>
<ref bean="ClassCodeMaintenanceDocument-EditClassCode" />
</list>
</property>
<property name="defaultExistenceChecks" >
<list>
<bean parent="ReferenceDefinition"
p:attributeName="endowmentTransactionCode"
p:attributeToHighlightOnFail="securityEndowmentTransactionCode" />
<bean parent="ReferenceDefinition"
p:attributeName="incomeEndowmentTransactionPost"
p:attributeToHighlightOnFail="securityIncomeEndowmentTransactionPostCode" />
<bean parent="ReferenceDefinition"
p:attributeName="reportingGroup"
p:attributeToHighlightOnFail="securityReportingGrp" />
<bean parent="ReferenceDefinition"
p:attributeName="accrualMethod"
p:attributeToHighlightOnFail="securityAccrualMethod" />
<bean parent="ReferenceDefinition"
p:attributeName="securityValuationMethod"
p:attributeToHighlightOnFail="valuationMethod" />
</list>
</property>
<property name="lockingKeys" >
<list>
<value>code</value>
</list>
</property>
<property name="documentTypeName" value="ClassCodeMaintenanceDocument" />
<property name="businessRulesClass" value="org.kuali.kfs.module.endow.document.validation.impl.ClassCodeRule" />
<property name="documentAuthorizerClass" value="org.kuali.kfs.sys.document.authorization.FinancialSystemMaintenanceDocumentAuthorizerBase" />
<property name="documentPresentationControllerClass" value="org.kuali.kfs.module.endow.document.authorization.ClassCodeDocumentPresentationController" />
<property name="webScriptFiles" >
<list>
<value>../dwr/interface/EndowmentTransactionCodeService.js</value>
<value>../scripts/module/endow/transactionCode.js</value>
</list>
</property>
<property name="workflowAttributes">
<ref bean="ClassCodeMaintenanceDocument-workflowAttributes" />
</property>
</bean>
<!-- Maintenance Section Definitions -->
<bean id="ClassCodeMaintenanceDocument-EditClassCode" parent="ClassCodeMaintenanceDocument-EditClassCode-parentBean" />
<bean id="ClassCodeMaintenanceDocument-EditClassCode-parentBean" abstract="true" parent="ClassCodeMaintenanceDocument-ClassCodeTransaction-parentBean" />
<bean id="ClassCodeMaintenanceDocument-ClassCodeTransaction-parentBean" abstract="true" parent="MaintainableSectionDefinition">
<property name="id" value="Edit Class Code" />
<property name="title" value="Edit Class Code" />
<property name="maintainableItems" >
<list>
<bean parent="MaintainableFieldDefinition"
p:name="code"
p:required="true" />
<bean parent="MaintainableFieldDefinition"
p:name="name"
p:required="true" />
<bean parent="MaintainableFieldDefinition"
p:name="securityReportingGrp"
p:required="true" />
<bean parent="MaintainableFieldDefinition"
p:name="securityAccrualMethod"
p:required="true"
p:defaultValue="N" />
<bean parent="MaintainableFieldDefinition"
p:name="securityEndowmentTransactionCode"
p:required="true"
p:webUILeaveFieldFunction="loadEndTransDesc" />
<bean parent="MaintainableFieldDefinition"
p:name="endowmentTransactionCode.name"
p:unconditionallyReadOnly="true" />
<bean parent="MaintainableFieldDefinition"
p:name="securityIncomeEndowmentTransactionPostCode"
p:required="true"
p:webUILeaveFieldFunction="loadIncEndTransPostDesc"/>
<bean parent="MaintainableFieldDefinition"
p:name="incomeEndowmentTransactionPost.name"
p:unconditionallyReadOnly="true" />
<bean parent="MaintainableFieldDefinition"
p:name="taxLotIndicator"
p:defaultValue="false" />
<bean parent="MaintainableFieldDefinition"
p:name="classCodeType"
p:required="true" />
<bean parent="MaintainableFieldDefinition"
p:name="valuationMethod"
p:required="true"
p:defaultValue="U" />
<bean parent="MaintainableFieldDefinition"
p:name="active"
p:defaultValue="true" />
</list>
</property>
</bean>
<!-- workflow attributes -->
<bean id="ClassCodeMaintenanceDocument-workflowAttributes" parent="ClassCodeMaintenanceDocument-workflowAttributes-parentBean" />
<bean id="ClassCodeMaintenanceDocument-workflowAttributes-parentBean" abstract="true" parent="WorkflowAttributes">
</bean>
</beans>
| {
"content_hash": "2cce3f823f92b106d9e1014644146690",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 157,
"avg_line_length": 47.05925925925926,
"alnum_prop": 0.6760585550133795,
"repo_name": "Ariah-Group/Finance",
"id": "512c3d4195c546cba920a7fd8515510b58c37505",
"size": "6353",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "af_webapp/src/main/resources/org/kuali/kfs/module/endow/document/datadictionary/ClassCodeMaintenanceDocument.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
define([],
function () {
var getGovUkUrl = function (req) {
return ['https://', req.app.get('govukHost'), req.originalUrl].join('');
};
var commonConfig = function (req) {
return {
url: req.originalUrl,
govukUrl: this.getGovUkUrl(req),
requirePath: req.app.get('requirePath'),
assetPath: req.app.get('assetPath'),
assetDigest: req.app.get('assetDigest'),
environment: req.app.get('environment'),
backdropUrl: req.app.get('backdropUrl'),
clientRequiresCors: req.app.get('clientRequiresCors'),
bigScreenBaseURL: req.app.get('bigScreenBaseURL'),
requestId: req.get('Request-Id'),
govukRequestId: req.get('GOVUK-Request-Id')
};
};
var PageConfig = {};
PageConfig.getGovUkUrl = getGovUkUrl;
PageConfig.commonConfig = commonConfig;
return PageConfig;
});
| {
"content_hash": "32f719656087676ccc5872858197b97c",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 76,
"avg_line_length": 29.20689655172414,
"alnum_prop": 0.6505312868949232,
"repo_name": "tijmenb/spotlight",
"id": "2866aa243e539e57bceb3f65083ddc840df419cf",
"size": "847",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/page_config.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "73090"
},
{
"name": "HTML",
"bytes": "46589"
},
{
"name": "JavaScript",
"bytes": "894433"
},
{
"name": "Shell",
"bytes": "160"
}
],
"symlink_target": ""
} |
package org.kuali.rice.krad.lookup;
import org.kuali.rice.krad.uif.view.ViewPresentationControllerBase;
/**
* Implementation of {@link org.kuali.rice.krad.uif.view.ViewPresentationController} for
* {@link org.kuali.rice.krad.uif.view.LookupView} instances
*
* <p>
* Adds flag for export of inquiry record
* </p>
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public class LookupViewPresentationControllerBase extends ViewPresentationControllerBase {
private static final long serialVersionUID = -1571703041784821056L;
}
| {
"content_hash": "32dc43860b542b917ce732b89691ae15",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 90,
"avg_line_length": 28.3,
"alnum_prop": 0.7402826855123675,
"repo_name": "ua-eas/ksd-kc5.2.1-rice2.3.6-ua",
"id": "7c8f51e6abfaf28c4190fe5ff8854998ad8a11e7",
"size": "1201",
"binary": false,
"copies": "2",
"ref": "refs/heads/development",
"path": "rice-framework/krad-web-framework/src/main/java/org/kuali/rice/krad/lookup/LookupViewPresentationControllerBase.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "542248"
},
{
"name": "Groovy",
"bytes": "2403552"
},
{
"name": "HTML",
"bytes": "3275928"
},
{
"name": "Java",
"bytes": "30805440"
},
{
"name": "JavaScript",
"bytes": "2486893"
},
{
"name": "PHP",
"bytes": "15766"
},
{
"name": "PLSQL",
"bytes": "108325"
},
{
"name": "SQLPL",
"bytes": "51212"
},
{
"name": "Shell",
"bytes": "1808"
},
{
"name": "XSLT",
"bytes": "109576"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.Linq;
using Baseline;
using Oakton.Descriptions;
using Spectre.Console;
namespace Jasper.RabbitMQ.Internal
{
public partial class RabbitMqTransport : ITreeDescriber
{
void ITreeDescriber.Describe(TreeNode parentNode)
{
var props = new Dictionary<string, object>
{
{ "HostName", ConnectionFactory.HostName },
{ "Port", ConnectionFactory.Port == -1 ? 5672 : ConnectionFactory.Port },
{ nameof(AutoProvision), AutoProvision },
{ nameof(AutoPurgeAllQueues), AutoPurgeAllQueues }
};
var table = props.BuildTableForProperties();
parentNode.AddNode(table);
if (Exchanges.Any())
{
var exchangesNode = parentNode.AddNode("Exchanges");
foreach (var exchange in Exchanges)
{
var exchangeNode = exchangesNode.AddNode(exchange.Name);
if (exchange.Bindings().Any())
{
var bindings = exchangeNode.AddNode("Bindings");
var bindingTable = new Table();
bindingTable.AddColumn("Key");
bindingTable.AddColumn("Queue Name");
bindingTable.AddColumn("Arguments");
foreach (var binding in exchange.Bindings())
{
bindingTable.AddRow(binding.BindingKey ?? string.Empty, binding.Queue.Name ?? string.Empty,
binding.Arguments.Select(pair => $"{pair.Key}={pair.Value}").Join(", "));
}
bindings.AddNode(bindingTable);
}
}
}
var queueNode = parentNode.AddNode("Queues");
foreach (var queue in Queues) queueNode.AddNode(queue.Name);
}
}
}
| {
"content_hash": "25c8199d41583e2e7583d906f2596563",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 119,
"avg_line_length": 36.4,
"alnum_prop": 0.5164835164835165,
"repo_name": "JasperFx/jasper",
"id": "c162a3aca7f3b86f961ef5989377f4d42ccbe8aa",
"size": "2002",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Jasper.RabbitMQ/Internal/RabbitMqTransport.Describes.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "357"
},
{
"name": "C#",
"bytes": "2043884"
},
{
"name": "PowerShell",
"bytes": "297"
},
{
"name": "Ruby",
"bytes": "7354"
},
{
"name": "Shell",
"bytes": "98"
}
],
"symlink_target": ""
} |
package org.elasticsearch.rest.action.cat;
import org.elasticsearch.action.admin.cluster.state.ClusterStateRequest;
import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse;
import org.elasticsearch.action.admin.indices.stats.CommonStats;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsRequest;
import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
import org.elasticsearch.action.admin.indices.stats.ShardStats;
import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.UnassignedInfo;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.Table;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.engine.CommitStats;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.RestActionListener;
import org.elasticsearch.rest.action.RestResponseListener;
import java.util.Locale;
import static org.elasticsearch.rest.RestRequest.Method.GET;
public class RestShardsAction extends AbstractCatAction {
public RestShardsAction(Settings settings, RestController controller) {
super(settings);
controller.registerHandler(GET, "/_cat/shards", this);
controller.registerHandler(GET, "/_cat/shards/{index}", this);
}
@Override
public String getName() {
return "cat_shards_action";
}
@Override
protected void documentation(StringBuilder sb) {
sb.append("/_cat/shards\n");
sb.append("/_cat/shards/{index}\n");
}
@Override
public RestChannelConsumer doCatRequest(final RestRequest request, final NodeClient client) {
final String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
final ClusterStateRequest clusterStateRequest = new ClusterStateRequest();
clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local()));
clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout()));
clusterStateRequest.clear().nodes(true).metaData(true).routingTable(true).indices(indices);
return channel -> client.admin().cluster().state(clusterStateRequest, new RestActionListener<ClusterStateResponse>(channel) {
@Override
public void processResponse(final ClusterStateResponse clusterStateResponse) {
IndicesStatsRequest indicesStatsRequest = new IndicesStatsRequest();
indicesStatsRequest.all();
indicesStatsRequest.indices(indices);
client.admin().indices().stats(indicesStatsRequest, new RestResponseListener<IndicesStatsResponse>(channel) {
@Override
public RestResponse buildResponse(IndicesStatsResponse indicesStatsResponse) throws Exception {
return RestTable.buildResponse(buildTable(request, clusterStateResponse, indicesStatsResponse), channel);
}
});
}
});
}
@Override
protected Table getTableWithHeader(final RestRequest request) {
Table table = new Table();
table.startHeaders()
.addCell("index", "default:true;alias:i,idx;desc:index name")
.addCell("shard", "default:true;alias:s,sh;desc:shard name")
.addCell("prirep", "alias:p,pr,primaryOrReplica;default:true;desc:primary or replica")
.addCell("state", "default:true;alias:st;desc:shard state")
.addCell("docs", "alias:d,dc;text-align:right;desc:number of docs in shard")
.addCell("store", "alias:sto;text-align:right;desc:store size of shard (how much disk it uses)")
.addCell("ip", "default:true;desc:ip of node where it lives")
.addCell("id", "default:false;desc:unique id of node where it lives")
.addCell("node", "default:true;alias:n;desc:name of node where it lives");
table.addCell("sync_id", "alias:sync_id;default:false;desc:sync id");
table.addCell("unassigned.reason", "alias:ur;default:false;desc:reason shard is unassigned");
table.addCell("unassigned.at", "alias:ua;default:false;desc:time shard became unassigned (UTC)");
table.addCell("unassigned.for", "alias:uf;default:false;text-align:right;desc:time has been unassigned");
table.addCell("unassigned.details", "alias:ud;default:false;desc:additional details as to why the shard became unassigned");
table.addCell("recoverysource.type", "alias:rs;default:false;desc:recovery source type");
table.addCell("completion.size", "alias:cs,completionSize;default:false;text-align:right;desc:size of completion");
table.addCell("fielddata.memory_size", "alias:fm,fielddataMemory;default:false;text-align:right;desc:used fielddata cache");
table.addCell("fielddata.evictions", "alias:fe,fielddataEvictions;default:false;text-align:right;desc:fielddata evictions");
table.addCell("query_cache.memory_size", "alias:qcm,queryCacheMemory;default:false;text-align:right;desc:used query cache");
table.addCell("query_cache.evictions", "alias:qce,queryCacheEvictions;default:false;text-align:right;desc:query cache evictions");
table.addCell("flush.total", "alias:ft,flushTotal;default:false;text-align:right;desc:number of flushes");
table.addCell("flush.total_time", "alias:ftt,flushTotalTime;default:false;text-align:right;desc:time spent in flush");
table.addCell("get.current", "alias:gc,getCurrent;default:false;text-align:right;desc:number of current get ops");
table.addCell("get.time", "alias:gti,getTime;default:false;text-align:right;desc:time spent in get");
table.addCell("get.total", "alias:gto,getTotal;default:false;text-align:right;desc:number of get ops");
table.addCell("get.exists_time", "alias:geti,getExistsTime;default:false;text-align:right;desc:time spent in successful gets");
table.addCell("get.exists_total", "alias:geto,getExistsTotal;default:false;text-align:right;desc:number of successful gets");
table.addCell("get.missing_time", "alias:gmti,getMissingTime;default:false;text-align:right;desc:time spent in failed gets");
table.addCell("get.missing_total", "alias:gmto,getMissingTotal;default:false;text-align:right;desc:number of failed gets");
table.addCell("indexing.delete_current", "alias:idc,indexingDeleteCurrent;default:false;text-align:right;desc:number of current deletions");
table.addCell("indexing.delete_time", "alias:idti,indexingDeleteTime;default:false;text-align:right;desc:time spent in deletions");
table.addCell("indexing.delete_total", "alias:idto,indexingDeleteTotal;default:false;text-align:right;desc:number of delete ops");
table.addCell("indexing.index_current", "alias:iic,indexingIndexCurrent;default:false;text-align:right;desc:number of current indexing ops");
table.addCell("indexing.index_time", "alias:iiti,indexingIndexTime;default:false;text-align:right;desc:time spent in indexing");
table.addCell("indexing.index_total", "alias:iito,indexingIndexTotal;default:false;text-align:right;desc:number of indexing ops");
table.addCell("indexing.index_failed", "alias:iif,indexingIndexFailed;default:false;text-align:right;desc:number of failed indexing ops");
table.addCell("merges.current", "alias:mc,mergesCurrent;default:false;text-align:right;desc:number of current merges");
table.addCell("merges.current_docs", "alias:mcd,mergesCurrentDocs;default:false;text-align:right;desc:number of current merging docs");
table.addCell("merges.current_size", "alias:mcs,mergesCurrentSize;default:false;text-align:right;desc:size of current merges");
table.addCell("merges.total", "alias:mt,mergesTotal;default:false;text-align:right;desc:number of completed merge ops");
table.addCell("merges.total_docs", "alias:mtd,mergesTotalDocs;default:false;text-align:right;desc:docs merged");
table.addCell("merges.total_size", "alias:mts,mergesTotalSize;default:false;text-align:right;desc:size merged");
table.addCell("merges.total_time", "alias:mtt,mergesTotalTime;default:false;text-align:right;desc:time spent in merges");
table.addCell("refresh.total", "alias:rto,refreshTotal;default:false;text-align:right;desc:total refreshes");
table.addCell("refresh.time", "alias:rti,refreshTime;default:false;text-align:right;desc:time spent in refreshes");
table.addCell("refresh.listeners", "alias:rli,refreshListeners;default:false;text-align:right;desc:number of pending refresh listeners");
table.addCell("search.fetch_current", "alias:sfc,searchFetchCurrent;default:false;text-align:right;desc:current fetch phase ops");
table.addCell("search.fetch_time", "alias:sfti,searchFetchTime;default:false;text-align:right;desc:time spent in fetch phase");
table.addCell("search.fetch_total", "alias:sfto,searchFetchTotal;default:false;text-align:right;desc:total fetch ops");
table.addCell("search.open_contexts", "alias:so,searchOpenContexts;default:false;text-align:right;desc:open search contexts");
table.addCell("search.query_current", "alias:sqc,searchQueryCurrent;default:false;text-align:right;desc:current query phase ops");
table.addCell("search.query_time", "alias:sqti,searchQueryTime;default:false;text-align:right;desc:time spent in query phase");
table.addCell("search.query_total", "alias:sqto,searchQueryTotal;default:false;text-align:right;desc:total query phase ops");
table.addCell("search.scroll_current", "alias:scc,searchScrollCurrent;default:false;text-align:right;desc:open scroll contexts");
table.addCell("search.scroll_time", "alias:scti,searchScrollTime;default:false;text-align:right;desc:time scroll contexts held open");
table.addCell("search.scroll_total", "alias:scto,searchScrollTotal;default:false;text-align:right;desc:completed scroll contexts");
table.addCell("segments.count", "alias:sc,segmentsCount;default:false;text-align:right;desc:number of segments");
table.addCell("segments.memory", "alias:sm,segmentsMemory;default:false;text-align:right;desc:memory used by segments");
table.addCell("segments.index_writer_memory", "alias:siwm,segmentsIndexWriterMemory;default:false;text-align:right;desc:memory used by index writer");
table.addCell("segments.version_map_memory", "alias:svmm,segmentsVersionMapMemory;default:false;text-align:right;desc:memory used by version map");
table.addCell("segments.fixed_bitset_memory", "alias:sfbm,fixedBitsetMemory;default:false;text-align:right;desc:memory used by fixed bit sets for nested object field types and type filters for types referred in _parent fields");
table.addCell("seq_no.max", "alias:sqm,maxSeqNo;default:false;text-align:right;desc:max sequence number");
table.addCell("seq_no.local_checkpoint", "alias:sql,localCheckpoint;default:false;text-align:right;desc:local checkpoint");
table.addCell("seq_no.global_checkpoint", "alias:sqg,globalCheckpoint;default:false;text-align:right;desc:global checkpoint");
table.addCell("warmer.current", "alias:wc,warmerCurrent;default:false;text-align:right;desc:current warmer ops");
table.addCell("warmer.total", "alias:wto,warmerTotal;default:false;text-align:right;desc:total warmer ops");
table.addCell("warmer.total_time", "alias:wtt,warmerTotalTime;default:false;text-align:right;desc:time spent in warmers");
table.endHeaders();
return table;
}
private Table buildTable(RestRequest request, ClusterStateResponse state, IndicesStatsResponse stats) {
Table table = getTableWithHeader(request);
for (ShardRouting shard : state.getState().routingTable().allShards()) {
ShardStats shardStats = stats.asMap().get(shard);
CommonStats commonStats = null;
CommitStats commitStats = null;
if (shardStats != null) {
commonStats = shardStats.getStats();
commitStats = shardStats.getCommitStats();
}
table.startRow();
table.addCell(shard.getIndexName());
table.addCell(shard.id());
if (shard.primary()) {
table.addCell("p");
} else {
table.addCell("r");
}
table.addCell(shard.state());
table.addCell(commonStats == null ? null : commonStats.getDocs().getCount());
table.addCell(commonStats == null ? null : commonStats.getStore().getSize());
if (shard.assignedToNode()) {
String ip = state.getState().nodes().get(shard.currentNodeId()).getHostAddress();
String nodeId = shard.currentNodeId();
StringBuilder name = new StringBuilder();
name.append(state.getState().nodes().get(shard.currentNodeId()).getName());
if (shard.relocating()) {
String reloIp = state.getState().nodes().get(shard.relocatingNodeId()).getHostAddress();
String reloNme = state.getState().nodes().get(shard.relocatingNodeId()).getName();
String reloNodeId = shard.relocatingNodeId();
name.append(" -> ");
name.append(reloIp);
name.append(" ");
name.append(reloNodeId);
name.append(" ");
name.append(reloNme);
}
table.addCell(ip);
table.addCell(nodeId);
table.addCell(name);
} else {
table.addCell(null);
table.addCell(null);
table.addCell(null);
}
table.addCell(commitStats == null ? null : commitStats.getUserData().get(Engine.SYNC_COMMIT_ID));
if (shard.unassignedInfo() != null) {
table.addCell(shard.unassignedInfo().getReason());
table.addCell(UnassignedInfo.DATE_TIME_FORMATTER.printer().print(shard.unassignedInfo().getUnassignedTimeInMillis()));
table.addCell(TimeValue.timeValueMillis(System.currentTimeMillis() - shard.unassignedInfo().getUnassignedTimeInMillis()));
table.addCell(shard.unassignedInfo().getDetails());
} else {
table.addCell(null);
table.addCell(null);
table.addCell(null);
table.addCell(null);
}
if (shard.recoverySource() != null) {
table.addCell(shard.recoverySource().getType().toString().toLowerCase(Locale.ROOT));
} else {
table.addCell(null);
}
table.addCell(commonStats == null ? null : commonStats.getCompletion().getSize());
table.addCell(commonStats == null ? null : commonStats.getFieldData().getMemorySize());
table.addCell(commonStats == null ? null : commonStats.getFieldData().getEvictions());
table.addCell(commonStats == null ? null : commonStats.getQueryCache().getMemorySize());
table.addCell(commonStats == null ? null : commonStats.getQueryCache().getEvictions());
table.addCell(commonStats == null ? null : commonStats.getFlush().getTotal());
table.addCell(commonStats == null ? null : commonStats.getFlush().getTotalTime());
table.addCell(commonStats == null ? null : commonStats.getGet().current());
table.addCell(commonStats == null ? null : commonStats.getGet().getTime());
table.addCell(commonStats == null ? null : commonStats.getGet().getCount());
table.addCell(commonStats == null ? null : commonStats.getGet().getExistsTime());
table.addCell(commonStats == null ? null : commonStats.getGet().getExistsCount());
table.addCell(commonStats == null ? null : commonStats.getGet().getMissingTime());
table.addCell(commonStats == null ? null : commonStats.getGet().getMissingCount());
table.addCell(commonStats == null ? null : commonStats.getIndexing().getTotal().getDeleteCurrent());
table.addCell(commonStats == null ? null : commonStats.getIndexing().getTotal().getDeleteTime());
table.addCell(commonStats == null ? null : commonStats.getIndexing().getTotal().getDeleteCount());
table.addCell(commonStats == null ? null : commonStats.getIndexing().getTotal().getIndexCurrent());
table.addCell(commonStats == null ? null : commonStats.getIndexing().getTotal().getIndexTime());
table.addCell(commonStats == null ? null : commonStats.getIndexing().getTotal().getIndexCount());
table.addCell(commonStats == null ? null : commonStats.getIndexing().getTotal().getIndexFailedCount());
table.addCell(commonStats == null ? null : commonStats.getMerge().getCurrent());
table.addCell(commonStats == null ? null : commonStats.getMerge().getCurrentNumDocs());
table.addCell(commonStats == null ? null : commonStats.getMerge().getCurrentSize());
table.addCell(commonStats == null ? null : commonStats.getMerge().getTotal());
table.addCell(commonStats == null ? null : commonStats.getMerge().getTotalNumDocs());
table.addCell(commonStats == null ? null : commonStats.getMerge().getTotalSize());
table.addCell(commonStats == null ? null : commonStats.getMerge().getTotalTime());
table.addCell(commonStats == null ? null : commonStats.getRefresh().getTotal());
table.addCell(commonStats == null ? null : commonStats.getRefresh().getTotalTime());
table.addCell(commonStats == null ? null : commonStats.getRefresh().getListeners());
table.addCell(commonStats == null ? null : commonStats.getSearch().getTotal().getFetchCurrent());
table.addCell(commonStats == null ? null : commonStats.getSearch().getTotal().getFetchTime());
table.addCell(commonStats == null ? null : commonStats.getSearch().getTotal().getFetchCount());
table.addCell(commonStats == null ? null : commonStats.getSearch().getOpenContexts());
table.addCell(commonStats == null ? null : commonStats.getSearch().getTotal().getQueryCurrent());
table.addCell(commonStats == null ? null : commonStats.getSearch().getTotal().getQueryTime());
table.addCell(commonStats == null ? null : commonStats.getSearch().getTotal().getQueryCount());
table.addCell(commonStats == null ? null : commonStats.getSearch().getTotal().getScrollCurrent());
table.addCell(commonStats == null ? null : commonStats.getSearch().getTotal().getScrollTime());
table.addCell(commonStats == null ? null : commonStats.getSearch().getTotal().getScrollCount());
table.addCell(commonStats == null ? null : commonStats.getSegments().getCount());
table.addCell(commonStats == null ? null : commonStats.getSegments().getMemory());
table.addCell(commonStats == null ? null : commonStats.getSegments().getIndexWriterMemory());
table.addCell(commonStats == null ? null : commonStats.getSegments().getVersionMapMemory());
table.addCell(commonStats == null ? null : commonStats.getSegments().getBitsetMemory());
table.addCell(shardStats == null || shardStats.getSeqNoStats() == null ? null : shardStats.getSeqNoStats().getMaxSeqNo());
table.addCell(shardStats == null || shardStats.getSeqNoStats() == null ? null : shardStats.getSeqNoStats().getLocalCheckpoint());
table.addCell(commitStats == null || shardStats.getSeqNoStats() == null ? null : shardStats.getSeqNoStats().getGlobalCheckpoint());
table.addCell(commonStats == null ? null : commonStats.getWarmer().current());
table.addCell(commonStats == null ? null : commonStats.getWarmer().total());
table.addCell(commonStats == null ? null : commonStats.getWarmer().totalTime());
table.endRow();
}
return table;
}
}
| {
"content_hash": "76444fc8ddf1a4c7b4daefcbaacd4c71",
"timestamp": "",
"source": "github",
"line_count": 302,
"max_line_length": 236,
"avg_line_length": 68.31788079470199,
"alnum_prop": 0.6856824350523458,
"repo_name": "fred84/elasticsearch",
"id": "a5a880061612ff080afe46812a93a730bc026168",
"size": "21420",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "server/src/main/java/org/elasticsearch/rest/action/cat/RestShardsAction.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "11082"
},
{
"name": "Batchfile",
"bytes": "11603"
},
{
"name": "Emacs Lisp",
"bytes": "3341"
},
{
"name": "FreeMarker",
"bytes": "45"
},
{
"name": "Groovy",
"bytes": "356024"
},
{
"name": "HTML",
"bytes": "2186"
},
{
"name": "Java",
"bytes": "44964586"
},
{
"name": "Perl",
"bytes": "11756"
},
{
"name": "Python",
"bytes": "19852"
},
{
"name": "Shell",
"bytes": "100808"
}
],
"symlink_target": ""
} |
namespace ppapi_proxy {
// Implements the untrusted side of the PPB_Messaging interface.
class PluginMessaging {
public:
static const PPB_Messaging* GetInterface();
private:
NACL_DISALLOW_COPY_AND_ASSIGN(PluginMessaging);
};
} // namespace ppapi_proxy
#endif // NATIVE_CLIENT_SRC_SHARED_PPAPI_PROXY_PLUGIN_PPB_MESSAGING_H_
| {
"content_hash": "d47b401058d5d83daaf83ec189d5bfd2",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 71,
"avg_line_length": 22.4,
"alnum_prop": 0.7529761904761905,
"repo_name": "keishi/chromium",
"id": "96f3c229c0963bf49ba161511bf0926da7009e02",
"size": "732",
"binary": false,
"copies": "16",
"ref": "refs/heads/master",
"path": "ppapi/native_client/src/shared/ppapi_proxy/plugin_ppb_messaging.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "853"
},
{
"name": "Arduino",
"bytes": "464"
},
{
"name": "Assembly",
"bytes": "1172794"
},
{
"name": "C",
"bytes": "67452317"
},
{
"name": "C#",
"bytes": "1132"
},
{
"name": "C++",
"bytes": "132681259"
},
{
"name": "F#",
"bytes": "381"
},
{
"name": "Go",
"bytes": "19048"
},
{
"name": "Java",
"bytes": "361412"
},
{
"name": "JavaScript",
"bytes": "16603687"
},
{
"name": "Objective-C",
"bytes": "9609581"
},
{
"name": "PHP",
"bytes": "97796"
},
{
"name": "Perl",
"bytes": "918683"
},
{
"name": "Python",
"bytes": "6407891"
},
{
"name": "R",
"bytes": "524"
},
{
"name": "Shell",
"bytes": "4192593"
},
{
"name": "Tcl",
"bytes": "277077"
}
],
"symlink_target": ""
} |
#include "config.h"
#include <string.h>
#include "gresource.h"
#include "gresourcefile.h"
#include "gfileattribute.h"
#include <gfileattribute-priv.h>
#include <gfileinfo-priv.h>
#include "gfile.h"
#include "gseekable.h"
#include "gfileinputstream.h"
#include "gfileinfo.h"
#include "gfileenumerator.h"
#include "gcontenttype.h"
#include "gioerror.h"
#include <glib/gstdio.h>
#include "glibintl.h"
struct _GResourceFile
{
GObject parent_instance;
char *path;
};
struct _GResourceFileEnumerator
{
GFileEnumerator parent;
GFileAttributeMatcher *matcher;
char *path;
char *attributes;
GFileQueryInfoFlags flags;
int index;
char **children;
};
struct _GResourceFileEnumeratorClass
{
GFileEnumeratorClass parent_class;
};
typedef struct _GResourceFileEnumerator GResourceFileEnumerator;
typedef struct _GResourceFileEnumeratorClass GResourceFileEnumeratorClass;
static void g_resource_file_file_iface_init (GFileIface *iface);
static GFileAttributeInfoList *resource_writable_attributes = NULL;
static GFileAttributeInfoList *resource_writable_namespaces = NULL;
static GType _g_resource_file_enumerator_get_type (void);
#define G_TYPE_RESOURCE_FILE_ENUMERATOR (_g_resource_file_enumerator_get_type ())
#define G_RESOURCE_FILE_ENUMERATOR(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), G_TYPE_RESOURCE_FILE_ENUMERATOR, GResourceFileEnumerator))
#define G_RESOURCE_FILE_ENUMERATOR_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), G_TYPE_RESOURCE_FILE_ENUMERATOR, GResourceFileEnumeratorClass))
#define G_IS_RESOURCE_FILE_ENUMERATOR(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), G_TYPE_RESOURCE_FILE_ENUMERATOR))
#define G_IS_RESOURCE_FILE_ENUMERATOR_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), G_TYPE_RESOURCE_FILE_ENUMERATOR))
#define G_RESOURCE_FILE_ENUMERATOR_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), G_TYPE_RESOURCE_FILE_ENUMERATOR, GResourceFileEnumeratorClass))
#define G_TYPE_RESOURCE_FILE_INPUT_STREAM (_g_resource_file_input_stream_get_type ())
#define G_RESOURCE_FILE_INPUT_STREAM(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), G_TYPE_RESOURCE_FILE_INPUT_STREAM, GResourceFileInputStream))
#define G_RESOURCE_FILE_INPUT_STREAM_CLASS(k) (G_TYPE_CHECK_CLASS_CAST((k), G_TYPE_RESOURCE_FILE_INPUT_STREAM, GResourceFileInputStreamClass))
#define G_IS_RESOURCE_FILE_INPUT_STREAM(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), G_TYPE_RESOURCE_FILE_INPUT_STREAM))
#define G_IS_RESOURCE_FILE_INPUT_STREAM_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), G_TYPE_RESOURCE_FILE_INPUT_STREAM))
#define G_RESOURCE_FILE_INPUT_STREAM_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS ((o), G_TYPE_RESOURCE_FILE_INPUT_STREAM, GResourceFileInputStreamClass))
typedef struct _GResourceFileInputStream GResourceFileInputStream;
typedef struct _GResourceFileInputStreamClass GResourceFileInputStreamClass;
#define g_resource_file_get_type _g_resource_file_get_type
G_DEFINE_TYPE_WITH_CODE (GResourceFile, g_resource_file, G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE (G_TYPE_FILE,
g_resource_file_file_iface_init))
#define g_resource_file_enumerator_get_type _g_resource_file_enumerator_get_type
G_DEFINE_TYPE (GResourceFileEnumerator, g_resource_file_enumerator, G_TYPE_FILE_ENUMERATOR);
static GFileEnumerator *_g_resource_file_enumerator_new (GResourceFile *file,
const char *attributes,
GFileQueryInfoFlags flags,
GCancellable *cancellable,
GError **error);
static GType _g_resource_file_input_stream_get_type (void) G_GNUC_CONST;
static GFileInputStream *_g_resource_file_input_stream_new (GInputStream *stream, GFile *file);
static void
g_resource_file_finalize (GObject *object)
{
GResourceFile *resource;
resource = G_RESOURCE_FILE (object);
g_free (resource->path);
G_OBJECT_CLASS (g_resource_file_parent_class)->finalize (object);
}
static void
g_resource_file_class_init (GResourceFileClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
gobject_class->finalize = g_resource_file_finalize;
resource_writable_attributes = g_file_attribute_info_list_new ();
resource_writable_namespaces = g_file_attribute_info_list_new ();
}
static void
g_resource_file_init (GResourceFile *resource)
{
}
static char *
canonicalize_filename (const char *filename)
{
char *canon, *start, *p, *q;
/* Skip multiple inital slashes */
while (filename[0] == '/' && filename[1] == '/')
filename++;
if (*filename != '/')
canon = g_strconcat ("/", filename, NULL);
else
canon = g_strdup (filename);
start = canon + 1;
p = start;
while (*p != 0)
{
if (p[0] == '.' && (p[1] == 0 || p[1] == '/'))
{
memmove (p, p+1, strlen (p+1)+1);
}
else if (p[0] == '.' && p[1] == '.' && (p[2] == 0 || p[2] == '/'))
{
q = p + 2;
/* Skip previous separator */
p = p - 2;
if (p < start)
p = start;
while (p > start && *p != '/')
p--;
if (*p == '/')
*p++ = '/';
memmove (p, q, strlen (q)+1);
}
else
{
/* Skip until next separator */
while (*p != 0 && *p != '/')
p++;
if (*p != 0)
{
/* Canonicalize one separator */
*p++ = '/';
}
}
/* Remove additional separators */
q = p;
while (*q && *q == '/')
q++;
if (p != q)
memmove (p, q, strlen (q)+1);
}
/* Remove trailing slashes */
if (p > start && *(p-1) == '/')
*(p-1) = 0;
return canon;
}
static GFile *
g_resource_file_new_for_path (const char *path)
{
GResourceFile *resource = g_object_new (G_TYPE_RESOURCE_FILE, NULL);
resource->path = canonicalize_filename (path);
return G_FILE (resource);
}
GFile *
_g_resource_file_new (const char *uri)
{
GFile *resource;
char *path;
path = g_uri_unescape_string (uri + strlen ("resource:"), NULL);
resource = g_resource_file_new_for_path (path);
g_free (path);
return G_FILE (resource);
}
static gboolean
g_resource_file_is_native (GFile *file)
{
return FALSE;
}
static gboolean
g_resource_file_has_uri_scheme (GFile *file,
const char *uri_scheme)
{
return g_ascii_strcasecmp (uri_scheme, "resource") == 0;
}
static char *
g_resource_file_get_uri_scheme (GFile *file)
{
return g_strdup ("resource");
}
static char *
g_resource_file_get_basename (GFile *file)
{
gchar *base;
base = strrchr (G_RESOURCE_FILE (file)->path, '/');
return g_strdup (base + 1);
}
static char *
g_resource_file_get_path (GFile *file)
{
return NULL;
}
static char *
g_resource_file_get_uri (GFile *file)
{
char *escaped, *res;
escaped = g_uri_escape_string (G_RESOURCE_FILE (file)->path, G_URI_RESERVED_CHARS_ALLOWED_IN_PATH, FALSE);
res = g_strconcat ("resource://", escaped, NULL);
g_free (escaped);
return res;
}
static char *
g_resource_file_get_parse_name (GFile *file)
{
return g_resource_file_get_uri (file);
}
static GFile *
g_resource_file_get_parent (GFile *file)
{
GResourceFile *resource = G_RESOURCE_FILE (file);
GResourceFile *parent;
gchar *end;
end = strrchr (resource->path, '/');
if (end == G_RESOURCE_FILE (file)->path)
return NULL;
parent = g_object_new (G_TYPE_RESOURCE_FILE, NULL);
parent->path = g_strndup (resource->path,
end - resource->path);
return G_FILE (parent);
}
static GFile *
g_resource_file_dup (GFile *file)
{
GResourceFile *resource = G_RESOURCE_FILE (file);
return g_resource_file_new_for_path (resource->path);
}
static guint
g_resource_file_hash (GFile *file)
{
GResourceFile *resource = G_RESOURCE_FILE (file);
return g_str_hash (resource->path);
}
static gboolean
g_resource_file_equal (GFile *file1,
GFile *file2)
{
GResourceFile *resource1 = G_RESOURCE_FILE (file1);
GResourceFile *resource2 = G_RESOURCE_FILE (file2);
return g_str_equal (resource1->path, resource2->path);
}
static const char *
match_prefix (const char *path,
const char *prefix)
{
int prefix_len;
prefix_len = strlen (prefix);
if (strncmp (path, prefix, prefix_len) != 0)
return NULL;
/* Handle the case where prefix is the root, so that
* the IS_DIR_SEPRARATOR check below works */
if (prefix_len > 0 &&
prefix[prefix_len-1] == '/')
prefix_len--;
return path + prefix_len;
}
static gboolean
g_resource_file_prefix_matches (GFile *parent,
GFile *descendant)
{
GResourceFile *parent_resource = G_RESOURCE_FILE (parent);
GResourceFile *descendant_resource = G_RESOURCE_FILE (descendant);
const char *remainder;
remainder = match_prefix (descendant_resource->path, parent_resource->path);
if (remainder != NULL && *remainder == '/')
return TRUE;
return FALSE;
}
static char *
g_resource_file_get_relative_path (GFile *parent,
GFile *descendant)
{
GResourceFile *parent_resource = G_RESOURCE_FILE (parent);
GResourceFile *descendant_resource = G_RESOURCE_FILE (descendant);
const char *remainder;
remainder = match_prefix (descendant_resource->path, parent_resource->path);
if (remainder != NULL && *remainder == '/')
return g_strdup (remainder + 1);
return NULL;
}
static GFile *
g_resource_file_resolve_relative_path (GFile *file,
const char *relative_path)
{
GResourceFile *resource = G_RESOURCE_FILE (file);
char *filename;
GFile *child;
if (relative_path[0] == '/')
return g_resource_file_new_for_path (relative_path);
filename = g_build_path ("/", resource->path, relative_path, NULL);
child = g_resource_file_new_for_path (filename);
g_free (filename);
return child;
}
static GFileEnumerator *
g_resource_file_enumerate_children (GFile *file,
const char *attributes,
GFileQueryInfoFlags flags,
GCancellable *cancellable,
GError **error)
{
GResourceFile *resource = G_RESOURCE_FILE (file);
return _g_resource_file_enumerator_new (resource,
attributes, flags,
cancellable, error);
}
static GFile *
g_resource_file_get_child_for_display_name (GFile *file,
const char *display_name,
GError **error)
{
GFile *new_file;
new_file = g_file_get_child (file, display_name);
return new_file;
}
static GFileInfo *
g_resource_file_query_info (GFile *file,
const char *attributes,
GFileQueryInfoFlags flags,
GCancellable *cancellable,
GError **error)
{
GResourceFile *resource = G_RESOURCE_FILE (file);
GError *my_error = NULL;
GFileInfo *info;
GFileAttributeMatcher *matcher;
gboolean res;
gsize size;
guint32 resource_flags;
char **children;
gboolean is_dir;
char *base;
is_dir = FALSE;
children = g_resources_enumerate_children (resource->path, 0, NULL);
if (children != NULL)
{
g_strfreev (children);
is_dir = TRUE;
}
/* root is always there */
if (strcmp ("/", resource->path) == 0)
is_dir = TRUE;
if (!is_dir)
{
res = g_resources_get_info (resource->path, 0, &size, &resource_flags, &my_error);
if (!res)
{
if (g_error_matches (my_error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND))
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
_("The resource at '%s' does not exist"),
resource->path);
}
else
g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
my_error->message);
g_clear_error (&my_error);
return FALSE;
}
}
matcher = g_file_attribute_matcher_new (attributes);
info = g_file_info_new ();
base = g_resource_file_get_basename (file);
g_file_info_set_name (info, base);
g_file_info_set_display_name (info, base);
_g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_READ, TRUE);
_g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_WRITE, FALSE);
_g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_EXECUTE, FALSE);
_g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_RENAME, FALSE);
_g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_DELETE, FALSE);
_g_file_info_set_attribute_boolean_by_id (info, G_FILE_ATTRIBUTE_ID_ACCESS_CAN_TRASH, FALSE);
if (is_dir)
{
g_file_info_set_file_type (info, G_FILE_TYPE_DIRECTORY);
}
else
{
GBytes *bytes;
char *content_type;
g_file_info_set_file_type (info, G_FILE_TYPE_REGULAR);
g_file_info_set_size (info, size);
if ((_g_file_attribute_matcher_matches_id (matcher, G_FILE_ATTRIBUTE_ID_STANDARD_CONTENT_TYPE) ||
((~resource_flags & G_RESOURCE_FLAGS_COMPRESSED) &&
_g_file_attribute_matcher_matches_id (matcher, G_FILE_ATTRIBUTE_ID_STANDARD_FAST_CONTENT_TYPE))) &&
(bytes = g_resources_lookup_data (resource->path, 0, NULL)))
{
const guchar *data;
gsize data_size;
data = g_bytes_get_data (bytes, &data_size);
content_type = g_content_type_guess (base, data, data_size, NULL);
g_bytes_unref (bytes);
}
else
content_type = NULL;
if (content_type)
{
_g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_CONTENT_TYPE, content_type);
_g_file_info_set_attribute_string_by_id (info, G_FILE_ATTRIBUTE_ID_STANDARD_FAST_CONTENT_TYPE, content_type);
g_free (content_type);
}
}
g_free (base);
g_file_attribute_matcher_unref (matcher);
return info;
}
static GFileAttributeInfoList *
g_resource_file_query_settable_attributes (GFile *file,
GCancellable *cancellable,
GError **error)
{
return g_file_attribute_info_list_ref (resource_writable_attributes);
}
static GFileAttributeInfoList *
g_resource_file_query_writable_namespaces (GFile *file,
GCancellable *cancellable,
GError **error)
{
return g_file_attribute_info_list_ref (resource_writable_namespaces);
}
static GFileInputStream *
g_resource_file_read (GFile *file,
GCancellable *cancellable,
GError **error)
{
GResourceFile *resource = G_RESOURCE_FILE (file);
GError *my_error = NULL;
GInputStream *stream;
GFileInputStream *res;
stream = g_resources_open_stream (resource->path, 0, &my_error);
if (stream == NULL)
{
if (g_error_matches (my_error, G_RESOURCE_ERROR, G_RESOURCE_ERROR_NOT_FOUND))
{
g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
_("The resource at '%s' does not exist"),
resource->path);
}
else
g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_FAILED,
my_error->message);
g_clear_error (&my_error);
return NULL;
}
res = _g_resource_file_input_stream_new (stream, file);
g_object_unref (stream);
return res;
}
static void
g_resource_file_file_iface_init (GFileIface *iface)
{
iface->dup = g_resource_file_dup;
iface->hash = g_resource_file_hash;
iface->equal = g_resource_file_equal;
iface->is_native = g_resource_file_is_native;
iface->has_uri_scheme = g_resource_file_has_uri_scheme;
iface->get_uri_scheme = g_resource_file_get_uri_scheme;
iface->get_basename = g_resource_file_get_basename;
iface->get_path = g_resource_file_get_path;
iface->get_uri = g_resource_file_get_uri;
iface->get_parse_name = g_resource_file_get_parse_name;
iface->get_parent = g_resource_file_get_parent;
iface->prefix_matches = g_resource_file_prefix_matches;
iface->get_relative_path = g_resource_file_get_relative_path;
iface->resolve_relative_path = g_resource_file_resolve_relative_path;
iface->get_child_for_display_name = g_resource_file_get_child_for_display_name;
iface->enumerate_children = g_resource_file_enumerate_children;
iface->query_info = g_resource_file_query_info;
iface->query_settable_attributes = g_resource_file_query_settable_attributes;
iface->query_writable_namespaces = g_resource_file_query_writable_namespaces;
iface->read_fn = g_resource_file_read;
iface->supports_thread_contexts = TRUE;
}
static GFileInfo *g_resource_file_enumerator_next_file (GFileEnumerator *enumerator,
GCancellable *cancellable,
GError **error);
static gboolean g_resource_file_enumerator_close (GFileEnumerator *enumerator,
GCancellable *cancellable,
GError **error);
static void
g_resource_file_enumerator_finalize (GObject *object)
{
GResourceFileEnumerator *resource;
resource = G_RESOURCE_FILE_ENUMERATOR (object);
g_strfreev (resource->children);
g_free (resource->path);
g_free (resource->attributes);
G_OBJECT_CLASS (g_resource_file_enumerator_parent_class)->finalize (object);
}
static void
g_resource_file_enumerator_class_init (GResourceFileEnumeratorClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
GFileEnumeratorClass *enumerator_class = G_FILE_ENUMERATOR_CLASS (klass);
gobject_class->finalize = g_resource_file_enumerator_finalize;
enumerator_class->next_file = g_resource_file_enumerator_next_file;
enumerator_class->close_fn = g_resource_file_enumerator_close;
}
static void
g_resource_file_enumerator_init (GResourceFileEnumerator *resource)
{
}
static GFileEnumerator *
_g_resource_file_enumerator_new (GResourceFile *file,
const char *attributes,
GFileQueryInfoFlags flags,
GCancellable *cancellable,
GError **error)
{
GResourceFileEnumerator *resource;
char **children;
gboolean res;
children = g_resources_enumerate_children (file->path, 0, NULL);
if (children == NULL &&
strcmp ("/", file->path) != 0)
{
res = g_resources_get_info (file->path, 0, NULL, NULL, NULL);
if (res)
g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_DIRECTORY,
_("The resource at '%s' is not a directory"),
file->path);
else
g_set_error (error, G_IO_ERROR, G_IO_ERROR_NOT_FOUND,
_("The resource at '%s' does not exist"),
file->path);
return NULL;
}
resource = g_object_new (G_TYPE_RESOURCE_FILE_ENUMERATOR,
"container", file,
NULL);
resource->children = children;
resource->path = g_strdup (file->path);
resource->attributes = g_strdup (attributes);
resource->flags = flags;
return G_FILE_ENUMERATOR (resource);
}
static GFileInfo *
g_resource_file_enumerator_next_file (GFileEnumerator *enumerator,
GCancellable *cancellable,
GError **error)
{
GResourceFileEnumerator *resource = G_RESOURCE_FILE_ENUMERATOR (enumerator);
char *path;
GFileInfo *info;
GFile *file;
if (resource->children == NULL ||
resource->children[resource->index] == NULL)
return NULL;
path = g_build_path ("/", resource->path, resource->children[resource->index++], NULL);
file = g_resource_file_new_for_path (path);
g_free (path);
info = g_file_query_info (file,
resource->attributes,
resource->flags,
cancellable,
error);
g_object_unref (file);
return info;
}
static gboolean
g_resource_file_enumerator_close (GFileEnumerator *enumerator,
GCancellable *cancellable,
GError **error)
{
return TRUE;
}
struct _GResourceFileInputStream
{
GFileInputStream parent_instance;
GInputStream *stream;
GFile *file;
};
struct _GResourceFileInputStreamClass
{
GFileInputStreamClass parent_class;
};
#define g_resource_file_input_stream_get_type _g_resource_file_input_stream_get_type
G_DEFINE_TYPE (GResourceFileInputStream, g_resource_file_input_stream, G_TYPE_FILE_INPUT_STREAM);
static gssize g_resource_file_input_stream_read (GInputStream *stream,
void *buffer,
gsize count,
GCancellable *cancellable,
GError **error);
static gssize g_resource_file_input_stream_skip (GInputStream *stream,
gsize count,
GCancellable *cancellable,
GError **error);
static gboolean g_resource_file_input_stream_close (GInputStream *stream,
GCancellable *cancellable,
GError **error);
static goffset g_resource_file_input_stream_tell (GFileInputStream *stream);
static gboolean g_resource_file_input_stream_can_seek (GFileInputStream *stream);
static gboolean g_resource_file_input_stream_seek (GFileInputStream *stream,
goffset offset,
GSeekType type,
GCancellable *cancellable,
GError **error);
static GFileInfo *g_resource_file_input_stream_query_info (GFileInputStream *stream,
const char *attributes,
GCancellable *cancellable,
GError **error);
static void
g_resource_file_input_stream_finalize (GObject *object)
{
GResourceFileInputStream *file = G_RESOURCE_FILE_INPUT_STREAM (object);
g_object_unref (file->stream);
g_object_unref (file->file);
G_OBJECT_CLASS (g_resource_file_input_stream_parent_class)->finalize (object);
}
static void
g_resource_file_input_stream_class_init (GResourceFileInputStreamClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
GInputStreamClass *stream_class = G_INPUT_STREAM_CLASS (klass);
GFileInputStreamClass *file_stream_class = G_FILE_INPUT_STREAM_CLASS (klass);
gobject_class->finalize = g_resource_file_input_stream_finalize;
stream_class->read_fn = g_resource_file_input_stream_read;
stream_class->skip = g_resource_file_input_stream_skip;
stream_class->close_fn = g_resource_file_input_stream_close;
file_stream_class->tell = g_resource_file_input_stream_tell;
file_stream_class->can_seek = g_resource_file_input_stream_can_seek;
file_stream_class->seek = g_resource_file_input_stream_seek;
file_stream_class->query_info = g_resource_file_input_stream_query_info;
}
static void
g_resource_file_input_stream_init (GResourceFileInputStream *info)
{
}
static GFileInputStream *
_g_resource_file_input_stream_new (GInputStream *in_stream, GFile *file)
{
GResourceFileInputStream *stream;
stream = g_object_new (G_TYPE_RESOURCE_FILE_INPUT_STREAM, NULL);
stream->stream = g_object_ref (in_stream);
stream->file = g_object_ref (file);
return G_FILE_INPUT_STREAM (stream);
}
static gssize
g_resource_file_input_stream_read (GInputStream *stream,
void *buffer,
gsize count,
GCancellable *cancellable,
GError **error)
{
GResourceFileInputStream *file = G_RESOURCE_FILE_INPUT_STREAM (stream);
return g_input_stream_read (file->stream,
buffer, count, cancellable, error);
}
static gssize
g_resource_file_input_stream_skip (GInputStream *stream,
gsize count,
GCancellable *cancellable,
GError **error)
{
GResourceFileInputStream *file = G_RESOURCE_FILE_INPUT_STREAM (stream);
return g_input_stream_skip (file->stream,
count, cancellable, error);
}
static gboolean
g_resource_file_input_stream_close (GInputStream *stream,
GCancellable *cancellable,
GError **error)
{
GResourceFileInputStream *file = G_RESOURCE_FILE_INPUT_STREAM (stream);
return g_input_stream_close (file->stream,
cancellable, error);
}
static goffset
g_resource_file_input_stream_tell (GFileInputStream *stream)
{
GResourceFileInputStream *file = G_RESOURCE_FILE_INPUT_STREAM (stream);
if (!G_IS_SEEKABLE (file->stream))
return 0;
return g_seekable_tell (G_SEEKABLE (file->stream));
}
static gboolean
g_resource_file_input_stream_can_seek (GFileInputStream *stream)
{
GResourceFileInputStream *file = G_RESOURCE_FILE_INPUT_STREAM (stream);
return G_IS_SEEKABLE (file->stream) && g_seekable_can_seek (G_SEEKABLE (file->stream));
}
static gboolean
g_resource_file_input_stream_seek (GFileInputStream *stream,
goffset offset,
GSeekType type,
GCancellable *cancellable,
GError **error)
{
GResourceFileInputStream *file = G_RESOURCE_FILE_INPUT_STREAM (stream);
if (!G_IS_SEEKABLE (file->stream))
{
g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED,
_("Input stream doesn't implement seek"));
return FALSE;
}
return g_seekable_seek (G_SEEKABLE (file->stream),
offset, type, cancellable, error);
}
static GFileInfo *
g_resource_file_input_stream_query_info (GFileInputStream *stream,
const char *attributes,
GCancellable *cancellable,
GError **error)
{
GResourceFileInputStream *file = G_RESOURCE_FILE_INPUT_STREAM (stream);
return g_file_query_info (file->file, attributes, 0, cancellable, error);
}
| {
"content_hash": "ca442de4a404bd628f25a145d8687c33",
"timestamp": "",
"source": "github",
"line_count": 858,
"max_line_length": 149,
"avg_line_length": 28.93822843822844,
"alnum_prop": 0.6630150227556486,
"repo_name": "AlexiaChen/ImageMagick_Cmake",
"id": "de262463a4320a0f660f3d69e21b68559873e225",
"size": "25717",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "glib/gio/gresourcefile.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "85363"
},
{
"name": "Assembly",
"bytes": "1065264"
},
{
"name": "Awk",
"bytes": "49170"
},
{
"name": "C",
"bytes": "84464044"
},
{
"name": "C#",
"bytes": "512751"
},
{
"name": "C++",
"bytes": "2129719"
},
{
"name": "CLIPS",
"bytes": "5291"
},
{
"name": "CSS",
"bytes": "139426"
},
{
"name": "Clean",
"bytes": "6801"
},
{
"name": "Component Pascal",
"bytes": "1754"
},
{
"name": "D",
"bytes": "964"
},
{
"name": "Emacs Lisp",
"bytes": "41"
},
{
"name": "GAP",
"bytes": "6068"
},
{
"name": "Java",
"bytes": "163191"
},
{
"name": "JavaScript",
"bytes": "51322"
},
{
"name": "Matlab",
"bytes": "259"
},
{
"name": "Objective-C",
"bytes": "153496"
},
{
"name": "Pascal",
"bytes": "198153"
},
{
"name": "Perl",
"bytes": "248659"
},
{
"name": "PowerShell",
"bytes": "4041"
},
{
"name": "Python",
"bytes": "726476"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Shell",
"bytes": "4350407"
},
{
"name": "TeX",
"bytes": "326716"
},
{
"name": "Vala",
"bytes": "1452"
},
{
"name": "Visual Basic",
"bytes": "26127"
},
{
"name": "XSLT",
"bytes": "43671"
}
],
"symlink_target": ""
} |
namespace content {
namespace {
int WindowFormat(gfx::BufferFormat format) {
switch (format) {
case gfx::BufferFormat::RGBA_8888:
return WINDOW_FORMAT_RGBA_8888;
case gfx::BufferFormat::ATC:
case gfx::BufferFormat::ATCIA:
case gfx::BufferFormat::DXT1:
case gfx::BufferFormat::DXT5:
case gfx::BufferFormat::ETC1:
case gfx::BufferFormat::R_8:
case gfx::BufferFormat::RGBA_4444:
case gfx::BufferFormat::RGBX_8888:
case gfx::BufferFormat::BGRA_8888:
case gfx::BufferFormat::YUV_420:
NOTREACHED();
return 0;
}
NOTREACHED();
return 0;
}
} // namespace
GpuMemoryBufferImplSurfaceTexture::GpuMemoryBufferImplSurfaceTexture(
gfx::GpuMemoryBufferId id,
const gfx::Size& size,
gfx::BufferFormat format,
const DestructionCallback& callback,
ANativeWindow* native_window)
: GpuMemoryBufferImpl(id, size, format, callback),
native_window_(native_window),
stride_(0) {}
GpuMemoryBufferImplSurfaceTexture::~GpuMemoryBufferImplSurfaceTexture() {
ANativeWindow_release(native_window_);
}
// static
scoped_ptr<GpuMemoryBufferImpl>
GpuMemoryBufferImplSurfaceTexture::CreateFromHandle(
const gfx::GpuMemoryBufferHandle& handle,
const gfx::Size& size,
gfx::BufferFormat format,
const DestructionCallback& callback) {
ANativeWindow* native_window = SurfaceTextureManager::GetInstance()->
AcquireNativeWidgetForSurfaceTexture(handle.id);
if (!native_window)
return scoped_ptr<GpuMemoryBufferImpl>();
ANativeWindow_setBuffersGeometry(
native_window, size.width(), size.height(), WindowFormat(format));
return make_scoped_ptr<GpuMemoryBufferImpl>(
new GpuMemoryBufferImplSurfaceTexture(
handle.id, size, format, callback, native_window));
}
bool GpuMemoryBufferImplSurfaceTexture::Map(void** data) {
TRACE_EVENT0("gpu", "GpuMemoryBufferImplSurfaceTexture::Map");
DCHECK(!mapped_);
DCHECK(native_window_);
ANativeWindow_Buffer buffer;
int status = ANativeWindow_lock(native_window_, &buffer, NULL);
if (status) {
VLOG(1) << "ANativeWindow_lock failed with error code: " << status;
return false;
}
DCHECK_LE(size_.width(), buffer.stride);
size_t row_size_in_bytes = 0;
bool valid_row_size =
RowSizeInBytes(buffer.stride, format_, 0, &row_size_in_bytes);
DCHECK(valid_row_size);
stride_ = row_size_in_bytes;
mapped_ = true;
*data = buffer.bits;
return true;
}
void GpuMemoryBufferImplSurfaceTexture::Unmap() {
TRACE_EVENT0("gpu", "GpuMemoryBufferImplSurfaceTexture::Unmap");
DCHECK(mapped_);
ANativeWindow_unlockAndPost(native_window_);
mapped_ = false;
}
void GpuMemoryBufferImplSurfaceTexture::GetStride(int* stride) const {
*stride = stride_;
}
gfx::GpuMemoryBufferHandle GpuMemoryBufferImplSurfaceTexture::GetHandle()
const {
gfx::GpuMemoryBufferHandle handle;
handle.type = gfx::SURFACE_TEXTURE_BUFFER;
handle.id = id_;
return handle;
}
} // namespace content
| {
"content_hash": "fd18ce3e16eef62565808db598171312",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 73,
"avg_line_length": 28.160377358490567,
"alnum_prop": 0.7165829145728643,
"repo_name": "Just-D/chromium-1",
"id": "088aaf57375b65679bc549ab77bbb4f2d1f7500b",
"size": "3390",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "content/common/gpu/client/gpu_memory_buffer_impl_surface_texture.cc",
"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": "9517927"
},
{
"name": "C++",
"bytes": "244067615"
},
{
"name": "CSS",
"bytes": "944025"
},
{
"name": "DM",
"bytes": "60"
},
{
"name": "Groff",
"bytes": "2494"
},
{
"name": "HTML",
"bytes": "27307576"
},
{
"name": "Java",
"bytes": "14757472"
},
{
"name": "JavaScript",
"bytes": "20666212"
},
{
"name": "Makefile",
"bytes": "70864"
},
{
"name": "Objective-C",
"bytes": "1772355"
},
{
"name": "Objective-C++",
"bytes": "10088862"
},
{
"name": "PHP",
"bytes": "97817"
},
{
"name": "PLpgSQL",
"bytes": "178732"
},
{
"name": "Perl",
"bytes": "63937"
},
{
"name": "Protocol Buffer",
"bytes": "485040"
},
{
"name": "Python",
"bytes": "8652947"
},
{
"name": "Shell",
"bytes": "481276"
},
{
"name": "Standard ML",
"bytes": "5106"
},
{
"name": "XSLT",
"bytes": "418"
},
{
"name": "nesC",
"bytes": "18347"
}
],
"symlink_target": ""
} |
/*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: android.text.style.MetricAffectingSpan
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ANDROID_TEXT_STYLE_METRICAFFECTINGSPAN_HPP_DECL
#define J2CPP_ANDROID_TEXT_STYLE_METRICAFFECTINGSPAN_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class Object; } } }
namespace j2cpp { namespace android { namespace text { class TextPaint; } } }
namespace j2cpp { namespace android { namespace text { namespace style { class CharacterStyle; } } } }
namespace j2cpp { namespace android { namespace text { namespace style { class UpdateAppearance; } } } }
namespace j2cpp { namespace android { namespace text { namespace style { class UpdateLayout; } } } }
#include <android/text/TextPaint.hpp>
#include <android/text/style/CharacterStyle.hpp>
#include <android/text/style/UpdateAppearance.hpp>
#include <android/text/style/UpdateLayout.hpp>
#include <java/lang/Object.hpp>
namespace j2cpp {
namespace android { namespace text { namespace style {
class MetricAffectingSpan;
class MetricAffectingSpan
: public object<MetricAffectingSpan>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_METHOD(3)
explicit MetricAffectingSpan(jobject jobj)
: object<MetricAffectingSpan>(jobj)
{
}
operator local_ref<java::lang::Object>() const;
operator local_ref<android::text::style::CharacterStyle>() const;
operator local_ref<android::text::style::UpdateAppearance>() const;
operator local_ref<android::text::style::UpdateLayout>() const;
MetricAffectingSpan();
void updateMeasureState(local_ref< android::text::TextPaint > const&);
local_ref< android::text::style::MetricAffectingSpan > getUnderlying();
local_ref< android::text::style::CharacterStyle > getUnderlying_1();
}; //class MetricAffectingSpan
} //namespace style
} //namespace text
} //namespace android
} //namespace j2cpp
#endif //J2CPP_ANDROID_TEXT_STYLE_METRICAFFECTINGSPAN_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_ANDROID_TEXT_STYLE_METRICAFFECTINGSPAN_HPP_IMPL
#define J2CPP_ANDROID_TEXT_STYLE_METRICAFFECTINGSPAN_HPP_IMPL
namespace j2cpp {
android::text::style::MetricAffectingSpan::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
android::text::style::MetricAffectingSpan::operator local_ref<android::text::style::CharacterStyle>() const
{
return local_ref<android::text::style::CharacterStyle>(get_jobject());
}
android::text::style::MetricAffectingSpan::operator local_ref<android::text::style::UpdateAppearance>() const
{
return local_ref<android::text::style::UpdateAppearance>(get_jobject());
}
android::text::style::MetricAffectingSpan::operator local_ref<android::text::style::UpdateLayout>() const
{
return local_ref<android::text::style::UpdateLayout>(get_jobject());
}
android::text::style::MetricAffectingSpan::MetricAffectingSpan()
: object<android::text::style::MetricAffectingSpan>(
call_new_object<
android::text::style::MetricAffectingSpan::J2CPP_CLASS_NAME,
android::text::style::MetricAffectingSpan::J2CPP_METHOD_NAME(0),
android::text::style::MetricAffectingSpan::J2CPP_METHOD_SIGNATURE(0)
>()
)
{
}
void android::text::style::MetricAffectingSpan::updateMeasureState(local_ref< android::text::TextPaint > const &a0)
{
return call_method<
android::text::style::MetricAffectingSpan::J2CPP_CLASS_NAME,
android::text::style::MetricAffectingSpan::J2CPP_METHOD_NAME(1),
android::text::style::MetricAffectingSpan::J2CPP_METHOD_SIGNATURE(1),
void
>(get_jobject(), a0);
}
local_ref< android::text::style::MetricAffectingSpan > android::text::style::MetricAffectingSpan::getUnderlying()
{
return call_method<
android::text::style::MetricAffectingSpan::J2CPP_CLASS_NAME,
android::text::style::MetricAffectingSpan::J2CPP_METHOD_NAME(2),
android::text::style::MetricAffectingSpan::J2CPP_METHOD_SIGNATURE(2),
local_ref< android::text::style::MetricAffectingSpan >
>(get_jobject());
}
local_ref< android::text::style::CharacterStyle > android::text::style::MetricAffectingSpan::getUnderlying_1()
{
return call_method<
android::text::style::MetricAffectingSpan::J2CPP_CLASS_NAME,
android::text::style::MetricAffectingSpan::J2CPP_METHOD_NAME(3),
android::text::style::MetricAffectingSpan::J2CPP_METHOD_SIGNATURE(3),
local_ref< android::text::style::CharacterStyle >
>(get_jobject());
}
J2CPP_DEFINE_CLASS(android::text::style::MetricAffectingSpan,"android/text/style/MetricAffectingSpan")
J2CPP_DEFINE_METHOD(android::text::style::MetricAffectingSpan,0,"<init>","()V")
J2CPP_DEFINE_METHOD(android::text::style::MetricAffectingSpan,1,"updateMeasureState","(Landroid/text/TextPaint;)V")
J2CPP_DEFINE_METHOD(android::text::style::MetricAffectingSpan,2,"getUnderlying","()Landroid/text/style/MetricAffectingSpan;")
J2CPP_DEFINE_METHOD(android::text::style::MetricAffectingSpan,3,"getUnderlying","()Landroid/text/style/CharacterStyle;")
} //namespace j2cpp
#endif //J2CPP_ANDROID_TEXT_STYLE_METRICAFFECTINGSPAN_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| {
"content_hash": "b91fe09f1c38504069a31eb3a59c582d",
"timestamp": "",
"source": "github",
"line_count": 153,
"max_line_length": 125,
"avg_line_length": 35.89542483660131,
"alnum_prop": 0.7161325564457393,
"repo_name": "hyEvans/ph-open",
"id": "8d7c290fdb694e4d2bb5270d69cb53a88e02a210",
"size": "5492",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "proj.android/jni/puzzleHero/platforms/android-9/android/text/style/MetricAffectingSpan.hpp",
"mode": "33261",
"license": "mit",
"language": [],
"symlink_target": ""
} |
title: Browser DevTools
type: activity
tasks:
-
id: network-weight
text: Use the <strong>Network tab</strong> to see the total page weight.
-
id: network-milestones
text: Use the <strong>Network tab</strong> to see time until the DOMContentLoaded and onLoad events.
-
id: network-heavy
text: Use the <strong>Network tab</strong> to find the heaviest resource on a web page.
-
id: network-latency
text: Use the <strong>Network tab</strong> to find the resource with the most latency.
-
id: network-lifecycle
text: Use the <strong>Network tab</strong> to look at the life cycle of the most latent request and determine where the latency ocurred.
-
id: audit-combinejs
text: Use the <strong>Audits tab</strong> to determine if some resources could be compressed to save bandwidth.
-
id: audit-uncss
text: Use the <strong>Audits tab</strong> to see how much CSS on the page is unused.
-
id: audit-image-dimensions
text: Use the <strong>Audits tab</strong> to find any images that lack <code>width</code>/<code>height</code> dimensions.
---
| {
"content_hash": "d9b94ae52d617e135480bff7fba244c1",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 140,
"avg_line_length": 38.51724137931034,
"alnum_prop": 0.7063563115487914,
"repo_name": "DavidHughes/frontend-perf",
"id": "a1e3f73230020b6beda4cde8c086bed90c1f0554",
"size": "1121",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "_audit/90-activity-devtools.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3668"
},
{
"name": "HTML",
"bytes": "18678"
},
{
"name": "JavaScript",
"bytes": "18609"
},
{
"name": "Ruby",
"bytes": "2350"
}
],
"symlink_target": ""
} |
/*
Tiles to summarize page performance
*/
import data from "../data";
import helper from "../helpers/helpers";
import dom from "../helpers/dom";
var summaryTilesComponent = {};
summaryTilesComponent.init = function(){
var createTile = function(title, value, titleFontSize){
titleFontSize = titleFontSize || 60;
var dl = dom.newTag("dl", {
class : "summary-tile"
});
dl.appendChild(dom.newTag("dt", {childElement : title}));
dl.appendChild(dom.newTag("dd", {childElement : value}, "font-size:"+titleFontSize+"px;"));
return dl;
};
var createAppendixDefValue = function(a, definition, value){
a.appendChild(dom.newTag("dt", {childElement : definition}));
a.appendChild(dom.newTag("dd", {text : value}));
};
var tilesHolder = dom.newTag("section", {
class : "tiles-holder chart-holder"
});
var appendix = dom.newTag("dl", {
class : "summary-tile-appendix"
});
[
createTile("Requests", data.requestsOnly.length||"0"),
createTile("Domains", data.requestsByDomain.length||"0"),
createTile(dom.combineNodes("Subdomains of ", dom.newTag("abbr", {title : "Top Level Domain", text : "TLD"})), data.hostSubdomains||"0"),
createTile(dom.combineNodes("Requests to ", dom.newTag("span", {title : location.host, text : "Host"})), data.hostRequests||"0"),
createTile(dom.combineNodes(dom.newTag("abbr", {title : "Top Level Domain", text : "TLD"}), "& Subdomain Requests"), data.currAndSubdomainRequests||"0"),
createTile("Total", data.perfTiming.loadEventEnd - data.perfTiming.navigationStart + "ms", 40),
createTile("Time to First Byte", data.perfTiming.responseStart - data.perfTiming.navigationStart + "ms", 40),
createTile(dom.newTag("span", {title : "domLoading to domContentLoadedEventStart", text : "DOM Content Loading"}), data.perfTiming.domContentLoadedEventStart - data.perfTiming.domLoading + "ms", 40),
createTile(dom.newTag("span", {title : "domLoading to loadEventStart", text : "DOM Processing"}), data.perfTiming.domComplete - data.perfTiming.domLoading + "ms", 40)
].forEach(function(tile){
tilesHolder.appendChild(tile);
});
if(data.allResourcesCalc.length > 0){
tilesHolder.appendChild(createTile(dom.newTag("span", {title : data.slowestCalls[0].name, text : "Slowest Call"}), dom.newTag("span", {title : data.slowestCalls[0].name, text : Math.floor(data.slowestCalls[0].duration) + "ms"}), 40));
tilesHolder.appendChild(createTile("Average Call", data.average + "ms", 40));
}
createAppendixDefValue(appendix, dom.newTag("abbr", {title : "Top Level Domain", text : "TLD"}, location.host.split(".").slice(-2).join(".")));
createAppendixDefValue(appendix, dom.newTextNode("Host:"), location.host);
createAppendixDefValue(appendix, dom.newTextNode("document.domain:"), document.domain);
tilesHolder.appendChild(appendix);
return tilesHolder;
};
export default summaryTilesComponent;
| {
"content_hash": "0aad7a407a4a6df7b8170615892bcc56",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 236,
"avg_line_length": 45.41269841269841,
"alnum_prop": 0.7098916462775253,
"repo_name": "ahmadassaf/Performance-bookmarklet",
"id": "3a1301b8e767c079d9c0155ae101294656e797bb",
"size": "2861",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "src/components/summaryTiles.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5796"
},
{
"name": "JavaScript",
"bytes": "119183"
}
],
"symlink_target": ""
} |
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.state.Node;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
public class EventLog implements EventLogInterface {
public static Logger log = Logger.getLogger(EventLog.class.getName());
private final Timer timer;
private final LinkedList<Event> eventLog = new LinkedList<>();
private final Map<Node, LinkedList<NodeEvent>> nodeLog = new TreeMap<>();
private final MetricUpdater metricUpdater; // may be null
private long eventsSeen = 0;
private final long startTime;
private int maxSize = 1024;
private int maxNodeSize = 1024;
private final long recentTimePeriod = 7 * 24 * 60 * 60 * 1000; // millisecs - 1 week
/** Note: metricReporter may be null. */
public EventLog(Timer timer, MetricUpdater metricUpdater) {
this.timer = timer;
this.startTime = timer.getCurrentTimeInMillis();
this.metricUpdater = metricUpdater;
}
public void setMaxSize(int size, int nodesize) {
if (size < 1 || nodesize < 1) {
throw new IllegalArgumentException("Max size must be at least 1");
}
maxSize = size;
while (eventLog.size() > maxSize) {
eventLog.remove(0);
}
maxNodeSize = nodesize;
for (List<NodeEvent> list : nodeLog.values()) {
while (list.size() > maxNodeSize) {
list.remove(0);
}
}
}
public long getRecentTimePeriod() { return recentTimePeriod; }
public void add(Event e) { add(e, true); }
public void add(Event e, boolean logInfo) {
++eventsSeen;
eventLog.add(e);
if (eventLog.size() > maxSize) {
eventLog.remove(0);
}
if (e instanceof NodeEvent) {
addNodeOnlyEvent((NodeEvent)e, logInfo ? Level.INFO: Level.FINE);
} else {
log.log(logInfo ? Level.INFO : Level.FINE, e::toString);
}
}
public void addNodeOnlyEvent(NodeEvent e, java.util.logging.Level level) {
log.log(level, "Added node only event: " + e.toString());
if (metricUpdater != null) {
metricUpdater.recordNewNodeEvent();
}
LinkedList<NodeEvent> nodeList = nodeLog.get(e.getNode().getNode());
if (nodeList == null) {
nodeList = new LinkedList<>();
nodeLog.put(e.getNode().getNode(), nodeList);
}
nodeList.add(e);
if (nodeList.size() > maxNodeSize) {
nodeList.remove(0);
}
}
public int getNodeEventsSince(Node n, long time) {
LinkedList<NodeEvent> events = nodeLog.get(n);
int count = 0;
if (events != null) {
Iterator<NodeEvent> it = events.descendingIterator();
while (it.hasNext()) {
NodeEvent e = it.next();
if (e.getTimeMs() < time) break;
++count;
}
}
return count;
}
/** Used in unit testing to verify events generated. */
public List<NodeEvent> getNodeEvents(Node n) {
return new ArrayList<>(nodeLog.get(n));
}
public void writeHtmlState(StringBuilder sb, Node node) {
TimeZone tz = TimeZone.getTimeZone("UTC");
LinkedList<Event> events = new LinkedList<>();
long currentTime = timer.getCurrentTimeInMillis();
long recentNodeEvents = 0;
if (node == null) {
events = eventLog;
sb.append("<h2 id=\"eventlog\">Event log</h2>\n")
.append("<p>A total number of " + eventsSeen + " has been seen since ").append(RealTimer.printDate(startTime, tz)).append(".</p>\n");
} else {
if (nodeLog.containsKey(node)) {
events.addAll(nodeLog.get(node));
}
recentNodeEvents = getNodeEventsSince(node, currentTime - recentTimePeriod);
sb.append("<h2>Node event log for " + node + "</h2>\n")
.append("<p>A total number of " + events.size() + " events has been seen since ")
.append(RealTimer.printDate(startTime, tz)).append(".</p>\n")
.append("<p>Recently, " + recentNodeEvents + " events has been seen since ")
.append(RealTimer.printDate(currentTime - recentTimePeriod, tz)).append(".</p>\n");
}
sb.append("<table border=\"1\" cellspacing=\"0\">\n")
.append("<tr><td>Date (").append(tz.getDisplayName(false, TimeZone.SHORT))
.append(")</td><td>Type</td><td>Node</td><td>Bucket space</td><td>Event</td></tr>\n");
int nr = 0;
Iterator<Event> eventIterator = (events == null ? null : events.descendingIterator());
if (eventIterator != null) while (eventIterator.hasNext()) {
Event e = eventIterator.next();
String colStart = "<font color=\"" + (++nr > recentNodeEvents ? "grey" : "black") + "\">";
String colEnd = "</font>";
sb.append("<tr>\n");
addNobrTableCell(sb, colStart, colEnd, RealTimer.printDate(e.getTimeMs(), tz));
addNobrTableCell(sb, colStart, colEnd, e.getCategory());
if (e instanceof NodeEvent) {
NodeEvent nodeEvent = (NodeEvent)e;
addNobrTableCell(sb, colStart, colEnd, nodeEvent.getNode().toString());
addNobrTableCell(sb, colStart, colEnd, nodeEvent.getBucketSpace().orElse(" - "));
} else {
addNobrTableCell(sb, colStart, colEnd, " - ");
addNobrTableCell(sb, colStart, colEnd, " - ");
}
addTableCell(sb, colStart, colEnd, e.getDescription());
sb.append("</tr>\n");
}
sb.append("</table>\n");
}
private static void addNobrTableCell(StringBuilder sb, String colStart, String colEnd, String cellValue) {
sb.append(" <td><nobr>").append(colStart).append(cellValue).append(colEnd).append("</nobr></td>\n");
}
private static void addTableCell(StringBuilder sb, String colStart, String colEnd, String cellValue) {
sb.append(" <td>").append(colStart).append(cellValue).append(colEnd).append("</td>\n");
}
}
| {
"content_hash": "88fd1341f529cc6bf092477a95733e4b",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 147,
"avg_line_length": 40.092592592592595,
"alnum_prop": 0.5919938414164743,
"repo_name": "vespa-engine/vespa",
"id": "0058d12f640797d4d5fb6073e0c444c82628996b",
"size": "6495",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clustercontroller-core/src/main/java/com/yahoo/vespa/clustercontroller/core/EventLog.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "8130"
},
{
"name": "C",
"bytes": "60315"
},
{
"name": "C++",
"bytes": "29580035"
},
{
"name": "CMake",
"bytes": "593981"
},
{
"name": "Emacs Lisp",
"bytes": "91"
},
{
"name": "GAP",
"bytes": "3312"
},
{
"name": "Go",
"bytes": "560664"
},
{
"name": "HTML",
"bytes": "54520"
},
{
"name": "Java",
"bytes": "40814190"
},
{
"name": "JavaScript",
"bytes": "73436"
},
{
"name": "LLVM",
"bytes": "6152"
},
{
"name": "Lex",
"bytes": "11499"
},
{
"name": "Makefile",
"bytes": "5553"
},
{
"name": "Objective-C",
"bytes": "12369"
},
{
"name": "Perl",
"bytes": "23134"
},
{
"name": "Python",
"bytes": "52392"
},
{
"name": "Roff",
"bytes": "17506"
},
{
"name": "Ruby",
"bytes": "10690"
},
{
"name": "Shell",
"bytes": "268737"
},
{
"name": "Yacc",
"bytes": "14735"
}
],
"symlink_target": ""
} |
using Orleans.Runtime;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Orleans;
using Orleans.Internal;
namespace UnitTests.StorageTests.Relational
{
/// <summary>
/// Utility function to provide random values to some tests.
/// </summary>
public static class RandomUtilities
{
/// <summary>
/// A sentinel value for when a generic parameter isn't used and applied to some function call.
/// </summary>
private class NotApplicable { };
/// <summary>
/// This type code is consistent with Orleans.Runtime.Category.Grain = 3, used also like
/// "public Category IdCategory { get { return GetCategory(TypeCodeData); } }".
/// Note that 0L would likely do also.
/// </summary>
public const long NormalGrainTypeCode = 3L;
/// <summary>
/// This type code is consistent with Orleans.Runtime.Category.Grain = 6, used also like
/// "public Category IdCategory { get { return GetCategory(TypeCodeData); } }".
/// Note that 0L would likely do also.
/// </summary>
public const long KeyExtensionGrainTypeCode = 6L;
/// <summary>
/// A rudimentary type switch that is read-only after construction and doesn't take into account inheritance etc. This is to simply
/// some generic code that bridges calls to non-generic code.
/// </summary>
/// <remarks>This switch could take the key generator function as a parameter, so the called could use this same code to
/// create known grain ID values.</remarks>
private static Dictionary<Type, Func<IInternalGrainFactory, Type, bool, object, IAddressable>> GrainReferenceTypeSwitch { get; } = new Dictionary<Type, Func<IInternalGrainFactory, Type, bool, object, IAddressable>>
{
[typeof(Guid)] = (grainFactory, type, keyExtension, state) =>
{
var range = ((Tuple<Range<long>, SymbolSet>)state).Item1;
var symbolSet = ((Tuple<Range<long>, SymbolSet>)state).Item2;
var extension = keyExtension ? GetRandomCharacters(symbolSet, range) : null;
Guid grainId = GetRandom<Guid>();
if(type != typeof(NotApplicable))
{
return grainFactory.GetGrain(LegacyGrainId.GetGrainId(UniqueKey.NewKey(grainId, keyExtension ? UniqueKey.Category.KeyExtGrain : UniqueKey.Category.Grain, keyExtension ? KeyExtensionGrainTypeCode : NormalGrainTypeCode, extension)));
}
return grainFactory.GetGrain(LegacyGrainId.GetGrainId(UniqueKey.NewKey(grainId, keyExtension ? UniqueKey.Category.KeyExtGrain : UniqueKey.Category.Grain, keyExtension ? KeyExtensionGrainTypeCode : NormalGrainTypeCode, extension)));
},
[typeof(long)] = (grainFactory, type, keyExtension, state) =>
{
var range = ((Tuple<Range<long>, SymbolSet>)state).Item1;
var symbolSet = ((Tuple<Range<long>, SymbolSet>)state).Item2;
var extension = keyExtension ? GetRandomCharacters(symbolSet, range) : null;
long grainId = GetRandom<long>();
if(type != typeof(NotApplicable))
{
return grainFactory.GetGrain(GrainId.Create("faketype", grainId.ToString()));
}
return grainFactory.GetGrain(LegacyGrainId.GetGrainId(UniqueKey.NewKey(grainId, keyExtension ? UniqueKey.Category.KeyExtGrain : UniqueKey.Category.Grain, keyExtension ? KeyExtensionGrainTypeCode : NormalGrainTypeCode, extension)));
},
[typeof(string)] = (grainFactory, type, keyExtension, state) =>
{
var range = ((Tuple<Range<long> , SymbolSet>)state).Item1;
var symbolSet = ((Tuple<Range<long>, SymbolSet>)state).Item2;
var grainId = GetRandomCharacters(symbolSet, range);
if(type != typeof(NotApplicable))
{
return grainFactory.GetGrain(LegacyGrainId.FromParsableString(LegacyGrainId.GetGrainId(NormalGrainTypeCode, grainId).ToParsableString()));
}
return grainFactory.GetGrain(LegacyGrainId.GetGrainId(NormalGrainTypeCode, grainId).ToGrainId());
}
};
/// <summary>
/// Pseudo-random number generator wrapped to protect from multi-threaded access.
/// </summary>
private static SafeRandom SafePseudoRandom { get; } = new SafeRandom();
/// <summary>
/// A list of random generators being used. This list is read-only after construction.
/// </summary>
/// <remarks>The state, basically the <see cref="Range{T}"/> object isn't used currently.</remarks>
private static Dictionary<Type, object> RandomGenerators { get; } = new Dictionary<Type, object>
{
[typeof(Guid)] = new Func<object, Guid>(state => { return Guid.NewGuid(); }),
[typeof(int)] = new Func<object, int>(state => { return SafePseudoRandom.Next(); }),
[typeof(long)] = new Func<object, long>(state =>
{
var bufferInt64 = new byte[sizeof(long)];
SafePseudoRandom.NextBytes(bufferInt64);
return BitConverter.ToInt64(bufferInt64, 0);
}),
[typeof(string)] = new Func<object, string>(symbolSet =>
{
var count = ((Tuple<Range<long>, SymbolSet>)symbolSet).Item1.Start;
var symbols = ((Tuple<Range<long>, SymbolSet>)symbolSet).Item2;
var builder = new StringBuilder();
for(long i = 0; i < count; ++i)
{
var symbolRange = symbols.SetRanges[SafePseudoRandom.Next(symbols.SetRanges.Count)];
builder.Append((char)SafePseudoRandom.Next(symbolRange.Start, symbolRange.End));
}
return builder.ToString();
})
};
/// <summary>
/// Get a random value of the given type.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns>Random value of the given type.</returns>
/// <exception cref="ArgumentException"/>.
public static T GetRandom<T>(Range<long> range = null)
{
object randomGenerator;
if(RandomGenerators.TryGetValue(typeof(T), out randomGenerator))
{
//If this a string type, some symbol set from which to draw the symbols needs to given
//and a special kind of a parameter constructed.
if((typeof(T) == typeof(string)))
{
const long SymbolsDefaultCount = 15;
var symbols = new SymbolSet(SymbolSet.Latin1);
return ((Func<object, T>)randomGenerator)(Tuple.Create(range ?? new Range<long>(SymbolsDefaultCount, SymbolsDefaultCount), symbols));
}
return ((Func<object, T>)randomGenerator)(null);
}
throw new ArgumentException(typeof(T).Name);
}
/// <summary>
/// Get random symbols.
/// </summary>
/// <param name="symbolSet">The set of symbols from which the random characters are drawn from.</param>
/// <param name="count">The count of random symbols.</param>
/// <returns>A random string.</returns>
/// <exception cref="ArgumentNullException"/>.
/// <exception cref="ArgumentOutOfRangeException"/>.
public static string GetRandomCharacters(SymbolSet symbolSet, long count)
{
return GetRandomCharacters(symbolSet, new Range<long>(count, count));
}
/// <summary>
/// Get random symbols.
/// </summary>
/// <param name="symbolSet">The set of symbols from which the random characters are drawn from.</param>
/// <param name="count">The count of random symbols.</param>
/// <returns>A random string.</returns>
/// <exception cref="ArgumentNullException"/>.
/// <exception cref="ArgumentOutOfRangeException"/>.
public static string GetRandomCharacters(SymbolSet symbolSet, Range<long> count)
{
if(symbolSet == null)
{
throw new ArgumentNullException(nameof(symbolSet));
}
if(count.Start < 1)
{
throw new ArgumentOutOfRangeException(nameof(count), "The count news to be more than zero.");
}
object randomGenerator = RandomGenerators[typeof(string)];
return ((Func<object, string>)randomGenerator)(Tuple.Create(count, symbolSet));
}
/// <summary>
/// Get a random grain reference.
/// </summary>
/// <typeparam name="TGrainKey">The grain key type.</typeparam>
/// <typeparam name="TGrainGeneric">The type of the generic part of a grain.</typeparam>
/// <param name="grainFactory">The grain factory.</param>
/// <param name="keyExtension">Should an extension key be defined or not.</param>
/// <returns>Random value of the given type.</returns>
/// <exception cref="ArgumentException"/>.
internal static GrainReference GetRandomGrainReference<TGrainKey, TGrainGeneric>(IInternalGrainFactory grainFactory, bool keyExtension)
{
Func<IInternalGrainFactory, Type, bool, object, IAddressable> func;
if(GrainReferenceTypeSwitch.TryGetValue(typeof(TGrainKey), out func))
{
//If this a string type, some symbol set from which to draw the symbols needs to given
//and a special kind of a parameter constructed.
const long SymbolsDefaultCount = 15;
var symbols = new SymbolSet(SymbolSet.Latin1);
return (GrainReference)func(grainFactory, typeof(TGrainGeneric), keyExtension, Tuple.Create(new Range<long>(SymbolsDefaultCount, SymbolsDefaultCount), symbols));
}
throw new ArgumentException(typeof(TGrainKey).Name);
}
/// <summary>
/// Get a random grain reference.
/// </summary>
/// <typeparam name="TGrainKey">The grain key type.</typeparam>
/// <typeparam name="TGrainGeneric">The type of the generic part of a grain.</typeparam>
/// <param name="grainFactory">The grain factory.</param>
/// <param name="symbolSet">symbolset to use.</param>
/// <param name="symbolCount">number of symbols to take from symbol set.</param>
/// <param name="keyExtension">Should an extension key be defined or not.</param>
/// <returns>Random value of the given type.</returns>
/// <exception cref="ArgumentException"/>.
internal static GrainReference GetRandomGrainReference<TGrainKey, TGrainGeneric>(IInternalGrainFactory grainFactory, SymbolSet symbolSet, long symbolCount = 15, bool keyExtension = false)
{
if(symbolSet == null)
{
throw new ArgumentNullException(nameof(symbolSet));
}
Func<IInternalGrainFactory, Type, bool, object, IAddressable> func;
if(GrainReferenceTypeSwitch.TryGetValue(typeof(TGrainKey), out func))
{
return (GrainReference)func(grainFactory, typeof(TGrainGeneric), keyExtension, Tuple.Create(new Range<long>(symbolCount, symbolCount), symbolSet));
}
throw new ArgumentException(typeof(TGrainKey).Name);
}
/// <summary>
/// Get a random grain reference.
/// </summary>
/// <param name="grainFactory">The grain factory.</param>
/// <param name="extensionKey">The grain extension key.</param>
/// <returns>Random value of the given type.</returns>
/// <exception cref="ArgumentException"/>.
internal static GrainReference GetRandomGrainReference<T>(IInternalGrainFactory grainFactory, bool extensionKey = false)
{
return GetRandomGrainReference<T, NotApplicable>(grainFactory, extensionKey);
}
}
}
| {
"content_hash": "56382f204018c985ed9a5d6d91b3822b",
"timestamp": "",
"source": "github",
"line_count": 254,
"max_line_length": 251,
"avg_line_length": 48.37007874015748,
"alnum_prop": 0.6089858375386619,
"repo_name": "ReubenBond/orleans",
"id": "354adada5694f9c928a7fe72d5a95472cdea4132",
"size": "12286",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "test/TesterInternal/StorageTests/RandomUtilities.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "8781"
},
{
"name": "C#",
"bytes": "9388748"
},
{
"name": "F#",
"bytes": "2433"
},
{
"name": "PLSQL",
"bytes": "23948"
},
{
"name": "PLpgSQL",
"bytes": "53492"
},
{
"name": "PowerShell",
"bytes": "2622"
},
{
"name": "Smalltalk",
"bytes": "1436"
},
{
"name": "TSQL",
"bytes": "22808"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Angular2 Seed</title>
</head>
<body>
<app>
Loading...
</app>
<script src="dist/polyfills.bundle.js"></script>
<script src="dist/vendor.bundle.js"></script>
<script src="dist/main.bundle.js"></script>
</body>
</html>
| {
"content_hash": "57b175fd2a2d2a9afa0b60b875378654",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 72,
"avg_line_length": 20.63157894736842,
"alnum_prop": 0.6045918367346939,
"repo_name": "pikachu49/is2-2016-2-final",
"id": "56f77f23fa05b287a75315defb15218d2ffddd10",
"size": "392",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/server/statics/webapps/dashboard/src/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1449"
},
{
"name": "HTML",
"bytes": "3500"
},
{
"name": "JavaScript",
"bytes": "12264"
},
{
"name": "TypeScript",
"bytes": "44620"
}
],
"symlink_target": ""
} |
/*
* ContextoSpring.java
*
* Created on 12 de Outubro de 2007, 17:09
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package br.uff.ic.oceano.contexto;
import br.uff.ic.oceano.util.SystemUtil;
/**
*
* @author Kann
*/
public class ConstantesAplicacao {
public final static String DIR_BASE_CHECKOUTS = "checkouts-oceano" + SystemUtil.FILESEPARATOR;
public static String DIR_BASE_JNLP = "/upload/jnlp/peixeespada";
public static String DIR_FILE_INFO_UPLOAD = "/info.txt";
//perfins
// public final static String IMAGEM_OSTRA = "ostra.jpg";
public final static String IMAGEM_OSTRA = "ostraInterno.jpg";
public final static String IMAGEM_PEIXE_ESPADA = "espada.PNG";
public final static String IMAGEM_OCEANO = "oceano.jpg";
public final static String IMAGEM_POLVO = "polvo.jpg";
public final static String MESSAGES_PROPERTIES = "br.uff.ic.oceano.messages.Mensagens";
public static String IMAGEM_INTERNO = IMAGEM_OCEANO;
}
| {
"content_hash": "f046206990eb1c5e753dfbdf964c620e",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 98,
"avg_line_length": 34.193548387096776,
"alnum_prop": 0.6981132075471698,
"repo_name": "gems-uff/oceano",
"id": "f0cad6a33c92cadfd64ac71aad1795030ed2f2ce",
"size": "1060",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/src/main/java/br/uff/ic/oceano/contexto/ConstantesAplicacao.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AspectJ",
"bytes": "12287"
},
{
"name": "C",
"bytes": "43307"
},
{
"name": "C++",
"bytes": "4018320"
},
{
"name": "CMake",
"bytes": "14856"
},
{
"name": "CSS",
"bytes": "23225"
},
{
"name": "HTML",
"bytes": "217913"
},
{
"name": "Java",
"bytes": "6597786"
},
{
"name": "JavaScript",
"bytes": "9776"
},
{
"name": "Makefile",
"bytes": "3470"
},
{
"name": "Shell",
"bytes": "1260"
}
],
"symlink_target": ""
} |
title: "Use secrets management in Sensu"
linkTitle: "Use Secrets Management"
description: "Sensu's secrets management allows you to avoid exposing secrets like usernames and passwords in your Sensu configuration. In this guide, you'll learn how to use Sensu's built-in secrets provider or HashiCorp Vault and refer to external secrets in your Sensu configuration."
weight: 175
version: "5.17"
product: "Sensu Go"
platformContent: False
menu:
sensu-go-5.17:
parent: guides
---
- [Retrieve your PagerDuty Integration Key](#retrieve-your-pagerduty-integration-key)
- [Use Env for secrets management](#use-env-for-secrets-management)
- [Create your backend environment variable](#create-your-backend-environment-variable)
- [Create your Env secret](#create-your-env-secret)
- [Use HashiCorp Vault for secrets management](#use-hashicorp-vault-for-secrets-management)
- [Configure your Vault authentication method (token or TLS)](#configure-your-vault-authentication-method-token-or-tls)
- [Create your Vault secret](#create-your-vault-secret)
- [Add a handler](#add-a-handler)
- [Register the PagerDuty handler asset](#register-the-pagerduty-handler-asset)
- [Add your secret to the handler spec](#add-your-secret-to-the-handler-spec)
- [Next steps](#next-steps)
**COMMERCIAL FEATURE**: Access the Env and VaultProvider secrets provider datatypes in the packaged Sensu Go distribution.
For more information, see [Get started with commercial features][20].
Sensu's secrets management allows you to avoid exposing secrets like usernames, passwords, and access keys in your Sensu configuration.
In this guide, you'll learn how to use Sensu's built-in secrets provider, `Env`, or [HashiCorp Vault][1] as your external [secrets provider][2] and authenticate without exposing your secrets.
You'll set up your PagerDuty Integration Key as a secret and create a PagerDuty handler definition that requires the secret.
Your Sensu backend can then execute the handler with any check.
To follow this guide, you’ll need to [install the Sensu backend][5], have at least one [Sensu agent][11] running, and [install and configure sensuctl][7].
Secrets are configured via [secrets resources][8].
A secret resource definition refers to the secrets provider (`Env` or `VaultProvider`) and an ID (the named secret to fetch from the secrets provider).
This guide only covers the handler use case, but you can use secrets management in handler, mutator, and check execution.
For secrets management in checks, the Sensu backend will transmit requests over its secure transport (TLS-encrypted websockets) to your Sensu agent to execute your check, so mTLS must be enabled.
The secret included in your Sensu handler will be exposed to Sensu services at runtime as an environment variable.
Sensu only exposes secrets to Sensu services like environment variables and automatically redacts secrets from all logs, the API, and the web UI.
## Retrieve your PagerDuty Integration Key
The example in this guide uses the [PagerDuty][31] Integration Key as a secret and a PagerDuty handler definition that requires the secret.
Here's how to find your Integration Key in PagerDuty so you can set it up as your secret:
1. Log in to your PagerDuty account.
2. In the **Configuration** drop-down menu, select **Services**.
3. Click your Sensu service.
4. Click the **Integrations** tab. The Integration Key is listed in the second column.
<div style="text-align:center">
<img alt="PagerDuty Integration Key location" title="PagerDuty Integration Key location" src="/images/sensu-pagerduty-integration-key.png" width="800 px">
</div>
<p style="text-align:center"><i>PagerDuty Integration Key location</i></p>
Make a note of your Integration Key — you'll need it to create your [backend environment variable][28] or [HashiCorp Vault secret][29].
## Use Env for secrets management
The [Sensu Go commercial distribution][1] includes a built-in secrets provider, `Env`, that exposes secrets from [environment variables][21] on your Sensu backend nodes.
The `Env` secrets provider is automatically created with an empty `spec` when you start your Sensu backend.
### Create your backend environment variable
To use the built-in `Env` secrets provider, you will add your secret as a backend environment variable.
First, make sure you have created the files you need to store [backend environment variables][21].
Then, run the following code, replacing `INTEGRATION_KEY` with your PagerDuty Integration Key:
{{< language-toggle >}}
{{< highlight "Ubuntu/Debian" >}}
$ echo 'SENSU_PAGERDUTY_KEY=INTEGRATION_KEY' | sudo tee -a /etc/default/sensu-backend
$ sudo systemctl restart sensu-backend
{{< /highlight >}}
{{< highlight "RHEL/CentOS" >}}
$ echo 'SENSU_PAGERDUTY_KEY=INTEGRATION_KEY' | sudo tee -a /etc/sysconfig/sensu-backend
$ sudo systemctl restart sensu-backend
{{< /highlight >}}
{{< /language-toggle >}}
This configures the `SENSU_PAGERDUTY_KEY` environment variable to your PagerDuty Integration Key in the context of the sensu-backend process.
### Create your Env secret
Now you'll use `sensuctl create` to create your secret.
This code creates a secret named `pagerduty_key` that refers to the environment variable ID `SENSU_PAGERDUTY_KEY`.
Run:
{{< highlight shell >}}
cat << EOF | sensuctl create
---
type: Secret
api_version: secrets/v1
metadata:
name: pagerduty_key
namespace: default
spec:
id: SENSU_PAGERDUTY_KEY
provider: env
EOF
{{< /highlight >}}
You can securely pass your PagerDuty Integration Key in Sensu checks, handlers, and mutators by referring to the `pagerduty_key` secret.
Skip to the [add a handler][19] section, where you'll use your `pagerduty_key` secret in your handler definition.
## Use HashiCorp Vault for secrets management
This section explains how to use [HashiCorp Vault][1] as your external [secrets provider][2] to authenticate via the HashiCorp Vault integration's [token auth method][3] or [TLS certificate auth method][4].
_**NOTE**: You must set up [HashiCorp Vault][15] to use `VaultProvider` secrets management in production. The examples in this guide use the [Vault dev server][32], which is useful for learning and experimenting. The Vault dev server gives you access to a preconfigured, running Vault server with in-memory storage that you can use right away. Follow the [HashiCorp Learn curriculum][16] when you are ready to set up a production server in Vault.<br><br>The examples in this guide use the [Vault KV secrets engine][27] with the path `"secret/"`. Using the Vault KV secrets engine with the Vault dev server requires v2 connections.
For this reason, in the `VaultProvider` spec in these examples, the client `version` value is **v2**._
### Configure your Vault authentication method (token or TLS)
If you use [HashiCorp Vault][1] as your external [secrets provider][2], you can authenticate via the HashiCorp Vault integration's [token][3] or [transport layer security (TLS) certificate][4] authentication method.
#### Vault token authentication
Follow the steps in this section to use HashiCorp Vault as your external [secrets provider][2] to authenticate with the HashiCorp Vault integration's [token auth method][3].
##### Retrieve your Vault root token
_**NOTE**: The examples in this guide use the `Root Token` for the the [Vault dev server][18], which gives you access to a preconfigured, running Vault server with in-memory storage that you can use right away. Follow the [HashiCorp Learn curriculum][16] when you are ready to set up a production server in Vault._
To retrieve your Vault root token:
1. [Download and install][25] the Vault edition for your operating system.
2. Open a terminal window and run `vault server -dev`.
The command output includes a `Root Token` line.
Find this line in your command output and copy the `Root Token` value.
You will use it next to create your Vault secrets provider.
<div style="text-align:center">
<img alt="HashiCorp Vault Root Token location" title="HashiCorp Vault Root Token location" src="/images/vault-dev-root-token.png">
</div>
<p style="text-align:center"><i>HashiCorp Vault Root Token location</i></p>
Leave the Vault dev server running.
Because you aren't using TLS, you will need to set `VAULT_ADDR=http://127.0.0.1:8200` in your shell environment.
##### Create your Vault secrets provider
_**NOTE**: In Vault's dev server, TLS is not enabled, so you won't be able to use certificate-based authentication._
Use `sensuctl create` to create your secrets provider, `vault`.
In the code below, replace `ROOT_TOKEN` with the `Root Token` value for your Vault dev server.
Then, run:
{{< highlight shell >}}
cat << EOF | sensuctl create
---
type: VaultProvider
api_version: secrets/v1
metadata:
name: vault
spec:
client:
address: http://localhost:8200
token: ROOT_TOKEN
version: v2
tls: null
max_retries: 2
timeout: 20s
rate_limiter:
limit: 10
burst: 100
EOF
{{< /highlight >}}
To continue, skip ahead to [create your Vault secret][29].
#### Vault TLS certificate authentication
This section explains how use HashiCorp Vault as your external [secrets provider][2] to authenticate with the HashiCorp Vault integration's [TLS certificate auth method][4].
_**NOTE**: You will need to set up [HashiCorp Vault][15] in production to use TLS certificate-based authentication. In Vault's dev server, TLS is not enabled. Follow the [HashiCorp Learn curriculum][16] when you are ready to set up a production server in Vault._
First, in your Vault, [enable and configure certificate authentication][33].
For example, your Vault might be configured for certificate authentication like this:
{{< highlight shell >}}
vault write auth/cert/certs/sensu-backend \
display_name=sensu-backend \
policies=sensu-backend-policy \
certificate=@sensu-backend-vault.pem \
ttl=3600
{{< /highlight >}}
Second, configure your `VaultProvider` in Sensu:
{{< highlight yaml >}}
---
type: VaultProvider
api_version: secrets/v1
metadata:
name: vault
spec:
client:
address: https://vault.example.com:8200
version: v2
tls:
ca_cert: /path/to/your/ca.pem
client_cert: /etc/sensu/ssl/sensu-backend-vault.pem
client_key: /etc/sensu/ssl/sensu-backend-vault-key.pem
cname: sensu-backend.example.com
max_retries: 2
timeout: 20s
rate_limiter:
limit: 10
burst: 100
{{< /highlight >}}
The certificate you specify for `tls.client_cert` should be the same certificate you configured in your Vault for certificate authentication.
Next, [create your Vault secret][29].
### Create your Vault secret
First, retrieve your [PagerDuty Integration Key][30] (the secret you will set up in Vault).
Next, open a new terminal and run `vault kv put secret/pagerduty key=INTEGRATION_KEY`.
Replace `INTEGRATION_KEY` with your PagerDuty Integration Key.
This writes your secret into Vault.
In this example, the name of the secret is `pagerduty`.
The `pagerduty` secret contains a key, and you specified that the `key` value is your PagerDuty Integration Key.
The `id` value for your secret will be `secret/pagerduty#key`.
_**NOTE**: The `id` value for secrets that target a HashiCorp Vault must start with the name of the secret's path in Vault.
The Vault dev server is preconfigured with the `secret` keyspace already set up, so we recommend using the `secret/` path for the `id` value while you are learning and getting started with Vault secrets management._
Run `vault kv get secret/pagerduty` to see the secret you just set up.
Use `sensuctl create` to create your `vault` secret:
{{< highlight shell >}}
cat << EOF | sensuctl create
---
type: Secret
api_version: secrets/v1
metadata:
name: pagerduty_key
namespace: default
spec:
id: secret/pagerduty#key
provider: vault
EOF
{{< /highlight >}}
Now you can securely pass your PagerDuty Integration Key in the handlers, and mutators by referring to the `pagerduty_key` secret.
In the [add a handler][19] section, you'll use your `pagerduty_key` secret in your handler definition.
## Add a handler
### Register the PagerDuty Handler asset
To begin, register the [Sensu PagerDuty Handler asset][23] with [`sensuctl asset add`][22]:
{{< highlight shell >}}
sensuctl asset add sensu/sensu-pagerduty-handler:1.2.0 -r pagerduty-handler
{{< /highlight >}}
This example uses the `-r` (rename) flag to specify a shorter name for the asset: `pagerduty-handler`.
_**NOTE**: You can [adjust the asset definition][26] according to your Sensu configuration if needed._
Run `sensuctl asset list --format yaml` to confirm that the asset is ready to use.
With this handler, Sensu can trigger and resolve PagerDuty incidents.
However, you still need to add your secret to the handler spec so that it requires your backend to request secrets from your secrets provider.
### Add your secret to the handler spec
To create a handler definition that uses your `pagerduty_key` secret, run:
{{< highlight shell >}}
cat << EOF | sensuctl create
---
api_version: core/v2
type: Handler
metadata:
namespace: default
name: pagerduty
spec:
type: pipe
command: pagerduty-handler --token $PD_TOKEN
secrets:
- name: PD_TOKEN
secret: pagerduty_key
runtime_assets:
- pagerduty-handler
timeout: 10
filters:
- is_incident
EOF
{{< /highlight >}}
Now that your handler is set up and Sensu can create incidents in PagerDuty, you can automate this workflow by adding your `pagerduty` handler to your Sensu service check definitions.
See [Monitor server resources][24] to learn more.
## Next steps
Read the [secrets][9] or [secrets providers][10] reference for in-depth secrets management documentation.
[1]: https://www.vaultproject.io/docs/what-is-vault/
[2]: ../../reference/secrets-providers/
[3]: https://www.vaultproject.io/docs/auth/token/
[4]: https://www.vaultproject.io/docs/auth/cert/
[5]: ../../installation/install-sensu/#install-the-sensu-backend
[6]: ../../installation/install-sensu/#install-sensu-agents
[7]: ../../installation/install-sensu/#install-sensuctl
[8]: ../../api/secrets/
[9]: ../../reference/secrets/
[10]: ../../reference/secrets-providers/
[11]: ../../installation/install-sensu/#install-sensu-agents
[12]: https://www.vaultproject.io/docs/concepts/lease.html#lease-durations-and-renewal
[13]: ../../api/secrets#providers-provider-put
[14]: ../../api/secrets#secrets-secret-put
[15]: https://www.vaultproject.io/docs/install/
[16]: https://learn.hashicorp.com/vault
[17]: ../../reference/secrets-providers#tls-vault
[18]: https://learn.hashicorp.com/vault/getting-started/dev-server
[19]: #add-a-handler
[20]: ../../commercial/
[21]: ../../reference/backend/#configuration-via-environment-variables
[22]: ../../sensuctl/reference/#install-asset-definitions
[23]: https://bonsai.sensu.io/assets/sensu/sensu-pagerduty-handler
[24]: ../monitor-server-resources/
[25]: https://www.vaultproject.io/downloads/
[26]: ../install-check-executables-with-assets/#2-adjust-the-asset-definition
[27]: https://www.vaultproject.io/api/secret/kv/kv-v2.html
[28]: #create-your-backend-environment-variable
[29]: #create-your-vault-secret
[30]: #retrieve-your-pagerduty-integration-key
[31]: https://www.pagerduty.com/
[32]: https://www.vaultproject.io/docs/concepts/dev-server/
[33]: https://www.vaultproject.io/docs/auth/cert/#configuration
| {
"content_hash": "e20195e390f841c83bdc1171e44a3ef5",
"timestamp": "",
"source": "github",
"line_count": 347,
"max_line_length": 630,
"avg_line_length": 44.242074927953894,
"alnum_prop": 0.7514981761334029,
"repo_name": "sensu/sensu-docs",
"id": "fd5c18b094334679149daf94f8982996e416cfde",
"size": "15358",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "archived/sensu-go/5.17/guides/secrets-management.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "123020"
},
{
"name": "JavaScript",
"bytes": "61971"
},
{
"name": "Procfile",
"bytes": "14"
},
{
"name": "Python",
"bytes": "3764"
},
{
"name": "Ruby",
"bytes": "4422"
},
{
"name": "SCSS",
"bytes": "32403"
},
{
"name": "Shell",
"bytes": "30924"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="ko-kr">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="generator" content="Hugo 0.15" />
<title>#Ludens</title>
<meta property="og:site_name" content="#Ludens" />
<meta property="og:locale" content="ko-kr" />
<meta property="og:url" content="http://ludens.kr/tags/the-incredible-machine/" />
<meta property="fb:pages" content="1707155736233413"/>
<meta property="fb:admins" content="100001662925065"/>
<meta property="fb:app_id" content="326482430777833"/>
<meta property="fb:article_style" content="default" />
<meta name="twitter:site" content="@ludensk" />
<meta name="twitter:creator" content="@ludensk" />
<meta name="google-site-verification" content="RPY_1Z0am0hoduGzENYtuwF3BBoE0x5l3UxhUplLWPU" />
<meta name="naver-site-verification" content="f84c50bc744edf7a543994325914265117555d53" />
<meta name="p:domain_verify" content="381496f2247c95edc614061bacd92e08" />
<meta name="msvalidate.01" content="9137E6F3A8C1C4AE6DC4809DEDB06FD9" />
<meta property="og:title" content="The Incredible Machine" />
<meta property="og:type" content="website" />
<meta name="description" content="페이스북부터 심리학 그리고 워드프레스까지 온갖 잡지식을 가끔씩 끄적이고 있습니다." />
<meta name="twitter:card" content="summary" />
<link rel="author" href="humans.txt" />
<link rel="me" href="https://twitter.com/ludensk" />
<link rel="me" href="https://google.com/+ludensk" />
<link rel="me" href="https://github.com/ludens" />
<link rel="pingback" href="https://webmention.io/ludens.kr/xmlrpc" />
<link rel="webmention" href="https://webmention.io/ludens.kr/webmention" />
<link href="https://plus.google.com/+ludensk" rel="publisher">
<link rel="canonical" href="http://ludens.kr/tags/the-incredible-machine/" />
<link rel="alternate" type="application/rss+xml" title="#Ludens" href="http://ludens.kr/rss/" />
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="#Ludens">
<meta name="mobile-web-app-capable" content="yes">
<meta name="theme-color" content="#111111">
<meta name="msapplication-navbutton-color" content="#111111">
<meta name="msapplication-TileColor" content="#111111">
<meta name="application-name" content="#Ludens">
<meta name="msapplication-tooltip" content="페이스북부터 심리학 그리고 워드프레스까지 온갖 잡지식을 가끔씩 끄적이고 있습니다.">
<meta name="msapplication-starturl" content="/">
<meta http-equiv="cleartype" content="on">
<meta name="msapplication-tap-highlight" content="no">
<link rel="apple-touch-icon" sizes="57x57" href="http://ludens.kr/favicon/apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="http://ludens.kr/favicon/apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="http://ludens.kr/favicon/apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="http://ludens.kr/favicon/apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="http://ludens.kr/favicon/apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="http://ludens.kr/favicon/apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="http://ludens.kr/favicon/apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="http://ludens.kr/favicon/apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="http://ludens.kr/favicon/apple-touch-icon-180x180.png">
<link rel="icon" type="image/png" href="http://ludens.kr/favicon/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="http://ludens.kr/favicon/favicon-194x194.png" sizes="194x194">
<link rel="icon" type="image/png" href="http://ludens.kr/favicon/favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="http://ludens.kr/favicon/android-chrome-192x192.png" sizes="192x192">
<link rel="icon" type="image/png" href="http://ludens.kr/favicon/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="http://ludens.kr/favicon/manifest.json">
<link rel="mask-icon" href="http://ludens.kr/favicon/safari-pinned-tab.svg" color="#5bbad5">
<meta name="msapplication-TileImage" content="/mstile-144x144.png">
<link rel="stylesheet" href="http://ludens.kr/css/pure/pure-min.css" />
<link rel="stylesheet" href="http://ludens.kr/css/pure/grids-responsive-min.css" />
<link rel='stylesheet' href='http://ludens.kr/font/fonts.css'>
<link rel="stylesheet" href="http://ludens.kr/font/font-awesome.min.css">
<link rel="stylesheet" href="http://ludens.kr/css/style.css"/>
<script src="http://ludens.kr/js/jquery-2.2.1.min.js"></script>
</head>
<body>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '326482430777833',
xfbml : true,
version : 'v2.6'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/ko_KR/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
<header class="pure-g">
<div class="pure-u-1 pure-u-sm-1-3 center">
<h1><a href="http://ludens.kr">#LUDENS</a></h1>
</div>
<nav class="pure-u-1 pure-u-sm-2-3 center">
<a href="http://ludens.kr/" class="home" title="Home">HOME</a>
<a href="http://ludens.kr/categories/" class="category" title="Category">CATEGORY</a>
<a href="http://ludens.kr/post/" class="archive" title="Archive">ARCHIVE</a>
<a href="http://ludens.kr/tags/" class="tag" title="Tag">TAG</a>
<a href="http://ludens.kr/guestbook/" class="guestbook" title="Guestbook">GUESTBOOK</a>
</nav>
</header>
<main class="list mainWrap">
<h2 class="ellipsis"><small>Posts about </small>The Incredible Machine</h2>
<h3 id="2015">2015</h3>
<div class="pure-g">
<div class="pure-u-1 pure-u-sm-1-2">
<a href="http://ludens.kr/post/19th-bifan-movies/" class="cover" style="background-image: url('/images/old/cfile29.uf.224BF03F5593DD1E1A1D4A.jpg');"></a>
<div class="category ubuntu300 grey">
<a class="grey" href="http://ludens.kr/categories/movie" title="Movie">Movie</a>
at <time datetime="1 Jul 2015 77:00">2015/7/1</time>
</div>
<h3 class="ellipsis margintop0"><a href="http://ludens.kr/post/19th-bifan-movies/" title="19번째 부천국제판타스틱 영화제서 보고싶은 영화들">19번째 부천국제판타스틱 영화제서 보고싶은 영화들</a></h3>
</div>
</div>
</main>
<footer>
<div class="footerWrap pure-g">
<div class="pure-u-1 pure-u-md-2-5 copyright center">
ⓒ 2016 Ludens | Published with <a class="black dotline" href="http://gohugo.io" target="_blank" rel="nofollow">Hugo</a>
</div>
<nav class="pure-u-1 pure-u-md-3-5 center">
<a href="https://twitter.com/ludensk" class="twitter" title="Twitter"><i class='fa fa-twitter-square'></i></a>
<a href="https://fb.com/ludensk" class="facebook" title="Facebook"><i class='fa fa-facebook-square'></i></a>
<a href="https://instagr.am/ludensk" class="instagram" title="Instagram"><i class='fa fa-instagram'></i></a>
<a href="https://pinterest.com/ludensk" class="pinterest" title="Pinterest"><i class='fa fa-pinterest-square'></i></a>
<a href="https://www.youtube.com/user/ludensk" class="youtube" title="YouTube"><i class='fa fa-youtube-square'></i></a>
<a href="https://ludensk.tumblr.com" class="tumblr" title="Tumblr"><i class='fa fa-tumblr-square'></i></a>
<a href="https://linkedin.com/in/ludensk" class="linkedin" title="LinkedIn"><i class='fa fa-linkedin-square'></i></a>
<a href="https://github.com/ludens" class="github" title="GitHub"><i class='fa fa-github-square'></i></a>
<a href="http://ludens.kr/rss/" class="rss" title="RSS"><i class='fa fa-rss-square'></i></a>
</nav>
</div>
</footer>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-29269230-1', 'auto');
ga('send', 'pageview');
</script>
<script type="text/javascript" src="//wcs.naver.net/wcslog.js"></script>
<script type="text/javascript">
if(!wcs_add) var wcs_add = {};
wcs_add["wa"] = "123cefa73667c5c";
wcs_do();
</script>
<script>
!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','//connect.facebook.net/en_US/fbevents.js');
fbq('init','1143503702345044');
fbq('track',"PageView");
</script>
<noscript><img height="1" width="1" style="display:none" src="//www.facebook.com/tr?id=1143503702345044&ev=PageView&noscript=1" /></noscript>
<script src="//twemoji.maxcdn.com/twemoji.min.js"></script>
<script>var emoji=document.getElementsByClassName("emoji");twemoji.parse(emoji[0],{size:16});</script>
<script src="http://ludens.kr/js/jquery.keep-ratio.min.js"></script>
<script type="text/javascript">
$(function() {
$('.kofic-poster').keepRatio({ ratio: 27/40, calculate: 'height' });
$('.articleWrap .cover, .post_latest .cover,.articleWrap header figure').keepRatio({ ratio: 12/5, calculate: 'height' });
if ($(window).width() >= 568) {
$('.futher .cover,.error .cover,.post_two .cover,.list .cover').keepRatio({ ratio: 4/3, calculate: 'height' });
$('.categories .cover').keepRatio({ ratio: 1/1, calculate: 'height' });
}
else {
$('.futher .cover,.error .cover,.post_two .cover,.list .cover,.categories .cover').keepRatio({ ratio: 12/5, calculate: 'height' });
}
});
</script>
</body>
</html> | {
"content_hash": "1b5d8c6d4c55553be6055b061af2313f",
"timestamp": "",
"source": "github",
"line_count": 229,
"max_line_length": 370,
"avg_line_length": 45.51091703056768,
"alnum_prop": 0.6567837267319132,
"repo_name": "ludens/ludens.kr",
"id": "f718cc8bf6747afcc6c8cbfbe5f7f4b50e854a96",
"size": "10652",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "tags/the-incredible-machine/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "18631"
},
{
"name": "HTML",
"bytes": "24946646"
},
{
"name": "JavaScript",
"bytes": "8525"
}
],
"symlink_target": ""
} |
import urllib
import pytest
from mitmproxy.test import taddons
from mitmproxy.test import tflow
import mitmproxy.test.tutils
from mitmproxy.addons import serverplayback
from mitmproxy import options
from mitmproxy import exceptions
from mitmproxy import io
def tdump(path, flows):
w = io.FlowWriter(open(path, "wb"))
for i in flows:
w.add(i)
def test_config(tmpdir):
s = serverplayback.ServerPlayback()
with taddons.context() as tctx:
fpath = str(tmpdir.join("flows"))
tdump(fpath, [tflow.tflow(resp=True)])
tctx.configure(s, server_replay=[fpath])
with pytest.raises(exceptions.OptionsError):
tctx.configure(s, server_replay=[str(tmpdir)])
def test_tick():
s = serverplayback.ServerPlayback()
with taddons.context() as tctx:
s.stop = True
s.final_flow = tflow.tflow()
s.final_flow.live = False
s.tick()
assert tctx.master.has_event("processing_complete")
def test_server_playback():
sp = serverplayback.ServerPlayback()
sp.configure(options.Options(), [])
f = tflow.tflow(resp=True)
assert not sp.flowmap
sp.load_flows([f])
assert sp.flowmap
assert sp.next_flow(f)
assert not sp.flowmap
sp.load_flows([f])
assert sp.flowmap
sp.clear()
assert not sp.flowmap
def test_ignore_host():
sp = serverplayback.ServerPlayback()
sp.configure(options.Options(server_replay_ignore_host=True), [])
r = tflow.tflow(resp=True)
r2 = tflow.tflow(resp=True)
r.request.host = "address"
r2.request.host = "address"
assert sp._hash(r) == sp._hash(r2)
r2.request.host = "wrong_address"
assert sp._hash(r) == sp._hash(r2)
def test_ignore_content():
s = serverplayback.ServerPlayback()
s.configure(options.Options(server_replay_ignore_content=False), [])
r = tflow.tflow(resp=True)
r2 = tflow.tflow(resp=True)
r.request.content = b"foo"
r2.request.content = b"foo"
assert s._hash(r) == s._hash(r2)
r2.request.content = b"bar"
assert not s._hash(r) == s._hash(r2)
s.configure(options.Options(server_replay_ignore_content=True), [])
r = tflow.tflow(resp=True)
r2 = tflow.tflow(resp=True)
r.request.content = b"foo"
r2.request.content = b"foo"
assert s._hash(r) == s._hash(r2)
r2.request.content = b"bar"
assert s._hash(r) == s._hash(r2)
r2.request.content = b""
assert s._hash(r) == s._hash(r2)
r2.request.content = None
assert s._hash(r) == s._hash(r2)
def test_ignore_content_wins_over_params():
s = serverplayback.ServerPlayback()
s.configure(
options.Options(
server_replay_ignore_content=True,
server_replay_ignore_payload_params=[
"param1", "param2"
]
),
[]
)
# NOTE: parameters are mutually exclusive in options
r = tflow.tflow(resp=True)
r.request.headers["Content-Type"] = "application/x-www-form-urlencoded"
r.request.content = b"paramx=y"
r2 = tflow.tflow(resp=True)
r2.request.headers["Content-Type"] = "application/x-www-form-urlencoded"
r2.request.content = b"paramx=x"
# same parameters
assert s._hash(r) == s._hash(r2)
def test_ignore_payload_params_other_content_type():
s = serverplayback.ServerPlayback()
with taddons.context() as tctx:
tctx.configure(
s,
server_replay_ignore_content=False,
server_replay_ignore_payload_params=[
"param1", "param2"
]
)
r = tflow.tflow(resp=True)
r.request.headers["Content-Type"] = "application/json"
r.request.content = b'{"param1":"1"}'
r2 = tflow.tflow(resp=True)
r2.request.headers["Content-Type"] = "application/json"
r2.request.content = b'{"param1":"1"}'
# same content
assert s._hash(r) == s._hash(r2)
# distint content (note only x-www-form-urlencoded payload is analysed)
r2.request.content = b'{"param1":"2"}'
assert not s._hash(r) == s._hash(r2)
def test_hash():
s = serverplayback.ServerPlayback()
s.configure(options.Options(), [])
r = tflow.tflow()
r2 = tflow.tflow()
assert s._hash(r)
assert s._hash(r) == s._hash(r2)
r.request.headers["foo"] = "bar"
assert s._hash(r) == s._hash(r2)
r.request.path = "voing"
assert s._hash(r) != s._hash(r2)
r.request.path = "path?blank_value"
r2.request.path = "path?"
assert s._hash(r) != s._hash(r2)
def test_headers():
s = serverplayback.ServerPlayback()
s.configure(options.Options(server_replay_use_headers=["foo"]), [])
r = tflow.tflow(resp=True)
r.request.headers["foo"] = "bar"
r2 = tflow.tflow(resp=True)
assert not s._hash(r) == s._hash(r2)
r2.request.headers["foo"] = "bar"
assert s._hash(r) == s._hash(r2)
r2.request.headers["oink"] = "bar"
assert s._hash(r) == s._hash(r2)
r = tflow.tflow(resp=True)
r2 = tflow.tflow(resp=True)
assert s._hash(r) == s._hash(r2)
def test_load():
s = serverplayback.ServerPlayback()
s.configure(options.Options(), [])
r = tflow.tflow(resp=True)
r.request.headers["key"] = "one"
r2 = tflow.tflow(resp=True)
r2.request.headers["key"] = "two"
s.load_flows([r, r2])
assert s.count() == 2
n = s.next_flow(r)
assert n.request.headers["key"] == "one"
assert s.count() == 1
n = s.next_flow(r)
assert n.request.headers["key"] == "two"
assert not s.flowmap
assert s.count() == 0
assert not s.next_flow(r)
def test_load_with_server_replay_nopop():
s = serverplayback.ServerPlayback()
s.configure(options.Options(server_replay_nopop=True), [])
r = tflow.tflow(resp=True)
r.request.headers["key"] = "one"
r2 = tflow.tflow(resp=True)
r2.request.headers["key"] = "two"
s.load_flows([r, r2])
assert s.count() == 2
s.next_flow(r)
assert s.count() == 2
def test_ignore_params():
s = serverplayback.ServerPlayback()
s.configure(
options.Options(
server_replay_ignore_params=["param1", "param2"]
),
[]
)
r = tflow.tflow(resp=True)
r.request.path = "/test?param1=1"
r2 = tflow.tflow(resp=True)
r2.request.path = "/test"
assert s._hash(r) == s._hash(r2)
r2.request.path = "/test?param1=2"
assert s._hash(r) == s._hash(r2)
r2.request.path = "/test?param2=1"
assert s._hash(r) == s._hash(r2)
r2.request.path = "/test?param3=2"
assert not s._hash(r) == s._hash(r2)
def thash(r, r2, setter):
s = serverplayback.ServerPlayback()
s.configure(
options.Options(
server_replay_ignore_payload_params=["param1", "param2"]
),
[]
)
setter(r, paramx="x", param1="1")
setter(r2, paramx="x", param1="1")
# same parameters
assert s._hash(r) == s._hash(r2)
# ignored parameters !=
setter(r2, paramx="x", param1="2")
assert s._hash(r) == s._hash(r2)
# missing parameter
setter(r2, paramx="x")
assert s._hash(r) == s._hash(r2)
# ignorable parameter added
setter(r2, paramx="x", param1="2")
assert s._hash(r) == s._hash(r2)
# not ignorable parameter changed
setter(r2, paramx="y", param1="1")
assert not s._hash(r) == s._hash(r2)
# not ignorable parameter missing
setter(r2, param1="1")
r2.request.content = b"param1=1"
assert not s._hash(r) == s._hash(r2)
def test_ignore_payload_params():
def urlencode_setter(r, **kwargs):
r.request.content = urllib.parse.urlencode(kwargs).encode()
r = tflow.tflow(resp=True)
r.request.headers["Content-Type"] = "application/x-www-form-urlencoded"
r2 = tflow.tflow(resp=True)
r2.request.headers["Content-Type"] = "application/x-www-form-urlencoded"
thash(r, r2, urlencode_setter)
boundary = 'somefancyboundary'
def multipart_setter(r, **kwargs):
b = "--{0}\n".format(boundary)
parts = []
for k, v in kwargs.items():
parts.append(
"Content-Disposition: form-data; name=\"%s\"\n\n"
"%s\n" % (k, v)
)
c = b + b.join(parts) + b
r.request.content = c.encode()
r.request.headers["content-type"] = 'multipart/form-data; boundary=' +\
boundary
r = tflow.tflow(resp=True)
r2 = tflow.tflow(resp=True)
thash(r, r2, multipart_setter)
def test_server_playback_full():
s = serverplayback.ServerPlayback()
with taddons.context() as tctx:
tctx.configure(
s,
refresh_server_playback = True,
)
f = tflow.tflow()
f.response = mitmproxy.test.tutils.tresp(content=f.request.content)
s.load_flows([f, f])
tf = tflow.tflow()
assert not tf.response
s.request(tf)
assert tf.response == f.response
tf = tflow.tflow()
tf.request.content = b"gibble"
assert not tf.response
s.request(tf)
assert not tf.response
assert not s.stop
s.tick()
assert not s.stop
tf = tflow.tflow()
s.request(tflow.tflow())
assert s.stop
def test_server_playback_kill():
s = serverplayback.ServerPlayback()
with taddons.context() as tctx:
tctx.configure(
s,
refresh_server_playback = True,
replay_kill_extra=True
)
f = tflow.tflow()
f.response = mitmproxy.test.tutils.tresp(content=f.request.content)
s.load_flows([f])
f = tflow.tflow()
f.request.host = "nonexistent"
tctx.cycle(s, f)
assert f.reply.value == exceptions.Kill
| {
"content_hash": "f7bd8dadf8b2e5365e9ffe64464267ed",
"timestamp": "",
"source": "github",
"line_count": 360,
"max_line_length": 79,
"avg_line_length": 27.094444444444445,
"alnum_prop": 0.5952429772401067,
"repo_name": "xaxa89/mitmproxy",
"id": "7078b66e35af392762c8ab07d327deaf24637f4d",
"size": "9754",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/mitmproxy/addons/test_serverplayback.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "17714"
},
{
"name": "HTML",
"bytes": "4270"
},
{
"name": "JavaScript",
"bytes": "150625"
},
{
"name": "PowerShell",
"bytes": "494"
},
{
"name": "Python",
"bytes": "1535155"
},
{
"name": "Shell",
"bytes": "3660"
}
],
"symlink_target": ""
} |
package com.navercorp.pinpoint.web.service.stat;
import com.navercorp.pinpoint.common.hbase.HBaseAdminTemplate;
import com.navercorp.pinpoint.common.hbase.HBaseTables;
import org.apache.hadoop.hbase.TableName;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
* @author HyunGil Jeong
*/
@Deprecated
@Service("legacyAgentStatChartServiceFactory")
public class LegacyAgentStatChartServiceFactory implements FactoryBean<LegacyAgentStatChartService> {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("#{pinpointWebProps['web.stat.format.compatibility.version'] ?: 'v2'}")
private String mode = "v2";
@Autowired
@Qualifier("legacyAgentStatChartV1Service")
private LegacyAgentStatChartService v1;
@Autowired
@Qualifier("legacyAgentStatChartV2Service")
private LegacyAgentStatChartService v2;
@Autowired
@Qualifier("legacyAgentStatChartCompatibilityService")
private LegacyAgentStatChartService compatibility;
@Autowired
private HBaseAdminTemplate adminTemplate;
@Override
public LegacyAgentStatChartService getObject() throws Exception {
logger.info("LegacyAgentStatService Compatibility {}", mode);
final TableName v1TableName = HBaseTables.AGENT_STAT;
final TableName v2TableName = HBaseTables.AGENT_STAT_VER2;
if (mode.equalsIgnoreCase("v1")) {
if (this.adminTemplate.tableExists(v1TableName)) {
return v1;
} else {
logger.error("LegacyAgentStatService configured for v1, but {} table does not exist", v1TableName);
throw new IllegalStateException(v1TableName + " table does not exist");
}
} else if (mode.equalsIgnoreCase("v2")) {
if (this.adminTemplate.tableExists(v2TableName)) {
return v2;
} else {
logger.error("LegacyAgentStatService configured for v2, but {} table does not exist", v2TableName);
throw new IllegalStateException(v2TableName + " table does not exist");
}
} else if (mode.equalsIgnoreCase("compatibilityMode")) {
boolean v1TableExists = this.adminTemplate.tableExists(v1TableName);
boolean v2TableExists = this.adminTemplate.tableExists(v2TableName);
if (v1TableExists && v2TableExists) {
return compatibility;
} else {
logger.error("LegacyAgentStatService configured for compatibilityMode, but {} and {} tables do not exist", v1TableName, v2TableName);
throw new IllegalStateException(v1TableName + ", " + v2TableName + " tables do not exist");
}
} else {
throw new IllegalStateException("Unknown LegacyAgentStatService configuration : " + mode);
}
}
@Override
public Class<?> getObjectType() {
return LegacyAgentStatChartService.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
| {
"content_hash": "5214e471a453eac2c71156d5e6d26ef2",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 149,
"avg_line_length": 38.172413793103445,
"alnum_prop": 0.6934658235471244,
"repo_name": "wziyong/pinpoint",
"id": "2654f559ae31931453f5b6633d1f0b6ff22081a6",
"size": "3915",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "web/src/main/java/com/navercorp/pinpoint/web/service/stat/LegacyAgentStatChartServiceFactory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "22853"
},
{
"name": "CSS",
"bytes": "109953"
},
{
"name": "CoffeeScript",
"bytes": "10124"
},
{
"name": "Groovy",
"bytes": "1423"
},
{
"name": "HTML",
"bytes": "515287"
},
{
"name": "Java",
"bytes": "8984255"
},
{
"name": "JavaScript",
"bytes": "1864793"
},
{
"name": "Makefile",
"bytes": "5246"
},
{
"name": "PLSQL",
"bytes": "4156"
},
{
"name": "Python",
"bytes": "3523"
},
{
"name": "Ruby",
"bytes": "943"
},
{
"name": "Shell",
"bytes": "30663"
},
{
"name": "Thrift",
"bytes": "7543"
}
],
"symlink_target": ""
} |
package com.twu.biblioteca;
/**
* Created by aarni on 1/8/15.
*/
public class MyProfileOption extends Option {
Library library;
public MyProfileOption(Library library){
this.library = library;
}
public void execute(){
showProfile();
}
public void showProfile(){
if(library.isLoggedIn()){
System.out.println(this.library.getCurrentUser().showDetails());
}else{
System.out.println("You must login to see your profile.");
}
}
}
| {
"content_hash": "2d47d9e3fd597b8ccb81a5236c72a789",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 76,
"avg_line_length": 21.791666666666668,
"alnum_prop": 0.6061185468451242,
"repo_name": "anikarni/twu-biblioteca-anike",
"id": "d5b908496d99e4e7fc42463d2b22860f3cfc0ec9",
"size": "523",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/twu/biblioteca/MyProfileOption.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "40147"
}
],
"symlink_target": ""
} |
function foo() {
return Number.isNaN();
};
%PrepareFunctionForOptimization(foo);
assertFalse(foo());
assertFalse(foo());
%OptimizeFunctionOnNextCall(foo);
assertFalse(foo());
| {
"content_hash": "b32cb004b2b56a677817d4910c5a3369",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 37,
"avg_line_length": 22.125,
"alnum_prop": 0.7457627118644068,
"repo_name": "youtube/cobalt_sandbox",
"id": "e1a70cfb95820ba451ecddfea037e28d2c2913d7",
"size": "379",
"binary": false,
"copies": "11",
"ref": "refs/heads/main",
"path": "third_party/v8/test/mjsunit/regress/regress-6082.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<?php
namespace app\modules\library\models;
use Yii;
/**
* This is the model class for table "library_book_formats".
*
* @property integer $id
* @property string $name
* @property string $description
* @property string $date_created
* @property string $date_update
*
* @property BookPrinting[] $bookPrintings
*/
class Format extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'library_formats';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['name', 'description', 'date_created'], 'required'],
[['description'], 'string'],
[['date_created', 'date_update'], 'safe'],
[['name'], 'string', 'max' => 100],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'description' => 'Description',
'date_created' => 'Date Created',
'date_update' => 'Date Update',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getBookPrintings()
{
return $this->hasMany(BookPrinting::className(), ['format_id' => 'id']);
}
}
| {
"content_hash": "bb8fa97d3b2aaf384640a8b7fd051550",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 80,
"avg_line_length": 20.870967741935484,
"alnum_prop": 0.517774343122102,
"repo_name": "nihilco/NF2",
"id": "23ae7219094cf1b7af8da09c4bb9489664e59c4b",
"size": "1294",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/library/models/Format.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "1030"
},
{
"name": "CSS",
"bytes": "1364"
},
{
"name": "PHP",
"bytes": "1112741"
}
],
"symlink_target": ""
} |
"""Global registry for OpDefs."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.core.framework import op_def_pb2
_registered_ops = {}
def register_op_list(op_list):
"""Register all the ops in an op_def_pb2.OpList."""
if not isinstance(op_list, op_def_pb2.OpList):
raise TypeError("%s is %s, not an op_def_pb2.OpList" %
(op_list, type(op_list)))
for op_def in op_list.op:
if op_def.name in _registered_ops:
assert _registered_ops[op_def.name] == op_def
else:
_registered_ops[op_def.name] = op_def
def get_registered_ops():
"""Returns a dictionary mapping names to OpDefs."""
return _registered_ops
| {
"content_hash": "991e33a3ecdd5c11b6714e66a1230a21",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 58,
"avg_line_length": 27.333333333333332,
"alnum_prop": 0.6639566395663956,
"repo_name": "kcartier/tensorflow-toe-in-the-water",
"id": "28e55a47a444909185d74890734c49147a76a50a",
"size": "738",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "tensorflow/python/framework/op_def_registry.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "127901"
},
{
"name": "C++",
"bytes": "4986624"
},
{
"name": "CSS",
"bytes": "107"
},
{
"name": "HTML",
"bytes": "638824"
},
{
"name": "Java",
"bytes": "44388"
},
{
"name": "JavaScript",
"bytes": "4876"
},
{
"name": "Objective-C",
"bytes": "630"
},
{
"name": "Protocol Buffer",
"bytes": "45325"
},
{
"name": "Python",
"bytes": "2494316"
},
{
"name": "Shell",
"bytes": "1714"
},
{
"name": "TypeScript",
"bytes": "238945"
}
],
"symlink_target": ""
} |
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var abstract_1 = require("./abstract");
var ContainerReflection = (function (_super) {
__extends(ContainerReflection, _super);
function ContainerReflection() {
return _super !== null && _super.apply(this, arguments) || this;
}
ContainerReflection.prototype.getChildrenByKind = function (kind) {
var values = [];
for (var key in this.children) {
var child = this.children[key];
if (child.kindOf(kind)) {
values.push(child);
}
}
return values;
};
ContainerReflection.prototype.traverse = function (callback) {
if (this.children) {
this.children.forEach(function (child) {
callback(child, abstract_1.TraverseProperty.Children);
});
}
};
ContainerReflection.prototype.toObject = function () {
var result = _super.prototype.toObject.call(this);
if (this.groups) {
var groups_1 = [];
this.groups.forEach(function (group) {
groups_1.push(group.toObject());
});
result['groups'] = groups_1;
}
if (this.sources) {
var sources_1 = [];
this.sources.forEach(function (source) {
sources_1.push({
fileName: source.fileName,
line: source.line,
character: source.character
});
});
result['sources'] = sources_1;
}
return result;
};
return ContainerReflection;
}(abstract_1.Reflection));
exports.ContainerReflection = ContainerReflection;
//# sourceMappingURL=container.js.map | {
"content_hash": "88242b3c9122e459b612eb754047b3ab",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 93,
"avg_line_length": 37.19672131147541,
"alnum_prop": 0.5403261348611723,
"repo_name": "ShareTracs/app",
"id": "5ab716a3210ff1068d5aacd2818c4b478c0dbbc5",
"size": "2269",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "node_modules/typedoc/dist/lib/models/reflections/container.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7088"
},
{
"name": "HTML",
"bytes": "105849"
},
{
"name": "JavaScript",
"bytes": "50657"
},
{
"name": "TypeScript",
"bytes": "25853"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "ff52f5defa9dd82c69dc0fec19025852",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "30fcd8e3fbff97bf9868becbe3511a7091b65fd3",
"size": "195",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Apiales/Griseliniaceae/Griselinia/Griselinia carlomunizii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2009-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<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/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>unifiedendpoint</artifactId>
<groupId>org.wso2.carbon.business-process</groupId>
<version>4.4.9-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.unifiedendpoint.core</artifactId>
<packaging>bundle</packaging>
<name>WSO2 Carbon - Component - Unified-Endpoint - Core</name>
<url>http://wso2.org</url>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>org.apache.synapse</groupId>-->
<!--<artifactId>synapse-core</artifactId>-->
<!--</dependency>-->
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.registry</groupId>
<artifactId>org.wso2.carbon.registry.ws.client</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Export-Package>
org.wso2.carbon.unifiedendpoint.core.*,
</Export-Package>
<Import-Package>
org.apache.axiom.*;
version="${axiom.osgi.version.range.unifiedendpoint}",
*;resolution:=optional
</Import-Package>
<DynamicImport-Package>*</DynamicImport-Package>
<Axis2Module>${project.artifactId}-${carbon.business-process.version}</Axis2Module>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>
| {
"content_hash": "2d2f0f527d48073f02eba88872b4a588",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 204,
"avg_line_length": 40.03157894736842,
"alnum_prop": 0.5811201682881936,
"repo_name": "NatashaWso2/carbon-business-process",
"id": "a67a01f1db4b83186746998b5a190ca69cd4ead8",
"size": "3803",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "components/unified-endpoint/org.wso2.carbon.unifiedendpoint.core/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "153131"
},
{
"name": "HTML",
"bytes": "33350"
},
{
"name": "Java",
"bytes": "5259666"
},
{
"name": "JavaScript",
"bytes": "1092769"
}
],
"symlink_target": ""
} |
class Application < Rails::Application
config.time_zone = "America/Indiana/Indianapolis"
end
| {
"content_hash": "e42058f8afe0c2556ece664c51a2e91d",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 51,
"avg_line_length": 31.666666666666668,
"alnum_prop": 0.7894736842105263,
"repo_name": "Bulldogse45/website_on_rails",
"id": "90e53d1ef54d9f8b2bb995fcc8cf3e0a04c867e1",
"size": "95",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/application.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "17721"
},
{
"name": "CoffeeScript",
"bytes": "1055"
},
{
"name": "HTML",
"bytes": "28282"
},
{
"name": "JavaScript",
"bytes": "5848"
},
{
"name": "Ruby",
"bytes": "47288"
}
],
"symlink_target": ""
} |
import zasim
import sys
ca_init, display_init, histogram_init = sys.argv[1:]
if ca_init == "constructor":
binrule = zasim.ca.BinRule(
rule = 110,
initial = zasim.conf.RandomConfiguration)
# this API must support setting the size manually and then initializing it
# from random data, zeros, ones, whatever as well as initializing it from
# a file
binrule.size = 300
binrule.init()
elif ca_init == "properties":
binRule = zasim.ca.BinRule()
# several attributes would actually be properties with getters and setters
binrule.rule = 110
binrule.size = (400,)
binrule.init(zasim.conf.RandomConfiguration)
if display_init == "constructor":
binrule_display = zasim.display.HistoryDisplay(
ca=binrule,
lines=300,
scale=2)
elif display_init == "properties":
binrule_display = zasim.display.HistoryDisplay()
binrule_display.ca = binrule
binrule_display.size = (800, 600)
elif display_init == "strange":
# maybe it would be nice if the different ca classes knew what kind of display
# is right for them
binrule_display = binrule.create_display(800, 600)
if histogram_init == "one_zero_distribution":
histogram = zasim.histogram.DistributionDisplay(binrule)
elif histogram_init == "activity_history":
histogram = zasim.histogram.ActivityHistoryDisplay(binrule)
elif histogram_init == "distribution_history":
histogram = zasim.histogram.DistributionHistoryDisplay(binrule)
histogram.show()
# open up the window
binrule_display.show()
# step once
# also update all guis related
binrule.step()
# do ten steps, update the gui as fast as possible
binrule.step(10)
# fast-forward 1000 steps without updating the gui
binrule.fast_step(1000)
# let the gui drive the stepping with delays
binrule_display.animate_steps(steps=1000, delay=0.01)
# why not also let the user say for how long it should animate?
binrule_display.animate_steps(steps=1000, time=10)
# displays should be able to save out images
binrule_display.screenshot("pretty.png")
# cas should be able to snapshot configurations or clone themselves
snap1 = binrule.snapshot()
binrule.step(100)
binrule.restore(snap1)
# maybe something like this is interesting
_snaps = []
def step_hook(ca):
_snaps.append(ca.snapshot())
binrule.step_hook(step_hook)
binrule.step(100)
binrule.step_hook(None)
# comparing configurations of different automatons - as long as they are
# comparable at all - is pretty neat, i suppose.
other_ca = binrule.shallow_clone()
# manipulation of cells should be possible from the gui as well as the shell
other_ca[10:15] = [0, 1, 0, 1, 1]
other_ca.step(100)
binrule.step(100)
# displaying a comparison between two configurations might work like this
diff = other_ca.diff(binrule)
diff_disp = zasim.display.DiffDisplay(diff)
# TODO zellularautomat game of life
# TODO moebius-bandtransformation
# TODO beliebige waende aneinanderkopieren
# 1. qt geschwindigkeit untersuchen: 1x1 pixel pro feld, 3x3 pixel, bilder
# 1d automat mit history, 2d automat (game of life z.B.)
# 2. vision implementieren
| {
"content_hash": "2a532d0cd31886cacec42d3f37535495",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 82,
"avg_line_length": 30.398058252427184,
"alnum_prop": 0.7304375598850208,
"repo_name": "timo/zasim",
"id": "b1ef79f0f897afce4502489d1369a3a35ec2c6da",
"size": "3131",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/vision.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "423165"
},
{
"name": "Shell",
"bytes": "4509"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="etc">
<select id="getList" resultType="map">
SELECT
SEQ as seq,
EMAIL as email,
WRITER as writer,
TITLE as title,
CONTENTS as contents,
STARTTIME as starttime,
ENDTIME as endtime,
REGTIME as regtime,
UPTIME as uptime
FROM SCHEDULE_VIEW
WHERE (TO_DAYS(STARTTIME) BETWEEN TO_DAYS(#{sDay}) AND TO_DAYS(LAST_DAY(#{eDay})) OR TO_DAYS(ENDTIME) BETWEEN TO_DAYS(#{sDay}) AND TO_DAYS(LAST_DAY(#{eDay})) OR TO_DAYS(#{sDay}) BETWEEN TO_DAYS(STARTTIME) AND TO_DAYS(ENDTIME))
AND ETCYN = 'Y'
ORDER BY STARTTIME ASC
</select>
<select id="getChart" resultType="map">
SELECT
(
SELECT
COUNT(s.SEQ)
FROM SCHEDULE_VIEW s
WHERE s.WRITER = e.NAME
AND (TO_DAYS(STARTTIME) BETWEEN TO_DAYS(#{sDay}) AND TO_DAYS(LAST_DAY(#{eDay})) OR TO_DAYS(ENDTIME) BETWEEN TO_DAYS(#{sDay}) AND TO_DAYS(LAST_DAY(#{eDay})) OR TO_DAYS(#{sDay}) BETWEEN TO_DAYS(STARTTIME) AND TO_DAYS(ENDTIME))
AND s.ETCYN = 'Y'
)as cnt,
e.NAME as name,
e.EMAIL as email
FROM EMPLOYEE e
</select>
</mapper> | {
"content_hash": "4c907e162df8814ad27da955f07d8938",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 228,
"avg_line_length": 34.27777777777778,
"alnum_prop": 0.6450567260940032,
"repo_name": "ParkMinKyu/intranet",
"id": "5fcd92340a10f4499cdcb0f8814433c998b57e81",
"size": "1234",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/resources/sqlmap/mysql/etc.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "340758"
},
{
"name": "FreeMarker",
"bytes": "3268"
},
{
"name": "HTML",
"bytes": "159357"
},
{
"name": "Java",
"bytes": "159427"
},
{
"name": "JavaScript",
"bytes": "2600908"
},
{
"name": "PHP",
"bytes": "9344"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.dynamodbv2.datamodeling.unmarshallers;
import java.lang.reflect.Method;
import com.amazonaws.services.dynamodbv2.datamodeling.ArgumentUnmarshaller;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
abstract class LUnmarshaller implements ArgumentUnmarshaller {
@Override
public void typeCheck(AttributeValue value, Method setter) {
if ( value.getL() == null ) {
throw new DynamoDBMappingException("Expected L in value " + value + " when invoking " + setter);
}
}
}
| {
"content_hash": "f3f5607f47665f2fa4ac8785a4a2ad76",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 108,
"avg_line_length": 33.421052631578945,
"alnum_prop": 0.7622047244094489,
"repo_name": "mhurne/aws-sdk-java",
"id": "786acb4739099deaa1f067e476d0a38d87a555d5",
"size": "1177",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/datamodeling/unmarshallers/LUnmarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "123790"
},
{
"name": "Java",
"bytes": "110875821"
},
{
"name": "Scilab",
"bytes": "3561"
}
],
"symlink_target": ""
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-guide-concepts-2-production</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.24/angular.min.js"></script>
<script src="invoice1.js"></script>
</head>
<body >
<div ng-app="invoice1" ng-controller="InvoiceController as invoice">
<b>Invoice:</b>
<div>
Quantity: <input type="number" ng-model="invoice.qty" required >
</div>
<div>
Costs: <input type="number" ng-model="invoice.cost" required >
<select ng-model="invoice.inCurr">
<option ng-repeat="c in invoice.currencies">{{c}}</option>
</select>
</div>
<div>
<b>Total:</b>
<span ng-repeat="c in invoice.currencies">
{{invoice.total(c) | currency:c}}
</span>
<button class="btn" ng-click="invoice.pay()">Pay</button>
</div>
</div>
</body>
</html> | {
"content_hash": "360084d85795a85207ad2125efe66805",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 89,
"avg_line_length": 27.257142857142856,
"alnum_prop": 0.5765199161425576,
"repo_name": "Zyckzto/angularjs-app",
"id": "35168c1fa5172542fb998c11e15b89fa6321a01a",
"size": "954",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "angular/docs/examples/example-guide-concepts-2/index-production.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "47035"
},
{
"name": "HTML",
"bytes": "2225102"
},
{
"name": "JavaScript",
"bytes": "196267"
}
],
"symlink_target": ""
} |
<link rel="import" href="/components/app-link/app-link.html">
<link rel="import" href="../layout-admin/layout-admin.html">
<link rel="import" href="../style-page/style-page.html">
<link rel="import" href="form-category.html">
<dom-module id="page-category">
<template>
<style include="style-page"></style>
<layout-admin>
<div class="container">
<h2>Edit category</h2>
<form-category model="{{model}}"></form-category>
</div>
</layout-admin>
</template>
</dom-module>
<script>
Polymer({
is: 'page-category',
properties: {
model: {
type: Object,
value: function () { return {}; }
}
}
});
</script> | {
"content_hash": "9c3645793ddb679558e0ff69eab12a69",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 61,
"avg_line_length": 21.53125,
"alnum_prop": 0.5849056603773585,
"repo_name": "x-project/x-project-example-user",
"id": "91073d3957c7f8ce33424e08e7f6e334a031e471",
"size": "689",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/admin/page-category/page-category.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "72540"
},
{
"name": "JavaScript",
"bytes": "10520"
}
],
"symlink_target": ""
} |
find_package(Ogg CONFIG)
if(NOT TARGET Ogg::ogg)
find_package(PkgConfig REQUIRED)
pkg_check_modules(Ogg REQUIRED IMPORTED_TARGET ogg)
set_target_properties(PkgConfig::Ogg PROPERTIES IMPORTED_GLOBAL TRUE)
add_library(Ogg::ogg ALIAS PkgConfig::Ogg)
endif()
| {
"content_hash": "1ed947989509ef8b3e7973dce22afbac",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 71,
"avg_line_length": 37.57142857142857,
"alnum_prop": 0.779467680608365,
"repo_name": "xiph/opusfile",
"id": "f18da8258c09eea3fd2b267211ef80436fdaace4",
"size": "263",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cmake/FindOgg.cmake",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "439981"
},
{
"name": "CMake",
"bytes": "14541"
},
{
"name": "Dockerfile",
"bytes": "585"
},
{
"name": "M4",
"bytes": "17226"
},
{
"name": "Makefile",
"bytes": "14750"
},
{
"name": "Ruby",
"bytes": "139"
},
{
"name": "Shell",
"bytes": "4890"
}
],
"symlink_target": ""
} |
'use strict';
var tape = require('tape');
var _test = require('tape-promise');
var test = _test(tape);
var rewire = require('rewire');
var path = require('path');
var util = require('util');
var testUtil = require('./util.js');
var fs = require('fs-extra');
var utils = require('fabric-client/lib/utils.js');
var FileKeyValueStore = require('fabric-client/lib/impl/FileKeyValueStore.js');
var keyValStorePath = path.join(getUserHome(), 'kvsTemp');
//Note: unix relative path does not start with '/'
//windows relative path starts with '/'
var keyValStorePath1 = 'tmp/keyValStore1';
var keyValStorePath2 = '/tmp/keyValStore2';
var keyValStorePath3 = '/tmp/keyValStore3';
var keyValStorePath4 = '/tmp/keyValStore4';
var keyValStorePath5 = '/tmp/keyValStore5';
var keyValStorePath6 = '/tmp/keyValStore6';
var testKey = 'keyValFileStoreName';
var testValue = 'secretKeyValue';
var store1 = '';
var store2 = '';
var store3 = '';
var store4 = '';
test('\n\n ** FileKeyValueStore - read and write test **\n\n', function (t) {
// clean up
if (testUtil.existsSync(keyValStorePath)) {
fs.removeSync(keyValStorePath);
}
utils.newKeyValueStore({
path: keyValStorePath
})
.then(
function (store) {
if (testUtil.existsSync(keyValStorePath)) {
t.pass('FileKeyValueStore read and write test: Successfully created new directory for testValueStore');
} else {
t.fail('FileKeyValueStore read and write test: failed to create new directory for testValueStore');
t.end();
}
store1 = store;
return store.setValue(testKey, testValue);
}
).then(
function (result) {
if (result == testValue) {
t.pass('FileKeyValueStore read and write test: Successfully set value');
} else {
t.fail('FileKeyValueStore read and write test: set value '+result+ 'does not match testValue '+testValue);
t.end();
}
if (testUtil.existsSync(path.join(keyValStorePath, testKey))) {
t.pass('FileKeyValueStore read and write test: Verified the file for key ' + testKey + ' does exist');
return store1.getValue(testKey);
} else {
t.fail('FileKeyValueStore read and write test: Failed to create file for key ' + testKey);
t.end();
}
},
function (reason) {
t.fail('FileKeyValueStore read and write test: Failed to set value, reason: ' + reason);
t.end();
}
).then(
// Log the fulfillment value
function (val) {
if (val != testValue)
t.fail('FileKeyValueStore read and write test: get value ' + val + ' does not equal testValue of ' + testValue);
else
t.pass('FileKeyValueStore read and write test: Successfully retrieved value');
t.end();
},
// Log the rejection reason
function (reason) {
t.fail('FileKeyValueStore read and write test: Failed getValue, reason: ' + reason);
t.end();
}
).catch(
function (err) {
t.fail('FileKeyValueStore read and write test, err: ' + err);
t.end();
}
);
});
test('\n\n ** FileKeyValueStore - constructor setValue getValue test store1 **\n\n', function (t) {
cleanupFileKeyValueStore(keyValStorePath1);
cleanupFileKeyValueStore(keyValStorePath2);
var promise1 = new FileKeyValueStore({ path: getRelativePath(keyValStorePath1) })
.then(
function(store) {
var exists = testUtil.existsSync(getAbsolutePath(keyValStorePath1));
if (exists)
t.pass('FileKeyValueStore constructor test: Successfully created new directory');
else
t.fail('FileKeyValueStore constructor test: Failed to create new directory: ' + keyValStorePath1);
store1 = store;
return store.setValue(testKey, testValue);
}
).then(
function (result) {
t.pass('FileKeyValueStore store1 setValue test: Successfully set value');
if (result == testValue) {
t.pass('FileKeyValueStore store1 setValue test store1');
} else {
t.fail('FileKeyValueStore store1 setValue test store1, result '+result+' does not match testValue '+testValue);
t.end();
}
return store1.getValue(testKey);
}
).then(
function (val) {
if (val != testValue)
t.fail('FileKeyValueStore read and write test store1: get value ' + val + ' does not equal testValue of ' + testValue);
else
t.pass('FileKeyValueStore read and write test store1: Successfully retrieved value');
t.end();
}
).catch (
function(err) {
t.fail('FileKeyValueStore store1 setValue test store1, caught err: ' + err);
t.end();
}
);
});
test('\n\n ** FileKeyValueStore - constructor setValue getValue test store2 **\n\n', function (t) {
cleanupFileKeyValueStore(keyValStorePath2);
var promise2 = new FileKeyValueStore({ path: getRelativePath(keyValStorePath2) })
.then(
function(store) {
var exists = testUtil.existsSync(getAbsolutePath(keyValStorePath2));
if (exists)
t.pass('FileKeyValueStore constructor test store2: Successfully created new directory');
else
t.fail('FileKeyValueStore constructor test store2: Failed to create new directory: ' + keyValStorePath2);
store2 = store;
return store.setValue(testKey, testValue);
}
).then(
function (result) {
t.pass('FileKeyValueStore store2 setValue test: Successfully set value');
if (result == testValue) {
t.pass('FileKeyValueStore store2 setValue test store2');
} else {
t.fail('FileKeyValueStore store2 setValue test store2, result '+result+' does not match testValue '+testValue);
t.end();
}
return store2.getValue(testKey);
}
).then(
function (val) {
if (val != testValue)
t.fail('FileKeyValueStore read and write test store2: get value ' + val + ' does not equal testValue of ' + testValue);
else
t.pass('FileKeyValueStore read and write test store2: Successfully retrieved value');
t.end();
}
).catch (
// Log the rejection reason
function (reason) {
t.fail('FileKeyValueStore store2 setValue test store2, reason: ' + reason);
t.end();
}
);
});
test('\n\n** FileKeyValueStore error check tests **\n\n', function (t) {
t.throws(
function () {
store3 = new FileKeyValueStore();
},
/^Error: Must provide the path/,
'FileKeyValueStore error check tests: new FileKeyValueStore with no options should throw ' +
'"Must provide the path to the directory to hold files for the store."'
);
t.throws(
function () {
store3 = new FileKeyValueStore({ dir: getRelativePath(keyValStorePath3) });
},
/^Error: Must provide the path/,
'FileKeyValueStore error check tests: new FileKeyValueStore with no options.path should throw ' +
'"Must provide the path to the directory to hold files for the store."'
);
cleanupFileKeyValueStore(keyValStorePath3);
var promise3 = new FileKeyValueStore({ path: getRelativePath(keyValStorePath3) })
.then(
function(store) {
store3 = store;
return store.setValue(testKey, testValue);
})
.then(
function (result) {
t.comment('FileKeyValueStore error check tests: Delete store & getValue test. Successfully set value');
var exists = testUtil.existsSync(getAbsolutePath(keyValStorePath3));
if (exists) {
t.comment('FileKeyValueStore error check tests: Delete store & getValue test. Verified the file for key ' + testKey + ' does exist');
cleanupFileKeyValueStore(keyValStorePath3);
exists = testUtil.existsSync(getAbsolutePath(keyValStorePath3));
t.comment('FileKeyValueStore error check tests: Delete store & getValue test. Deleted store, exists: ' + exists);
return store3.getValue(testKey);
} else {
t.fail('FileKeyValueStore error check tests: Delete store & getValue test. Failed to create file for key ' + testKey);
t.end();
}
})
.then(
// Log the fulfillment value
function (val) {
if (val === null) {
t.pass('FileKeyValueStore error check tests: Delete store & getValue test. getValue is null');
} else {
t.fail('FileKeyValueStore error check tests: Delete store & getValue test. getValue successfully retrieved value: ' + val);
}
cleanupFileKeyValueStore(keyValStorePath4);
return new FileKeyValueStore({ path: getRelativePath(keyValStorePath4) });
},
function (reason) {
t.fail('FileKeyValueStore error check tests: Delete store & getValue test. getValue caught unexpected error: ' + reason);
}
)
.then(
function (store) {
store4 = store;
cleanupFileKeyValueStore(keyValStorePath4);
var exists = testUtil.existsSync(getAbsolutePath(keyValStorePath4));
t.comment('FileKeyValueStore error check tests: Delete store & setValue test. Deleted store, exists: ' + exists);
return store4.setValue(testKey, testValue);
})
.then(
function (result) {
t.fail('FileKeyValueStore error check tests: Delete store & setValue test. Successfully set value but should have failed.');
t.end();
},
function (reason) {
t.pass('FileKeyValueStore error check tests: Delete store & setValue test. Failed to set value as expected: ' + reason);
t.end();
})
.catch(
function (err) {
t.fail('Failed with unexpected error: ' + err.stack ? err.stack : err);
t.end();
});
});
function getUserHome() {
return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
}
function cleanupFileKeyValueStore(keyValStorePath) {
var absPath = getAbsolutePath(keyValStorePath);
var exists = testUtil.existsSync(absPath);
if (exists) {
fs.removeSync(absPath);
}
}
// prepend absolute path where this test is running, then join to the relative path
function getAbsolutePath(dir) {
return path.join(process.cwd(), getRelativePath(dir));
}
// get relative file path for either Unix or Windows
// unix relative path does not start with '/'
// windows relative path starts with '/'
function getRelativePath(dir /*string*/) {
if (/^win/.test(process.platform)) {
if (!(dir.toString().substr(0, 1) === '/')) dir = '/' + dir;
dir = path.resolve(dir);
dir = dir.replace(/([A-Z]:[\\\/]).*?/gi, '');
return dir;
} else {
if (dir.toString().substr(0, 1) === '/') dir = dir.substr(1);
return dir;
}
}
| {
"content_hash": "9f0e75ef309917ce07834a1cb61c675f",
"timestamp": "",
"source": "github",
"line_count": 298,
"max_line_length": 138,
"avg_line_length": 33.218120805369125,
"alnum_prop": 0.6931003131629457,
"repo_name": "Sechin/fabric-sdk-node",
"id": "edd66164db2f4070ea00b9560409ab953b400799",
"size": "10511",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/unit/file-key-value-store.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Emacs Lisp",
"bytes": "103"
},
{
"name": "JavaScript",
"bytes": "563782"
},
{
"name": "Protocol Buffer",
"bytes": "76786"
}
],
"symlink_target": ""
} |
/**
* @author Dan Nuffer
*/
#include "OW_config.h"
#include "OW_CppSimpleInstanceProviderIFC.hpp"
#include "OW_CIMClass.hpp"
#include "OW_CIMInstance.hpp"
#include "OW_CIMException.hpp"
#include "OW_CIMValue.hpp"
#include "OW_CIMProperty.hpp"
#include "OW_CIMObjectPath.hpp"
#include "OW_CIMObjectPathEnumeration.hpp"
#include "OW_OperationContext.hpp"
#include "OW_ResultHandlerIFC.hpp"
#include "OW_Logger.hpp"
#include "OW_CIMOMHandleIFC.hpp"
#include "OW_RepositoryIFC.hpp"
namespace OW_NAMESPACE
{
namespace
{
const String COMPONENT_NAME("ow.provider.CIM_Namespace");
}
using namespace WBEMFlags;
namespace
{
class NSHandlerInst : public StringResultHandlerIFC
{
public:
NSHandlerInst(CIMInstanceResultHandlerIFC& result_,
const CIMClass& cls,
const String& sccn, const String& sn,
const String& omccn, const String& omn)
: result(result_)
, inst(cls.newInstance())
{
inst.setProperty("SystemCreationClassName", CIMValue(sccn));
inst.setProperty("SystemName", CIMValue(sn));
inst.setProperty("ObjectManagerCreationClassName", CIMValue(omccn));
inst.setProperty("ObjectManagerName", CIMValue(omn));
inst.setProperty("CreationClassName", CIMValue("CIM_Namespace"));
}
void doHandle(const String& s)
{
inst.setProperty("Name", CIMValue(s));
// This property is Required
inst.setProperty("ClassInfo", CIMValue(0));
//newInst.setProperty("Caption", CIMValue(/* TODO: Put the value here */));
//newInst.setProperty("Description", CIMValue(/* TODO: Put the value here */));
//newInst.setProperty("ElementName", CIMValue(/* TODO: Put the value here */));
result.handle(inst);
}
private:
CIMInstanceResultHandlerIFC& result;
CIMInstance inst;
};
class DeleteHandler : public StringResultHandlerIFC
{
public:
void doHandle(const String&)
{
OW_THROWCIMMSG(CIMException::FAILED, "Cannot delete namespace because it is not empty");
}
};
}
class CIM_NamespaceInstProv : public CppSimpleInstanceProviderIFC
{
public:
////////////////////////////////////////////////////////////////////////////
virtual ~CIM_NamespaceInstProv()
{
}
////////////////////////////////////////////////////////////////////////////
virtual void getInstanceProviderInfo(InstanceProviderInfo& info)
{
info.addInstrumentedClass("CIM_Namespace");
}
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
virtual void doSimpleEnumInstances(
const ProviderEnvironmentIFCRef& env,
const String& ns,
const CIMClass& cimClass,
CIMInstanceResultHandlerIFC& result,
EPropertiesFlag propertiesFlag)
{
OW_LOG_DEBUG(env->getLogger(COMPONENT_NAME), "In CIM_NamespaceInstProv::enumInstances");
CIMOMHandleIFCRef hdl = env->getCIMOMHandle();
CIMObjectPathEnumeration e = hdl->enumInstanceNamesE(ns, "CIM_ObjectManager");
String sccn;
String sn;
String omccn;
String omn;
if (e.numberOfElements() < 1)
{
// no CIM_ObjectManager... we'll just make these up then.
sccn = "CIM_System";
sn = "unknown";
omccn = "CIM_ObjectManager";
omn = "OpenWBEM";
}
else
{
// assume there'll only be one OpenWBEM_ObjectManager.
CIMObjectPath objectManager = e.nextElement();
sccn = objectManager.getKeyT("SystemCreationClassName").getValueT().toString();
sn = objectManager.getKeyT("SystemName").getValueT().toString();
omccn = objectManager.getKeyT("CreationClassName").getValueT().toString();
omn = objectManager.getKeyT("Name").getValueT().toString();
}
NSHandlerInst nshandler(result, cimClass, sccn, sn, omccn, omn);
RepositoryIFCRef rep = env->getRepository();
rep->enumNameSpace(nshandler, env->getOperationContext());
}
#if !defined(OW_DISABLE_INSTANCE_MANIPULATION)
////////////////////////////////////////////////////////////////////////////
virtual CIMObjectPath createInstance(
const ProviderEnvironmentIFCRef& env,
const String& ns,
const CIMInstance& cimInstance )
{
OW_LOG_DEBUG(env->getLogger(COMPONENT_NAME), "In CIM_NamespaceInstProv::createInstance");
#if !defined(OW_DISABLE_NAMESPACE_MANIPULATION)
try
{
String name = cimInstance.getPropertyT("Name").getValueT().toString();
RepositoryIFCRef rep = env->getRepository();
rep->createNameSpace(name, env->getOperationContext());
}
catch (const CIMException& e)
{
throw;
}
catch (const Exception& e)
{
OW_THROWCIM_SUBEX(CIMException::INVALID_PARAMETER, e);
}
#else
OW_THROWCIMMSG(CIMException::FAILED, "namespace creation not supported");
#endif
return CIMObjectPath(ns, cimInstance);
}
////////////////////////////////////////////////////////////////////////////
virtual void modifyInstance(
const ProviderEnvironmentIFCRef& env,
const String& ns,
const CIMInstance& modifiedInstance,
const CIMInstance& previousInstance,
EIncludeQualifiersFlag includeQualifiers,
const StringArray* propertyList,
const CIMClass& theClass)
{
// This is just a no-op since we don't really care about any properties
// other than the keys (which can't change.)
//OW_THROWCIMMSG(CIMException::FAILED, "Provider does not support modifyInstance");
}
////////////////////////////////////////////////////////////////////////////
virtual void deleteInstance(
const ProviderEnvironmentIFCRef& env,
const String& ns,
const CIMObjectPath& cop)
{
OW_LOG_DEBUG(env->getLogger(COMPONENT_NAME), "In CIM_NamespaceInstProv::createInstance");
#if !defined(OW_DISABLE_NAMESPACE_MANIPULATION)
try
{
String name = cop.getKeyT("Name").getValueT().toString();
RepositoryIFCRef rep = env->getRepository();
// The client can't delete a non-empty namespace. If we find any class names, we'll throw an exception
DeleteHandler handler;
rep->enumClassNames(name,"", handler, E_SHALLOW, env->getOperationContext());
rep->deleteNameSpace(name, env->getOperationContext());
}
catch (const CIMException& e)
{
throw;
}
catch (const Exception& e)
{
OW_THROWCIM_SUBEX(CIMException::FAILED, e);
}
#else
OW_THROWCIMMSG(CIMException::FAILED, "namespace creation not supported");
#endif
}
#endif // #ifndef OW_DISABLE_INSTANCE_MANIPULATION
};
} // end namespace OW_NAMESPACE
OW_PROVIDERFACTORY(OW_NAMESPACE::CIM_NamespaceInstProv, owprovinstCIM_Namespace)
| {
"content_hash": "7e9589f6a89e554f04fc3b9fd3d92e51",
"timestamp": "",
"source": "github",
"line_count": 200,
"max_line_length": 106,
"avg_line_length": 31.79,
"alnum_prop": 0.6653035545769109,
"repo_name": "kkaempf/openwbem",
"id": "68dbc3ee11f32a98a2647ae9330c98d2fa274086",
"size": "8063",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/providers/cpp/instance/CIM_Namespace/OW_provinstCIM_Namespace.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "447743"
},
{
"name": "C++",
"bytes": "8054531"
},
{
"name": "Perl",
"bytes": "2789"
},
{
"name": "Shell",
"bytes": "102214"
}
],
"symlink_target": ""
} |
#ifndef XBB_DETAIL_CONSTANCY_THROUGH_ADDITION_H
#define XBB_DETAIL_CONSTANCY_THROUGH_ADDITION_H
namespace xbb {
namespace detail {
// Use template specialization to specify the constancy when two
// values are added together
template<Constancy LeftT, Constancy RightT>
struct ConstancyThroughAddition
{};
template<>
struct ConstancyThroughAddition<ConstantZero, ConstantZero>
{ static const Constancy c = ConstantZero; };
template<>
struct ConstancyThroughAddition<ConstantZero, ConstantOne>
{ static const Constancy c = ConstantOne; };
template<>
struct ConstancyThroughAddition<ConstantZero, NotConstant>
{ static const Constancy c = NotConstant; };
template<>
struct ConstancyThroughAddition<ConstantOne, ConstantZero>
{ static const Constancy c = ConstantOne; };
template<>
struct ConstancyThroughAddition<ConstantOne, ConstantOne>
{ static const Constancy c = NotConstant; };
template<>
struct ConstancyThroughAddition<ConstantOne, NotConstant>
{ static const Constancy c = NotConstant; };
template<>
struct ConstancyThroughAddition<NotConstant, ConstantZero>
{ static const Constancy c = NotConstant; };
template<>
struct ConstancyThroughAddition<NotConstant, ConstantOne>
{ static const Constancy c = NotConstant; };
template<>
struct ConstancyThroughAddition<NotConstant, NotConstant>
{ static const Constancy c = NotConstant; };
} // namespace detail
} // namespace
#endif // XBB_DETAIL_CONSTANCY_THROUGH_ADDITION_H
| {
"content_hash": "3471fcf6aeda19eb0bacf23046ee8023",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 68,
"avg_line_length": 29.345454545454544,
"alnum_prop": 0.7106567534076828,
"repo_name": "01org/XBB",
"id": "11035cfd363aaced716b27405c3db473db61deda",
"size": "3119",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "include/xbb/detail/ConstancyThroughAddition.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "4862"
},
{
"name": "C++",
"bytes": "592683"
},
{
"name": "Makefile",
"bytes": "3542"
}
],
"symlink_target": ""
} |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.operator;
import com.facebook.presto.block.BlockBuilder;
import com.facebook.presto.execution.TaskId;
import com.facebook.presto.operator.FilterAndProjectOperator.FilterAndProjectOperatorFactory;
import com.facebook.presto.spi.RecordCursor;
import com.facebook.presto.sql.analyzer.Session;
import com.facebook.presto.tuple.TupleInfo;
import com.facebook.presto.tuple.TupleReadable;
import com.facebook.presto.util.MaterializedResult;
import com.google.common.collect.ImmutableList;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.List;
import java.util.concurrent.ExecutorService;
import static com.facebook.presto.operator.OperatorAssertion.assertOperatorEquals;
import static com.facebook.presto.operator.ProjectionFunctions.singleColumn;
import static com.facebook.presto.operator.RowPagesBuilder.rowPagesBuilder;
import static com.facebook.presto.tuple.TupleInfo.SINGLE_LONG;
import static com.facebook.presto.tuple.TupleInfo.SINGLE_VARBINARY;
import static com.facebook.presto.tuple.TupleInfo.Type.FIXED_INT_64;
import static com.facebook.presto.tuple.TupleInfo.Type.VARIABLE_BINARY;
import static com.facebook.presto.util.Threads.daemonThreadsNamed;
import static java.util.concurrent.Executors.newCachedThreadPool;
@Test(singleThreaded = true)
public class TestFilterAndProjectOperator
{
private ExecutorService executor;
private DriverContext driverContext;
@BeforeMethod
public void setUp()
{
executor = newCachedThreadPool(daemonThreadsNamed("test"));
Session session = new Session("user", "source", "catalog", "schema", "address", "agent");
driverContext = new TaskContext(new TaskId("query", "stage", "task"), executor, session)
.addPipelineContext(true, true)
.addDriverContext();
}
@AfterMethod
public void tearDown()
{
executor.shutdownNow();
}
@Test
public void test()
throws Exception
{
List<Page> input = rowPagesBuilder(SINGLE_VARBINARY, SINGLE_LONG)
.addSequencePage(100, 0, 0)
.build();
OperatorFactory operatorFactory = new FilterAndProjectOperatorFactory(
0,
new FilterFunction()
{
@Override
public boolean filter(TupleReadable... cursors)
{
long value = cursors[1].getLong();
return 10 <= value && value < 20;
}
@Override
public boolean filter(RecordCursor cursor)
{
long value = cursor.getLong(0);
return 10 <= value && value < 20;
}
}, ImmutableList.of(singleColumn(VARIABLE_BINARY, 0), new Add5Projection(1)));
Operator operator = operatorFactory.createOperator(driverContext);
MaterializedResult expected = MaterializedResult.resultBuilder(VARIABLE_BINARY, FIXED_INT_64)
.row("10", 15)
.row("11", 16)
.row("12", 17)
.row("13", 18)
.row("14", 19)
.row("15", 20)
.row("16", 21)
.row("17", 22)
.row("18", 23)
.row("19", 24)
.build();
assertOperatorEquals(operator, input, expected);
}
private static class Add5Projection
implements ProjectionFunction
{
private final int channelIndex;
public Add5Projection(int channelIndex)
{
this.channelIndex = channelIndex;
}
@Override
public TupleInfo getTupleInfo()
{
return SINGLE_LONG;
}
@Override
public void project(TupleReadable[] cursors, BlockBuilder output)
{
if (cursors[channelIndex].isNull()) {
output.appendNull();
}
else {
output.append(cursors[channelIndex].getLong() + 5);
}
}
@Override
public void project(RecordCursor cursor, BlockBuilder output)
{
if (cursor.isNull(channelIndex)) {
output.appendNull();
}
else {
output.append(cursor.getLong(channelIndex) + 5);
}
}
}
}
| {
"content_hash": "4bca9029ad61341a8dd5778739a8bafd",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 101,
"avg_line_length": 34.605442176870746,
"alnum_prop": 0.6225673284843719,
"repo_name": "HackShare/Presto",
"id": "4acccd66a6a998d14470edba9a4412d4e0447c1e",
"size": "5087",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "presto-main/src/test/java/com/facebook/presto/operator/TestFilterAndProjectOperator.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GAP",
"bytes": "41747"
},
{
"name": "HTML",
"bytes": "25433"
},
{
"name": "Java",
"bytes": "6562972"
},
{
"name": "Makefile",
"bytes": "6819"
},
{
"name": "PLSQL",
"bytes": "8346"
},
{
"name": "Python",
"bytes": "4319"
}
],
"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.
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Represents a method symbol for a lambda method.
''' </summary>
Friend MustInherit Class LambdaSymbol
Inherits MethodSymbol
''' <summary>
''' This symbol is used as the return type of a LambdaSymbol when we are interpreting
''' lambda's body in order to infer its return type.
''' </summary>
Friend Shared ReadOnly ReturnTypeIsBeingInferred As TypeSymbol = New ErrorTypeSymbol()
''' <summary>
''' This symbol is used as the return type of a LambdaSymbol when we failed to
''' infer lambda's return type, but still want to interpret its body.
''' </summary>
Friend Shared ReadOnly ReturnTypeIsUnknown As TypeSymbol = New ErrorTypeSymbol()
''' <summary>
''' This symbol is used as the return type of a LambdaSymbol when we are dealing with
''' query lambda and the return type should be taken from the target delegate upon
''' successful conversion. The LambdaSymbol will be mutated then.
''' </summary>
Friend Shared ReadOnly ReturnTypePendingDelegate As TypeSymbol = New ErrorTypeSymbol()
''' <summary>
''' This symbol is used as the return type of a LambdaSymbol when System.Void is used in code.
''' </summary>
Friend Shared ReadOnly ReturnTypeVoidReplacement As TypeSymbol = New ErrorTypeSymbol()
''' <summary>
''' This symbol is used as a sentinel while we are binding a lambda in error recovery mode.
''' </summary>
Friend Shared ReadOnly ErrorRecoveryInferenceError As TypeSymbol = New ErrorTypeSymbol()
Private ReadOnly _syntaxNode As SyntaxNode
Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol)
''' <summary>
''' Can mutate for a query lambda from ReturnTypePendingDelegate
''' to the return type of the target delegate.
''' </summary>
Protected m_ReturnType As TypeSymbol
' The binder associated with the block containing this lambda
Private ReadOnly _binder As Binder
Protected Sub New(
syntaxNode As SyntaxNode,
parameters As ImmutableArray(Of BoundLambdaParameterSymbol),
returnType As TypeSymbol,
binder As Binder
)
Debug.Assert(syntaxNode IsNot Nothing)
Debug.Assert(returnType IsNot Nothing)
_syntaxNode = syntaxNode
_parameters = StaticCast(Of ParameterSymbol).From(parameters)
m_ReturnType = returnType
_binder = binder
For Each param In parameters
param.SetLambdaSymbol(Me)
Next
End Sub
Public MustOverride ReadOnly Property SynthesizedKind As SynthesizedLambdaKind
Friend NotOverridable Overrides ReadOnly Property IsQueryLambdaMethod As Boolean
Get
Return SynthesizedKind.IsQueryLambda
End Get
End Property
Public Overrides ReadOnly Property Arity As Integer
Get
Return 0
End Get
End Property
Friend Overrides ReadOnly Property HasSpecialName As Boolean
Get
Return False
End Get
End Property
Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String)
Return ImmutableArray(Of String).Empty
End Function
Public Overrides ReadOnly Property AssociatedSymbol As Symbol
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention
Get
Return Cci.CallingConvention.Default
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _binder.ContainingMember
End Get
End Property
Friend ReadOnly Property ContainingBinder As Binder
Get
Return _binder
End Get
End Property
''' <summary>
''' "Me" parameter for this lambda will be that of the containing symbol
''' </summary>
Friend Overrides Function TryGetMeParameter(<Out> ByRef meParameter As ParameterSymbol) As Boolean
Debug.Assert(ContainingSymbol IsNot Nothing)
Select Case ContainingSymbol.Kind
Case SymbolKind.Field
meParameter = DirectCast(ContainingSymbol, FieldSymbol).MeParameter
Case SymbolKind.Property
meParameter = DirectCast(ContainingSymbol, PropertySymbol).MeParameter
Case SymbolKind.Method
meParameter = DirectCast(ContainingSymbol, MethodSymbol).MeParameter
Case Else
meParameter = Nothing
End Select
Return True
End Function
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.Private
End Get
End Property
Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol)
Get
Return ImmutableArray(Of MethodSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property IsExtensionMethod As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsExternalMethod As Boolean
Get
Return False
End Get
End Property
Public Overrides Function GetDllImportData() As DllImportData
Return Nothing
End Function
Friend Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes
Get
Return Nothing
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property HasDeclarativeSecurity As Boolean
Get
Return False
End Get
End Property
Friend NotOverridable Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute)
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverloads As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property IsShared As Boolean
Get
Dim container As Symbol = ContainingSymbol
Select Case container.Kind
Case SymbolKind.Field, SymbolKind.Property, SymbolKind.Method
Return container.IsShared
Case Else
Return True
End Select
End Get
End Property
Public Overrides ReadOnly Property IsSub As Boolean
Get
Return m_ReturnType.IsVoidType()
End Get
End Property
Public Overrides ReadOnly Property IsVararg As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray.Create(_syntaxNode.GetLocation())
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray.Create(_syntaxNode.GetReference())
End Get
End Property
Friend Overrides ReadOnly Property IsLambdaMethod As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property MethodKind As MethodKind
Get
Return MethodKind.LambdaMethod
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol)
Get
Return _parameters
End Get
End Property
Public Overrides ReadOnly Property ReturnsByRef As Boolean
Get
Return False
End Get
End Property
Public Overrides ReadOnly Property ReturnType As TypeSymbol
Get
Return m_ReturnType
End Get
End Property
Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return ImmutableArray(Of CustomModifier).Empty
End Get
End Property
Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier)
Get
Return ImmutableArray(Of CustomModifier).Empty
End Get
End Property
Friend Overrides ReadOnly Property Syntax As SyntaxNode
Get
Return _syntaxNode
End Get
End Property
Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol)
Get
Return ImmutableArray(Of TypeSymbol).Empty
End Get
End Property
Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol)
Get
Return ImmutableArray(Of TypeParameterSymbol).Empty
End Get
End Property
Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Nothing
End Get
End Property
Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean
Return False
End Function
Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean
Get
' lambdas contain user code
Return True
End Get
End Property
Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer
Throw ExceptionUtilities.Unreachable
End Function
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Me Then
Return True
End If
Dim symbol = TryCast(obj, LambdaSymbol)
Return symbol IsNot Nothing AndAlso
symbol._syntaxNode Is Me._syntaxNode AndAlso
Equals(symbol.ContainingSymbol, Me.ContainingSymbol) AndAlso
MethodSignatureComparer.AllAspectsSignatureComparer.Equals(symbol, Me)
End Function
Public Overrides Function GetHashCode() As Integer
Dim hc As Integer = Hash.Combine(Me.Syntax.GetHashCode(), Me._parameters.Length)
hc = Hash.Combine(hc, Me.ReturnType.GetHashCode())
For i = 0 To Me._parameters.Length - 1
hc = Hash.Combine(hc, Me._parameters(i).Type.GetHashCode())
Next
Return hc
End Function
End Class
End Namespace
| {
"content_hash": "31fa293a4275278f7aa7a2c72446eede",
"timestamp": "",
"source": "github",
"line_count": 371,
"max_line_length": 128,
"avg_line_length": 34.482479784366575,
"alnum_prop": 0.6191667318064566,
"repo_name": "heejaechang/roslyn",
"id": "39855f0b3fdc5d4a7b904752ebf4aed7073f671b",
"size": "12795",
"binary": false,
"copies": "13",
"ref": "refs/heads/master",
"path": "src/Compilers/VisualBasic/Portable/Symbols/Source/LambdaSymbol.vb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "1C Enterprise",
"bytes": "289100"
},
{
"name": "Batchfile",
"bytes": "8656"
},
{
"name": "C#",
"bytes": "118758550"
},
{
"name": "C++",
"bytes": "5392"
},
{
"name": "CMake",
"bytes": "9153"
},
{
"name": "Dockerfile",
"bytes": "2102"
},
{
"name": "F#",
"bytes": "508"
},
{
"name": "PowerShell",
"bytes": "148999"
},
{
"name": "Rich Text Format",
"bytes": "14887"
},
{
"name": "Shell",
"bytes": "61712"
},
{
"name": "Smalltalk",
"bytes": "622"
},
{
"name": "Visual Basic",
"bytes": "69269077"
}
],
"symlink_target": ""
} |
package com.qulice.checkstyle;
import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck;
import java.io.File;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
/**
* Make sure each line indentation is either:
* <ul>
* <li>the same as previous one or less
* <li>bigger than previous by exactly 4
* </ul>
* All other cases must cause a failure.
*
* @author Hamdi Douss (douss.hamdi@gmail.com)
* @version $Id$
*/
public final class CascadeIndentationCheck extends AbstractFileSetCheck {
/**
* Exact indentation increase difference.
*/
private static final int LINE_INDENT_DIFF = 4;
@Override
public void processFiltered(final File file, final List<String> lines) {
int previous = 0;
for (int pos = 0; pos < lines.size(); pos += 1) {
final String line = lines.get(pos);
final int current = CascadeIndentationCheck.indentation(line);
if (CascadeIndentationCheck.inCommentBlock(line)
|| line.length() == 0) {
continue;
}
if (current > previous
&& current != previous + LINE_INDENT_DIFF) {
this.log(
pos + 1,
String.format(
StringUtils.join(
"Indentation (%d) must be same or ",
"less than previous line (%d), or ",
"bigger by exactly 4"
),
current,
previous
)
);
}
previous = current;
}
}
/**
* Checks if the line belongs to a comment block.
* @param line Input.
* @return True if the line belongs to a comment block.
*/
private static boolean inCommentBlock(final String line) {
final String trimmed = line.trim();
return trimmed.length() > 0
&& (trimmed.charAt(0) == '*'
|| trimmed.startsWith("/*")
|| trimmed.startsWith("*/")
);
}
/**
* Calculates indentation of a line.
* @param line Input line
* @return Indentation of the given line.
*/
private static int indentation(final String line) {
int result = 0;
for (int pos = 0; pos < line.length(); pos += 1) {
if (!Character.isWhitespace(line.charAt(pos))) {
break;
}
result += 1;
}
return result;
}
}
| {
"content_hash": "c927ace7851986945bf2fc5ba9101e77",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 76,
"avg_line_length": 30.258823529411764,
"alnum_prop": 0.5186625194401244,
"repo_name": "HDouss/qulice",
"id": "7068b0de971bb29a547f98a5e28c717c0576f60d",
"size": "4135",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "qulice-checkstyle/src/main/java/com/qulice/checkstyle/CascadeIndentationCheck.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Groovy",
"bytes": "40611"
},
{
"name": "Java",
"bytes": "482768"
},
{
"name": "JavaScript",
"bytes": "57"
},
{
"name": "Shell",
"bytes": "570"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="shortcut icon" type="image/x-icon" href="../../../../../../../favicon.ico" />
<title>Polyline | Android Developers</title>
<!-- STYLESHEETS -->
<link rel="stylesheet"
href="http://fonts.googleapis.com/css?family=Roboto:regular,medium,thin,italic,mediumitalic,bold" title="roboto">
<link href="../../../../../../../assets/css/default.css" rel="stylesheet" type="text/css">
<!-- FULLSCREEN STYLESHEET -->
<link href="../../../../../../../assets/css/fullscreen.css" rel="stylesheet" class="fullscreen"
type="text/css">
<!-- JAVASCRIPT -->
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script src="../../../../../../../assets/js/global-libraries-combined.js" type="text/javascript"></script>
<script type="text/javascript">
var toRoot = "../../../../../../../";
</script>
<script src="../../../../../../../assets/js/docs.js" type="text/javascript"></script>
<script src="../../../../../../../navtree_data.js" type="text/javascript"></script>
</head>
<body class="gc-documentation
develop" itemscope itemtype="http://schema.org/Article">
<div id="doc-api-level" class="" style="display:none"></div>
<a name="top"></a>
<!-- Header -->
<div id="header">
<div class="wrap" id="header-wrap">
<div class="col-3 logo">
<a href="../../../../../../../index.html">
<img src="../../../../../../../assets/images/dac_logo.png" width="123" height="25" alt="Android Developers" />
</a>
<div class="btn-quicknav" id="btn-quicknav">
<a href="#" class="arrow-inactive">Quicknav</a>
<a href="#" class="arrow-active">Quicknav</a>
</div>
</div>
<ul class="nav-x col-9">
<li class="design">
<a href="../../../../../../../design/index.html"
zh-TW-lang="設計"
zh-CN-lang="设计"
ru-lang="Проектирование"
ko-lang="디자인"
ja-lang="設計"
es-lang="Diseñar"
>Design</a></li>
<li class="develop"><a href="../../../../../../../develop/index.html" class="selected"
zh-TW-lang="開發"
zh-CN-lang="开发"
ru-lang="Разработка"
ko-lang="개발"
ja-lang="開発"
es-lang="Desarrollar"
>Develop</a></li>
<li class="distribute last"><a href="../../../../../../../distribute/index.html"
zh-TW-lang="發佈"
zh-CN-lang="分发"
ru-lang="Распространение"
ko-lang="배포"
ja-lang="配布"
es-lang="Distribuir"
>Distribute</a></li>
</ul>
<!-- New Search -->
<div class="menu-container">
<div class="moremenu">
<div id="more-btn"></div>
</div>
<div class="morehover" id="moremenu">
<div class="top"></div>
<div class="mid">
<div class="header">Links</div>
<ul>
<li><a href="https://play.google.com/apps/publish/">Google Play Developer Console</a></li>
<li><a href="http://android-developers.blogspot.com/">Android Developers Blog</a></li>
<li><a href="../../../../../../../about/index.html">About Android</a></li>
</ul>
<div class="header">Android Sites</div>
<ul>
<li><a href="http://www.android.com">Android.com</a></li>
<li class="active"><a>Android Developers</a></li>
<li><a href="http://source.android.com">Android Open Source Project</a></li>
</ul>
<!-- <div class="header">Support</div>
<ul>
<li><a href="../../../../../../../support.html">Developer Support</a></li>
</ul> -->
<div class="header">Languages</div>
<div id="language" class="locales">
<select name="language" onChange="changeLangPref(this.value, true)">
<option value="en">English</option>
<option value="es">Español</option>
<option value="ja">日本語</option>
<option value="ko">한국어</option>
<option value="ru">Русский</option>
<option value="zh-CN">中文 (中国)</option>
<option value="zh-TW">中文 (台灣)</option>
</select>
</div>
<script type="text/javascript">
<!--
loadLangPref();
//-->
</script>
<br class="clearfix" />
</div>
<div class="bottom"></div>
</div>
<div class="search" id="search-container">
<div class="search-inner">
<div id="search-btn"></div>
<div class="left"></div>
<form onsubmit="return submit_search()">
<input id="search_autocomplete" type="text" value="" autocomplete="off" name="q"
onfocus="search_focus_changed(this, true)" onblur="search_focus_changed(this, false)"
onkeydown="return search_changed(event, true, '../../../../../../../')"
onkeyup="return search_changed(event, false, '../../../../../../../')" />
</form>
<div class="right"></div>
<a class="close hide">close</a>
<div class="left"></div>
<div class="right"></div>
</div>
</div>
<div id="search_filtered_wrapper">
<div id="search_filtered_div" class="no-display">
<ul id="search_filtered">
</ul>
</div>
</div>
</div>
<!-- /New Search>
<!-- Expanded quicknav -->
<div id="quicknav" class="col-9">
<ul>
<li class="design">
<ul>
<li><a href="../../../../../../../design/index.html">Get Started</a></li>
<li><a href="../../../../../../../design/style/index.html">Style</a></li>
<li><a href="../../../../../../../design/patterns/index.html">Patterns</a></li>
<li><a href="../../../../../../../design/building-blocks/index.html">Building Blocks</a></li>
<li><a href="../../../../../../../design/downloads/index.html">Downloads</a></li>
<li><a href="../../../../../../../design/videos/index.html">Videos</a></li>
</ul>
</li>
<li class="develop">
<ul>
<li><a href="../../../../../../../training/index.html"
zh-TW-lang="訓練課程"
zh-CN-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li><a href="../../../../../../../guide/components/index.html"
zh-TW-lang="API 指南"
zh-CN-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li><a href="../../../../../../../reference/packages.html"
zh-TW-lang="參考資源"
zh-CN-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li><a href="../../../../../../../tools/index.html"
zh-TW-lang="相關工具"
zh-CN-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a>
<ul><li><a href="../../../../../../../sdk/index.html">Get the SDK</a></li></ul>
</li>
<li><a href="../../../../../../../google/index.html">Google Services</a>
</li>
</ul>
</li>
<li class="distribute last">
<ul>
<li><a href="../../../../../../../distribute/index.html">Google Play</a></li>
<li><a href="../../../../../../../distribute/googleplay/publish/index.html">Publishing</a></li>
<li><a href="../../../../../../../distribute/googleplay/promote/index.html">Promoting</a></li>
<li><a href="../../../../../../../distribute/googleplay/quality/index.html">App Quality</a></li>
<li><a href="../../../../../../../distribute/googleplay/spotlight/index.html">Spotlight</a></li>
<li><a href="../../../../../../../distribute/open.html">Open Distribution</a></li>
</ul>
</li>
</ul>
</div>
<!-- /Expanded quicknav -->
</div>
</div>
<!-- /Header -->
<div id="searchResults" class="wrap" style="display:none;">
<h2 id="searchTitle">Results</h2>
<div id="leftSearchControl" class="search-control">Loading...</div>
</div>
<!-- Secondary x-nav -->
<div id="nav-x">
<div class="wrap">
<ul class="nav-x col-9 develop" style="width:100%">
<li><a href="../../../../../../../training/index.html"
zh-TW-lang="訓練課程"
zh-CN-lang="培训"
ru-lang="Курсы"
ko-lang="교육"
ja-lang="トレーニング"
es-lang="Capacitación"
>Training</a></li>
<li><a href="../../../../../../../guide/components/index.html"
zh-TW-lang="API 指南"
zh-CN-lang="API 指南"
ru-lang="Руководства по API"
ko-lang="API 가이드"
ja-lang="API ガイド"
es-lang="Guías de la API"
>API Guides</a></li>
<li><a href="../../../../../../../reference/packages.html" class="selected"
zh-TW-lang="參考資源"
zh-CN-lang="参考"
ru-lang="Справочник"
ko-lang="참조문서"
ja-lang="リファレンス"
es-lang="Referencia"
>Reference</a></li>
<li><a href="../../../../../../../tools/index.html"
zh-TW-lang="相關工具"
zh-CN-lang="工具"
ru-lang="Инструменты"
ko-lang="도구"
ja-lang="ツール"
es-lang="Herramientas"
>Tools</a></li>
<li><a href="../../../../../../../google/index.html"
>Google Services</a>
</li>
</ul>
</div>
</div>
<!-- /Sendondary x-nav -->
<div class="wrap clearfix" id="body-content">
<div class="col-4" id="side-nav" itemscope itemtype="http://schema.org/SiteNavigationElement">
<div id="devdoc-nav">
<a class="totop" href="#top" data-g-event="left-nav-top">to top</a>
<div id="api-nav-header">
<div id="api-level-toggle">
<label for="apiLevelCheckbox" class="disabled">API level: </label>
<div class="select-wrapper">
<select id="apiLevelSelector">
<!-- option elements added by buildApiLevelSelector() -->
</select>
</div>
</div><!-- end toggle -->
<div id="api-nav-title">Android APIs</div>
</div><!-- end nav header -->
<script>
var SINCE_DATA = [ ];
buildApiLevelSelector();
</script>
<div id="swapper">
<div id="nav-panels">
<div id="resize-packages-nav">
<div id="packages-nav" class="scroll-pane">
<ul>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/package-summary.html">com.google.android.gms</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/auth/package-summary.html">com.google.android.gms.auth</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/package-summary.html">com.google.android.gms.common</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/data/package-summary.html">com.google.android.gms.common.data</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/common/images/package-summary.html">com.google.android.gms.common.images</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/maps/package-summary.html">com.google.android.gms.maps</a></li>
<li class="selected api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/maps/model/package-summary.html">com.google.android.gms.maps.model</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/panorama/package-summary.html">com.google.android.gms.panorama</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/package-summary.html">com.google.android.gms.plus</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/model/moments/package-summary.html">com.google.android.gms.plus.model.moments</a></li>
<li class="api apilevel-">
<a href="../../../../../../../reference/com/google/android/gms/plus/model/people/package-summary.html">com.google.android.gms.plus.model.people</a></li>
</ul><br/>
</div> <!-- end packages-nav -->
</div> <!-- end resize-packages -->
<div id="classes-nav" class="scroll-pane">
<ul>
<li><h2>Interfaces</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/TileProvider.html">TileProvider</a></li>
</ul>
</li>
<li><h2>Classes</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/BitmapDescriptor.html">BitmapDescriptor</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/BitmapDescriptorFactory.html">BitmapDescriptorFactory</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CameraPosition.html">CameraPosition</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CameraPosition.Builder.html">CameraPosition.Builder</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Circle.html">Circle</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/CircleOptions.html">CircleOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/GroundOverlay.html">GroundOverlay</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/GroundOverlayOptions.html">GroundOverlayOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLngBounds.html">LatLngBounds</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLngBounds.Builder.html">LatLngBounds.Builder</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Marker.html">Marker</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/MarkerOptions.html">MarkerOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polygon.html">Polygon</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/PolygonOptions.html">PolygonOptions</a></li>
<li class="selected api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html">Polyline</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/PolylineOptions.html">PolylineOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Tile.html">Tile</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/TileOverlay.html">TileOverlay</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/TileOverlayOptions.html">TileOverlayOptions</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/UrlTileProvider.html">UrlTileProvider</a></li>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/VisibleRegion.html">VisibleRegion</a></li>
</ul>
</li>
<li><h2>Exceptions</h2>
<ul>
<li class="api apilevel-"><a href="../../../../../../../reference/com/google/android/gms/maps/model/RuntimeRemoteException.html">RuntimeRemoteException</a></li>
</ul>
</li>
</ul><br/>
</div><!-- end classes -->
</div><!-- end nav-panels -->
<div id="nav-tree" style="display:none" class="scroll-pane">
<div id="tree-list"></div>
</div><!-- end nav-tree -->
</div><!-- end swapper -->
<div id="nav-swap">
<a class="fullscreen">fullscreen</a>
<a href='#' onclick='swapNav();return false;'><span id='tree-link'>Use Tree Navigation</span><span id='panel-link' style='display:none'>Use Panel Navigation</span></a>
</div>
</div> <!-- end devdoc-nav -->
</div> <!-- end side-nav -->
<script type="text/javascript">
// init fullscreen based on user pref
var fullscreen = readCookie("fullscreen");
if (fullscreen != 0) {
if (fullscreen == "false") {
toggleFullscreen(false);
} else {
toggleFullscreen(true);
}
}
// init nav version for mobile
if (isMobile) {
swapNav(); // tree view should be used on mobile
$('#nav-swap').hide();
} else {
chooseDefaultNav();
if ($("#nav-tree").is(':visible')) {
init_default_navtree("../../../../../../../");
}
}
// scroll the selected page into view
$(document).ready(function() {
scrollIntoView("packages-nav");
scrollIntoView("classes-nav");
});
</script>
<script>
$(document).ready(function() {
changeDocLang(getLangPref());
});
</script>
<div class="col-12" id="doc-col">
<div id="api-info-block">
<div class="sum-details-links">
Summary:
<a href="#pubctors">Ctors</a>
| <a href="#pubmethods">Methods</a>
| <a href="#inhmethods">Inherited Methods</a>
| <a href="#" onclick="return toggleAllClassInherited()" id="toggleAllClassInherited">[Expand All]</a>
</div><!-- end sum-details-links -->
<div class="api-level">
</div>
</div><!-- end api-info-block -->
<!-- ======== START OF CLASS DATA ======== -->
<div id="jd-header">
public
final
class
<h1 itemprop="name">Polyline</h1>
extends <a href="http://developer.android.com/reference/java/lang/Object.html">Object</a><br/>
</div><!-- end header -->
<div id="naMessage"></div>
<div id="jd-content" class="api apilevel-">
<table class="jd-inheritance-table">
<tr>
<td colspan="2" class="jd-inheritance-class-cell"><a href="http://developer.android.com/reference/java/lang/Object.html">java.lang.Object</a></td>
</tr>
<tr>
<td class="jd-inheritance-space"> ↳</td>
<td colspan="1" class="jd-inheritance-class-cell">com.google.android.gms.maps.model.Polyline</td>
</tr>
</table>
<div class="jd-descr">
<h2>Class Overview</h2>
<p itemprop="articleBody">A polyline is a list of points, where line segments are drawn between consecutive points. A
polyline has the following properties:
<p>
<dl>
<dt>Points</dt>
<dd>The vertices of the line. Line segments are drawn between consecutive points. A polyline is
<em>not</em> closed by default; to form a closed polyline, the start and end points must be the
same.
<dt>Width</dt>
<dd>Line segment width in screen pixels. The width is constant and independent of the camera's
zoom level. The default value is 10.</dd>
<dt>Color</dt>
<dd>Line segment color in ARGB format, the same format used by <code><a href="../../../../../../../http://developer.android.com/reference/android/graphics/Color.html">Color</a></code>.
The default value is black (<code>0xff000000</code>).</dd>
<dt>Z-Index</dt>
<dd>The order in which this polyline is drawn with respect to other overlays, including
<code><a href="../../../../../../../reference/com/google/android/gms/maps/model/GroundOverlay.html">GroundOverlay</a></code>s and <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/TileOverlay.html">TileOverlay</a></code>s, but not <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/Marker.html">Marker</a></code>s. An overlay with a
larger z-index is drawn over overlays with smaller z-indices. The order of overlays with the same
z-index value is arbitrary. The default is 0.</dd>
<dt>Visibility</dt>
<dd>Indicates if the polyline is visible or invisible, i.e., whether it is drawn on the map. An
invisible polyline is not drawn, but retains all of its other properties. The default is
<code>true</code>, i.e., visible.</dd>
<dt>Geodesic status</dt>
<dd>Indicates whether the segments of the polyline should be drawn as geodesics, as opposed to
straight lines on the Mercator projection. A geodesic is the shortest path between two points on
the Earth's surface. The geodesic curve is constructed assuming the Earth is a sphere</dd>
</dl>
<p>
Methods that modify a Polyline must be called on the main thread. If not, an
<code><a href="../../../../../../../http://developer.android.com/reference/java/lang/IllegalStateException.html">IllegalStateException</a></code> will be thrown at runtime.
<h3>Example</h3>
<pre> <code>GoogleMap map;
// ... get a map.
// Add a thin red line from London to New York.
Polyline line = map.addPolyline(new PolylineOptions()
.add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0))
.width(5)
.color(Color.RED));</code></pre>
<p>
<h3>Developer Guide</h3>
<p>
For more information, read the <a
href="https://developers.google.com/maps/documentation/android/lines">Polylines and Polygons</a>
developer guide.
</p>
</div><!-- jd-descr -->
<div class="jd-descr">
<h2>Summary</h2>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<table id="pubctors" class="jd-sumtable"><tr><th colspan="12">Public Constructors</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html#Polyline(com.google.android.gms.maps.model.internal.IPolylineDelegate)">Polyline</a></span>(<a href="../../../../../../../reference/com/google/android/gms/maps/model/internal/IPolylineDelegate.html">IPolylineDelegate</a> delegate)</nobr>
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="pubmethods" class="jd-sumtable"><tr><th colspan="12">Public Methods</th></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
boolean</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html#equals(java.lang.Object)">equals</a></span>(<a href="http://developer.android.com/reference/java/lang/Object.html">Object</a> other)</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html#getColor()">getColor</a></span>()</nobr>
<div class="jd-descrdiv">Gets the color of this polyline.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="http://developer.android.com/reference/java/lang/String.html">String</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html#getId()">getId</a></span>()</nobr>
<div class="jd-descrdiv">Gets this polyline's id.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="http://developer.android.com/reference/java/util/List.html">List</a><<a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a>></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html#getPoints()">getPoints</a></span>()</nobr>
<div class="jd-descrdiv">Returns a snapshot of the vertices of this polyline at this time .</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
float</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html#getWidth()">getWidth</a></span>()</nobr>
<div class="jd-descrdiv">Gets the width of this polyline.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
float</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html#getZIndex()">getZIndex</a></span>()</nobr>
<div class="jd-descrdiv">Gets the zIndex of this polyline.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html#hashCode()">hashCode</a></span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
boolean</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html#isGeodesic()">isGeodesic</a></span>()</nobr>
<div class="jd-descrdiv">Gets whether each segment of the line is drawn as a geodesic or not.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
boolean</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html#isVisible()">isVisible</a></span>()</nobr>
<div class="jd-descrdiv">Gets the visibility of this polyline.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html#remove()">remove</a></span>()</nobr>
<div class="jd-descrdiv">Removes this polyline from the map.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html#setColor(int)">setColor</a></span>(int color)</nobr>
<div class="jd-descrdiv">Sets the color of this polyline.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html#setGeodesic(boolean)">setGeodesic</a></span>(boolean geodesic)</nobr>
<div class="jd-descrdiv">Sets whether to draw each segment of the line as a geodesic or not.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html#setPoints(java.util.List<com.google.android.gms.maps.model.LatLng>)">setPoints</a></span>(<a href="http://developer.android.com/reference/java/util/List.html">List</a><<a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a>> points)</nobr>
<div class="jd-descrdiv">Sets the points of this polyline.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html#setVisible(boolean)">setVisible</a></span>(boolean visible)</nobr>
<div class="jd-descrdiv">Sets the visibility of this polyline.</div>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html#setWidth(float)">setWidth</a></span>(float width)</nobr>
<div class="jd-descrdiv">Sets the width of this polyline.</div>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad"><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html#setZIndex(float)">setZIndex</a></span>(float zIndex)</nobr>
<div class="jd-descrdiv">Sets the zIndex of this polyline.</div>
</td></tr>
</table>
<!-- ========== METHOD SUMMARY =========== -->
<table id="inhmethods" class="jd-sumtable"><tr><th>
<a href="#" class="toggle-all" onclick="return toggleAllInherited(this, null)">[Expand]</a>
<div style="clear:left;">Inherited Methods</div></th></tr>
<tr class="api apilevel-" >
<td colspan="12">
<a href="#" onclick="return toggleInherited(this, null)" id="inherited-methods-java.lang.Object" class="jd-expando-trigger closed"
><img id="inherited-methods-java.lang.Object-trigger"
src="../../../../../../../assets/images/triangle-closed.png"
class="jd-expando-trigger-img" /></a>
From class
<a href="http://developer.android.com/reference/java/lang/Object.html">java.lang.Object</a>
<div id="inherited-methods-java.lang.Object">
<div id="inherited-methods-java.lang.Object-list"
class="jd-inheritedlinks">
</div>
<div id="inherited-methods-java.lang.Object-summary" style="display: none;">
<table class="jd-sumtable-expando">
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="http://developer.android.com/reference/java/lang/Object.html">Object</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">clone</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
boolean</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">equals</span>(<a href="http://developer.android.com/reference/java/lang/Object.html">Object</a> arg0)</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">finalize</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
final
<a href="http://developer.android.com/reference/java/lang/Class.html">Class</a><?></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">getClass</span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
int</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">hashCode</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">notify</span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">notifyAll</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
<a href="http://developer.android.com/reference/java/lang/String.html">String</a></nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">toString</span>()</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">wait</span>()</nobr>
</td></tr>
<tr class=" api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">wait</span>(long arg0, int arg1)</nobr>
</td></tr>
<tr class="alt-color api apilevel-" >
<td class="jd-typecol"><nobr>
final
void</nobr>
</td>
<td class="jd-linkcol" width="100%"><nobr>
<span class="sympad">wait</span>(long arg0)</nobr>
</td></tr>
</table>
</div>
</div>
</td></tr>
</table>
</div><!-- jd-descr (summary) -->
<!-- Details -->
<!-- XML Attributes -->
<!-- Enum Values -->
<!-- Constants -->
<!-- Fields -->
<!-- Public ctors -->
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<h2>Public Constructors</h2>
<A NAME="Polyline(com.google.android.gms.maps.model.internal.IPolylineDelegate)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
</span>
<span class="sympad">Polyline</span>
<span class="normal">(<a href="../../../../../../../reference/com/google/android/gms/maps/model/internal/IPolylineDelegate.html">IPolylineDelegate</a> delegate)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<!-- Protected ctors -->
<!-- ========= METHOD DETAIL ======== -->
<!-- Public methdos -->
<h2>Public Methods</h2>
<A NAME="equals(java.lang.Object)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
boolean
</span>
<span class="sympad">equals</span>
<span class="normal">(<a href="http://developer.android.com/reference/java/lang/Object.html">Object</a> other)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<A NAME="getColor()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">getColor</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Gets the color of this polyline.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>the color in ARGB format.
</li></ul>
</div>
</div>
</div>
<A NAME="getId()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="http://developer.android.com/reference/java/lang/String.html">String</a>
</span>
<span class="sympad">getId</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Gets this polyline's id.
<p>
When a map is restored from a <code><a href="../../../../../../../http://developer.android.com/reference/android/os/Bundle.html">Bundle</a></code>, polylines that were on that map are
also restored. However, those polylines will then be represented by different
<code>Polyline</code> objects. A polyline's id can be used to retrieve the new instance of a
Polyline object after such restoration.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>this polyline's id.
</li></ul>
</div>
</div>
</div>
<A NAME="getPoints()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
<a href="http://developer.android.com/reference/java/util/List.html">List</a><<a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a>>
</span>
<span class="sympad">getPoints</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Returns a snapshot of the vertices of this polyline at this time . The list returned is a
copy of the list of vertices and so changes to the polyline's vertices will not be reflected
by this list, nor will changes to this list be reflected by the polyline. To change the
vertices of the polyline, call <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/Polyline.html#setPoints(java.util.List<com.google.android.gms.maps.model.LatLng>)">setPoints(List)</a></code>.
</p></div>
</div>
</div>
<A NAME="getWidth()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
float
</span>
<span class="sympad">getWidth</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Gets the width of this polyline.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>the width in screen pixels.
</li></ul>
</div>
</div>
</div>
<A NAME="getZIndex()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
float
</span>
<span class="sympad">getZIndex</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Gets the zIndex of this polyline.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>the zIndex of the polyline.
</li></ul>
</div>
</div>
</div>
<A NAME="hashCode()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
int
</span>
<span class="sympad">hashCode</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p></p></div>
</div>
</div>
<A NAME="isGeodesic()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
boolean
</span>
<span class="sympad">isGeodesic</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Gets whether each segment of the line is drawn as a geodesic or not.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li><code>true</code> if each segment is drawn as a geodesic; <code>false</code> if each segment is
drawn as a straight line on the Mercator projection.
</li></ul>
</div>
</div>
</div>
<A NAME="isVisible()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
boolean
</span>
<span class="sympad">isVisible</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Gets the visibility of this polyline.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Returns</h5>
<ul class="nolist"><li>this polyline's visibility.
</li></ul>
</div>
</div>
</div>
<A NAME="remove()"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
void
</span>
<span class="sympad">remove</span>
<span class="normal">()</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Removes this polyline from the map. After a polyline has been removed, the behavior of all
its methods is undefined.
</p></div>
</div>
</div>
<A NAME="setColor(int)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
void
</span>
<span class="sympad">setColor</span>
<span class="normal">(int color)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the color of this polyline.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>color</td>
<td>the color in ARGB format
</td>
</tr>
</table>
</div>
</div>
</div>
<A NAME="setGeodesic(boolean)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
void
</span>
<span class="sympad">setGeodesic</span>
<span class="normal">(boolean geodesic)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets whether to draw each segment of the line as a geodesic or not.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>geodesic</td>
<td>if <code>true</code>, then each segment is drawn as a geodesic; if <code>false</code>,
each segment is drawn as a straight line on the Mercator projection.
</td>
</tr>
</table>
</div>
</div>
</div>
<A NAME="setPoints(java.util.List<com.google.android.gms.maps.model.LatLng>)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
void
</span>
<span class="sympad">setPoints</span>
<span class="normal">(<a href="http://developer.android.com/reference/java/util/List.html">List</a><<a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a>> points)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the points of this polyline. This method will take a copy of the points, so further
mutations to <code>points</code> will have no effect on this polyline.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>points</td>
<td>an list of <code><a href="../../../../../../../reference/com/google/android/gms/maps/model/LatLng.html">LatLng</a></code>s that are the vertices of the polyline.
</td>
</tr>
</table>
</div>
</div>
</div>
<A NAME="setVisible(boolean)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
void
</span>
<span class="sympad">setVisible</span>
<span class="normal">(boolean visible)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the visibility of this polyline. When not visible, a polyline is not drawn, but it keeps
all its other properties.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>visible</td>
<td>if <code>true</code>, then the polyline is visible; if <code>false</code>, it is not.
</td>
</tr>
</table>
</div>
</div>
</div>
<A NAME="setWidth(float)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
void
</span>
<span class="sympad">setWidth</span>
<span class="normal">(float width)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the width of this polyline.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>width</td>
<td>the width in screen pixels
</td>
</tr>
</table>
</div>
</div>
</div>
<A NAME="setZIndex(float)"></A>
<div class="jd-details api apilevel-">
<h4 class="jd-details-title">
<span class="normal">
public
void
</span>
<span class="sympad">setZIndex</span>
<span class="normal">(float zIndex)</span>
</h4>
<div class="api-level">
<div></div>
</div>
<div class="jd-details-descr">
<div class="jd-tagdata jd-tagdescr"><p>Sets the zIndex of this polyline. Polylines with higher zIndices are drawn above those with
lower indices.</p></div>
<div class="jd-tagdata">
<h5 class="jd-tagtitle">Parameters</h5>
<table class="jd-tagtable">
<tr>
<th>zIndex</td>
<td>the zIndex of this polyline.
</td>
</tr>
</table>
</div>
</div>
</div>
<!-- ========= METHOD DETAIL ======== -->
<!-- ========= END OF CLASS DATA ========= -->
<A NAME="navbar_top"></A>
<div id="footer" class="wrap" >
<div id="copyright">
Except as noted, this content is licensed under <a
href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>.
For details and restrictions, see the <a href="../../../../../../../license.html">
Content License</a>.
</div>
<div id="build_info">
Android r — 12 Mar 2013 3:07
</div>
<div id="footerlinks">
<p>
<a href="../../../../../../../about/index.html">About Android</a> |
<a href="../../../../../../../legal.html">Legal</a> |
<a href="../../../../../../../support.html">Support</a>
</p>
</div>
</div> <!-- end footer -->
</div> <!-- jd-content -->
</div><!-- end doc-content -->
</div> <!-- end body-content -->
<!-- Grid - for dev
<script type="text/javascript">
window.gOverride = {
gColor: '#FF0000',
pColor: '#EEEEEE',
gOpacity: 0.10,
pOpacity: 0.40,
pHeight: 16,
pOffset: 2,
gColumns:16,
gEnabled:false,
pEnabled:false
}
</script>
<link href="../../../../../../../assets/js/grid/960.gridder.css" rel="stylesheet" type="text/css">
<script src="../../../../../../../assets/js/grid/960.gridder.js" type="text/javascript"></script>
-->
<script type="text/javascript">
init(); /* initialize android-developer-docs.js */
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-5831155-1");
pageTracker._trackPageview();
</script>
</body>
</html>
| {
"content_hash": "a28067746be8c53c75730b60df79e69d",
"timestamp": "",
"source": "github",
"line_count": 1969,
"max_line_length": 404,
"avg_line_length": 27.697308278313866,
"alnum_prop": 0.5099017162974916,
"repo_name": "photo/mobile-android",
"id": "ed747b28c5254fbbdad45be06e3e737a0bc9ea33",
"size": "54948",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "submodules/google-play-services_lib/docs/reference/com/google/android/gms/maps/model/Polyline.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "170044"
},
{
"name": "Java",
"bytes": "2476932"
},
{
"name": "JavaScript",
"bytes": "133527"
}
],
"symlink_target": ""
} |
module ag.grid {
export class VerticalStack {
isLayoutPanel: any;
childPanels: any;
eGui: any;
constructor() {
this.isLayoutPanel = true;
this.childPanels = [];
this.eGui = document.createElement('div');
this.eGui.style.height = '100%';
}
addPanel(panel: any, height: any) {
var component: any;
if (panel.isLayoutPanel) {
this.childPanels.push(panel);
component = panel.getGui();
} else {
component = panel;
}
if (height) {
component.style.height = height;
}
this.eGui.appendChild(component);
}
getGui() {
return this.eGui;
}
doLayout() {
for (var i = 0; i < this.childPanels.length; i++) {
this.childPanels[i].doLayout();
}
}
}
}
| {
"content_hash": "70a028e050ce821cb51566f441ca8389",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 63,
"avg_line_length": 24.404761904761905,
"alnum_prop": 0.4302439024390244,
"repo_name": "dsmarcoantonio/GTAC_AWS",
"id": "272ddcc8226bf70af55b5c81c08f76019de2610a",
"size": "1025",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "node_modules/ag-grid/src/ts/layout/verticalStack.ts",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "628"
},
{
"name": "CSS",
"bytes": "416952"
},
{
"name": "CoffeeScript",
"bytes": "7615"
},
{
"name": "HTML",
"bytes": "436111"
},
{
"name": "JavaScript",
"bytes": "6411747"
},
{
"name": "PHP",
"bytes": "772906"
},
{
"name": "Shell",
"bytes": "14022"
},
{
"name": "TypeScript",
"bytes": "958684"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2005-2015 Red Hat, Inc.
Red Hat 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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.fabric8.forge</groupId>
<artifactId>forge-addons</artifactId>
<version>2.3-SNAPSHOT</version>
</parent>
<artifactId>camel</artifactId>
<name>Fabric8 :: Forge Addons :: Camel</name>
<properties>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- to include hawtio version in pom.xml which is needed by camel setup command -->
<hawtio.version>1.4.51</hawtio.version>
<!-- docker maven plugin -->
<docker.version>0.12.0</docker.version>
<!-- jube version -->
<jube.version>2.1.5</jube.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.forge</groupId>
<artifactId>forge-bom</artifactId>
<version>${jboss.forge.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.jboss.spec</groupId>
<artifactId>jboss-javaee-6.0</artifactId>
<version>3.0.2.Final</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.fabric8.forge</groupId>
<artifactId>utils</artifactId>
<version>${project.version}</version>
</dependency>
<!-- forge provided -->
<dependency>
<groupId>org.jboss.forge.addon</groupId>
<artifactId>maven-api</artifactId>
<scope>provided</scope>
</dependency>
<!--forge addons -->
<dependency>
<groupId>org.jboss.forge.addon</groupId>
<artifactId>maven</artifactId>
<classifier>forge-addon</classifier>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.forge.furnace.container</groupId>
<artifactId>cdi</artifactId>
<classifier>forge-addon</classifier>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.forge.addon</groupId>
<artifactId>ui</artifactId>
<classifier>forge-addon</classifier>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.forge.addon</groupId>
<artifactId>projects</artifactId>
<classifier>forge-addon</classifier>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.forge.addon</groupId>
<artifactId>parser-java</artifactId>
<classifier>forge-addon</classifier>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.forge.addon</groupId>
<artifactId>parser-xml</artifactId>
<classifier>forge-addon</classifier>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.forge.addon</groupId>
<artifactId>rest-client</artifactId>
<classifier>forge-addon</classifier>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.forge.addon</groupId>
<artifactId>templates</artifactId>
<classifier>forge-addon</classifier>
<scope>provided</scope>
</dependency>
<!--camel -->
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-commands-jolokia</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-catalog</artifactId>
<version>${camel.version}</version>
</dependency>
</dependencies>
<build>
<finalName>camel</finalName>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<executions>
<execution>
<id>create-forge-addon</id>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
<configuration>
<classifier>forge-addon</classifier>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<!-- <profile>
<id>release</id>
<activation />
<build>
<plugins>
<plugin>
<groupId>org.jboss.forge.furnace</groupId>
<artifactId>furnace-maven-plugin</artifactId>
<version>${version.furnace}</version>
<executions>
<execution>
<id>generate-dot</id>
<phase>prepare-package</phase>
<goals>
<goal>generate-dot</goal>
</goals>
<configuration>
<attach>true</attach>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>-->
</profiles>
</project>
| {
"content_hash": "aef3faa8c0da149bb610f26f60d23f29",
"timestamp": "",
"source": "github",
"line_count": 191,
"max_line_length": 204,
"avg_line_length": 31.68586387434555,
"alnum_prop": 0.6044282881692002,
"repo_name": "migue/fabric8",
"id": "af3ff1d76a6b99f352f6e613dc64400f25a8411a",
"size": "6052",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "forge/addons/camel/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "4010"
},
{
"name": "HTML",
"bytes": "93376"
},
{
"name": "Java",
"bytes": "3783403"
},
{
"name": "JavaScript",
"bytes": "965"
},
{
"name": "Scala",
"bytes": "5260"
},
{
"name": "Shell",
"bytes": "39395"
}
],
"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.6.0_26) on Sat Jun 21 06:31:59 UTC 2014 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.apache.hadoop.lib.service.security.GroupsService (Apache Hadoop HttpFS 2.4.1 API)
</TITLE>
<META NAME="date" CONTENT="2014-06-21">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.hadoop.lib.service.security.GroupsService (Apache Hadoop HttpFS 2.4.1 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= 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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/lib/service/security/GroupsService.html" title="class in org.apache.hadoop.lib.service.security"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</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">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/hadoop/lib/service/security//class-useGroupsService.html" target="_top"><B>FRAMES</B></A>
<A HREF="GroupsService.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>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.hadoop.lib.service.security.GroupsService</B></H2>
</CENTER>
No usage of org.apache.hadoop.lib.service.security.GroupsService
<P>
<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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/apache/hadoop/lib/service/security/GroupsService.html" title="class in org.apache.hadoop.lib.service.security"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</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">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../index.html?org/apache/hadoop/lib/service/security//class-useGroupsService.html" target="_top"><B>FRAMES</B></A>
<A HREF="GroupsService.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>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2014 <a href="http://www.apache.org">Apache Software Foundation</a>. All Rights Reserved.
</BODY>
</HTML>
| {
"content_hash": "e4e89e4c86a83f97254fe8fa91a35fbb",
"timestamp": "",
"source": "github",
"line_count": 145,
"max_line_length": 253,
"avg_line_length": 44.04137931034483,
"alnum_prop": 0.6144691512683996,
"repo_name": "devansh2015/hadoop-2.4.1",
"id": "06f92dd75e1583885e5be22a3396d36d80c27859",
"size": "6386",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "share/doc/hadoop/hadoop-hdfs-httpfs/apidocs/org/apache/hadoop/lib/service/security/class-use/GroupsService.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "94903"
},
{
"name": "C",
"bytes": "29267"
},
{
"name": "C++",
"bytes": "16604"
},
{
"name": "CSS",
"bytes": "430608"
},
{
"name": "HTML",
"bytes": "61553856"
},
{
"name": "JavaScript",
"bytes": "15941"
},
{
"name": "Shell",
"bytes": "170866"
},
{
"name": "XSLT",
"bytes": "21772"
}
],
"symlink_target": ""
} |
package no.uio.studentweb.sword;
/**
* Exeception class to be thrown when the EndpointDiscovery has been unable
* to acquire a service document url or a service document itself, for
* whatever reasons
*/
public class NoServiceException extends DiscoveryException
{
public NoServiceException()
{
super();
}
public NoServiceException(String message)
{
super(message);
}
public NoServiceException(String message, Throwable cause)
{
super(message, cause);
}
public NoServiceException(Throwable cause)
{
super(cause);
}
}
| {
"content_hash": "49aab152059d07106d38e0647eb9dc81",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 75,
"avg_line_length": 18.2,
"alnum_prop": 0.7454212454212454,
"repo_name": "nye-duo/StudentWeb",
"id": "9f0d07fead12253b5362ac096dcf9abc8adee461",
"size": "2064",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/no/uio/studentweb/sword/NoServiceException.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "1391"
},
{
"name": "Java",
"bytes": "108609"
}
],
"symlink_target": ""
} |
package com.github.binding;
import java.util.List;
import java.util.ArrayList;
import com.github.event.PropertyChangeListener;
import com.github.util.ObjectUtil;
/**
* Hold a property for a class.
*
* A sophisticated wrapper for a property, supporting {@code PropertyChangeListener}s.
*
* Used with the data binding framework.
*
* @param <T>
* The type of this property.
*/
public class Property<T> {
/**
* A listener that is used to update this property.
*
* When this property is bound to another property, it will listen to
* changes to the other property and update itself on change.
*/
private class OnPropertyChangeUpdater implements PropertyChangeListener<T> {
@Override public void propertyChanged(Property<T> property) {
set(property.get());
}
}
private T data;
private List<PropertyChangeListener<T>> listeners = new ArrayList<PropertyChangeListener<T>>();
private OnPropertyChangeUpdater updateListener = new OnPropertyChangeUpdater();
public Property(T data) {
this.data = data;
}
/**
* @return The data contained in this property.
*/
public T get() {
return data;
}
/**
* Override this method to receive property changes.
*
* Called before other bindings are notified.
*
* Note: Changing the property inside {@code onChange} triggers a recursive call.
*/
protected void onChange(T newValue) {
// Empty.
}
/**
* Create a binding between this property and {@code other}.
*
* Immediately notify {@code other} of our value, unless our value is null.
*/
public void bind(Property<T> other) {
PropertyChangeListener<T> listener = other.getOnPropertyChangeUpdater();
addListener(listener);
if (get() != null) {
listener.propertyChanged(this);
}
}
/**
* Create a binding builder with this as the source.
*
* Example:
* <pre>
* {@code
* property.bind().to(anotherProperty).build();
* }
* </pre>
*/
public BindingBuilder<T> bind() {
return new BindingBuilder<T>().from(this);
}
/**
* Set the data for this property.
*
* Notifies listeners that the data was changed.
*/
public void set(T data) {
if (ObjectUtil.equals(this.data, data)) {
this.data = data;
} else {
this.data = data;
onChange(data);
notifyListeners();
}
}
protected void notifyListeners() {
for (PropertyChangeListener<T> listener : listeners) {
listener.propertyChanged(this);
}
}
void addListener(PropertyChangeListener<T> listener) {
listeners.add(listener);
}
void removeListener(PropertyChangeListener<T> listener) {
listeners.remove(listener);
}
PropertyChangeListener<T> getOnPropertyChangeUpdater() {
return updateListener;
}
}
| {
"content_hash": "325c3b7e2ff8436f964bb2d2c0d14524",
"timestamp": "",
"source": "github",
"line_count": 121,
"max_line_length": 99,
"avg_line_length": 25.520661157024794,
"alnum_prop": 0.6042746113989638,
"repo_name": "orbekk/jadab",
"id": "afedb7a9defb22edec7bd50d00631bec745778ad",
"size": "3717",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Jadab/src/main/java/com/github/binding/Property.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "56073"
}
],
"symlink_target": ""
} |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct base_unit_info<metric::ton_base_unit></title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../boost_units/Reference.html#header.boost.units.base_units.metric.ton_hpp" title="Header <boost/units/base_units/metric/ton.hpp>">
<link rel="prev" href="base_unit_inf_idp366259296.html" title="Struct base_unit_info<metric::nautical_mile_base_unit>">
<link rel="next" href="metric/torr_base_unit.html" title="Struct torr_base_unit">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="base_unit_inf_idp366259296.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_units/Reference.html#header.boost.units.base_units.metric.ton_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="metric/torr_base_unit.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.units.base_unit_inf_idp366267200"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct base_unit_info<metric::ton_base_unit></span></h2>
<p>boost::units::base_unit_info<metric::ton_base_unit></p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../boost_units/Reference.html#header.boost.units.base_units.metric.ton_hpp" title="Header <boost/units/base_units/metric/ton.hpp>">boost/units/base_units/metric/ton.hpp</a>>
</span>
<span class="keyword">struct</span> <a class="link" href="base_unit_inf_idp366267200.html" title="Struct base_unit_info<metric::ton_base_unit>">base_unit_info</a><span class="special"><</span><span class="identifier">metric</span><span class="special">::</span><span class="identifier">ton_base_unit</span><span class="special">></span> <span class="special">{</span>
<span class="comment">// <a class="link" href="base_unit_inf_idp366267200.html#idp366268304-bb">public static functions</a></span>
<span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a class="link" href="base_unit_inf_idp366267200.html#idp366268864-bb"><span class="identifier">name</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a class="link" href="base_unit_inf_idp366267200.html#idp366269984-bb"><span class="identifier">symbol</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idp483566352"></a><h2>Description</h2>
<div class="refsect2">
<a name="idp483566768"></a><h3>
<a name="idp366268304-bb"></a><code class="computeroutput">base_unit_info</code> public static functions</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem"><pre class="literallayout"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a name="idp366268864-bb"></a><span class="identifier">name</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre></li>
<li class="listitem"><pre class="literallayout"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a name="idp366269984-bb"></a><span class="identifier">symbol</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre></li>
</ol></div>
</div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2008 Matthias Christian Schabel<br>Copyright © 2007-2010 Steven
Watanabe<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="base_unit_inf_idp366259296.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_units/Reference.html#header.boost.units.base_units.metric.ton_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="metric/torr_base_unit.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "3304e8cc58c5d0e647144102ddfb0d83",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 494,
"avg_line_length": 91.33823529411765,
"alnum_prop": 0.6776686523909193,
"repo_name": "calvinfarias/IC2015-2",
"id": "3dc71dc3beb13b169f64292f3e05edb6fbf49dd7",
"size": "6211",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "BOOST/boost_1_61_0/doc/html/boost/units/base_unit_inf_idp366267200.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "223360"
},
{
"name": "Batchfile",
"bytes": "32233"
},
{
"name": "C",
"bytes": "2977162"
},
{
"name": "C#",
"bytes": "40804"
},
{
"name": "C++",
"bytes": "184445796"
},
{
"name": "CMake",
"bytes": "119765"
},
{
"name": "CSS",
"bytes": "427923"
},
{
"name": "Cuda",
"bytes": "111870"
},
{
"name": "DIGITAL Command Language",
"bytes": "6246"
},
{
"name": "FORTRAN",
"bytes": "5291"
},
{
"name": "Groff",
"bytes": "5189"
},
{
"name": "HTML",
"bytes": "234946752"
},
{
"name": "IDL",
"bytes": "14"
},
{
"name": "JavaScript",
"bytes": "682223"
},
{
"name": "Lex",
"bytes": "1231"
},
{
"name": "M4",
"bytes": "29689"
},
{
"name": "Makefile",
"bytes": "1083443"
},
{
"name": "Max",
"bytes": "36857"
},
{
"name": "Objective-C",
"bytes": "11406"
},
{
"name": "Objective-C++",
"bytes": "630"
},
{
"name": "PHP",
"bytes": "59030"
},
{
"name": "Perl",
"bytes": "39008"
},
{
"name": "Perl6",
"bytes": "2053"
},
{
"name": "Python",
"bytes": "1759984"
},
{
"name": "QML",
"bytes": "593"
},
{
"name": "QMake",
"bytes": "16692"
},
{
"name": "Rebol",
"bytes": "354"
},
{
"name": "Ruby",
"bytes": "5532"
},
{
"name": "Shell",
"bytes": "355247"
},
{
"name": "Tcl",
"bytes": "1172"
},
{
"name": "TeX",
"bytes": "126042"
},
{
"name": "XSLT",
"bytes": "552736"
},
{
"name": "Yacc",
"bytes": "19623"
}
],
"symlink_target": ""
} |
<?php
namespace Iltar\HttpBundle\DoctrineBridge;
use Doctrine\ORM\Mapping\MappingException;
use Symfony\Bridge\Doctrine\RegistryInterface;
use Symfony\Component\PropertyAccess\PropertyAccess;
/**
* @author Iltar van der Berg <kjarli@gmail.com>
*/
class EntityIdResolverTest extends \PHPUnit_Framework_TestCase
{
public function testArray()
{
$manager = $this->prophesize(RegistryInterface::class);
$accessor = PropertyAccess::createPropertyAccessor();
$resolver = new EntityIdDescriptor($manager->reveal(), $accessor);
self::assertFalse($resolver->isManaged(['id' => 400]));
}
public function testObjectNotEntity()
{
$object = $this->prophesize(TestObject::class);
$manager = $this->prophesize(RegistryInterface::class);
$accessor = PropertyAccess::createPropertyAccessor();
$resolver = new EntityIdDescriptor($manager->reveal(), $accessor);
$manager->getRepository(get_class($object->reveal()))->shouldBeCalled()->willThrow(new MappingException());
self::assertFalse($resolver->isManaged($object->reveal()));
// should hit the cache
self::assertFalse($resolver->isManaged($object->reveal()));
self::assertAttributeSame([get_class($object->reveal()) => false], 'resolvedCache', $resolver);
}
public function testEntity()
{
$entity = $this->prophesize(TestObject::class);
$manager = $this->prophesize(RegistryInterface::class);
$accessor = PropertyAccess::createPropertyAccessor();
$resolver = new EntityIdDescriptor($manager->reveal(), $accessor);
$manager->getRepository(get_class($entity->reveal()))->shouldBeCalled();
self::assertTrue($resolver->isManaged($entity->reveal()));
}
}
interface TestObject
{
}
| {
"content_hash": "1a2dac2b5ddaff0e9302e4c260b89548",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 115,
"avg_line_length": 33.53703703703704,
"alnum_prop": 0.6775262286029817,
"repo_name": "iltar/http-bundle",
"id": "3de5bdeaaebff4e2f362e5cf11dd3de3aca54593",
"size": "1811",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/DoctrineBridge/EntityIdDescriptorTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "52714"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<!-- MOTW-DISABLED saved from url=(0014)about:internet -->
<title>How to add a computed field to a data set</title>
<link rel="StyleSheet" href="css/retrieving-data.css" type="text/css" media="all" />
<link rel="StyleSheet" href="css/webworks.css" type="text/css" media="all" />
<link rel="StyleSheet" href="webworks.css" type="text/css" media="all" />
<script type="text/javascript" language="JavaScript1.2">
<!--
var WebWorksRootPath = "";
// -->
</script>
</head>
<body class="" style="">
<div style="text-align: left;">
<table cellspacing="0" summary="">
<tr>
<td>
<a href="retrieving-data.3.5.html"><img src="images/prev.gif" alt="Previous" border="0" /></a>
</td>
<td>
<a href="retrieving-data.3.7.html"><img src="images/next.gif" alt="Next" border="0" /></a>
</td>
</tr>
</table>
</div>
<hr align="left" />
<blockquote>
<h4 class="N_hth_HowToHelp"><a name="204977">How to add a computed field to a data set</a></h4>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">1 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="191189">In Edit Data Set, choose Computed Columns.</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">2 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="244995">Choose New to create a new computed field.</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">3 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="244997">On New Computed Column:</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n2_NumList2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n2_NumList2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023FormatGray">1 </span>
</div>
</td>
<td width="100%">
<div class="N_n2_NumList2_inner"><a name="191191">In Column Name, type a name for the computed field.</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n2_NumList2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n2_NumList2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023FormatGray">2 </span>
</div>
</td>
<td width="100%">
<div class="N_n2_NumList2_inner"><a name="213212">In Data Type, select a data type appropriate for the data returned by </a>the computed field.</div>
</td>
</tr>
</table>
</div>
<div class="N_n2_NumList2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n2_NumList2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023FormatGray">3 </span>
</div>
</td>
<td width="100%">
<div class="N_n2_NumList2_inner"><a name="291783">To perform a calculation on all the rows in the data set, in Aggregation, </a>select an aggregate function. If performing an aggregate calculation, you can optionally specify a filter expression in Filter to determine which rows to include in the calculation.</div>
</td>
</tr>
</table>
</div>
<div class="N_n2_NumList2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n2_NumList2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023FormatGray">4 </span>
</div>
</td>
<td width="100%">
<div class="N_n2_NumList2_inner"><a name="291787">In Expression, specify the expression to calculate the desired value. </a>You can either type the expression or use the expression builder to construct the expression. To use the expression builder, complete the following steps:</div>
</td>
</tr>
</table>
</div>
<p class="N_sb_ScanBold"><a name="191207"><img class="Default" src="images/icon_builder.gif" width="22" height="22" style="display: inline; float: none; left: 0.0; top: 0.0;" alt="" /></a></p>
<div class="N_n3_NumList3_outer" style="margin-left: 28.3464pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n3_NumList3_inner" style="width: 14.173199999999997pt; white-space: nowrap;">
<span class="zAuto_0023FormatGray2">1 </span>
</div>
</td>
<td width="100%">
<div class="N_n3_NumList3_inner"><a name="208149">Choose the expression builder button to open the expression </a>builder. In Category, select Available Data sets, then select your data set.</div>
</td>
</tr>
</table>
</div>
<div class="N_i3_Indent3"><a name="208151">Double-click an </a>item to add it to the expression at the insertion point. <a href="#215147" title="How to add a computed field to a data set">Figure 3‑5</a> shows how to create an expression for a computed column.</div>
<p class="i4_Image4"><a name="208162"><img class="Default" src="images/computed_column_expression1.gif" width="631" height="515" style="display: inline; float: none; left: 0.0; top: 0.0;" alt="Figure 3-5 Creating an expression for a computed column" /></a></p>
<div class="fc4_FigCall4Title_outer" style="margin-left: 42.5196pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="fc4_FigCall4Title_inner" style="width: 70.866pt; white-space: nowrap;">
<b class="Bold">Figure 3‑5 </b>
</div>
</td>
<td width="100%">
<div class="fc4_FigCall4Title_inner"><a name="215147">Creating an expression for a computed column</a></div>
</td>
</tr>
</table>
</div>
<div class="N_n3_NumList3_outer" style="margin-left: 28.3464pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n3_NumList3_inner" style="width: 14.173199999999997pt; white-space: nowrap;">
<span class="zAuto_0023FormatGray2">2 </span>
</div>
</td>
<td width="100%">
<div class="N_n3_NumList3_inner"><a name="208138">Choose OK to save the expression. The expression appears in the </a>Expression field in New Computed Column.</div>
</td>
</tr>
</table>
</div>
<div class="N_n2_NumList2_outer" style="margin-left: 14.1732pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n2_NumList2_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023FormatGray">5 </span>
</div>
</td>
<td width="100%">
<div class="N_n2_NumList2_inner"><a name="245014">Choose OK to save the computed field. Computed Columns displays </a>the computed field and the expression you defined.</div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">4 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="224681">To see all the columns that are specified in the data set, choose Output </a>Columns. The computed field you created appears on this page.</div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">5 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="208140">Choose Preview Results to confirm that the computed field returns the </a>correct data. </div>
</td>
</tr>
</table>
</div>
<div class="N_n1_NumList1_outer" style="margin-left: 0pt;">
<table border="0" cellspacing="0" cellpadding="0" summary="">
<tr style="vertical-align: baseline;">
<td>
<div class="N_n1_NumList1_inner" style="width: 14.1732pt; white-space: nowrap;">
<span class="zAuto_0023Format">6 </span>
</div>
</td>
<td width="100%">
<div class="N_n1_NumList1_inner"><a name="212114">Choose OK to save your changes to the data set.</a></div>
</td>
</tr>
</table>
</div>
</blockquote>
<hr align="left" />
<table align="right" summary="">
<tr>
<td class="WebWorks_Company_Name_Bottom">
<a href="notices.html">(c) Copyright Actuate Corporation 2009</a>
</td>
</tr>
</table>
</body>
</html> | {
"content_hash": "8a870694f330e3ee004f2cc45f2f5e5b",
"timestamp": "",
"source": "github",
"line_count": 243,
"max_line_length": 329,
"avg_line_length": 48.74074074074074,
"alnum_prop": 0.5491388044579534,
"repo_name": "00wendi00/MyProject",
"id": "6fc5ce6d90ba6d9a3661ade287699e5d449b12b1",
"size": "11848",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "W_myeclipse/plugins/org.eclipse.birt.doc_2.5.2.me201003052220/birt/retrieving-data.3.6.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "430521"
},
{
"name": "C",
"bytes": "17868156"
},
{
"name": "C++",
"bytes": "5054355"
},
{
"name": "CMake",
"bytes": "7325"
},
{
"name": "CSS",
"bytes": "3874611"
},
{
"name": "Groff",
"bytes": "409306"
},
{
"name": "HTML",
"bytes": "7833410"
},
{
"name": "Java",
"bytes": "13395187"
},
{
"name": "JavaScript",
"bytes": "2319278"
},
{
"name": "Logos",
"bytes": "6864"
},
{
"name": "M",
"bytes": "20108"
},
{
"name": "Makefile",
"bytes": "2540551"
},
{
"name": "Objective-C",
"bytes": "546363"
},
{
"name": "Perl",
"bytes": "11763"
},
{
"name": "Python",
"bytes": "3285"
},
{
"name": "R",
"bytes": "8138"
},
{
"name": "Rebol",
"bytes": "3080"
},
{
"name": "Shell",
"bytes": "1020448"
},
{
"name": "SuperCollider",
"bytes": "8013"
},
{
"name": "XSLT",
"bytes": "220483"
}
],
"symlink_target": ""
} |
@interface LCApplication ()
@property (nonatomic) NSString *identifier;
@property (nonatomic) NSString *key;
- (NSString *)identifierThrowException;
- (NSString *)keyThrowException;
@end
| {
"content_hash": "14be72c7b25bf31ab69b3a752e48af0a",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 43,
"avg_line_length": 21.11111111111111,
"alnum_prop": 0.7631578947368421,
"repo_name": "leancloud/objc-sdk",
"id": "41280889487f31da0baa878dffa9c3f7621725b0",
"size": "365",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AVOS/Sources/Foundation/LCApplication_Internal.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "93210"
},
{
"name": "Objective-C",
"bytes": "2514989"
},
{
"name": "Ruby",
"bytes": "65481"
},
{
"name": "Shell",
"bytes": "2037"
},
{
"name": "Swift",
"bytes": "355909"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.